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 |
|---|---|---|---|---|---|
mlem/wesnoth | data/ai/micro_ais/cas/ca_stationed_guardian.lua | 24 | 4530 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local function get_guardian(cfg)
local filter = cfg.filter or { id = cfg.id }
local guardian = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", filter }
}[1]
return guardian
end
local ca_stationed_guardian = {}
function ca_stationed_guardian:evaluation(ai, cfg)
if get_guardian(cfg) then return cfg.ca_score end
return 0
end
function ca_stationed_guardian:execution(ai, cfg)
-- (s_x, s_y): coordinates where guardian is stationed; tries to move here if there is nobody to attack
-- (g_x, g_y): location that the guardian guards
local guardian = get_guardian(cfg)
local enemies = wesnoth.get_units {
{ "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } },
{ "filter_location", { x = guardian.x, y = guardian.y, radius = cfg.distance } }
}
-- If no enemies are within cfg.distance: keep guardian from doing anything and exit
if not enemies[1] then
AH.checked_stopunit_moves(ai, guardian)
return
end
-- Otherwise, guardian will either attack or move toward station
-- Enemies must be within cfg.distance of guardian, (s_x, s_y) *and* (g_x, g_y)
-- simultaneously for guardian to attack
local min_dist, target = 9e99
for _,enemy in ipairs(enemies) do
local dist_s = H.distance_between(cfg.station_x, cfg.station_y, enemy.x, enemy.y)
local dist_g = H.distance_between(cfg.guard_x or cfg.station_x, cfg.guard_y or cfg.station_y, enemy.x, enemy.y)
-- If valid target found, save the one with the shortest distance from (g_x, g_y)
if (dist_s <= cfg.distance) and (dist_g <= cfg.distance) and (dist_g < min_dist) then
target, min_dist = enemy, dist_g
end
end
-- If a valid target was found, guardian attacks this target, or moves toward it
if target then
-- Find tiles adjacent to the target
-- Save the one with the highest defense rating that guardian can reach
local best_defense, attack_loc = -9e99
for xa,ya in H.adjacent_tiles(target.x, target.y) do
-- Only consider unoccupied hexes
local occ_hex = wesnoth.get_units { x = xa, y = ya, { "not", { id = guardian.id } } }[1]
if not occ_hex then
local defense = 100 - wesnoth.unit_defense(guardian, wesnoth.get_terrain(xa, ya))
local nh = AH.next_hop(guardian, xa, ya)
if nh then
if (nh[1] == xa) and (nh[2] == ya) and (defense > best_defense) then
best_defense, attack_loc = defense, { xa, ya }
end
end
end
end
-- If a valid hex was found: move there and attack
if attack_loc then
AH.movefull_stopunit(ai, guardian, attack_loc)
if (not guardian) or (not guardian.valid) then return end
if (not target) or (not target.valid) then return end
AH.checked_attack(ai, guardian, target)
else -- Otherwise move toward that enemy
local reach = wesnoth.find_reach(guardian)
-- Go through all hexes the guardian can reach, find closest to target
-- Cannot use next_hop here since target hex is occupied by enemy
local min_dist, nh = 9e99
for _,hex in ipairs(reach) do
-- Only consider unoccupied hexes
local occ_hex = wesnoth.get_units { x = hex[1], y = hex[2], { "not", { id = guardian.id } } }[1]
if not occ_hex then
local dist = H.distance_between(hex[1], hex[2], target.x, target.y)
if (dist < min_dist) then
min_dist, nh = dist, { hex[1], hex[2] }
end
end
end
AH.movefull_stopunit(ai, guardian, nh)
end
-- If no enemy is within the target zone, move toward station position
else
local nh = AH.next_hop(guardian, cfg.station_x, cfg.station_y)
if not nh then
nh = { guardian.x, guardian.y }
end
AH.movefull_stopunit(ai, guardian, nh)
end
if (not guardian) or (not guardian.valid) then return end
AH.checked_stopunit_moves(ai, guardian)
-- If there are attacks left and guardian ended up next to an enemy, we'll leave this to RCA AI
end
return ca_stationed_guardian
| gpl-2.0 |
nasomi/darkstar | scripts/globals/items/dolphin_staff.lua | 41 | 1077 | -----------------------------------------
-- ID: 17134
-- Item: Dolphin Staff
-- Additional Effect: Water Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_WATER_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Mamook/npcs/qm2.lua | 16 | 1163 | -----------------------------------
-- Area: Mamook
-- NPC: ??? (Spawn Iriri Samariri(ZNM T2))
-- @pos -118 7 -80 65
-----------------------------------
package.loaded["scripts/zones/Mamook/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mamook/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(2579,1) and trade:getItemCount() == 1) then -- Trade Samariri Corpsehair
player:tradeComplete();
SpawnMob(17043888,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
mkjanke/Focus-Points | focuspoints.lrdevplugin/NikonDuplicates.lua | 3 | 1050 | --[[
Copyright 2016 Whizzbang Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
Maps out which cameras have the same focus point maps as others.
NikonDuplicates["d7100"] = "d7200" means that the D7100 has the same mapping
as the D7200, and the D7200 text file will be used.
--]]
NikonDuplicates = {}
NikonDuplicates["nikon d7100"] = "nikon d7200"
NikonDuplicates["nikon d800e"] = "nikon d800"
NikonDuplicates["nikon d810"] = "nikon d800"
NikonDuplicates["nikon d5300"] = "nikon d5500"
NikonDuplicates["nikon d5200"] = "nikon d5500" | apache-2.0 |
nasomi/darkstar | scripts/globals/spells/absorb-dex.lua | 18 | 1300 | --------------------------------------
-- Spell: Absorb-DEX
-- Steals an enemy's dexterity.
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_DEX_DOWN) or caster:hasStatusEffect(EFFECT_DEX_BOOST)) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,37,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
spell:setMsg(330);
caster:addStatusEffect(EFFECT_DEX_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains DEX
target:addStatusEffect(EFFECT_DEX_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASBLE); -- target loses DEX
end
end
return EFFECT_DEX_DOWN;
end; | gpl-3.0 |
mpeterv/ltq | src/ltq/builtins.lua | 1 | 4566 | -- Builtins are represented by functions taking compilation environment, varible name and arguments
-- and returning nested arrays of strings representing statement and expression parts of result.
local builtins = {}
-- Returns a builtin for a prefix unary opator.
local function unop(op)
return function(env, var, a)
local a_stat, a_expr = env:compile(a, var)
return a_stat, {op, "(", a_expr, ")"}
end
end
-- Returns a builtin for an infix binary operator.
local function binop(op)
return function(env, var, a, b)
local a_stat, a_expr = env:compile(a, var)
local b_stat, b_expr = env:compile(b, var)
return {a_stat, b_stat}, {"(", a_expr, ")", op, "(", b_expr, ")"}
end
end
-- FIXME: bound functions must be added to environment.
-- Returns a builtin for a Lua function taking one argument.
local function bind1(fname)
return function(env, var, a)
local a_stat, a_expr = env:compile(a, var)
return a_stat, {fname, "(", a_expr, ")"}
end
end
builtins.unm = unop("-")
builtins.add = binop("+")
builtins.sub = binop("-")
builtins.mul = binop("*")
builtins.div = binop("/")
builtins.pow = binop("^")
builtins.mod = binop("%")
builtins.len = unop("#")
builtins.concat = binop("..")
builtins.eq = binop("==")
builtins.neq = binop("~=")
builtins.lt = binop("<")
builtins.lte = binop("<=")
builtins.gt = binop(">")
builtins.gte = binop(">=")
builtins["not"] = unop("not")
builtins["and"] = binop("and")
builtins["or"] = binop("or")
function builtins.index(env, var, a, b)
local a_stat, a_expr = env:compile(a, var)
local b_stat, b_expr = env:compile(b, var)
return {a_stat, b_stat}, {"(", a_expr, ")[", b_expr, "]"}
end
builtins["if"] = function(env, var, cond, t, f)
local res_var = env:var()
local cond_stat, cond_expr = env:compile(cond, var)
local true_stat, true_expr = env:compile(t, var)
local false_stat, false_expr = env:compile(f, var)
return {
cond_stat,
"local ", res_var, "\n",
"if ", cond_expr, " then\n",
true_stat,
res_var, " = ", true_expr, "\n",
"else\n",
false_stat,
res_var, " = ", false_expr, "\n",
"end\n"
}, {res_var}
end
function builtins.map(env, var, f, a)
assert(f.tag == "Func")
local fb = f[1]
local arr_var = env:var()
local res_var = env:var()
local i_var = env:var()
local item_var = env:var()
local arr_stat, arr_expr = env:compile(a, var)
local fb_stat, fb_expr = env:compile(fb, item_var)
return {arr_stat,
"local ", arr_var, " = ", arr_expr, "\n",
"local ", res_var, " = {}\n",
"for ", i_var, " = 1, #", arr_var, " do\n",
"local ", item_var, " = ", arr_var, "[", i_var, "]\n",
fb_stat,
res_var, "[", i_var, "] = ", fb_expr, "\n",
"end\n"
}, {res_var}
end
function builtins.filter(env, var, f, a)
assert(f.tag == "Func")
local fb = f[1]
local arr_var = env:var()
local res_var = env:var()
local c_var = env:var()
local i_var = env:var()
local item_var = env:var()
local arr_stat, arr_expr = env:compile(a, var)
local fb_stat, fb_expr = env:compile(fb, item_var)
return {arr_stat,
"local ", arr_var, " = ", arr_expr, "\n",
"local ", res_var, " = {}\n",
"local ", c_var, " = 0\n",
"for ", i_var, " = 1, #", arr_var, " do\n",
"local ", item_var, " = ", arr_var, "[", i_var, "]\n",
fb_stat,
"if ", fb_expr, " then\n",
c_var, " = ", c_var, " + 1\n",
res_var, "[", c_var, "] = ", item_var, "\n",
"end\n",
"end\n"
}, {res_var}
end
builtins.sort1 = bind1("sort")
function builtins.sort2(env, var, f, a)
assert(f.tag == "Func")
local fb = f[1]
-- table.sort takes a comparator function, ltq sort takes a key function.
-- To convert, build a table mapping items to their keys.
-- FIXME: key can happen to be nil or NaN.
local arr_var = env:var()
local keys_var = env:var()
local i_var = env:var()
local item_var = env:var()
local arr_stat, arr_expr = env:compile(a, var)
local key_stat, key_expr = env:compile(fb, item_var)
return {arr_stat,
"local ", arr_var, " = ", arr_expr, "\n",
"local ", keys_var, " = {}\n",
"for ", i_var, " = 1, #", arr_var, " do\n",
"local ", item_var, " = ", arr_var, "[", i_var, "]\n",
key_stat,
keys_var, "[", item_var, "] = ", key_expr, "\n",
"end\n"
}, {"sort(", arr_var, ", function(a, b) return ", keys_var, "[a] < ", keys_var, "[b] end)"}
end
return builtins
| mit |
thesabbir/luci | applications/luci-app-splash/luasrc/controller/splash/splash.lua | 40 | 4649 | module("luci.controller.splash.splash", package.seeall)
local uci = luci.model.uci.cursor()
local util = require "luci.util"
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), _("Client-Splash"), 90)
entry({"admin", "services", "splash", "splashtext" }, form("splash/splashtext"), _("Splashtext"), 10)
local e
e = node("splash")
e.target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
node("splash", "blocked").target = template("splash/blocked")
entry({"admin", "status", "splash"}, call("action_status_admin"), _("Client-Splash"))
local page = node("splash", "publicstatus")
page.target = call("action_status_public")
page.leaf = true
end
function ip_to_mac(ip)
local ipc = require "luci.ip"
local i, n
for i, n in ipairs(ipc.neighbors()) do
if n.mac and n.dest and n.dest:equal(ip) then
return n.mac
end
end
end
function action_dispatch()
local uci = luci.model.uci.cursor_state()
local mac = ip_to_mac(luci.http.getenv("REMOTE_ADDR")) or ""
local access = false
uci:foreach("luci_splash", "lease", function(s)
if s.mac and s.mac:lower() == mac then access = true end
end)
uci:foreach("luci_splash", "whitelist", function(s)
if s.mac and s.mac:lower() == mac then access = true end
end)
if #mac > 0 and access then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function blacklist()
leased_macs = { }
uci:foreach("luci_splash", "blacklist",
function(s) leased_macs[s.mac:lower()] = true
end)
return leased_macs
end
function action_activate()
local ipc = require "luci.ip"
local mac = ip_to_mac(luci.http.getenv("REMOTE_ADDR") or "127.0.0.1") or ""
local uci_state = require "luci.model.uci".cursor_state()
local blacklisted = false
if mac and luci.http.formvalue("accept") then
uci:foreach("luci_splash", "blacklist",
function(s) if s.mac and s.mac:lower() == mac then blacklisted = true end
end)
if blacklisted then
luci.http.redirect(luci.dispatcher.build_url("splash" ,"blocked"))
else
local redirect_url = uci:get("luci_splash", "general", "redirect_url")
if not redirect_url then
redirect_url = uci_state:get("luci_splash_locations", mac:gsub(':', ''):lower(), "location")
end
if not redirect_url then
redirect_url = luci.model.uci.cursor():get("freifunk", "community", "homepage") or 'http://www.freifunk.net'
end
remove_redirect(mac:gsub(':', ''):lower())
os.execute("luci-splash lease "..mac.." >/dev/null 2>&1")
luci.http.redirect(redirect_url)
end
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
function action_status_admin()
local uci = luci.model.uci.cursor_state()
local macs = luci.http.formvaluetable("save")
local changes = {
whitelist = { },
blacklist = { },
lease = { },
remove = { }
}
for key, _ in pairs(macs) do
local policy = luci.http.formvalue("policy.%s" % key)
local mac = luci.http.protocol.urldecode(key)
if policy == "whitelist" or policy == "blacklist" then
changes[policy][#changes[policy]+1] = mac
elseif policy == "normal" then
changes["lease"][#changes["lease"]+1] = mac
elseif policy == "kicked" then
changes["remove"][#changes["remove"]+1] = mac
end
end
if #changes.whitelist > 0 then
os.execute("luci-splash whitelist %s >/dev/null"
% table.concat(changes.whitelist))
end
if #changes.blacklist > 0 then
os.execute("luci-splash blacklist %s >/dev/null"
% table.concat(changes.blacklist))
end
if #changes.lease > 0 then
os.execute("luci-splash lease %s >/dev/null"
% table.concat(changes.lease))
end
if #changes.remove > 0 then
os.execute("luci-splash remove %s >/dev/null"
% table.concat(changes.remove))
end
luci.template.render("admin_status/splash", { is_admin = true })
end
function action_status_public()
luci.template.render("admin_status/splash", { is_admin = false })
end
function remove_redirect(mac)
local mac = mac:lower()
mac = mac:gsub(":", "")
local uci = require "luci.model.uci".cursor_state()
local redirects = uci:get_all("luci_splash_locations")
--uci:load("luci_splash_locations")
uci:revert("luci_splash_locations")
-- For all redirects
for k, v in pairs(redirects) do
if v[".type"] == "redirect" then
if v[".name"] ~= mac then
-- Rewrite state
uci:section("luci_splash_locations", "redirect", v[".name"], {
location = v.location
})
end
end
end
uci:save("luci_splash_redirects")
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/TextIDs.lua | 9 | 1760 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6383; -- You cannot obtain the <item>. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6390; -- You obtain <param2 number> <param1 item>!
BEASTMEN_BANNER = 7124; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7544; -- You can't fish here.
-- Conquest
CONQUEST = 7211; -- You've earned conquest points!
-- Quest Dialogs
SENSE_OF_FOREBODING = 6399; -- You are suddenly overcome with a sense of foreboding...
STURDY_BRANCH = 7752; -- It is a beautiful, sturdy branch.
NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here.
-- ZM4 Dialog
CANNOT_REMOVE_FRAG = 7725; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7726; -- You have already obtained this monument's
FOUND_ALL_FRAGS = 7728; -- You now have all 8 fragments of light!
ZILART_MONUMENT = 7729; -- It is an ancient Zilart monument.
-- conquest Base
CONQUEST_BASE = 7043; -- Tallying conquest results...
-- chocobo digging
DIG_THROW_AWAY = 7557; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full.
FIND_NOTHING = 7559; -- You dig and you dig, but find nothing.
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/bataquiche_+1.lua | 35 | 1474 | -----------------------------------------
-- ID: 5169
-- Item: Bataquiche +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 10
-- Agility 1
-- Vitality -1
-- Ranged ATT % 7
-- Ranged ATT Cap 20
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5169);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_FOOD_RATTP, 7);
target:addMod(MOD_FOOD_RATT_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_FOOD_RATTP, 7);
target:delMod(MOD_FOOD_RATT_CAP, 20);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Leujaoam_Sanctum/IDs.lua | 33 | 3149 | Leujaoam = {
text = {
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6378, -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6381, -- Obtained: <item>
GIL_OBTAINED = 6384, -- Obtained <number> gil
KEYITEM_OBTAINED = 6384, -- Obtained key item: <keyitem>
-- Assault Texts
ASSAULT_01_START = 7417,
ASSAULT_02_START = 7418,
ASSAULT_03_START = 7419,
ASSAULT_04_START = 7420,
ASSAULT_05_START = 7421,
ASSAULT_06_START = 7422,
ASSAULT_07_START = 7423,
ASSAULT_08_START = 7424,
ASSAULT_09_START = 7425,
ASSAULT_10_START = 7426,
TIME_TO_COMPLETE = 7477,
MISSION_FAILED = 7478,
RUNE_UNLOCKED_POS = 7479,
RUNE_UNLOCKED = 7480,
ASSAULT_POINTS_OBTAINED = 7481,
TIME_REMAINING_MINUTES = 7482,
TIME_REMAINING_SECONDS = 7483,
PARTY_FALLEN = 7485
},
mobs = {
-- Leujaoam Cleansing
[1] = {
LEUJAOAM_WORM1 = 17059841,
LEUJAOAM_WORM2 = 17059842,
LEUJAOAM_WORM3 = 17059843,
LEUJAOAM_WORM4 = 17059844,
LEUJAOAM_WORM5 = 17059845,
LEUJAOAM_WORM6 = 17059846,
LEUJAOAM_WORM7 = 17059847,
LEUJAOAM_WORM8 = 17059848,
LEUJAOAM_WORM9 = 17059849,
LEUJAOAM_WORM10 = 17059850,
LEUJAOAM_WORM11 = 17059851,
LEUJAOAM_WORM12 = 17059852,
LEUJAOAM_WORM13 = 17059853,
LEUJAOAM_WORM14 = 17059854,
LEUJAOAM_WORM14 = 17059855,
}
},
npcs = {
ANCIENT_LOCKBOX = 17060014,
RUNE_OF_RELEASE = 17060015,
_1X1 = 17060116,
_1X2 = 17060117,
_1X3 = 17060118,
_1X4 = 17060119,
_1X5 = 17060120,
_1X6 = 17060121,
_1X7 = 17060122,
_1X8 = 17060123,
_1X9 = 17060124,
_1XA = 17060125,
_1XB = 17060126,
_1XC = 17060127,
_1XD = 17060128,
_1XE = 17060129,
_1XF = 17060130,
_1XG = 17060131,
_1XH = 17060132,
_1XI = 17060133,
_1XJ = 17060134,
_1XK = 17060135,
_1XL = 17060136,
_1XM = 17060137,
_1XN = 17060138,
_1XO = 17060139,
_1XP = 17060140,
_1XQ = 17060141,
_1XR = 17060142,
_1XS = 17060143,
_1XT = 17060144,
_1XU = 17060145,
_1XV = 17060146,
_1XW = 17060147,
_1XX = 17060148,
_1XY = 17060149,
_1XZ = 17060150,
_JX0 = 17060151,
_JX1 = 17060152,
_JX2 = 17060153,
_JX3 = 17060154,
_JX4 = 17060155,
_JX5 = 17060156,
_JX6 = 17060157,
_JX7 = 17060158,
_JX8 = 17060159,
_JX9 = 17060160,
_JXA = 17060161,
_JXB = 17060162,
_JXC = 17060163,
_JXD = 17060164,
_JXE = 17060165,
_JXF = 17060166,
_JXG = 17060167,
_JXH = 17060168,
_JXI = 17060169,
_JXJ = 17060170,
_JXK = 17060171,
}
} | gpl-3.0 |
nasomi/darkstar | scripts/zones/Vunkerl_Inlet_[S]/Zone.lua | 34 | 1337 | -----------------------------------
--
-- Zone: Vunkerl_Inlet_[S] (83)
--
-----------------------------------
package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-393.238,-50.034,741.199,2);
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/zones/LaLoff_Amphitheater/npcs/qm2.lua | 17 | 2200 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: Shimmering Circle (BCNM Exits)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
---- 0:
---- 1:
---- 2:
---- 3:
---- 4:
---- 5:
---- 6:
---- 7:
---- 8:
---- 9:
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvaan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Southern_San_dOria/npcs/HomePoint#3.lua | 17 | 1262 | -----------------------------------
-- Area: Southern San dOria
-- NPC: HomePoint#3
-- @pos 140 -2 123 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fe, 2);
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 == 0x21fe) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
shangjiyu/luci-with-extra | build/luadoc/luadoc/doclet/debug.lua | 175 | 1048 | -----------------------------------------------------------------
-- LuaDoc debugging facilities.
-- @release $Id: debug.lua,v 1.3 2007/04/18 14:28:39 tomas Exp $
-----------------------------------------------------------------
module "luadoc.doclet.debug"
function printline()
print(string.rep('-', 79))
end
-----------------------------------------------------------------
-- Print debug information about document
-- @param doc Table with the structured documentation.
function start (doc)
print("Files:")
for _, filepath in ipairs(doc.files) do
print('\t', filepath)
end
printline()
print("Modules:")
for _, modulename in ipairs(doc.modules) do
print('\t', modulename)
end
printline()
for i, v in pairs(doc.files) do
print('\t', i, v)
end
printline()
for i, v in pairs(doc.files[doc.files[1]]) do
print(i, v)
end
printline()
for i, v in pairs(doc.files[doc.files[1]].doc[1]) do
print(i, v)
end
printline()
print("Params")
for i, v in pairs(doc.files[doc.files[1]].doc[1].param) do
print(i, v)
end
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Port_San_dOria/npcs/Noquerelle.lua | 36 | 1376 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Noquerelle
-- 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(0x247);
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/Temenos/mobs/Enhanced_Beetle.lua | 16 | 1046 | -----------------------------------
-- Area: Temenos W T
-- NPC: Enhanced_Beetle
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local cofferID=Randomcoffer(3,GetInstanceRegion(1298));
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
GetNPCByID(16929237):setStatus(STATUS_NORMAL);
if (cofferID~=0) then
GetNPCByID(16928768+cofferID):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+cofferID):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
nicholas-leonard/nn | Decorator.lua | 5 | 1585 | local Decorator, parent = torch.class("nn.Decorator", "nn.Container")
function Decorator:__init(module)
parent.__init(self)
-- so that it can be handled like a Container
self.modules[1] = module
end
function Decorator:updateOutput(input)
self.output = self.modules[1]:updateOutput(input)
return self.output
end
function Decorator:updateGradInput(input, gradOutput)
self.gradInput = self.modules[1]:updateGradInput(input, gradOutput)
return self.gradInput
end
function Decorator:accGradParameters(input, gradOutput, scale)
self.modules[1]:accGradParameters(input, gradOutput, scale)
end
function Decorator:accUpdateGradParameters(input, gradOutput, lr)
self.modules[1]:accUpdateGradParameters(input, gradOutput, lr)
end
function Decorator:sharedAccUpdateGradParameters(input, gradOutput, lr)
self.modules[1]:sharedAccUpdateGradParameters(input, gradOutput, lr)
end
function Decorator:__tostring__()
if self.modules[1].__tostring__ then
return torch.type(self) .. ' @ ' .. self.modules[1]:__tostring__()
else
return torch.type(self) .. ' @ ' .. torch.type(self.modules[1])
end
end
-- useful for multiple-inheritance
function Decorator.decorate(class)
class.updateOutput = nn.Decorator.updateOutput
class.updateGradInput = nn.Decorator.updateGradInput
class.accGradParameters = nn.Decorator.accGradParameters
class.accUpdateGradParameters = nn.Decorator.accUpdateGradParameters
class.sharedAccUpdateGradParameters = nn.Decorator.sharedAccUpdateGradParameters
class.__tostring__ = nn.Decorator.__tostring__
end
| bsd-3-clause |
nasomi/darkstar | scripts/globals/spells/bluemagic/death_ray.lua | 18 | 1602 | -----------------------------------------
-- Spell: Death Ray
-- Deals dark damage to an enemy
-- Spell cost: 49 MP
-- Monster Type: Amorphs
-- Spell Type: Magical (Dark)
-- Blue Magic Points: 2
-- Stat Bonus: HP-5, MP+5
-- Level: 34
-- Casting Time: 4.5 seconds
-- Recast Time: 29.25 seconds
-- Magic Bursts on: Compression, Gravitation, Darkness
-- Combos: None
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
local multi = 1.625;
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 2.0;
end
params.multiplier = multi;
params.tMultiplier = 1.0;
params.duppercap = 51;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.2;
params.mnd_wsc = 0.1;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Northern_San_dOria/npcs/Morunaude.lua | 36 | 1428 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Morunaude
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x027a);
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 |
kaustubhcs/torch-toolbox | Convert-MM/convertLinearmodelConvMM.lua | 3 | 1857 | --[[Author: Aysegul Dundar (adundar@purdue.edu)
-- This file converts Linear layers in the network to ConvolutionMM
-- so in the demo, you can step in the image.
-- Please update the input size based on your network.
-- ]]
require 'nnx'
if not arg[1] then print "Network unspecified (type it after the program's name)" return
else print('Loading: ' .. arg[1]) end
local network = torch.load(arg[1]):float()
local input = torch.Tensor(3, 149, 149):float()
torch.setdefaulttensortype('torch.FloatTensor')
local new_network = nn.Sequential()
function convert(network)
for i=1, #network.modules do
if network.modules[i].__typename == 'nn.Sequential' then
convert(network.modules[i])
else
if network.modules[i].__typename == 'nn.Reshape' then
-- do nothing
elseif network.modules[i].__typename == 'nn.Linear' then
if (#input:size() == 3) then
tmp_module = nn.SpatialConvolutionMM(input:size(1), network.modules[i].weight:size(1), input:size(2), input:size(3))
else
tmp_module = nn.SpatialConvolutionMM(network.modules[i].weight[1], network.modules[i].weight[2], 1, 1)
end
tmp_module.weight:copy(network.modules[i].weight):resize(tmp_module.weight:size())
tmp_module.bias:copy(network.modules[i].bias)
new_network:add(tmp_module)
input = tmp_module:forward(input)
elseif network.modules[i].__typename == 'nn.Dropout' then
-- turn of the dropping
network.modules[i].train = false
new_network:add(network.modules[i])
else
new_network:add(network.modules[i])
input = network.modules[i]:forward(input)
end
end
end
end
convert(network)
torch.save('new_network.net', new_network)
| bsd-3-clause |
nasomi/darkstar | scripts/globals/items/buttered_nebimonite.lua | 35 | 1401 | -----------------------------------------
-- ID: 4267
-- Item: Buttered Nebimonite
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 1
-- Vitality 2
-- defense % 25
-- defense Cap 75
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4267);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 75);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 75);
end;
| gpl-3.0 |
kerr-huang/SL4A | lua/luasocket/etc/qp.lua | 59 | 1025 | -----------------------------------------------------------------------------
-- Little program to convert to and from Quoted-Printable
-- LuaSocket sample files
-- Author: Diego Nehab
-- RCS ID: $Id: qp.lua,v 1.5 2004/06/17 21:46:22 diego Exp $
-----------------------------------------------------------------------------
local ltn12 = require("ltn12")
local mime = require("mime")
local convert
arg = arg or {}
local mode = arg and arg[1] or "-et"
if mode == "-et" then
local normalize = mime.normalize()
local qp = mime.encode("quoted-printable")
local wrap = mime.wrap("quoted-printable")
convert = ltn12.filter.chain(normalize, qp, wrap)
elseif mode == "-eb" then
local qp = mime.encode("quoted-printable", "binary")
local wrap = mime.wrap("quoted-printable")
convert = ltn12.filter.chain(qp, wrap)
else convert = mime.decode("quoted-printable") end
local source = ltn12.source.chain(ltn12.source.file(io.stdin), convert)
local sink = ltn12.sink.file(io.stdout)
ltn12.pump.all(source, sink)
| apache-2.0 |
mlem/wesnoth | data/ai/lua/battle_calcs.lua | 28 | 74789 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local LS = wesnoth.require "lua/location_set.lua"
-- This is a collection of Lua functions used for custom AI development.
-- Note that this is still work in progress with significant changes occurring
-- frequently. Backward compatibility cannot be guaranteed at this time in
-- development releases, but it is of course easily possible to copy a function
-- from a previous release directly into an add-on if it is needed there.
local battle_calcs = {}
function battle_calcs.unit_attack_info(unit, cache)
-- Return a table containing information about attack-related properties of @unit
-- The result can be cached if variable @cache is given
-- This is done in order to avoid duplication of slow processes, such as access to unit.__cfg
-- Return table has fields:
-- - attacks: the attack tables from unit.__cfg
-- - resist_mod: resistance modifiers (multiplicative factors) index by attack type
-- - alignment: just that
-- Set up a cache index. We use id+max_hitpoints+side, since the
-- unit can level up. Side is added to avoid the problem of MP leaders sometimes having
-- the same id when the game is started from the command-line
local cind = 'UI-' .. unit.id .. unit.max_hitpoints .. unit.side
-- If cache for this unit exists, return it
if cache and cache[cind] then
return cache[cind]
end
-- Otherwise collect the information
local unit_cfg = unit.__cfg
local unit_info = {
attacks = {},
resist_mod = {},
alignment = unit_cfg.alignment
}
for attack in H.child_range(unit_cfg, 'attack') do
-- Extract information for specials; we do this first because some
-- custom special might have the same name as one of the default scalar fields
local a = {}
for special in H.child_range(attack, 'specials') do
for _,sp in ipairs(special) do
if (sp[1] == 'damage') then -- this is 'backstab'
if (sp[2].id == 'backstab') then
a.backstab = true
else
if (sp[2].id == 'charge') then a.charge = true end
end
else
-- magical, marksman
if (sp[1] == 'chance_to_hit') then
a[sp[2].id] = true
else
a[sp[1]] = true
end
end
end
end
-- Now extract the scalar (string and number) values from attack
for k,v in pairs(attack) do
if (type(v) == 'number') or (type(v) == 'string') then
a[k] = v
end
end
-- [attack]number= defaults to zero; must be defined for battle_calcs.best_weapons()
a.number = a.number or 0
table.insert(unit_info.attacks, a)
end
local attack_types = { "arcane", "blade", "cold", "fire", "impact", "pierce" }
for _,attack_type in ipairs(attack_types) do
unit_info.resist_mod[attack_type] = wesnoth.unit_resistance(unit, attack_type) / 100.
end
if cache then cache[cind] = unit_info end
return unit_info
end
function battle_calcs.strike_damage(attacker, defender, att_weapon, def_weapon, dst, cache)
-- Return the single strike damage of an attack by @attacker on @defender
-- Also returns the other information about the attack (since we're accessing the information already anyway)
-- Here, @att_weapon and @def_weapon are the weapon numbers in Lua counts, i.e., counts start at 1
-- If @def_weapon = 0, return 0 for defender damage
-- This can be used for defenders that do not have the right kind of weapon, or if
-- only the attacker damage is of interest
-- @dst: attack location, to take terrain time of day, illumination etc. into account
-- For the defender, the current location is assumed
--
-- 'cache' can be given to cache strike damage and to pass through to battle_calcs.unit_attack_info()
-- Set up a cache index. We use id+max_hitpoints+side for each unit, since the
-- unit can level up.
-- Also need to add the weapons and lawful_bonus values for each unit
local att_lawful_bonus = wesnoth.get_time_of_day({ dst[1], dst[2], true }).lawful_bonus
local def_lawful_bonus = wesnoth.get_time_of_day({ defender.x, defender.y, true }).lawful_bonus
local cind = 'SD-' .. attacker.id .. attacker.max_hitpoints .. attacker.side
cind = cind .. 'x' .. defender.id .. defender.max_hitpoints .. defender.side
cind = cind .. '-' .. att_weapon .. 'x' .. def_weapon
cind = cind .. '-' .. att_lawful_bonus .. 'x' .. def_lawful_bonus
-- If cache for this unit exists, return it
if cache and cache[cind] then
return cache[cind].att_damage, cache[cind].def_damage, cache[cind].att_attack, cache[cind].def_attack
end
local attacker_info = battle_calcs.unit_attack_info(attacker, cache)
local defender_info = battle_calcs.unit_attack_info(defender, cache)
-- Attacker base damage
local att_damage = attacker_info.attacks[att_weapon].damage
-- Opponent resistance modifier
local att_multiplier = defender_info.resist_mod[attacker_info.attacks[att_weapon].type] or 1
-- TOD modifier
att_multiplier = att_multiplier * AH.get_unit_time_of_day_bonus(attacker_info.alignment, att_lawful_bonus)
-- Now do all this for the defender, if def_weapon ~= 0
local def_damage, def_multiplier = 0, 1.
if (def_weapon ~= 0) then
-- Defender base damage
def_damage = defender_info.attacks[def_weapon].damage
-- Opponent resistance modifier
def_multiplier = attacker_info.resist_mod[defender_info.attacks[def_weapon].type] or 1
-- TOD modifier
def_multiplier = def_multiplier * AH.get_unit_time_of_day_bonus(defender_info.alignment, def_lawful_bonus)
end
-- Take 'charge' into account
if attacker_info.attacks[att_weapon].charge then
att_damage = att_damage * 2
def_damage = def_damage * 2
end
-- Rounding of .5 values is done differently depending on whether the
-- multiplier is greater or smaller than 1
if (att_multiplier > 1) then
att_damage = H.round(att_damage * att_multiplier - 0.001)
else
att_damage = H.round(att_damage * att_multiplier + 0.001)
end
if (def_weapon ~= 0) then
if (def_multiplier > 1) then
def_damage = H.round(def_damage * def_multiplier - 0.001)
else
def_damage = H.round(def_damage * def_multiplier + 0.001)
end
end
if cache then
cache[cind] = {
att_damage = att_damage,
def_damage = def_damage,
att_attack = attacker_info.attacks[att_weapon],
def_attack = defender_info.attacks[def_weapon]
}
end
return att_damage, def_damage, attacker_info.attacks[att_weapon], defender_info.attacks[def_weapon]
end
function battle_calcs.best_weapons(attacker, defender, dst, cache)
-- Return the number (index) of the best weapons for @attacker and @defender
-- @dst: attack location, to take terrain time of day, illumination etc. into account
-- For the defender, the current location is assumed
-- Ideally, we would do a full attack_rating here for all combinations,
-- but that would take too long. So we simply define the best weapons
-- as those that has the biggest difference between
-- damage done and damage received (the latter divided by 2)
-- Returns 0 if defender does not have a weapon for this range
--
-- 'cache' can be given to cache best weapons
-- Set up a cache index. We use id+max_hitpoints+side for each unit, since the
-- unit can level up.
-- Also need to add the weapons and lawful_bonus values for each unit
local att_lawful_bonus = wesnoth.get_time_of_day({ dst[1], dst[2], true }).lawful_bonus
local def_lawful_bonus = wesnoth.get_time_of_day({ defender.x, defender.y, true }).lawful_bonus
local cind = 'BW-' .. attacker.id .. attacker.max_hitpoints .. attacker.side
cind = cind .. 'x' .. defender.id .. defender.max_hitpoints .. defender.side
cind = cind .. '-' .. att_lawful_bonus .. 'x' .. def_lawful_bonus
-- If cache for this unit exists, return it
if cache and cache[cind] then
return cache[cind].best_att_weapon, cache[cind].best_def_weapon
end
local attacker_info = battle_calcs.unit_attack_info(attacker, cache)
local defender_info = battle_calcs.unit_attack_info(defender, cache)
-- Best attacker weapon
local max_rating, best_att_weapon, best_def_weapon = -9e99, 0, 0
for att_weapon_number,att_weapon in ipairs(attacker_info.attacks) do
local att_damage = battle_calcs.strike_damage(attacker, defender, att_weapon_number, 0, { dst[1], dst[2] }, cache)
local max_def_rating, tmp_best_def_weapon = -9e99, 0
for def_weapon_number,def_weapon in ipairs(defender_info.attacks) do
if (def_weapon.range == att_weapon.range) then
local def_damage = battle_calcs.strike_damage(defender, attacker, def_weapon_number, 0, { defender.x, defender.y }, cache)
local def_rating = def_damage * def_weapon.number
if (def_rating > max_def_rating) then
max_def_rating, tmp_best_def_weapon = def_rating, def_weapon_number
end
end
end
local rating = att_damage * att_weapon.number
if (max_def_rating > -9e99) then rating = rating - max_def_rating / 2. end
if (rating > max_rating) then
max_rating, best_att_weapon, best_def_weapon = rating, att_weapon_number, tmp_best_def_weapon
end
end
if cache then
cache[cind] = { best_att_weapon = best_att_weapon, best_def_weapon = best_def_weapon }
end
return best_att_weapon, best_def_weapon
end
function battle_calcs.add_next_strike(cfg, arr, n_att, n_def, att_strike, hit_miss_counts, hit_miss_str)
-- Recursive function that sets up the sequences of strikes (misses and hits)
-- Each call corresponds to one strike of one of the combattants and can be
-- either miss (value 0) or hit (1)
--
-- Inputs:
-- - @cfg: config table with sub-tables att/def for the attacker/defender with the following fields:
-- - strikes: total number of strikes
-- - max_hits: maximum number of hits the unit can survive
-- - firststrike: set to true if attack has firststrike special
-- - @arr: an empty array that will hold the output table
-- - Other parameters of for recursion purposes only and are initialized below
-- On the first call of this function, initialize variables
-- Counts for hits/misses by both units:
-- - Indices 1 & 2: hit/miss for attacker
-- - Indices 3 & 4: hit/miss for defender
hit_miss_counts = hit_miss_counts or { 0, 0, 0, 0 }
hit_miss_str = hit_miss_str or '' -- string with the hit/miss sequence; for visualization only
-- Strike counts
-- - n_att/n_def = number of strikes taken by attacker/defender
-- - att_strike: if true, it's the attacker's turn, otherwise it's the defender's turn
if (not n_att) then
if cfg.def.firststrike and (not cfg.att.firststrike) then
n_att = 0
n_def = 1
att_strike = false
else
n_att = 1
n_def = 0
att_strike = true
end
else
if att_strike then
if (n_def < cfg.def.strikes) then
n_def = n_def + 1
att_strike = false
else
n_att = n_att + 1
end
else
if (n_att < cfg.att.strikes) then
n_att = n_att + 1
att_strike = true
else
n_def = n_def + 1
end
end
end
-- Create both a hit and a miss
for i = 0,1 do -- 0:miss, 1: hit
-- hit/miss counts and string for this call
local tmp_hmc = AH.table_copy(hit_miss_counts)
local tmp_hmstr = ''
-- Flag whether the opponent was killed by this strike
local killed_opp = false -- Defaults to falso
if att_strike then
tmp_hmstr = hit_miss_str .. i -- attacker hit/miss in string: 0 or 1
tmp_hmc[i+1] = tmp_hmc[i+1] + 1 -- Increment hit/miss counts
-- Set variable if opponent was killed:
if (tmp_hmc[2] > cfg.def.max_hits) then killed_opp = true end
-- Even values of n are strikes by the defender
else
tmp_hmstr = hit_miss_str .. (i+2) -- defender hit/miss in string: 2 or 3
tmp_hmc[i+3] = tmp_hmc[i+3] + 1 -- Increment hit/miss counts
-- Set variable if opponent was killed:
if (tmp_hmc[4] > cfg.att.max_hits) then killed_opp = true end
end
-- If we've reached the total number of strikes, add this hit/miss combination to table,
-- but only if the opponent wasn't killed, as that would end the battle
if (n_att + n_def < cfg.att.strikes + cfg.def.strikes) and (not killed_opp) then
battle_calcs.add_next_strike(cfg, arr, n_att, n_def, att_strike, tmp_hmc, tmp_hmstr)
-- Otherwise, call the next recursion level
else
table.insert(arr, { hit_miss_str = tmp_hmstr, hit_miss_counts = tmp_hmc })
end
end
end
function battle_calcs.battle_outcome_coefficients(cfg, cache)
-- Determine the coefficients needed to calculate the hitpoint probability distribution
-- of a given battle
-- Inputs:
-- - @cfg: config table with sub-tables att/def for the attacker/defender with the following fields:
-- - strikes: total number of strikes
-- - max_hits: maximum number of hits the unit can survive
-- - firststrike: whether the unit has firststrike weapon special on this attack
-- The result can be cached if variable 'cache' is given
--
-- Output: table with the coefficients needed to calculate the distribution for both attacker and defender
-- First index: number of hits landed on the defender. Each of those contains an array of
-- coefficient tables, of format:
-- { num = value, am = value, ah = value, dm = value, dh = value }
-- This gives one term in a sum of form:
-- num * ahp^ah * (1-ahp)^am * dhp^dh * (1-dhp)^dm
-- where ahp is the probability that the attacker will land a hit
-- and dhp is the same for the defender
-- Terms that have exponents of 0 are omitted
-- Set up the cache id
local cind = 'coeff-' .. cfg.att.strikes .. '-' .. cfg.att.max_hits
if cfg.att.firststrike then cind = cind .. 'fs' end
cind = cind .. 'x' .. cfg.def.strikes .. '-' .. cfg.def.max_hits
if cfg.def.firststrike then cind = cind .. 'fs' end
-- If cache for this unit exists, return it
if cache and cache[cind] then
return cache[cind].coeffs_att, cache[cind].coeffs_def
end
-- Get the hit/miss counts for the battle
local hit_miss_counts = {}
battle_calcs.add_next_strike(cfg, hit_miss_counts)
-- We first calculate the coefficients for the defender HP distribution
-- so this is sorted by the number of hits the attacker lands
-- 'counts' is an array 4 layers deep, where the indices are the number of misses/hits
-- are the indices in order attacker miss, attacker hit, defender miss, defender hit
-- This is so that they can be grouped by number of attacker hits/misses, for
-- subsequent simplification
-- The element value is number of times we get the given combination of hits/misses
local counts = {}
for _,count in ipairs(hit_miss_counts) do
local i1 = count.hit_miss_counts[1]
local i2 = count.hit_miss_counts[2]
local i3 = count.hit_miss_counts[3]
local i4 = count.hit_miss_counts[4]
if not counts[i1] then counts[i1] = {} end
if not counts[i1][i2] then counts[i1][i2] = {} end
if not counts[i1][i2][i3] then counts[i1][i2][i3] = {} end
counts[i1][i2][i3][i4] = (counts[i1][i2][i3][i4] or 0) + 1
end
local coeffs_def = {}
for am,v1 in pairs(counts) do -- attacker miss count
for ah,v2 in pairs(v1) do -- attacker hit count
-- Set up the exponent coefficients for attacker hits/misses
local exp = {} -- Array for an individual set of coefficients
-- Only populate those indices that have exponents > 0
if (am > 0) then exp.am = am end
if (ah > 0) then exp.ah = ah end
-- We combine results by testing whether they produce the same sum
-- with two very different hit probabilities, hp1 = 0.6, hp2 = 0.137
-- This will only happen is the coefficients add up to multiples of 1
local sum1, sum2 = 0,0
local hp1, hp2 = 0.6, 0.137
for dm,v3 in pairs(v2) do -- defender miss count
for dh,num in pairs(v3) do -- defender hit count
sum1 = sum1 + num * hp1^dh * (1 - hp1)^dm
sum2 = sum2 + num * hp2^dh * (1 - hp2)^dm
end
end
-- Now, coefficients are set up for each value of total hits by attacker
-- This holds all the coefficients that need to be added to get the propability
-- of the defender receiving this number of hits
if (not coeffs_def[ah]) then coeffs_def[ah] = {} end
-- If sum1 and sum2 are equal, that means all the defender probs added up to 1, or
-- multiple thereof, which means the can all be combine in the calculation
if (math.abs(sum1 - sum2) < 1e-9) then
exp.num = sum1
table.insert(coeffs_def[ah], exp)
-- If not, the defender probs don't add up to something nice and all
-- need to be calculated one by one
else
for dm,v3 in pairs(v2) do -- defender miss count
for dh,num in pairs(v3) do -- defender hit count
local tmp_exp = AH.table_copy(exp)
tmp_exp.num = num
if (dm > 0) then tmp_exp.dm = dm end
if (dh > 0) then tmp_exp.dh = dh end
table.insert(coeffs_def[ah], tmp_exp)
end
end
end
end
end
-- Now we do the same for the HP distribution of the attacker,
-- which means everything needs to be sorted by defender hits
local counts = {}
for _,count in ipairs(hit_miss_counts) do
local i1 = count.hit_miss_counts[3] -- note that the order here is different from above
local i2 = count.hit_miss_counts[4]
local i3 = count.hit_miss_counts[1]
local i4 = count.hit_miss_counts[2]
if not counts[i1] then counts[i1] = {} end
if not counts[i1][i2] then counts[i1][i2] = {} end
if not counts[i1][i2][i3] then counts[i1][i2][i3] = {} end
counts[i1][i2][i3][i4] = (counts[i1][i2][i3][i4] or 0) + 1
end
local coeffs_att = {}
for dm,v1 in pairs(counts) do -- defender miss count
for dh,v2 in pairs(v1) do -- defender hit count
-- Set up the exponent coefficients for attacker hits/misses
local exp = {} -- Array for an individual set of coefficients
-- Only populate those indices that have exponents > 0
if (dm > 0) then exp.dm = dm end
if (dh > 0) then exp.dh = dh end
-- We combine results by testing whether they produce the same sum
-- with two very different hit probabilities, hp1 = 0.6, hp2 = 0.137
-- This will only happen is the coefficients add up to multiples of 1
local sum1, sum2 = 0,0
local hp1, hp2 = 0.6, 0.137
for am,v3 in pairs(v2) do -- attacker miss count
for ah,num in pairs(v3) do -- attacker hit count
sum1 = sum1 + num * hp1^ah * (1 - hp1)^am
sum2 = sum2 + num * hp2^ah * (1 - hp2)^am
end
end
-- Now, coefficients are set up for each value of total hits by attacker
-- This holds all the coefficients that need to be added to get the propability
-- of the defender receiving this number of hits
if (not coeffs_att[dh]) then coeffs_att[dh] = {} end
-- If sum1 and sum2 are equal, that means all the defender probs added up to 1, or
-- multiple thereof, which means the can all be combine in the calculation
if (math.abs(sum1 - sum2) < 1e-9) then
exp.num = sum1
table.insert(coeffs_att[dh], exp)
-- If not, the defender probs don't add up to something nice and all
-- need to be calculated one by one
else
for am,v3 in pairs(v2) do -- defender miss count
for ah,num in pairs(v3) do -- defender hit count
local tmp_exp = AH.table_copy(exp)
tmp_exp.num = num
if (am > 0) then tmp_exp.am = am end
if (ah > 0) then tmp_exp.ah = ah end
table.insert(coeffs_att[dh], tmp_exp)
end
end
end
end
end
-- The probability for the number of hits with the most terms can be skipped
-- and 1-sum(other_terms) can be used instead. Set a flag for which term to skip
local max_number, biggest_equation = 0, -1
for hits,v in pairs(coeffs_att) do
local number = 0
for _,c in pairs(v) do number = number + 1 end
if (number > max_number) then
max_number, biggest_equation = number, hits
end
end
coeffs_att[biggest_equation].skip = true
local max_number, biggest_equation = 0, -1
for hits,v in pairs(coeffs_def) do
local number = 0
for _,c in pairs(v) do number = number + 1 end
if (number > max_number) then
max_number, biggest_equation = number, hits
end
end
coeffs_def[biggest_equation].skip = true
if cache then cache[cind] = { coeffs_att = coeffs_att, coeffs_def = coeffs_def } end
return coeffs_att, coeffs_def
end
function battle_calcs.print_coefficients()
-- Print out the set of coefficients for a given number of attacker and defender strikes
-- Also print numerical values for a given hit probability
-- This function is for debugging purposes only
-- Configure these values at will
local attacker_strikes, defender_strikes = 3, 3 -- number of strikes
local att_hit_prob, def_hit_prob = 0.8, 0.4 -- probability of landing a hit attacker/defender
local attacker_coeffs = true -- attacker coefficients if set to true, defender coefficients otherwise
local defender_firststrike, attacker_firststrike = true, false
-- Go through all combinations of maximum hits either attacker or defender can survive
-- Note how this has to be crossed between ahits and defender_strikes and vice versa
for ahits = defender_strikes,0,-1 do
for dhits = attacker_strikes,0,-1 do
-- Get the coefficients for this case
local cfg = {
att = { strikes = attacker_strikes, max_hits = ahits, firststrike = attacker_firststrike },
def = { strikes = defender_strikes, max_hits = dhits, firststrike = defender_firststrike }
}
local coeffs, dummy = {}, {}
if attacker_coeffs then
coeffs = battle_calcs.battle_outcome_coefficients(cfg)
else
dummy, coeffs = battle_calcs.battle_outcome_coefficients(cfg)
end
print()
print('Attacker: ' .. cfg.att.strikes .. ' strikes, can survive ' .. cfg.att.max_hits .. ' hits')
print('Defender: ' .. cfg.def.strikes .. ' strikes, can survive ' .. cfg.def.max_hits .. ' hits')
print('Chance of hits on defender: ')
-- The first indices of coeffs are the possible number of hits the attacker can land on the defender
for hits = 0,#coeffs do
local hit_prob = 0. -- probability for this number of hits
local str = '' -- output string
local combs = coeffs[hits] -- the combinations of coefficients to be evaluated
for i,exp in ipairs(combs) do -- exp: exponents (and factor) for a set
local prob = exp.num -- probability for this set
str = str .. exp.num
if exp.am then
prob = prob * (1 - att_hit_prob) ^ exp.am
str = str .. ' pma^' .. exp.am
end
if exp.ah then
prob = prob * att_hit_prob ^ exp.ah
str = str .. ' pha^' .. exp.ah
end
if exp.dm then
prob = prob * (1 - def_hit_prob) ^ exp.dm
str = str .. ' pmd^' .. exp.dm
end
if exp.dh then
prob = prob * def_hit_prob ^ exp.dh
str = str .. ' phd^' .. exp.dh
end
hit_prob = hit_prob + prob -- total probabilty for this number of hits landed
if (i ~= #combs) then str = str .. ' + ' end
end
local skip_str = ''
if combs.skip then skip_str = ' (skip)' end
print(hits .. skip_str .. ': ' .. str)
print(' = ' .. hit_prob)
end
end
end
end
function battle_calcs.hp_distribution(coeffs, att_hit_prob, def_hit_prob, starting_hp, damage, opp_attack)
-- Multiply out the coefficients from battle_calcs.battle_outcome_coefficients()
-- For a given attacker and defender hit/miss probability
-- Also needed: the starting HP for the unit and the damage done by the opponent
-- and the opponent attack information @opp_attack
local stats = { hp_chance = {}, average_hp = 0 }
local skip_hp, skip_prob = -1, 1
for hits = 0,#coeffs do
local hp = starting_hp - hits * damage
if (hp < 0) then hp = 0 end
-- Calculation of the outcome with the most terms can be skipped
if coeffs[hits].skip then
skip_hp = hp
else
local hp_prob = 0. -- probability for this number of hits
for _,exp in ipairs(coeffs[hits]) do -- exp: exponents (and factor) for a set
local prob = exp.num -- probability for this set
if exp.am then prob = prob * (1 - att_hit_prob) ^ exp.am end
if exp.ah then prob = prob * att_hit_prob ^ exp.ah end
if exp.dm then prob = prob * (1 - def_hit_prob) ^ exp.dm end
if exp.dh then prob = prob * def_hit_prob ^ exp.dh end
hp_prob = hp_prob + prob -- total probabilty for this number of hits landed
end
stats.hp_chance[hp] = hp_prob
stats.average_hp = stats.average_hp + hp * hp_prob
-- Also subtract this probability from the total prob. (=1), to get prob. of skipped outcome
skip_prob = skip_prob - hp_prob
end
end
-- Add in the outcome that was skipped
stats.hp_chance[skip_hp] = skip_prob
stats.average_hp = stats.average_hp + skip_hp * skip_prob
-- And always set hp_chance[0] since it is of such importance in the analysis
stats.hp_chance[0] = stats.hp_chance[0] or 0
-- Add poison probability
if opp_attack and opp_attack.poison then
stats.poisoned = 1. - stats.hp_chance[starting_hp]
else
stats.poisoned = 0
end
-- Add slow probability
if opp_attack and opp_attack.slow then
stats.slowed = 1. - stats.hp_chance[starting_hp]
else
stats.slowed = 0
end
return stats
end
function battle_calcs.battle_outcome(attacker, defender, cfg, cache)
-- Calculate the stats of a combat by @attacker vs. @defender
-- @cfg: optional input parameters
-- - att_weapon/def_weapon: attacker/defender weapon number
-- if not given, get "best" weapon (Note: both must be given, or they will both be determined)
-- - dst: { x, y }: the attack location; defaults to { attacker.x, attacker.y }
-- @cache: to be passed on to other functions. battle_outcome itself is not cached, too many factors enter
cfg = cfg or {}
local dst = cfg.dst or { attacker.x, attacker.y }
local att_weapon, def_weapon = 0, 0
if (not cfg.att_weapon) or (not cfg.def_weapon) then
att_weapon, def_weapon = battle_calcs.best_weapons(attacker, defender, dst, cache)
else
att_weapon, def_weapon = cfg.att_weapon, cfg.def_weapon
end
-- Collect all the information needed for the calculation
-- Strike damage and numbers
local att_damage, def_damage, att_attack, def_attack =
battle_calcs.strike_damage(attacker, defender, att_weapon, def_weapon, { dst[1], dst[2] }, cache)
-- Take swarm into account
local att_strikes, def_strikes = att_attack.number, 0
if (def_damage > 0) then
def_strikes = def_attack.number
end
if att_attack.swarm then
att_strikes = math.floor(att_strikes * attacker.hitpoints / attacker.max_hitpoints)
end
if def_attack and def_attack.swarm then
def_strikes = math.floor(def_strikes * defender.hitpoints / defender.max_hitpoints)
end
-- Maximum number of hits that either unit can survive
local att_max_hits = math.floor((attacker.hitpoints - 1) / def_damage)
if (att_max_hits > def_strikes) then att_max_hits = def_strikes end
local def_max_hits = math.floor((defender.hitpoints - 1) / att_damage)
if (def_max_hits > att_strikes) then def_max_hits = att_strikes end
-- Probability of landing a hit
local att_hit_prob = wesnoth.unit_defense(defender, wesnoth.get_terrain(defender.x, defender.y)) / 100.
local def_hit_prob = wesnoth.unit_defense(attacker, wesnoth.get_terrain(dst[1], dst[2])) / 100.
-- Magical: attack and defense, and under all circumstances
if att_attack.magical then att_hit_prob = 0.7 end
if def_attack and def_attack.magical then def_hit_prob = 0.7 end
-- Marksman: attack only, and only if terrain defense is less
if att_attack.marksman and (att_hit_prob < 0.6) then
att_hit_prob = 0.6
end
-- Get the coefficients for this kind of combat
local def_firstrike = false
if def_attack and def_attack.firststrike then def_firstrike = true end
local cfg = {
att = { strikes = att_strikes, max_hits = att_max_hits, firststrike = att_attack.firststrike },
def = { strikes = def_strikes, max_hits = def_max_hits, firststrike = def_firstrike }
}
local att_coeffs, def_coeffs = battle_calcs.battle_outcome_coefficients(cfg, cache)
-- And multiply out the factors
-- Note that att_hit_prob, def_hit_prob need to be in that order for both calls
local att_stats = battle_calcs.hp_distribution(att_coeffs, att_hit_prob, def_hit_prob, attacker.hitpoints, def_damage, def_attack)
local def_stats = battle_calcs.hp_distribution(def_coeffs, att_hit_prob, def_hit_prob, defender.hitpoints, att_damage, att_attack)
return att_stats, def_stats
end
function battle_calcs.simulate_combat_fake()
-- A function to return a fake simulate_combat result
-- Debug function to test how long simulate_combat takes
-- It doesn't need any arguments -> can be called with the arguments of other simulate_combat functions
local att_stats, def_stats = { hp_chance = {} }, { hp_chance = {} }
att_stats.hp_chance[0] = 0
att_stats.hp_chance[21], att_stats.hp_chance[23], att_stats.hp_chance[25], att_stats.hp_chance[27] = 0.125, 0.375, 0.375, 0.125
att_stats.poisoned, att_stats.slowed, att_stats.average_hp = 0.875, 0, 24
def_stats.hp_chance[0], def_stats.hp_chance[2], def_stats.hp_chance[10] = 0.09, 0.42, 0.49
def_stats.poisoned, def_stats.slowed, def_stats.average_hp = 0, 0, 1.74
return att_stats, def_stats
end
function battle_calcs.simulate_combat_loc(attacker, dst, defender, weapon)
-- Get simulate_combat results for unit @attacker attacking unit @defender
-- when on terrain of same type as that at @dst, which is of form { x, y }
-- If @weapon is set, use that weapon (Lua index starting at 1), otherwise use best weapon
local attacker_dst = wesnoth.copy_unit(attacker)
attacker_dst.x, attacker_dst.y = dst[1], dst[2]
if weapon then
return wesnoth.simulate_combat(attacker_dst, weapon, defender)
else
return wesnoth.simulate_combat(attacker_dst, defender)
end
end
function battle_calcs.attack_rating(attacker, defender, dst, cfg, cache)
-- Returns a common (but configurable) rating for attacks
-- Inputs:
-- @attacker: attacker unit
-- @defender: defender unit
-- @dst: the attack location in form { x, y }
-- @cfg: table of optional inputs and configurable rating parameters
-- Optional inputs:
-- - att_stats, def_stats: if given, use these stats, otherwise calculate them here
-- Note: these are calculated in combination, that is they either both need to be passed or both be omitted
-- - att_weapon/def_weapon: the attacker/defender weapon to be used if calculating battle stats here
-- This parameter is meaningless (unused) if att_stats/def_stats are passed
-- Defaults to weapon that does most damage to the opponent
-- Note: as with the stats, they either both need to be passed or both be omitted
-- @cache: cache table to be passed to battle_calcs.battle_outcome
--
-- Returns:
-- - Overall rating for the attack or attack combo
-- - Defender rating: not additive for attack combos; needs to be calculated for the
-- defender stats of the last attack in a combo (that works for everything except
-- the rating whether the defender is about to level in the attack combo)
-- - Attacker rating: this one is split up into two terms:
-- - a term that is additive for individual attacks in a combo
-- - a term that needs to be average for the individual attacks in a combo
-- - att_stats, def_stats: useful if they were calculated here, rather than passed down
cfg = cfg or {}
-- Set up the config parameters for the rating
local enemy_leader_weight = cfg.enemy_leader_weight or 5.
local defender_starting_damage_weight = cfg.defender_starting_damage_weight or 0.33
local xp_weight = cfg.xp_weight or 0.25
local level_weight = cfg.level_weight or 1.0
local defender_level_weight = cfg.defender_level_weight or 1.0
local distance_leader_weight = cfg.distance_leader_weight or 0.002
local defense_weight = cfg.defense_weight or 0.1
local occupied_hex_penalty = cfg.occupied_hex_penalty or -0.001
local own_value_weight = cfg.own_value_weight or 1.0
-- Get att_stats, def_stats
-- If they are passed in cfg, use those
local att_stats, def_stats = {}, {}
if (not cfg.att_stats) or (not cfg.def_stats) then
-- If cfg specifies the weapons use those, otherwise use "best" weapons
-- In the latter case, cfg.???_weapon will be nil, which will be passed on
local battle_cfg = { att_weapon = cfg.att_weapon, def_weapon = cfg.def_weapon, dst = dst }
att_stats,def_stats = battle_calcs.battle_outcome(attacker, defender, battle_cfg, cache)
else
att_stats, def_stats = cfg.att_stats, cfg.def_stats
end
-- We also need the leader (well, the location at least)
-- because if there's no other difference, prefer location _between_ the leader and the defender
local leader = wesnoth.get_units { side = attacker.side, canrecruit = 'yes' }[1]
------ All the attacker contributions: ------
-- Add up rating for the attacking unit
-- We add this up in units of fraction of max_hitpoints
-- It is multiplied by unit cost later, to get a gold equivalent value
-- Average damage to unit is negative rating
local damage = attacker.hitpoints - att_stats.average_hp
-- Count poisoned as additional 8 HP damage times probability of being poisoned
if (att_stats.poisoned ~= 0) then
damage = damage + 8 * (att_stats.poisoned - att_stats.hp_chance[0])
end
-- Count slowed as additional 6 HP damage times probability of being slowed
if (att_stats.slowed ~= 0) then
damage = damage + 6 * (att_stats.slowed - att_stats.hp_chance[0])
end
-- If attack is from a village, we count that as a 10 HP bonus
local is_village = wesnoth.get_terrain_info(wesnoth.get_terrain(dst[1], dst[2])).village
if is_village then
damage = damage - 10.
end
-- If attack is adjacent to an unoccupied village, that's bad
for xa,ya in H.adjacent_tiles(dst[1], dst[2]) do
local is_adjacent_village = wesnoth.get_terrain_info(wesnoth.get_terrain(xa, ya)).village
if is_adjacent_village and (not wesnoth.get_unit(xa, ya)) then
damage = damage + 10
end
end
if (damage < 0) then damage = 0 end
-- Fraction damage (= fractional value of the unit)
local value_fraction = - damage / attacker.max_hitpoints
-- Additional, subtract the chance to die, in order to (de)emphasize units that might die
value_fraction = value_fraction - att_stats.hp_chance[0]
-- In addition, potentially leveling up in this attack is a huge bonus,
-- proportional to the chance of it happening and the chance of not dying itself
local level_bonus = 0.
local defender_level = wesnoth.unit_types[defender.type].level
if (attacker.max_experience - attacker.experience <= defender_level) then
level_bonus = 1. - att_stats.hp_chance[0]
else
if (attacker.max_experience - attacker.experience <= defender_level * 8) then
level_bonus = (1. - att_stats.hp_chance[0]) * def_stats.hp_chance[0]
end
end
value_fraction = value_fraction + level_bonus * level_weight
-- Now convert this into gold-equivalent value
local attacker_value = wesnoth.unit_types[attacker.type].cost
-- Being closer to leveling is good (this makes AI prefer units with lots of XP)
local xp_bonus = attacker.experience / attacker.max_experience
attacker_value = attacker_value * (1. + xp_bonus * xp_weight)
local attacker_rating = value_fraction * attacker_value
------ Now (most of) the same for the defender ------
-- Average damage to defender is positive rating
local damage = defender.hitpoints - def_stats.average_hp
-- Count poisoned as additional 8 HP damage times probability of being poisoned
if (def_stats.poisoned ~= 0) then
damage = damage + 8 * (def_stats.poisoned - def_stats.hp_chance[0])
end
-- Count slowed as additional 6 HP damage times probability of being slowed
if (def_stats.slowed ~= 0) then
damage = damage + 6 * (def_stats.slowed - def_stats.hp_chance[0])
end
-- If defender is on a village, we count that as a 10 HP bonus
local is_village = wesnoth.get_terrain_info(wesnoth.get_terrain(defender.x, defender.y)).village
if is_village then
damage = damage - 10.
end
if (damage < 0) then damage = 0. end
-- Fraction damage (= fractional value of the unit)
local value_fraction = damage / defender.max_hitpoints
-- Additional, add the chance to kill, in order to emphasize enemies we might be able to kill
value_fraction = value_fraction + def_stats.hp_chance[0]
-- In addition, the defender potentially leveling up in this attack is a huge penalty,
-- proportional to the chance of it happening and the chance of not dying itself
local defender_level_penalty = 0.
local attacker_level = wesnoth.unit_types[attacker.type].level
if (defender.max_experience - defender.experience <= attacker_level) then
defender_level_penalty = 1. - def_stats.hp_chance[0]
else
if (defender.max_experience - defender.experience <= attacker_level * 8) then
defender_level_penalty = (1. - def_stats.hp_chance[0]) * att_stats.hp_chance[0]
end
end
value_fraction = value_fraction - defender_level_penalty * defender_level_weight
-- Now convert this into gold-equivalent value
local defender_value = wesnoth.unit_types[defender.type].cost
-- If this is the enemy leader, make damage to it much more important
if defender.canrecruit then
defender_value = defender_value * enemy_leader_weight
end
-- And prefer to attack already damaged enemies
local defender_starting_damage_fraction = (defender.max_hitpoints - defender.hitpoints) / defender.max_hitpoints
defender_value = defender_value * (1. + defender_starting_damage_fraction * defender_starting_damage_weight)
-- Being closer to leveling is good, we want to get rid of those enemies first
local xp_bonus = defender.experience / defender.max_experience
defender_value = defender_value * (1. + xp_bonus * xp_weight)
-- If defender is on a village, add a bonus rating (we want to get rid of those preferentially)
-- So yes, this is positive, even though it's a plus for the defender
-- Defenders on villages also got a negative damage rating above (these don't exactly cancel each other though)
local is_village = wesnoth.get_terrain_info(wesnoth.get_terrain(defender.x, defender.y)).village
if is_village then
defender_value = defender_value * (1. + 10. / attacker.max_hitpoints)
end
-- We also add a few contributions that are not directly attack/damage dependent
-- These are added to the defender rating for two reasons:
-- 1. Defender rating is positive (and thus contributions can be made positive)
-- 2. It is then independent of value of aggression (cfg.own_value_weight)
--
-- These are kept small though, so they mostly only serve as tie breakers
-- And yes, they might bring the overall rating from slightly negative to slightly positive
-- or vice versa, but as that is only approximate anyway, we keep it this way for simplicity
-- We don't need a bonus for good terrain for the attacker, as that is covered in the damage calculation
-- However, we add a small bonus for good terrain defense of the _defender_ on the _attack_ hex
-- This is in order to take good terrain away from defender on next move, all else being equal
local defender_defense = - wesnoth.unit_defense(defender, wesnoth.get_terrain(dst[1], dst[2])) / 100.
defender_value = defender_value + defender_defense * defense_weight
-- Get a very small bonus for hexes in between defender and AI leader
-- 'relative_distances' is larger for attack hexes closer to the side leader (possible values: -1 .. 1)
if leader then
local relative_distances =
H.distance_between(defender.x, defender.y, leader.x, leader.y)
- H.distance_between(dst[1], dst[2], leader.x, leader.y)
defender_value = defender_value + relative_distances * distance_leader_weight
end
-- Add a very small penalty for attack hexes occupied by other units
-- Note: it must be checked previously that the unit on the hex can move away
if (dst[1] ~= attacker.x) or (dst[2] ~= attacker.y) then
if wesnoth.get_unit(dst[1], dst[2]) then
defender_value = defender_value + occupied_hex_penalty
end
end
local defender_rating = value_fraction * defender_value
-- Finally apply factor of own unit weight to defender unit weight
attacker_rating = attacker_rating * own_value_weight
local rating = defender_rating + attacker_rating
return rating, defender_rating, attacker_rating, att_stats, def_stats
end
function battle_calcs.attack_combo_stats(tmp_attackers, tmp_dsts, defender, cache, cache_this_move)
-- Calculate attack combination outcomes using
-- @tmp_attackers: array of attacker units (this is done so that
-- the units need not be found here, as likely doing it in the
-- calling function is more efficient (because of repetition)
-- @tmp_dsts: array of the hexes (format { x, y }) from which the attackers attack
-- must be in same order as @attackers
-- @defender: the unit being attacked
-- @cache: the cache table to be passed through to other battle_calcs functions
-- attack_combo_stats itself is not cached, except for in cache_this_move below
-- @cache_this_move: an optional table of pre-calculated attack outcomes
-- - This is different from the other cache tables used in this file
-- - This table may only persist for this move (move, not turn !!!), as otherwise too many things change
--
-- Return values:
-- - The rating for this attack combination calculated from battle_calcs.attack_rating() results
-- - The sorted attackers and dsts arrays
-- - att_stats: an array of stats for each attacker, in the same order as 'attackers'
-- - defender combo stats: one set of stats containing the defender stats after the attack combination
-- - def_stats: an array of defender stats for each individual attack, in the same order as 'attackers'
cache_this_move = cache_this_move or {}
-- We first simulate and rate the individual attacks
local ratings, tmp_attacker_ratings = {}, {}
local tmp_att_stats, tmp_def_stats = {}, {}
local defender_ind = defender.x * 1000 + defender.y
for i,attacker in ipairs(tmp_attackers) do
-- Initialize or use the 'cache_this_move' table
local att_ind = attacker.x * 1000 + attacker.y
local dst_ind = tmp_dsts[i][1] * 1000 + tmp_dsts[i][2]
if (not cache_this_move[defender_ind]) then cache_this_move[defender_ind] = {} end
if (not cache_this_move[defender_ind][att_ind]) then cache_this_move[defender_ind][att_ind] = {} end
if (not cache_this_move[defender_ind][att_ind][dst_ind]) then
-- Get the base rating
local base_rating, def_rating, att_rating, att_stats, def_stats =
battle_calcs.attack_rating(attacker, defender, tmp_dsts[i], {}, cache )
tmp_attacker_ratings[i] = att_rating
tmp_att_stats[i], tmp_def_stats[i] = att_stats, def_stats
-- But for combos, also want units with highest attack outcome uncertainties to go early
-- So that we can change our mind in case of unfavorable outcome
--local outcome_variance = 0
--local av = tmp_def_stats[i].average_hp
--local n_outcomes = 0
--for hp,p in pairs(tmp_def_stats[i].hp_chance) do
-- if (p > 0) then
-- local dhp_norm = (hp - av) / defender.max_hitpoints * wesnoth.unit_types[defender.type].cost
-- local dvar = p * dhp_norm^2
--print(hp,p,av, dvar)
-- outcome_variance = outcome_variance + dvar
-- n_outcomes = n_outcomes + 1
-- end
--end
--outcome_variance = outcome_variance / n_outcomes
--print('outcome_variance', outcome_variance)
-- Note that this is a variance, not a standard deviations (as in, it's squared),
-- so it does not matter much for low-variance attacks, but takes on large values for
-- high variance attacks. I think that is what we want.
local rating = base_rating --+ outcome_variance
-- If attacker has attack with 'slow' special, it should always go first
-- Almost, bonus should not be quite as high as a really high CTK
-- This isn't quite true in reality, but can be refined later
if AH.has_weapon_special(attacker, "slow") then
rating = rating + wesnoth.unit_types[defender.type].cost / 2.
end
ratings[i] = { i, rating, base_rating, def_rating, att_rating }
-- Now add this attack to the cache_this_move table, so that next time around, we don't have to do this again
cache_this_move[defender_ind][att_ind][dst_ind] = {
rating = { -1, rating, base_rating, def_rating, att_rating }, -- Cannot use { i, rating, ... } here, as 'i' might be different next time
attacker_ratings = tmp_attacker_ratings[i],
att_stats = tmp_att_stats[i],
def_stats = tmp_def_stats[i]
}
else
local tmp_rating = cache_this_move[defender_ind][att_ind][dst_ind].rating
tmp_rating[1] = i
ratings[i] = tmp_rating
tmp_attacker_ratings[i] = cache_this_move[defender_ind][att_ind][dst_ind].attacker_ratings
tmp_att_stats[i] = cache_this_move[defender_ind][att_ind][dst_ind].att_stats
tmp_def_stats[i] = cache_this_move[defender_ind][att_ind][dst_ind].def_stats
end
end
-- Now sort all the arrays based on this rating
-- This will give the order in which the individual attacks are executed
table.sort(ratings, function(a, b) return a[2] > b[2] end)
-- Reorder attackers, dsts in this order
local attackers, dsts, att_stats, def_stats, attacker_ratings = {}, {}, {}, {}, {}
for i,rating in ipairs(ratings) do
attackers[i], dsts[i] = tmp_attackers[rating[1]], tmp_dsts[rating[1]]
end
-- Only keep the stats/ratings for the first attacker, the rest needs to be recalculated
att_stats[1], def_stats[1] = tmp_att_stats[ratings[1][1]], tmp_def_stats[ratings[1][1]]
attacker_ratings[1] = tmp_attacker_ratings[ratings[1][1]]
tmp_attackers, tmp_dsts, tmp_att_stats, tmp_def_stats, tmp_attacker_ratings = nil, nil, nil, nil, nil
-- Then we go through all the other attacks and calculate the outcomes
-- based on all the possible outcomes of the previous attacks
for i = 2,#attackers do
att_stats[i] = { hp_chance = {} }
def_stats[i] = { hp_chance = {} }
local dst_ind = dsts[i][1] * 1000 + dsts[i][2]
for hp1,prob1 in pairs(def_stats[i-1].hp_chance) do -- Note: need pairs(), not ipairs() !!
if (hp1 == 0) then
att_stats[i].hp_chance[attackers[i].hitpoints] =
(att_stats[i].hp_chance[attackers[i].hitpoints] or 0) + prob1
def_stats[i].hp_chance[0] = (def_stats[i].hp_chance[0] or 0) + prob1
else
local org_hp = defender.hitpoints
defender.hitpoints = hp1
local ast, dst
local att_ind_i = attackers[i].x * 1000 + attackers[i].y
if (not cache_this_move[defender_ind][att_ind_i][dst_ind][hp1]) then
ast, dst = battle_calcs.battle_outcome(attackers[i], defender, { dst = dsts[i] } , cache)
cache_this_move[defender_ind][att_ind_i][dst_ind][hp1] = { ast = ast, dst = dst }
else
ast = cache_this_move[defender_ind][att_ind_i][dst_ind][hp1].ast
dst = cache_this_move[defender_ind][att_ind_i][dst_ind][hp1].dst
end
defender.hitpoints = org_hp
for hp2,prob2 in pairs(ast.hp_chance) do
att_stats[i].hp_chance[hp2] = (att_stats[i].hp_chance[hp2] or 0) + prob1 * prob2
end
for hp2,prob2 in pairs(dst.hp_chance) do
def_stats[i].hp_chance[hp2] = (def_stats[i].hp_chance[hp2] or 0) + prob1 * prob2
end
-- Also do poisoned, slowed
if (not att_stats[i].poisoned) then
att_stats[i].poisoned = ast.poisoned
att_stats[i].slowed = ast.slowed
def_stats[i].poisoned = 1. - (1. - dst.poisoned) * (1. - def_stats[i-1].poisoned)
def_stats[i].slowed = 1. - (1. - dst.slowed) * (1. - def_stats[i-1].slowed)
end
end
end
-- Get the average HP
local av_hp = 0
for hp,prob in pairs(att_stats[i].hp_chance) do av_hp = av_hp + hp * prob end
att_stats[i].average_hp = av_hp
local av_hp = 0
for hp,prob in pairs(def_stats[i].hp_chance) do av_hp = av_hp + hp * prob end
def_stats[i].average_hp = av_hp
end
-- Get the total rating for this attack combo:
-- = sum of all the attacker ratings and the defender rating with the final def_stats
-- Rating for first attack exists already
local def_rating = ratings[1][4]
local att_rating = ratings[1][5]
-- The others need to be calculated with the new stats
for i = 2,#attackers do
local cfg = { att_stats = att_stats[i], def_stats = def_stats[i] }
local r, dr, ar = battle_calcs.attack_rating(attackers[i], defender, dsts[i], cfg, cache)
def_rating = dr
att_rating = att_rating + ar
end
local rating = def_rating + att_rating
return rating, attackers, dsts, att_stats, def_stats[#attackers], def_stats
end
function battle_calcs.get_attack_map_unit(unit, cfg)
-- Get all hexes that @unit can attack
-- Return value is a location set, where the values are tables, containing
-- - units: the number of units (always 1 for this function)
-- - hitpoints: the combined hitpoints of the units
-- - srcs: an array containing the positions of the units
-- @cfg: table with config parameters
-- max_moves: if set use max_moves for units (this setting is always used for units on other sides)
cfg = cfg or {}
-- 'moves' can be either "current" or "max"
-- For unit on current side: use "current" by default, or override by cfg.moves
local max_moves = cfg.max_moves
-- For unit on any other side, only max_moves=true makes sense
if (unit.side ~= wesnoth.current.side) then max_moves = true end
local old_moves = unit.moves
if max_moves then unit.moves = unit.max_moves end
local reach = {}
reach.units = LS.create()
reach.hitpoints = LS.create()
-- Also for units on the other side, take all units on this side with
-- MP left off the map (for enemy pathfinding)
local units_MP = {}
if (unit.side ~= wesnoth.current.side) then
local all_units = wesnoth.get_units { side = wesnoth.current.side }
for _,unit in ipairs(all_units) do
if (unit.moves > 0) then
table.insert(units_MP, unit)
wesnoth.extract_unit(unit)
end
end
end
-- Find hexes the unit can reach
local initial_reach = wesnoth.find_reach(unit, cfg)
-- Put the units back out there
if (unit.side ~= wesnoth.current.side) then
for _,uMP in ipairs(units_MP) do wesnoth.put_unit(uMP) end
end
for _,loc in ipairs(initial_reach) do
reach.units:insert(loc[1], loc[2], 1)
reach.hitpoints:insert(loc[1], loc[2], unit.hitpoints)
for xa,ya in H.adjacent_tiles(loc[1], loc[2]) do
reach.units:insert(xa, ya, 1)
reach.hitpoints:insert(xa, ya, unit.hitpoints)
end
end
if max_moves then unit.moves = old_moves end
return reach
end
function battle_calcs.get_attack_map(units, cfg)
-- Get all hexes that @units can attack. This is really just a wrapper
-- function for battle_calcs.get_attack_map_unit()
-- Return value is a location set, where the values are tables, containing
-- - units: the number of units (always 1 for this function)
-- - hitpoints: the combined hitpoints of the units
-- - srcs: an array containing the positions of the units
-- @cfg: table with config parameters
-- max_moves: if set use max_moves for units (this setting is always used for units on other sides)
local attack_map1 = {}
attack_map1.units = LS.create()
attack_map1.hitpoints = LS.create()
for _,unit in ipairs(units) do
local attack_map2 = battle_calcs.get_attack_map_unit(unit, cfg)
attack_map1.units:union_merge(attack_map2.units, function(x, y, v1, v2)
return (v1 or 0) + v2
end)
attack_map1.hitpoints:union_merge(attack_map2.hitpoints, function(x, y, v1, v2)
return (v1 or 0) + v2
end)
end
return attack_map1
end
function battle_calcs.relative_damage_map(units, enemies, cache)
-- Returns a location set map containing the relative damage of
-- @units vs. @enemies on the part of the map that the combined units
-- can reach. The damage is calculated as the sum of defender_rating
-- from attack_rating(), and thus (roughly) in gold units.
-- Also returns the same maps for the own and enemy units only
-- (with the enemy_damage_map having positive sign, while in the
-- overall damage map it is subtracted)
-- Get the attack maps for each unit in 'units' and 'enemies'
local my_attack_maps, enemy_attack_maps = {}, {}
for i,unit in ipairs(units) do
my_attack_maps[i] = battle_calcs.get_attack_map_unit(unit, cfg)
end
for i,e in ipairs(enemies) do
enemy_attack_maps[i] = battle_calcs.get_attack_map_unit(e, cfg)
end
-- Get the damage rating for each unit in 'units'. It is the maximum
-- defender_rating (roughly the damage that it can do in units of gold)
-- against any of the enemy units
local unit_ratings = {}
for i,unit in ipairs(units) do
local max_rating, best_enemy = -9e99, {}
for _,enemy in ipairs(enemies) do
local rating, defender_rating, attacker_rating =
battle_calcs.attack_rating(unit, enemy, { unit.x, unit.y }, { enemy_leader_weight = 1 }, cache)
local eff_rating = defender_rating
if (eff_rating > max_rating) then
max_rating = eff_rating
best_enemy = enemy
end
end
unit_ratings[i] = { rating = max_rating, unit_id = u.id, enemy_id = best_enemy.id }
end
-- Then we want the same thing for all of the enemy units (for the counter attack on enemy turn)
local enemy_ratings = {}
for i,enemy in ipairs(enemies) do
local max_rating, best_unit = -9e99, {}
for _,unit in ipairs(units) do
local rating, defender_rating, attacker_rating =
battle_calcs.attack_rating(enemy, unit, { enemy.x, enemy.y }, { enemy_leader_weight = 1 }, cache)
local eff_rating = defender_rating
if (eff_rating > max_rating) then
max_rating = eff_rating
best_unit = unit
end
end
enemy_ratings[i] = { rating = max_rating, unit_id = best_unit.id, enemy_id = enemy.id }
end
-- The damage map is now the sum of these ratings for each unit that can attack a given hex,
-- counting own-unit ratings as positive, enemy ratings as negative
local damage_map, own_damage_map, enemy_damage_map = LS.create(), LS.create(), LS.create()
for i,_ in ipairs(units) do
my_attack_maps[i].units:iter(function(x, y, v)
own_damage_map:insert(x, y, (own_damage_map:get(x, y) or 0) + unit_ratings[i].rating)
damage_map:insert(x, y, (damage_map:get(x, y) or 0) + unit_ratings[i].rating)
end)
end
for i,_ in ipairs(enemies) do
enemy_attack_maps[i].units:iter(function(x, y, v)
enemy_damage_map:insert(x, y, (enemy_damage_map:get(x, y) or 0) + enemy_ratings[i].rating)
damage_map:insert(x, y, (damage_map:get(x, y) or 0) - enemy_ratings[i].rating)
end)
end
return damage_map, own_damage_map, enemy_damage_map
end
function battle_calcs.best_defense_map(units, cfg)
-- Get a defense rating map of all hexes all units in @units can reach
-- For each hex, the value is the maximum of any of the units that can reach that hex
-- @cfg: table with config parameters
-- max_moves: if set use max_moves for units (this setting is always used for units on other sides)
-- ignore_these_units: table of enemy units whose ZoC is to be ignored for route finding
cfg = cfg or {}
local defense_map = LS.create()
if cfg.ignore_these_units then
for _,unit in ipairs(cfg.ignore_these_units) do wesnoth.extract_unit(unit) end
end
for _,unit in ipairs(units) do
-- Set max_moves according to the cfg value
local max_moves = cfg.max_moves
-- For unit on other than current side, only max_moves=true makes sense
if (unit.side ~= wesnoth.current.side) then max_moves = true end
local old_moves = unit.moves
if max_moves then unit.moves = unit.max_moves end
local reach = wesnoth.find_reach(unit, cfg)
if max_moves then unit.moves = old_moves end
for _,loc in ipairs(reach) do
local defense = 100 - wesnoth.unit_defense(unit, wesnoth.get_terrain(loc[1], loc[2]))
if (defense > (defense_map:get(loc[1], loc[2]) or -9e99)) then
defense_map:insert(loc[1], loc[2], defense)
end
end
end
if cfg.ignore_these_units then
for _,unit in ipairs(cfg.ignore_these_units) do wesnoth.put_unit(unit) end
end
return defense_map
end
function battle_calcs.get_attack_combos_subset(units, enemy, cfg)
-- Calculate combinations of attacks by @units on @enemy
-- This method does *not* produce all possible attack combinations, but is
-- meant to have a good chance to find either the best combination,
-- or something close to it, by only considering a subset of all possibilities.
-- It is also configurable to stop accumulating combinations when certain criteria are met.
--
-- The return value is an array of attack combinations, where each element is another
-- array of tables containing 'dst' and 'src' fields of the attacking units. It can be
-- specified whether the order of the attacks matters or not (see below).
--
-- Note: This function is optimized for speed, not elegance
--
-- Note 2: The structure of the returned table is different from the (current) return value
-- of ai_helper.get_attack_combos(), since the order of attacks never matters for the latter.
-- TODO: consider making the two consistent (not sure yet whether that is advantageous)
--
-- @cfg: Table of optional configuration parameters
-- - order_matters: if set, keep attack combos that use the same units on the same
-- hexes, but in different attack order (default: false)
-- - max_combos: stop adding attack combos if this number of combos has been reached
-- default: assemble all possible combinations
-- - max_time: stop adding attack combos if this much time (in seconds) has passed
-- default: assemble all possible combinations
-- note: this counts the time from the first call to add_attack(), not to
-- get_attack_combos_cfg(), so there's a bit of extra overhead in here.
-- This is done to prevent the return of no combos at all
-- Note 2: there is some overhead involved in reading the time from the system,
-- so don't use this unless it's needed
-- - skip_presort: by default, the units are presorted in order of the unit with
-- the highest rating first. This has the advantage of likely finding the best
-- (or at least close to the best) attack combination earlier, but it add overhead,
-- so it's actually a disadvantage for small numbers of combinations. skip_presort
-- specifies the number of units up to which the presorting is skipped. Default: 5
cfg = cfg or {}
cfg.order_matters = cfg.order_matters or false
cfg.max_combos = cfg.max_combos or 9e99
cfg.max_time = cfg.max_time or false
cfg.skip_presort = cfg.skip_presort or 5
----- begin add_attack() -----
-- Recursive local function adding another attack to the current combo
-- and adding the current combo to the overall attack_combos array
local function add_attack(attacks, reachable_hexes, n_reach, attack_combos, combos_str, current_combo, hexes_used, cfg)
local time_up = false
if cfg.max_time and (wesnoth.get_time_stamp() / 1000. - cfg.start_time >= cfg.max_time) then
time_up = true
end
-- Go through all the units
for ind_att,attack in ipairs(attacks) do -- 'attack' is array of all attacks for the unit
-- Then go through the individual attacks of the unit ...
for _,att in ipairs(attack) do
-- But only if this hex is not used yet and
-- the cutoff criteria are not met
if (not hexes_used[att.dst]) and (not time_up) and (#attack_combos < cfg.max_combos) then
-- Mark this hex as used by this unit
hexes_used[att.dst] = attack.src
-- Set up a string uniquely identifying the unit/attack hex pairs
-- for current_combo. This is used to exclude pairs that already
-- exist in a different order (if 'cfg.order_matters' is not set)
-- For this, we also add the numerical value of the attack_hex to
-- the 'hexes_used' table (in addition to the line above)
local str = ''
if (not cfg.order_matters) then
hexes_used[reachable_hexes[att.dst]] = attack.src
for ind_hex = 1,n_reach do
if hexes_used[ind_hex] then
str = str .. hexes_used[ind_hex] .. '-'
else
str = str .. '0-'
end
end
end
-- 'combos_str' contains all the strings of previous combos
-- (if 'cfg.order_matters' is not set)
-- Only add this combo if it does not yet exist
if (not combos_str[str]) then
-- Add the string identifyer to the array
if (not cfg.order_matters) then
combos_str[str] = true
end
-- Add the attack to 'current_combo'
table.insert(current_combo, { dst = att.dst, src = attack.src })
-- And *copy* the content of 'current_combo' into 'attack_combos'
local n_combos = #attack_combos + 1
attack_combos[n_combos] = {}
for ind_combo,combo in pairs(current_combo) do attack_combos[n_combos][ind_combo] = combo end
-- Finally, remove the current unit for 'attacks' for the call to the next recursion level
table.remove(attacks, ind_att)
add_attack(attacks, reachable_hexes, n_reach, attack_combos, combos_str, current_combo, hexes_used, cfg)
-- Reinsert the unit
table.insert(attacks, ind_att, attack)
-- And remove the last element (current attack) from 'current_combo'
table.remove(current_combo)
end
-- And mark the hex as usable again
if (not cfg.order_matters) then
hexes_used[reachable_hexes[att.dst]] = nil
end
hexes_used[att.dst] = nil
-- *** Important ***: We *only* consider one attack hex per unit, the
-- first that is found in the array of attacks for the unit. As they
-- are sorted by terrain defense, we simply use the first in the table
-- the unit can reach that is not occupied
-- That's what the 'break' does here:
break
end
end
end
end
----- end add_attack() -----
-- For units on the current side, we need to make sure that
-- there isn't a unit of the same side in the way that cannot move any more
-- Set up an array of hexes blocked in such a way
-- For units on other sides we always assume that they can move away
local blocked_hexes = LS.create()
if units[1] and (units[1].side == wesnoth.current.side) then
for xa,ya in H.adjacent_tiles(enemy.x, enemy.y) do
local unit_in_way = wesnoth.get_unit(xa, ya)
if unit_in_way then
-- Units on the same side are blockers if they cannot move away
if (unit_in_way.side == wesnoth.current.side) then
local reach = wesnoth.find_reach(unit_in_way)
if (#reach <= 1) then
blocked_hexes:insert(unit_in_way.x, unit_in_way.y)
end
else -- Units on other sides are always blockers
blocked_hexes:insert(unit_in_way.x, unit_in_way.y)
end
end
end
end
-- For sides other than the current, we always use max_moves,
-- for the current side we always use current moves
local old_moves = {}
for i,unit in ipairs(units) do
if (unit.side ~= wesnoth.current.side) then
old_moves[i] = unit.moves
unit.moves = unit.max_moves
end
end
-- Now set up an array containing the attack locations for each unit
local attacks = {}
-- We also need a numbered array of the possible attack hex coordinates
-- The order doesn't matter, as long as it is fixed
local reachable_hexes = {}
for i,unit in ipairs(units) do
local locs = {} -- attack locations for this unit
for xa,ya in H.adjacent_tiles(enemy.x, enemy.y) do
local loc = {} -- attack location information for this unit for this hex
-- Make sure the hex is not occupied by unit that cannot move out of the way
if (not blocked_hexes:get(xa, ya) or ((xa == unit.x) and (ya == unit.y))) then
-- Check whether the unit can get to the hex
-- helper.distance_between() is much faster than wesnoth.find_path()
--> pre-filter using the former
local cost = H.distance_between(unit.x, unit.y, xa, ya)
-- If the distance is <= the unit's MP, then see if it can actually get there
-- This also means that only short paths have to be evaluated (in most situations)
if (cost <= unit.moves) then
local path -- since cost is already defined outside this block
path, cost = wesnoth.find_path(unit, xa, ya)
end
-- If the unit can get to this hex
if (cost <= unit.moves) then
-- Store information about it in 'loc' and add this to 'locs'
-- Want coordinates (dst) and terrain defense (for sorting)
loc.dst = xa * 1000 + ya
loc.hit_prob = wesnoth.unit_defense(unit, wesnoth.get_terrain(xa, ya))
table.insert(locs, loc)
-- Also mark this hex as usable
reachable_hexes[loc.dst] = true
end
end
end
-- Also add some top-level information for the unit
if locs[1] then
locs.src = unit.x * 1000 + unit.y -- The current position of the unit
locs.unit_i = i -- The position of the unit in the 'units' array
-- Now sort the possible attack locations for this unit by terrain defense
table.sort(locs, function(a, b) return a.hit_prob < b.hit_prob end)
-- Finally, add the attack locations for this unit to the 'attacks' array
table.insert(attacks, locs)
end
end
-- Reset moves for all units
for i,unit in ipairs(units) do
if (unit.side ~= wesnoth.current.side) then
unit.moves = old_moves[i]
end
end
-- If the number of units that can attack is greater than cfg.skip_presort:
-- We also sort the attackers by their attack rating on their favorite hex
-- The motivation is that by starting with the strongest unit, we'll find the
-- best attack combo earlier, and it is more likely to find the best (or at
-- least a good combo) even when not all attack combinations are collected.
if (#attacks > cfg.skip_presort) then
for _,attack in ipairs(attacks) do
local dst = attack[1].dst
local x, y = math.floor(dst / 1000), dst % 1000
attack.rating = battle_calcs.attack_rating(units[attack.unit_i], enemy, { x, y })
end
table.sort(attacks, function(a, b) return a.rating > b.rating end)
end
-- To simplify and speed things up in the following, the field values
-- 'reachable_hexes' table needs to be consecutive integers
-- We also want a variable containing the number of elements in the array
-- (#reachable_hexes doesn't work because they keys are location indices)
local n_reach = 0
for k,hex in pairs(reachable_hexes) do
n_reach = n_reach + 1
reachable_hexes[k] = n_reach
end
-- If cfg.max_time is set, record the start time
-- For convenience, we store this in cfg
if cfg.max_time then
cfg.start_time = wesnoth.get_time_stamp() / 1000.
end
-- All this was just setting up the required information, now we call the
-- recursive function setting up the array of attackcombinations
local attack_combos = {} -- This will contain the return value
-- Temporary arrays (but need to be persistent across the recursion levels)
local combos_str, current_combo, hexes_used = {}, {}, {}
add_attack(attacks, reachable_hexes, n_reach, attack_combos, combos_str, current_combo, hexes_used, cfg)
cfg.start_time = nil
return attack_combos
end
return battle_calcs
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Wajaom_Woodlands/npcs/Harvesting_Point.lua | 29 | 1175 | -----------------------------------
-- Area: Wajaom Woodlands
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil;
package.loaded["scripts/globals/harvesting"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/Wajaom_Woodlands/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x01FB);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
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 |
icplus/OP-SDK | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/df.lua | 78 | 1628 | --[[
Luci configuration model for statistics - collectd df plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("luci_statistics",
translate("DF Plugin Configuration"),
translate(
"The df plugin collects statistics about the disk space " ..
"usage on different devices, mount points or filesystem types."
))
-- collectd_df config section
s = m:section( NamedSection, "collectd_df", "luci_statistics" )
-- collectd_df.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_df.devices (Device)
devices = s:option( Value, "Devices", translate("Monitor devices") )
devices.default = "/dev/mtdblock/4"
devices.optional = true
devices:depends( "enable", 1 )
-- collectd_df.mountpoints (MountPoint)
mountpoints = s:option( Value, "MountPoints", translate("Monitor mount points") )
mountpoints.default = "/overlay"
mountpoints.optional = true
mountpoints:depends( "enable", 1 )
-- collectd_df.fstypes (FSType)
fstypes = s:option( Value, "FSTypes", translate("Monitor filesystem types") )
fstypes.default = "tmpfs"
fstypes.optional = true
fstypes:depends( "enable", 1 )
-- collectd_df.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| gpl-2.0 |
lamefun/colosseum-xp | lua/common/json.lua | 1 | 15832 | <<
-----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.40
-- This module is released under the MIT License (MIT).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-- Colosseum XP
local encode
local decode
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.e", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.e"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
-- Character escaping is only used to escape the string delimiters
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
-- Colosseum XP
cc.tojson = encode
cc.fromjson = decode
>>
| gpl-2.0 |
nasomi/darkstar | scripts/globals/items/red_terrapin.lua | 18 | 1322 | -----------------------------------------
-- ID: 4402
-- Item: red_terrapin
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local 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,4402);
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 |
nasomi/darkstar | scripts/zones/Northern_San_dOria/npcs/Coullene.lua | 5 | 1527 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Coullene
-- Type: Involved in Quest (Flyers for Regine)
-- @zone: 231
-- @pos 146.420 0.000 127.601
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCoulene") == 0) then
player:messageSpecial(COULLENE_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeCoulene",1);
player:messageSpecial(FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getVar("tradeCoulene") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,COULLENE_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 |
nasomi/darkstar | scripts/zones/Castle_Oztroja/npcs/_47x.lua | 17 | 1247 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47x (Handle)
-- Notes: Opens door _477
-- @pos -99 -71 -41 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)
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if (player:getZPos() > -45) then
if (DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
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);
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/mobskills/Dread_Dive.lua | 25 | 1043 | ---------------------------------------------
-- Dread Dive
--
-- Description: Dives into a single target. Additional effect: Knockback + Stun
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes: Used instead of Gliding Spike by certain notorious monsters.
---------------------------------------------
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.4;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local typeEffect = EFFECT_STUN;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/serving_of_elysian_eclair.lua | 36 | 1430 | -----------------------------------------
-- ID: 5560
-- Item: Serving of Elysian Eclair
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10
-- MP +15
-- Intelligence +2
-- HP Recoverd while healing 2
-- MP Recovered while healing 2
-----------------------------------------
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,5560);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_MP, 15);
target:addMod(MOD_INT, 2);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_MP, 15);
target:delMod(MOD_INT, 2);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
Nelarius/wren | test/benchmark/fannkuch.lua | 13 | 1363 | -- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
local function fannkuch(n)
local p, q, s, sign, maxflips, sum = {}, {}, {}, 1, 0, 0
for i=1,n do p[i] = i; q[i] = i; s[i] = i end
repeat
-- Copy and flip.
local q1 = p[1] -- Cache 1st element.
if q1 ~= 1 then
for i=2,n do q[i] = p[i] end -- Work on a copy.
local flips = 1
repeat
local qq = q[q1]
if qq == 1 then -- ... until 1st element is 1.
sum = sum + sign*flips
if flips > maxflips then maxflips = flips end -- New maximum?
break
end
q[q1] = q1
if q1 >= 4 then
local i, j = 2, q1 - 1
repeat q[i], q[j] = q[j], q[i]; i = i + 1; j = j - 1; until i >= j
end
q1 = qq; flips = flips + 1
until false
end
-- Permute.
if sign == 1 then
p[2], p[1] = p[1], p[2]; sign = -1 -- Rotate 1<-2.
else
p[2], p[3] = p[3], p[2]; sign = 1 -- Rotate 1<-2 and 1<-2<-3.
for i=3,n do
local sx = s[i]
if sx ~= 1 then s[i] = sx-1; break end
if i == n then return sum, maxflips end -- Out of permutations.
s[i] = i
-- Rotate 1<-...<-i+1.
local t = p[1]; for j=1,i do p[j] = p[j+1] end; p[i+1] = t
end
end
until false
end
local n = 9
local sum, flips = fannkuch(n)
io.write(sum, "\nPfannkuchen(", n, ") = ", flips, "\n") | mit |
nasomi/darkstar | scripts/globals/spells/poisonga_ii.lua | 18 | 1099 | -----------------------------------------
-- Spell: Poisonga II
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_POISON;
local duration = 120;
local pINT = caster:getStat(MOD_INT);
local mINT = target:getStat(MOD_INT);
local dINT = (pINT - mINT);
local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 15 + 1;
if power > 15 then
power = 15;
end
local resist = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,effect);
if (resist == 1 or resist == 0.5) then -- effect taken
duration = duration * resist;
if (target:addStatusEffect(effect,power,3,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else -- resist entirely.
spell:setMsg(85);
end
return effect;
end; | gpl-3.0 |
icplus/OP-SDK | package/ramips/ui/luci-mtk/src/modules/base/luasrc/template.lua | 68 | 3061 | --[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local util = require "luci.util"
local config = require "luci.config"
local tparser = require "luci.template.parser"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv, rawget = getfenv, setfenv, rawget
local assert, type, error = assert, type, error
--- LuCI template library.
module "luci.template"
config.template = config.template or {}
viewdir = config.template.viewdir or util.libpath() .. "/view"
-- Define the namespace for template modules
context = util.threadlocal()
--- Render a certain template.
-- @param name Template name
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
-- Template class
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = setmetatable({}, {__mode = "v"})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
self.template = self.cache[name]
self.name = name
-- Create a new namespace for this template
self.viewns = context.viewns
-- If we have a cached template, skip compiling and loading
if not self.template then
-- Compile template
local err
local sourcefile = viewdir .. "/" .. name .. ".htm"
self.template, _, err = tparser.parse(sourcefile)
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error("Failed to load template '" .. name .. "'.\n" ..
"Error while parsing template '" .. sourcefile .. "':\n" ..
(err or "Unknown syntax error"))
else
self.cache[name] = self.template
end
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Put our predefined objects in the scope of the template
setfenv(self.template, setmetatable({}, {__index =
function(tbl, key)
return rawget(tbl, key) or self.viewns[key] or scope[key]
end}))
-- Now finally render the thing
local stat, err = util.copcall(self.template)
if not stat then
error("Failed to execute template '" .. self.name .. "'.\n" ..
"A runtime error occured: " .. tostring(err or "(nil)"))
end
end
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Attohwa_Chasm/npcs/Jakaka.lua | 19 | 2419 | -----------------------------------
-- Area: Attohwa Chasm
-- NPC: Jakaka
-- Type: ENM
-- @pos -144.711 6.246 -250.309 7
-----------------------------------
package.loaded["scripts/zones/Attohwa_Chasm/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Attohwa_Chasm/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Parradamo Stones
if (trade:hasItemQty(1778,1) and trade:getItemCount() == 1) then
player:tradeComplete();
player:startEvent(12);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local MiasmaFilterCD = player:getVar("[ENM]MiasmaFilter");
if (player:hasKeyItem(MIASMA_FILTER)) then
player:startEvent(11);
else
if (MiasmaFilterCD >= os.time(t)) then
-- Both Vanadiel time and unix timestamps are based on seconds. Add the difference to the event.
player:startEvent(14, VanadielTime()+(MiasmaFilterCD-os.time(t)));
else
if (player:hasItem(1778)==true or player:hasItem(1777)==true) then -- Parradamo Stones, Flaxen Pouch
player:startEvent(15);
else
player:startEvent(13);
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);
if (csid == 12) then
player:addKeyItem(MIASMA_FILTER);
player:messageSpecial(KEYITEM_OBTAINED,MIASMA_FILTER);
player:setVar("[ENM]MiasmaFilter",os.time(t)+86400*MIASMA_FILTER_COOLDOWN); -- Current time + 1dayInSeconds*MIASMA_FILTER_COOLDOWN
elseif (csid == 13) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1777); -- Flaxen Pouch
return;
else
player:addItem(1777);
player:messageSpecial(ITEM_OBTAINED, 1777); -- Flaxen Pouch
end
end
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Kelsha-Melansha.lua | 34 | 1040 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Kelsha-Melansha
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x029D);
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/Maze_of_Shakhrami/npcs/Grounds_Tome.lua | 34 | 1148 | -----------------------------------
-- Area: Maze of Shakhrami
-- 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_MAZE_OF_SHAKHRAMI,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,695,696,697,698,699,700,701,702,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,695,696,697,698,699,700,701,702,0,0,GOV_MSG_MAZE_OF_SHAKHRAMI);
end;
| gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-vsftpd/luasrc/model/cbi/vsftpd/general.lua | 10 | 4043 | --[[
LuCI - Lua Configuration Interface
Copyright 2016 Weijie Gao <hackpascal@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
$Id$
]]--
m = Map("vsftpd", translate("FTP Server - General Settings"))
sl = m:section(NamedSection, "listen", "listen", translate("Listening Settings"))
o = sl:option(Flag, "enable4", translate("Enable IPv4"))
o.rmempty = false
o.default = true
o = sl:option(Value, "ipv4", translate("IPv4 Address"))
o.datatype = "ip4addr"
o.default = "0.0.0.0"
o = sl:option(Flag, "enable6", translate("Enable IPv6"))
o.rmempty = false
o = sl:option(Value, "ipv6", translate("IPv6 Address"))
o.datatype = "ip6addr"
o.default = "::"
o = sl:option(Value, "port", translate("Listen Port"))
o.datatype = "uinteger"
o.default = "21"
o = sl:option(Value, "dataport", translate("Data Port"))
o.datatype = "uinteger"
o.default = "20"
sg = m:section(NamedSection, "global", "global", translate("Global Settings"))
o = sg:option(Flag, "write", translate("Enable write"), translate("When disabled, all write request will give permission denied."));
o.default = true
o = sg:option(Flag, "download", translate("Enable download"), translate("When disabled, all download request will give permission denied."));
o.default = true
o = sg:option(Flag, "dirlist", translate("Enable directory list"), translate("When disabled, list commands will give permission denied."))
o.default = true
o = sg:option(Flag, "lsrecurse", translate("Allow directory recursely list"))
o = sg:option(Flag, "dotfile", translate("Show dot files"), translate(". and .. are excluded."));
o.default = true
o = sg:option(Value, "umask", translate("File mode umask"), translate("Uploaded file mode will be 666 - <umask>; directory mode will be 777 - <umask>."))
o.default = "022"
o = sg:option(Value, "banner", translate("FTP Banner"))
o = sg:option(Flag, "dirmessage", translate("Enable directory message"), translate("A message will be displayed when entering a directory."))
o = sg:option(Value, "dirmsgfile", translate("Directory message filename"))
o.default = ".message"
sl = m:section(NamedSection, "local", "local", translate("Local Users"))
o = sl:option(Flag, "enabled", translate("Enable local user"))
o.rmempty = false
o = sl:option(Value, "root", translate("Root directory"), translate("Leave empty will use user's home directory"))
o.default = ""
sc = m:section(NamedSection, "connection", "connection", translate("Connection Settings"))
o = sc:option(Flag, "portmode", translate("Enable PORT mode"))
o = sc:option(Flag, "pasvmode", translate("Enable PASV mode"))
o = sc:option(ListValue, "ascii", translate("ASCII mode"))
o:value("disabled", translate("Disabled"))
o:value("download", translate("Download only"))
o:value("upload", translate("Upload only"))
o:value("both", translate("Both download and upload"))
o.default = "both"
o = sc:option(Value, "idletimeout", translate("Idle session timeout"), translate("in seconds"))
o.datatype = "uinteger"
o.default = "1800"
o = sc:option(Value, "conntimeout", translate("Connection timeout"), translate("in seconds"))
o.datatype = "uinteger"
o.default = "120"
o = sc:option(Value, "dataconntimeout", translate("Data connection timeout"), translate("in seconds"))
o.datatype = "uinteger"
o.default = "120"
o = sc:option(Value, "maxclient", translate("Max clients"), translate("0 means no limitation"))
o.datatype = "uinteger"
o.default = "0"
o = sc:option(Value, "maxperip", translate("Max clients per IP"), translate("0 means no limitation"))
o.datatype = "uinteger"
o.default = "0"
o = sc:option(Value, "maxrate", translate("Max transmit rate"), translate("in KB/s, 0 means no limitation"))
o.datatype = "uinteger"
o.default = "0"
o = sc:option(Value, "maxretry", translate("Max login fail count"), translate("Can not be zero, default is 3"))
o.datatype = "uinteger"
o.default = "3"
return m
| apache-2.0 |
nasomi/darkstar | scripts/zones/Apollyon/mobs/Proto-Omega.lua | 16 | 3073 | -----------------------------------
-- Area: Apollyon Centrale
-- NPC: Proto-Omega
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
--print("Proto-omega_engaged");
mob:setMod(MOD_SLASHRES,300);
mob:setMod(MOD_PIERCERES,300);
mob:setMod(MOD_IMPACTRES,300);
mob:setMod(MOD_HTHRES,300);
for n =1,table.getn (resistMod),1 do
mob:setMod(resistMod[n],-50);
end
for n =1,table.getn (defenseMod),1 do
mob:setMod(defenseMod[n],-50);
end
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local mobID = mob:getID();
local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100);
if (lifepourcent > 70 or lifepourcent <30) then
mob:AnimationSub(1);
elseif (lifepourcent > 30 and lifepourcent < 70) then
mob:AnimationSub(2);
end
if (lifepourcent > 30 and lifepourcent < 70 and mob:getLocalVar("form") == 8) then -- bipede
mob:setMod(MOD_SLASHRES,1400);
mob:setMod(MOD_PIERCERES,1400);
mob:setMod(MOD_IMPACTRES,1400);
mob:setMod(MOD_HTHRES,1400);
for n =1,table.getn (resistMod),1 do
mob:setMod(resistMod[n],100);
end
for n =1,table.getn (defenseMod),1 do
mob:setMod(defenseMod[n],100);
end
SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod
mob:setLocalVar("form", 9)
-- print("bipede");
elseif (lifepourcent < 30 and mob:getLocalVar("form") == 9 ) then -- quadripede
mob:setMod(MOD_SLASHRES,1450);
mob:setMod(MOD_PIERCERES,1450);
mob:setMod(MOD_IMPACTRES,1450);
mob:setMod(MOD_HTHRES,1450);
for n =1,table.getn (resistMod),1 do
mob:setMod(resistMod[n],-50);
end
for n =1,table.getn (defenseMod),1 do
mob:setMod(defenseMod[n],-50);
end
mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain,
SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod
mob:setLocalVar("form", 8);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
killer:addTitle(APOLLYON_RAVAGER);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+39):setStatus(STATUS_NORMAL);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/mobskills/Wire_Cutter.lua | 17 | 1077 | ---------------------------------------------------
-- Wire_Cutter
-- Single-target damage (~500-1500), absorbed by 2 Utsusemi shadows.
--
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobID = mob:getID(); --(16908295 ,16908302 ,16908309 =omega , 16928966=proto-ultima )
local mobhp = mob:getHPP();
if ((mobID == 16928966 and mobhp > 80) or(mobhp > 70 and(mobID == 16908295 or mobID == 16908302 or mobID == 16908309 ))) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 2;
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,info.hitslanded);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Cloister_of_Frost/bcnms/trial_by_ice.lua | 19 | 1842 | -----------------------------------
-- Area: Cloister of Frost
-- BCNM: Trial by Ice
-- @pos 558 0.1 596 203
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Cloister_of_Frost/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompleteQuest(SANDORIA,TRIAL_BY_ICE)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:delKeyItem(TUNING_FORK_OF_ICE);
player:addKeyItem(WHISPER_OF_FROST);
player:addTitle(HEIR_OF_THE_GREAT_ICE);
player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_FROST);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Markets/npcs/Umberto.lua | 38 | 1073 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Umberto
-- Type: Quest NPC
-- @zone: 235
-- @pos -56.896 -5 -134.267
--
-- Auto-Script: Requires Verification. Verified standard dialog - thrydwolf 12/18/2011
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x019b);
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 |
actboy168/YDWE | Development/Component/plugin/w3x2lni/script/core/slk/frontend_w3i.lua | 2 | 10516 | local lang = require 'lang'
local select = select
local w2l
local function unpack_flag(flag)
local tbl = {}
for i = 0, 64 do
local n = 1 << i
if n > flag then
break
end
if flag & n ~= 0 then
tbl[#tbl+1] = i + 1
end
end
return tbl
end
local function pack(...)
local tbl = {...}
tbl[#tbl] = nil
return tbl
end
local mt = {}
mt.__index = mt
function mt:set_index(...)
self.index = select(-1, ...)
return ...
end
function mt:unpack(str)
return self:set_index(str:unpack(self.content, self.index))
end
function mt:is_finish()
return ('I1'):unpack(self.content, self.index) == 0xFF
end
function mt:get_version(chunk)
local version = self:unpack 'l'
return version
end
function mt:add_head(chunk, version)
chunk[lang.w3i.MAP] = {
[lang.w3i.FILE_VERSION] = version,
[lang.w3i.MAP_VERSION] = self:unpack 'l',
[lang.w3i.WE_VERSION] = self:unpack 'l',
[lang.w3i.MAP_NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.AUTHOR_NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.MAP_DESC] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.PLAYER_DESC] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
chunk[lang.w3i.CAMERA] = {
[lang.w3i.CAMERA_BOUND] = pack(self:unpack 'ffffffff'),
[lang.w3i.CAMERA_COMPLEMENT] = pack(self:unpack 'llll'),
}
chunk[lang.w3i.MAP_INFO] = {
[lang.w3i.MAP_WIDTH] = self:unpack 'l',
[lang.w3i.MAP_HEIGHT] = self:unpack 'l',
}
local flag = self:unpack 'L'
chunk[lang.w3i.CONFIG] = {
[lang.w3i.DISABLE_PREVIEW] = flag >> 0 & 1,
[lang.w3i.CUSTOM_ALLY] = flag >> 1 & 1,
[lang.w3i.MELEE_MAP] = flag >> 2 & 1,
[lang.w3i.LARGE_MAP] = flag >> 3 & 1,
[lang.w3i.MASKED_AREA_SHOW_TERRAIN] = flag >> 4 & 1,
[lang.w3i.FIX_FORCE_SETTING] = flag >> 5 & 1,
[lang.w3i.CUSTOM_FORCE] = flag >> 6 & 1,
[lang.w3i.CUSTOM_TECHTREE] = flag >> 7 & 1,
[lang.w3i.CUSTOM_ABILITY] = flag >> 8 & 1,
[lang.w3i.CUSTOM_UPGRADE] = flag >> 9 & 1,
[lang.w3i.MAP_MENU_MARK] = flag >> 10 & 1,
[lang.w3i.SHOW_WAVE_ON_CLIFF] = flag >> 11 & 1,
[lang.w3i.SHOW_WAVE_ON_ROLLING] = flag >> 12 & 1,
[lang.w3i.UNKNOWN_1] = flag >> 13 & 1,
[lang.w3i.UNKNOWN_2] = flag >> 14 & 1,
[lang.w3i.UNKNOWN_3] = flag >> 15 & 1,
[lang.w3i.UNKNOWN_4] = flag >> 16 & 1,
[lang.w3i.UNKNOWN_5] = flag >> 17 & 1,
[lang.w3i.UNKNOWN_6] = flag >> 18 & 1,
[lang.w3i.UNKNOWN_7] = flag >> 19 & 1,
[lang.w3i.UNKNOWN_8] = flag >> 20 & 1,
[lang.w3i.UNKNOWN_9] = flag >> 21 & 1,
}
chunk[lang.w3i.MAP_INFO][lang.w3i.MAP_MAIN_GROUND] = self:unpack 'c1'
if version == 25 then
chunk[lang.w3i.LOADING_SCREEN] = {
[lang.w3i.ID] = self:unpack 'l',
[lang.w3i.PATH] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TEXT] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SUBTITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
chunk[lang.w3i.CONFIG][lang.w3i.GAME_DATA_SETTING] = self:unpack 'l'
chunk[lang.w3i.PROLOGUE] = {
[lang.w3i.PATH] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TEXT] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SUBTITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
chunk[lang.w3i.FOG] = {
[lang.w3i.TYPE] = self:unpack 'l',
[lang.w3i.START_Z] = self:unpack 'f',
[lang.w3i.END_Z] = self:unpack 'f',
[lang.w3i.DENSITY] = self:unpack 'f',
[lang.w3i.COLOR] = pack(self:unpack 'BBBB'),
}
chunk[lang.w3i.ENVIRONMENT] = {
[lang.w3i.WEATHER] = self:unpack 'c4',
[lang.w3i.SOUND] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.LIGHT] = self:unpack 'c1',
[lang.w3i.WATER_COLOR] = pack(self:unpack 'BBBB'),
}
elseif version == 18 then
chunk[lang.w3i.LOADING_SCREEN] = {
[lang.w3i.ID] = self:unpack 'l',
[lang.w3i.TEXT] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SUBTITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
chunk[lang.w3i.PROLOGUE] = {
[lang.w3i.ID] = self:unpack 'l',
[lang.w3i.TEXT] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.TITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SUBTITLE] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
end
end
function mt:add_player(chunk)
chunk[lang.w3i.PLAYER] = {
[lang.w3i.PLAYER_COUNT] = self:unpack 'l',
}
for i = 1, chunk[lang.w3i.PLAYER][lang.w3i.PLAYER_COUNT] do
chunk[lang.w3i.PLAYER..i] = {
[lang.w3i.PLAYER] = self:unpack 'l',
[lang.w3i.TYPE] = self:unpack 'l',
[lang.w3i.RACE] = self:unpack 'l',
[lang.w3i.FIX_START_POSITION] = self:unpack 'l',
[lang.w3i.NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.START_POSITION] = pack(self:unpack 'ff'),
[lang.w3i.ALLY_LOW_FLAG] = unpack_flag(self:unpack 'L'),
[lang.w3i.ALLY_HIGH_FLAG] = unpack_flag(self:unpack 'L'),
}
end
end
function mt:unpack_player_flag(chunk)
local flag = self:unpack 'L'
local tbl = unpack_flag(flag)
local exits = {}
for i = 1, chunk[lang.w3i.PLAYER][lang.w3i.PLAYER_COUNT] do
local player = chunk[lang.w3i.PLAYER..i]
local id = player[lang.w3i.PLAYER] + 1
exits[id] = true
end
local result = {}
for _, id in ipairs(tbl) do
if exits[id] then
result[#result+1] = id
end
end
return result
end
function mt:add_force(chunk)
chunk[lang.w3i.FORCE] = {
[lang.w3i.FORCE_COUNT] = self:unpack 'l',
}
for i = 1, chunk[lang.w3i.FORCE][lang.w3i.FORCE_COUNT] do
local flag = self:unpack 'L'
chunk[lang.w3i.FORCE..i] = {
[lang.w3i.ALLY] = flag >> 0 & 1,
[lang.w3i.ALLY_WIN] = flag >> 1 & 1,
[lang.w3i.SHARE_VISIBLE] = flag >> 3 & 1,
[lang.w3i.SHARE_CONTROL] = flag >> 4 & 1,
[lang.w3i.SHARE_ADVANCE] = flag >> 5 & 1,
[lang.w3i.PLAYER_LIST] = self:unpack_player_flag(chunk),
[lang.w3i.FORCE_NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
}
end
end
function mt:add_upgrade(chunk)
if self:is_finish() then
return
end
local count = self:unpack 'l'
for i = 1, count do
chunk[lang.w3i.UPGRADE..i] = {
[lang.w3i.PLAYER_LIST] = unpack_flag(self:unpack 'L'),
['ID'] = self:unpack 'c4',
[lang.w3i.LEVEL] = self:unpack 'l',
[lang.w3i.AVAILABLE] = self:unpack 'l',
}
end
end
function mt:add_tech(chunk)
if self:is_finish() then
return
end
local count = self:unpack 'l'
for i = 1, count do
chunk[lang.w3i.TECH..i] = {
[lang.w3i.PLAYER_LIST] = unpack_flag(self:unpack 'L'),
['ID'] = self:unpack 'c4',
}
end
end
function mt:add_randomgroup(chunk)
if self:is_finish() then
return
end
local count = self:unpack 'l'
for i = 1, count do
chunk[lang.w3i.RANDOM_GROUP..i] = {
['ID'] = self:unpack 'l',
[lang.w3i.RANDOM_GROUP_NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SETTING] = {},
}
local x = self:unpack 'l'
chunk[lang.w3i.RANDOM_GROUP..i][lang.w3i.POSITION_TYPE] = pack(self:unpack(('l'):rep(x)))
local y = self:unpack 'l'
for y = 1, y do
chunk[lang.w3i.RANDOM_GROUP..i][lang.w3i.SETTING][y] = {
[lang.w3i.CHANCE] = self:unpack 'l',
['ID'] = pack(self:unpack(('c4'):rep(x))),
}
end
end
end
function mt:add_randomitem(chunk)
if self:is_finish() then
return
end
local count = self:unpack 'l'
for i = 1, count do
chunk[lang.w3i.RANDOM_ITEM..i] = {
['ID'] = self:unpack 'l',
[lang.w3i.RANDOM_ITEM_NAME] = w2l:load_wts(self.wts, (self:unpack 'z')),
[lang.w3i.SETTING] = {},
}
--设置
local x = self:unpack 'l'
for x = 1, x do
chunk[lang.w3i.RANDOM_ITEM..i][lang.w3i.SETTING][x] = {}
local y = self:unpack 'l'
for y = 1, y do
chunk[lang.w3i.RANDOM_ITEM..i][lang.w3i.SETTING][x][y] = {
[lang.w3i.CHANCE] = self:unpack 'l',
['ID'] = self:unpack 'c4',
}
end
end
end
end
return function (w2l_, content, wts)
if not content then
return nil
end
w2l = w2l_
local index = 1
local tbl = setmetatable({}, mt)
local data = {}
tbl.content = content
tbl.index = index
tbl.wts = wts
local version = tbl:get_version(data)
if version == 25 then
tbl:add_head(data, version)
tbl:add_player(data)
tbl:add_force(data)
tbl:add_upgrade(data)
tbl:add_tech(data)
tbl:add_randomgroup(data)
tbl:add_randomitem(data)
elseif version == 18 then
tbl:add_head(data, version)
tbl:add_player(data)
tbl:add_force(data)
tbl:add_upgrade(data)
tbl:add_tech(data)
tbl:add_randomgroup(data)
end
return data
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/North_Gustaberg_[S]/Zone.lua | 16 | 1740 | -----------------------------------
--
-- Zone: North_Gustaberg_[S] (88)
--
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/North_Gustaberg_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(380.038,-2.25,147.627,192);
end
if (prevZone == 87 and player:getCampaignAllegiance() > 0 and player:getQuestStatus(CRYSTAL_WAR,BETTER_PART_OF_VALOR) == QUEST_AVAILABLE) then
cs = 0x0001;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0001) then
player:addQuest(CRYSTAL_WAR,BETTER_PART_OF_VALOR);
player:addKeyItem(CLUMP_OF_ANIMAL_HAIR);
player:messageSpecial(KEYITEM_OBTAINED,CLUMP_OF_ANIMAL_HAIR);
end
end; | gpl-3.0 |
appaquet/torch-android | android-demo-cifar/modelPrepare/test-only.lua | 4 | 7607 | ----------------------------------------------------------------------
-- This script test Cifar-10 test data set with pre-trained network.
--
-- This script is based on file from below address.
--
-- https://github.com/torch/demos/blob/master/train-on-cifar/train-on-cifar.lua
--
-- Training code are removed.
-- This script require trained model network and std_u, mean_u, std_v, mean_v files
-- from train-on-cifar.lua in same directory
--
-- Karam Park
----------------------------------------------------------------------
-- This script shows how to train different models on the CIFAR
-- dataset, using multiple optimization techniques (SGD, ASGD, CG)
--
-- This script demonstrates a classical example of training
-- well-known models (convnet, MLP, logistic regression)
-- on a 10-class classification problem.
--
-- It illustrates several points:
-- 1/ description of the model
-- 2/ choice of a loss function (criterion) to minimize
-- 3/ creation of a dataset as a simple Lua table
-- 4/ description of training and test procedures
--
-- Clement Farabet
----------------------------------------------------------------------
require 'torch'
require 'nn'
require 'nnx'
require 'optim'
require 'image'
----------------------------------------------------------------------
-- parse command-line options
--
dname,fname = sys.fpath()
cmd = torch.CmdLine()
cmd:text()
cmd:text('CIFAR Training')
cmd:text()
cmd:text('Options:')
cmd:option('-save', fname:gsub('.lua',''), 'subdirectory to save/log experiments in')
cmd:option('-network', '', 'reload pretrained network')
cmd:option('-model', 'convnet', 'type of model to train: convnet | mlp | linear')
cmd:option('-full', false, 'use full dataset (50,000 samples)')
cmd:option('-visualize', false, 'visualize input data and weights during training')
cmd:option('-seed', 1, 'fixed input seed for repeatable experiments')
cmd:option('-optimization', 'SGD', 'optimization method: SGD | ASGD | CG | LBFGS')
cmd:option('-learningRate', 1e-3, 'learning rate at t=0')
cmd:option('-batchSize', 1, 'mini-batch size (1 = pure stochastic)')
cmd:option('-weightDecay', 0, 'weight decay (SGD only)')
cmd:option('-momentum', 0, 'momentum (SGD only)')
cmd:option('-t0', 1, 'start averaging at t0 (ASGD only), in nb of epochs')
cmd:option('-maxIter', 5, 'maximum nb of iterations for CG and LBFGS')
cmd:option('-threads', 8, 'nb of threads to use')
cmd:text()
opt = cmd:parse(arg)
-- fix seed
torch.manualSeed(opt.seed)
-- threads
torch.setnumthreads(opt.threads)
print('<torch> set nb of threads to ' .. opt.threads)
----------------------------------------------------------------------
-- define model to train
-- on the 10-class classification problem
--
classes = {'airplane', 'automobile', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}
print(opt.network)
model=torch.load(opt.network)
-- retrieve parameters and gradients
parameters,gradParameters = model:getParameters()
-- verbose
print('<cifar> using model:')
print(model)
----------------------------------------------------------------------
-- loss function: negative log-likelihood
--
model:add(nn.LogSoftMax())
criterion = nn.ClassNLLCriterion()
----------------------------------------------------------------------
-- get/create dataset
--
if opt.full then
tesize = 10000
else
tesize = 1000
end
-- download dataset
if not paths.dirp('cifar-10-batches-t7') then
local www = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/cifar-10-torch.tar.gz'
local tar = paths.basename(www)
os.execute('wget ' .. www .. '; '.. 'tar xvf ' .. tar)
end
-- load dataset
subset = torch.load('cifar-10-batches-t7/test_batch.t7', 'ascii')
testData = {
data = subset.data:t():double(),
labels = subset.labels[1]:double(),
size = function() return tesize end
}
testData.labels = testData.labels + 1
-- resize dataset (if using small version)
testData.data = testData.data[{ {1,tesize} }]
testData.labels = testData.labels[{ {1,tesize} }]
-- reshape data
testData.data = testData.data:reshape(tesize,3,32,32)
----------------------------------------------------------------------
-- preprocess/normalize train/test sets
--
print '<trainer> preprocessing data (color space + normalization)'
-- preprocess trainSet
normalization = nn.SpatialContrastiveNormalization(1, image.gaussian1D(7))
-- preprocess testSet
for i = 1,testData:size() do
-- rgb -> yuv
local rgb = testData.data[i]
local yuv = image.rgb2yuv(rgb)
-- normalize y locally:
yuv[{1}] = normalization(yuv[{{1}}])
testData.data[i] = yuv
end
mean_u=torch.load('mean_u')
mean_v=torch.load('mean_v')
std_u=torch.load('std_u')
std_v=torch.load('std_v')
-- normalize u globally:
testData.data[{ {},2,{},{} }]:add(-mean_u)
testData.data[{ {},2,{},{} }]:div(-std_u)
-- normalize v globally:
testData.data[{ {},3,{},{} }]:add(-mean_v)
testData.data[{ {},3,{},{} }]:div(-std_v)
----------------------------------------------------------------------
-- define training and testing functions
--
-- this matrix records the current confusion across classes
confusion = optim.ConfusionMatrix(classes)
-- log results to files
testLogger = optim.Logger(paths.concat(opt.save, 'test.log'))
-- display function
function display(input)
iter = iter or 0
require 'image'
win_input = image.display{image=input, win=win_input, zoom=2, legend='input'}
if iter%10 == 0 then
if opt.model == 'convnet' then
win_w1 = image.display{image=model:get(2).weight, zoom=4, nrow=10,
min=-1, max=1,
win=win_w1, legend='stage 1: weights', padding=1}
win_w2 = image.display{image=model:get(6).weight, zoom=4, nrow=30,
min=-1, max=1,
win=win_w2, legend='stage 2: weights', padding=1}
elseif opt.model == 'mlp' then
local W1 = torch.Tensor(model:get(2).weight):resize(2048,1024)
win_w1 = image.display{image=W1, zoom=0.5,
min=-1, max=1,
win=win_w1, legend='W1 weights'}
local W2 = torch.Tensor(model:get(2).weight):resize(10,2048)
win_w2 = image.display{image=W2, zoom=0.5,
min=-1, max=1,
win=win_w2, legend='W2 weights'}
end
end
iter = iter + 1
end
-- test function
function test(dataset)
-- local vars
local time = sys.clock()
-- averaged param use?
if average then
cachedparams = parameters:clone()
parameters:copy(average)
end
-- test over given dataset
print('<trainer> on testing Set:')
for t = 1,dataset:size() do
-- disp progress
xlua.progress(t, dataset:size())
-- get new sample
local input = dataset.data[t]
local target = dataset.labels[t]
-- test sample
local pred = model:forward(input)
confusion:add(pred, target)
end
-- timing
time = sys.clock() - time
time = time / dataset:size()
print("<trainer> time to test 1 sample = " .. (time*1000) .. 'ms')
-- print confusion matrix
print(confusion)
testLogger:add{['% mean class accuracy (test set)'] = confusion.totalValid * 100}
confusion:zero()
-- averaged param use?
if average then
-- restore parameters
parameters:copy(cachedparams)
end
end
----------------------------------------------------------------------
-- and test!
--
-- train/test
test(testData)
-- plot errors
testLogger:style{['% mean class accuracy (test set)'] = '-'}
testLogger:plot()
| bsd-3-clause |
nasomi/darkstar | scripts/globals/items/apple_pie.lua | 34 | 1279 | -----------------------------------------
-- ID: 4413
-- Item: Apple Pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 25
-- Agility -1
-- Intelligence 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,4413);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 25);
target:addMod(MOD_AGI,-1);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 25);
target:delMod(MOD_AGI,-1);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
mkjanke/Focus-Points | focuspoints.lrdevplugin/ExifUtils.lua | 3 | 4542 | --[[
Copyright 2016 Whizzbang Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local LrTasks = import 'LrTasks'
local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'
local LrStringUtils = import "LrStringUtils"
local LrSystemInfo = import "LrSystemInfo"
local LrUUID = import "LrUUID"
ExifUtils = {}
exiftool = LrPathUtils.child( _PLUGIN.path, "bin" )
exiftool = LrPathUtils.child(exiftool, "exiftool")
exiftool = LrPathUtils.child(exiftool, "exiftool")
exiftoolWindows = LrPathUtils.child( _PLUGIN.path, "bin" )
exiftoolWindows = LrPathUtils.child(exiftoolWindows, "exiftool.exe")
--[[
-- BEGIN MOD.156 - Add Metadata filter
-- metaDataFile needs to be a global variable that can be accessed from metaDataDialog
--]]
metaDataFile = LrPathUtils.child(LrPathUtils.getStandardFilePath("temp"), LrUUID.generateUUID() .. ".txt")
function ExifUtils.getMetaDataFile()
return metaDataFile
end
-- END MOD.156 - Add Metadata filter
function ExifUtils.getExifCmd(targetPhoto)
local path = targetPhoto:getRawMetadata("path")
--[[MOD.156 - Add Metadata filter
local metaDataFile = LrPathUtils.child(LrPathUtils.getStandardFilePath("temp"), LrUUID.generateUUID() .. ".txt")
--]]
local singleQuoteWrap = '\'"\'"\''
local cmd
if (WIN_ENV) then
-- windows needs " around the entire command and then " around each path
-- example: ""C:\Users\Joshua\Desktop\Focus Points\focuspoints.lrdevplugin\bin\exiftool.exe" -a -u -sort "C:\Users\Joshua\Desktop\DSC_4636.NEF" > "C:\Users\Joshua\Desktop\DSC_4636-metadata.txt""
cmd = '""' .. exiftoolWindows .. '" -a -u -sort ' .. '"'.. path .. '" > "' .. metaDataFile .. '""';
else
exiftool = string.gsub(exiftool, "'", singleQuoteWrap)
path = string.gsub(path, "'", singleQuoteWrap)
cmd = "'".. exiftool .. "' -a -u -sort '" .. path .. "' > '" .. metaDataFile .. "'";
end
logDebug("ExifUtils", "Exif cmd: " .. cmd)
return cmd, metaDataFile
end
function ExifUtils.readMetaData(targetPhoto)
local cmd, metaDataFile = ExifUtils.getExifCmd(targetPhoto)
LrTasks.execute(cmd)
local fileInfo = LrFileUtils.readFile(metaDataFile)
--LrFileUtils.delete(metaDataFile)
return fileInfo
end
--[[
-- Transforms the output of ExifUtils.readMetaData and returns a key/value lua Table
-- targetPhoto - LrPhoto to extract the Exif from
--]]
function ExifUtils.readMetaDataAsTable(targetPhoto)
local metaData = ExifUtils.readMetaData(targetPhoto)
if metaData == nil then
return nil
end
local parsedTable = {}
for keyword, value in string.gmatch(metaData, "([^\:]+)\:([^\r\n]*)\r?\n") do
keyword = LrStringUtils.trimWhitespace(keyword)
value = LrStringUtils.trimWhitespace(value)
parsedTable[keyword] = value
logDebug("ExifUtils", "Parsed '" .. keyword .. "' = '" .. value .. "'")
end
return parsedTable
end
--[[
-- Returns the first value of "keys" that could be found within the metaDataTable table
-- Ignores nil and "(none)" as valid values
-- metaDataTable - the medaData key/value table
-- keys - the keys to be search for in order of importance
-- return 1. value of the first key match, 2. which key was used
--]]
function ExifUtils.findFirstMatchingValue(metaDataTable, keys)
local exifValue = nil
for key, value in pairs(keys) do -- value in the keys table is the current exif keyword to be searched
exifValue = metaDataTable[value]
if exifValue ~= nil and exifValue ~= "(none)" then
logInfo("ExifUtils", "Searching for " .. value .. " -> " .. exifValue)
return exifValue, key
end
end
logInfo("ExifUtils", "Searching for { " .. table.concat(keys, " ") .. " } returned nothing")
return nil
end
function ExifUtils.filterInput(str)
local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=-\\[\\]~`]", "?");
-- FIXME: doesn't strip - or ] correctly
--local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=\\-\\[\\\n\\\t~`-]", "?");
return result
end
| apache-2.0 |
shangjiyu/luci-with-extra | applications/luci-app-ntpc/luasrc/model/cbi/ntpc/ntpc.lua | 78 | 1289 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("ntpclient", translate("Time Synchronisation"), translate("Synchronizes the system time"))
s = m:section(TypedSection, "ntpclient", translate("General"))
s.anonymous = true
s.addremove = false
s:option(DummyValue, "_time", translate("Current system time")).value = os.date("%c")
interval = s:option(Value, "interval", translate("Update interval (in seconds)"))
interval.datatype = "and(uinteger,min(1))"
interval.rmempty = true
count = s:option(Value, "count", translate("Count of time measurements"), translate("empty = infinite"))
count.datatype = "and(uinteger,min(1))"
count.rmempty = true
s2 = m:section(TypedSection, "ntpdrift", translate("Clock Adjustment"))
s2.anonymous = true
s2.addremove = false
freq = s2:option(Value, "freq", translate("Offset frequency"))
freq.datatype = "integer"
freq.rmempty = true
s3 = m:section(TypedSection, "ntpserver", translate("Time Servers"))
s3.anonymous = true
s3.addremove = true
s3.template = "cbi/tblsection"
s3:option(Value, "hostname", translate("Hostname"))
port = s3:option(Value, "port", translate("Port"))
port.datatype = "port"
port.rmempty = true
return m
| apache-2.0 |
mahdi1378/FBI | plugins/owners.lua | 1467 | 12478 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
Maliv/SecretBot | plugins/owners.lua | 1467 | 12478 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
amirhoseinhastam1/1 | plugins/owners.lua | 1467 | 12478 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
nasomi/darkstar | scripts/globals/spells/paralyga.lua | 18 | 1691 | -----------------------------------------
-- Spell: Paralyze
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_PARALYSIS)) then --effect already on, do nothing
spell:setMsg(75);
else
-- Calculate duration.
local duration = math.random(20,120);
-- Grabbing variables for paralyze potency
local pMND = caster:getStat(MOD_MND);
local mMND = target:getStat(MOD_MND);
local dMND = (pMND - mMND);
-- Calculate potency.
local potency = (pMND + dMND)/5; --simplified from (2 * (pMND + dMND)) / 10
if potency > 30 then
potency = 30;
end
--printf("Duration : %u",duration);
--printf("Potency : %u",potency);
local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_PARALYSIS);
if (resist >= 0.5) then --there are no quarter or less hits, if target resists more than .5 spell is resisted completely
if (target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then
spell:setMsg(236);
else
-- no effect
spell:setMsg(75);
end
else
-- resist
spell:setMsg(85);
end
end
return EFFECT_PARALYSIS;
end;
| gpl-3.0 |
dageq/Dage-Aliraqi | plugins/ar-Dage_Aliraqi3.lua | 1 | 1088 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY Dage Aliraqi ▀▄ ▄▀
▀▄ ▄▀ BY Dage Aliraqi (@dageq) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY Dage Aliraqi ▀▄ ▄▀
▀▄ ▄▀ dev1 : dev ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
function run(msg, matches)
return [[
االبوت الذي يعمل على مجوعات السوبر 🔸
يعمل البوت على مجموعات سوبر تصل الى5k عضو 🔷
≪تم صنع البوت بواسطة المطور≫
『 @dageq 』
🔹#Dev #Dage_Aliraqi🔹
]]
end
return {
description = "Shows bot q",
usage = "spam Shows bot q",
patterns = {
"^(dev)$",
},
run = run
}
end
| gpl-2.0 |
mkjanke/Focus-Points | focuspoints.lrdevplugin/PentaxDelegates.lua | 5 | 7426 | --[[
Copyright 2016 Whizzbang Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
A collection of delegate functions to be passed into the DefaultPointRenderer
for Pentax cameras.
**Note:
Unlike other point delegates, this point delegates shows all in-active focus points. I'm
not sure what the means for the other delegates. Perhaps I'll update them. Perhaps I'll update this file.
Notes:
* Back focus button sets AFPointsInFocus to 'None' regardless of point
selection mode (sucks). AFPointSelected is set correctly with either button.
* For phase detection AF, the coordinates taken from the point map represent
the center of each AF point.
2017.03.29 - roguephysicist: works for Pentax K-50 with both phase and contrast detection
--]]
local LrStringUtils = import "LrStringUtils"
local LrErrors = import 'LrErrors'
require "Utils"
PentaxDelegates = {}
PentaxDelegates.focusPointsMap = nil
PentaxDelegates.focusPointDimen = nil
function PentaxDelegates.getAfPoints(photo, metaData)
local focusMode = ExifUtils.findFirstMatchingValue(metaData, { "Focus Mode" })
focusMode = splitTrim(focusMode, " ")
local result = nil
if focusMode[1] == "AF-A" or focusMode[1] == "AF-C" or focusMode[1] == "AF-S" then
result = PentaxDelegates.getAfPointsPhase(photo, metaData)
elseif focusMode[1] == "Contrast-detect" then
result = PentaxDelegates.getAfPointsContrast(photo, metaData)
elseif focusMode[1] == "Manual" then
LrErrors.throwUserError("Manual focus: no useful focusing information found.")
else
LrErrors.throwUserError("Could not determine the focus mode of the camera.")
end
return result
end
--[[
-- photo - the photo LR object
-- metaData - the metadata as read by exiftool
--]]
function PentaxDelegates.getAfPointsPhase(photo, metaData)
local afPointsSelected = ExifUtils.findFirstMatchingValue(metaData, { "AF Point Selected" })
if afPointsSelected == nil then
afPointsSelected = {}
else
afPointsSelected = splitTrim(afPointsSelected, ";") -- pentax separates with ';'
afPointsSelected = PentaxDelegates.fixCenter(afPointsSelected)
end
local afPointsInFocus = ExifUtils.findFirstMatchingValue(metaData, { "AF Points In Focus" })
if afPointsInFocus == nil then
afPointsInFocus = {}
else
afPointsInFocus = splitTrim(afPointsInFocus, ",")
afPointsInFocus = PentaxDelegates.fixCenter(afPointsInFocus)
end
local result = {
pointTemplates = DefaultDelegates.pointTemplates,
points = {}
}
for key,value in pairs(PentaxDelegates.focusPointsMap) do
local pointsMap = PentaxDelegates.focusPointsMap[key]
local x = pointsMap[1]
local y = pointsMap[2]
local width
local height
if (#pointsMap > 2) then
width = pointsMap[3]
height = pointsMap[4]
else
width = PentaxDelegates.focusPointDimen[1]
height = PentaxDelegates.focusPointDimen[2]
end
local pointType = DefaultDelegates.POINTTYPE_AF_INACTIVE
local isInFocus = arrayKeyOf(afPointsInFocus, key) ~= nil
local isSelected = arrayKeyOf(afPointsSelected, key) ~= nil
if isInFocus and isSelected then
pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS
elseif isInFocus then
pointType = DefaultDelegates.POINTTYPE_AF_INFOCUS
elseif isSelected then
pointType = DefaultDelegates.POINTTYPE_AF_SELECTED
end
table.insert(result.points, {
pointType = pointType,
x = x,
y = y,
width = width,
height = height
})
end
return result
end
--[[
Function to get the autofocus points and focus size of the camera when shot in
liveview mode returns typical points table
--]]
function PentaxDelegates.getAfPointsContrast(photo, metaData)
local imageSize = ExifUtils.findFirstMatchingValue(metaData, { "Default Crop Size" })
imageSize = splitTrim(imageSize, " ")
-- Can image size be obtained from lightroom directly? Or is accessing the metadata faster?
local result = {
pointTemplates = DefaultDelegates.pointTemplates,
points = {}
}
local contrastAfMode = ExifUtils.findFirstMatchingValue(metaData, { "AF Point Selected" })
contrastAfMode = splitTrim(contrastAfMode, ";") -- pentax separates with ';'
local faceDetectSize = ExifUtils.findFirstMatchingValue(metaData, { "Face Detect Frame Size" })
faceDetectSize = splitTrim(faceDetectSize, " ")
local facesDetected = ExifUtils.findFirstMatchingValue(metaData, { "Faces Detected" })
facesDetected = tonumber(facesDetected)
if (contrastAfMode[1] == "Face Detect AF" and facesDetected > 0) then
local faces = {}
for face=1,facesDetected do
local facePosition = ExifUtils.findFirstMatchingValue(metaData, { "Face " .. face .. " Position" })
facePosition = splitTrim(facePosition, " ")
local faceSize = ExifUtils.findFirstMatchingValue(metaData, { "Face " .. face .. " Size" })
faceSize = splitTrim(faceSize, " ")
faces[face] = {facePosition, faceSize}
local afAreaXPosition = faces[face][1][1]*imageSize[1]/faceDetectSize[1]
local afAreaYPosition = faces[face][1][2]*imageSize[2]/faceDetectSize[2]
local afAreaWidth = faces[face][2][1]*imageSize[1]/faceDetectSize[1]
local afAreaHeight = faces[face][2][2]*imageSize[2]/faceDetectSize[2]
if afAreaWidth > 0 and afAreaHeight > 0 then
table.insert(result.points, {
pointType = DefaultDelegates.POINTTYPE_FACE,
x = afAreaXPosition,
y = afAreaYPosition,
width = afAreaWidth,
height = afAreaHeight
})
end
end
elseif (contrastAfMode[1] == "Face Detect AF" and facesDetected == 0) then
LrErrors.throwUserError("Face Detect AF mode enabled, but no faces detected.")
else -- 'Automatic Tracking AF', 'Fixed Center', 'AF Select'
local contrastDetectArea = ExifUtils.findFirstMatchingValue(metaData, { "Contrast Detect AF Area" })
contrastDetectArea = splitTrim(contrastDetectArea, " ")
local afAreaXPosition = (contrastDetectArea[1]+0.5*contrastDetectArea[3])*imageSize[1]/faceDetectSize[1]
local afAreaYPosition = (contrastDetectArea[2]+0.5*contrastDetectArea[4])*imageSize[2]/faceDetectSize[2]
local afAreaWidth = contrastDetectArea[3]*imageSize[1]/faceDetectSize[1]
local afAreaHeight = contrastDetectArea[4]*imageSize[2]/faceDetectSize[2]
if afAreaWidth > 0 and afAreaHeight > 0 then
table.insert(result.points, {
pointType = DefaultDelegates.POINTTYPE_FACE,
x = afAreaXPosition,
y = afAreaYPosition,
width = afAreaWidth,
height = afAreaHeight
})
end
end
return result
end
function PentaxDelegates.fixCenter(points)
for k,v in pairs(points) do
if v == 'Center (vertical)' or v == 'Center (horizontal)' or v == 'Fixed Center' then
points[k] = 'Center'
end
end
return points
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/Grounds_Tome.lua | 34 | 1155 | -----------------------------------
-- Area: The Eldieme Necropolis
-- 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_ELDIEME_NECROPOLIS,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,671,672,673,674,675,676,678,679,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,671,672,673,674,675,676,678,679,0,0,GOV_MSG_ELDIEME_NECROPOLIS);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Southern_San_dOria/npcs/HomePoint#2.lua | 17 | 1260 | -----------------------------------
-- Area: Southern San dOria
-- NPC: HomePoint#2
-- @pos 45 2 -35 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
ngeiswei/ardour | share/scripts/voice_activate.lua | 3 | 1681 | ardour {
["type"] = "dsp",
name = "Voice/Level Activate",
category = "Utility",
author = "Ardour Team",
license = "MIT",
description = [[Roll the transport when the signal level on the plugin's input exceeds a given threshold.]]
}
function dsp_ioconfig ()
return
{
-- support all in/out as long as input port count equals output port count
{ audio_in = -1, audio_out = -1},
}
end
function dsp_params ()
return
{
{ ["type"] = "input", name = "Threshold", min = -20, max = 0, default = -6, doc = "Threshold in dBFS for all channels" },
{ ["type"] = "output", name = "Level", min = -120, max = 0 },
}
end
function dsp_configure (ins, outs)
n_channels = ins:n_audio()
end
function dsp_runmap (bufs, in_map, out_map, n_samples, offset)
local ctrl = CtrlPorts:array() -- get control port array (read/write)
if Session:transport_rolling() then
-- don't do anything if the transport is already rolling
ctrl[2] = -math.huge -- set control output port value
return
end
local threshold = 10 ^ (.05 * ctrl[1]) -- dBFS to coefficient
local level = -math.huge
for c = 1,n_channels do
local b = in_map:get(ARDOUR.DataType("audio"), c - 1) -- get id of audio-buffer for the given channel
if b ~= ARDOUR.ChanMapping.Invalid then -- check if channel is mapped
local a = ARDOUR.DSP.compute_peak(bufs:get_audio(b):data(offset), n_samples, 0) -- compute digital peak
if a > threshold then
Session:request_roll (ARDOUR.TransportRequestSource.TRS_UI)
end
if a > level then level = a end -- max level of all channels
end
end
ctrl[2] = ARDOUR.DSP.accurate_coefficient_to_dB (level) -- set control output port value
end
| gpl-2.0 |
shangjiyu/luci-with-extra | applications/luci-app-xware3/luasrc/model/cbi/xware3.lua | 4 | 3692 | local fs = require "nixio.fs"
local util = require "nixio.util"
local running=(luci.sys.call("pidof etm_xware > /dev/null") == 0)
local button=""
local xunleiinfo=""
local tblXLInfo={}
local detailInfo = "迅雷远程下载尚未运行。"
if running then
xunleiinfo = luci.sys.exec("wget http://localhost:19000/getsysinfo -qO-")
button = " " .. translate("运行状态:") .. xunleiinfo
m = Map("xware3", translate("Xware3"), translate("迅雷远程下载 正在运行...") .. button)
string.gsub(string.sub(xunleiinfo, 2, -2),'[^,]+',function(w) table.insert(tblXLInfo, w) end)
detailInfo = [[<p>启动信息:]] .. xunleiinfo .. [[</p>]]
if tonumber(tblXLInfo[1]) == 0 then
detailInfo = detailInfo .. [[<p>状态正常</p>]]
else
detailInfo = detailInfo .. [[<p style="color:red">执行异常</p>]]
end
if tonumber(tblXLInfo[2]) == 0 then
detailInfo = detailInfo .. [[<p style="color:red">网络异常</p>]]
else
detailInfo = detailInfo .. [[<p>网络正常</p>]]
end
if tonumber(tblXLInfo[4]) == 0 then
detailInfo = detailInfo .. [[<p>未绑定]].. [[ 激活码:]].. tblXLInfo[5] ..[[</p>]]
else
detailInfo = detailInfo .. [[<p>已绑定</p>]]
end
if tonumber(tblXLInfo[6]) == 0 then
detailInfo = detailInfo .. [[<p style="color:red">磁盘挂载检测失败</p>]]
else
detailInfo = detailInfo .. [[<p>磁盘挂载检测成功</p>]]
end
else
m = Map("xware3", "Xware3", "[迅雷远程下载 尚未启动]")
end
-----------
--Xware--
-----------
s = m:section(TypedSection, "xware3_general","Xware基本设置")
s.anonymous = true
s:option(Flag, "enabled", "启用 迅雷远程下载")
if not nixio.fs.access("/usr/bin/etm_xware") then
s:option(Value, "prog_path", "Xware3主程序路径", "<br />Xware3主程序所在路径,例如:/mnt/sda1/xware3。请确认已经将Xware3的主程序etm_xware复制到该目录下。")
end
s:option(Value, "etm_license", "Xware3 License", "<br />获取方式:打开下载的Xware3主程序中的xware_bash.sh,搜索set_etm_license,把函数中ETM_LICENSE=之后的引号中的内容贴在这里。")
if running then
s:option(DummyValue,"opennewwindow" ,"<br /><p align=\"justify\"><script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"获取启动信息\" onclick=\"window.open('http://'+window.location.host+':19000/getsysinfo')\" /></p>", detailInfo)
s:option(DummyValue,"opennewwindow" ,"<br /><p align=\"justify\"><script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"迅雷远程下载页面\" onclick=\"window.open('http://yuancheng.xunlei.com')\" /></p>", "将激活码填进网页即可绑定。")
end
s = m:section(TypedSection, "xware3_mount","Xware挂载点","请在此设置Xware3接受的挂载点前缀。例如设置为'/mnt/'将接受所有以'/mnt/'开头的挂载点。")
s.anonymous = true
s:option(DynamicList, "available_mounts", "挂载点前缀")
s = m:section(TypedSection, "xware3_mount","Xware配置文件","编辑Xware3配置文件")
s.anonymous = true
editconf = s:option(Value, "_editconf", "")
editconf.template = "cbi/tvalue"
editconf.rows = 20
editconf.wrap = "off"
function editconf.cfgvalue(self, section)
return fs.readfile("/etc/xware3.ini") or ""
end
function editconf.write(self, section, value3)
if value3 then
value3 = value3:gsub("\r\n?", "\n")
fs.writefile("/tmp/xware_cfg_tmp", value3)
if (luci.sys.call("cmp -s /tmp/xware_cfg_tmp /etc/xware3.ini") == 1) then
fs.writefile("/etc/xware3.ini", value3)
end
fs.remove("/tmp/xware_cfg_tmp")
end
end
return m
| apache-2.0 |
akornatskyy/lucid | spec/core/pretty_spec.lua | 1 | 1731 | local pretty = require 'core.pretty'
describe('core.pretty', function()
local dump = pretty.dump
it('dump nil', function()
assert.equals('nil', dump())
end)
it('dump default', function()
local cases = {
['1'] = 1,
['"a"'] = 'a',
['true'] = true,
['"<function>"'] = function() end,
['{}'] = {},
['{{}}'] = {{}},
['{1, 2}'] = {1, 2},
['{"a", "b"}'] = {'a', 'b'},
['{1, 2, ["a"] = 1, ["b"] = 2}'] = {1, 2, a=1, b=2},
['{["a"] = {["x"] = 1, ["y"] = 2}, ["b"] = 2}'] = {a={x=1, y=2}, b=2},
}
for expected, obj in next, cases do
assert.equals(expected, dump(obj))
end
end)
it('dump compact', function()
local cases = {
['{1, 2}'] = {1, 2},
['{1, 2, ["a"]=1, ["b"]=2}'] = {1, 2, a=1, b=2}
}
for expected, obj in next, cases do
assert.equals(expected, dump(obj, pretty.spaces.compact))
end
end)
it('dump indented', function()
local cases = {
['{\n 1,\n 2\n}'] = {1, 2},
['{\n 1,\n ["a"] = 1\n}'] = {1, a=1},
['{\n ["a"] = {\n ["x"] = 1\n }\n}'] = {a={x=1}}
}
for expected, obj in next, cases do
assert.equals(expected, dump(obj, pretty.spaces.indented))
end
end)
it('dump min', function()
local cases = {
['{1,2}'] = {1, 2},
['{1,2,["a"]=1,["b"]=2}'] = {1, 2, a=1, b=2}
}
for expected, obj in next, cases do
assert.equals(expected, dump(obj, pretty.spaces.min))
end
end)
end)
| mit |
shangjiyu/luci-with-extra | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/email.lua | 73 | 1673 | -- 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("E-Mail Plugin Configuration"),
translate(
"The email plugin creates a unix socket which can be used " ..
"to transmit email-statistics to a running collectd daemon. " ..
"This plugin is primarily intended to be used in conjunction " ..
"with Mail::SpamAssasin::Plugin::Collectd but can be used in " ..
"other ways as well."
))
-- collectd_email config section
s = m:section( NamedSection, "collectd_email", "luci_statistics" )
-- collectd_email.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_email.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile", translate("Socket file") )
socketfile.default = "/var/run/collect-email.sock"
socketfile:depends( "enable", 1 )
-- collectd_email.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup", translate("Socket group") )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_email.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
-- collectd_email.maxconns (MaxConns)
maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") )
maxconns.default = 5
maxconns.isinteger = true
maxconns.rmempty = true
maxconns.optional = true
maxconns:depends( "enable", 1 )
return m
| apache-2.0 |
mrfoxirani/mehran | plugins/translate.lua | 674 | 1637 |
--[[
-- Translate text using Google Translate.
-- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello
--]]
do
function translate(source_lang, target_lang, text)
local path = "http://translate.google.com/translate_a/single"
-- URL query parameters
local params = {
client = "t",
ie = "UTF-8",
oe = "UTF-8",
hl = "en",
dt = "t",
tl = target_lang or "en",
sl = source_lang or "auto",
text = URL.escape(text)
}
local query = format_http_params(params, true)
local url = path..query
local res, code = https.request(url)
-- Return nil if error
if code > 200 then return nil end
local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
return trans
end
function run(msg, matches)
-- Third pattern
if #matches == 1 then
print("First")
local text = matches[1]
return translate(nil, nil, text)
end
-- Second pattern
if #matches == 2 then
print("Second")
local target = matches[1]
local text = matches[2]
return translate(nil, target, text)
end
-- First pattern
if #matches == 3 then
print("Third")
local source = matches[1]
local target = matches[2]
local text = matches[3]
return translate(source, target, text)
end
end
return {
description = "Translate some text",
usage = {
"!translate text. Translate the text to English.",
"!translate target_lang text.",
"!translate source,target text",
},
patterns = {
"^!translate ([%w]+),([%a]+) (.+)",
"^!translate ([%w]+) (.+)",
"^!translate (.+)",
},
run = run
}
end
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Norg/Zone.lua | 17 | 2315 | -----------------------------------
--
-- Zone: Norg (252)
--
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
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(-19.238,-2.163,-63.964,187);
end
if (player:getCurrentMission(ZILART) == THE_NEW_FRONTIER) then
cs = 0x0001;
elseif (player:getCurrentMission(ZILART) == AWAKENING and player:getVar("ZilartStatus") == 0 or player:getVar("ZilartStatus") == 2) then
cs = 0x00B0;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0001) then
if (player:hasKeyItem(MAP_OF_NORG) == false) then
player:addKeyItem(MAP_OF_NORG);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_NORG);
end
player:completeMission(ZILART,THE_NEW_FRONTIER);
player:addMission(ZILART,WELCOME_TNORG);
elseif (csid == 0x00B0) then
player:setVar("ZilartStatus", player:getVar("ZilartStatus")+1);
end
end; | gpl-3.0 |
thesabbir/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk/dialzones.lua | 68 | 3276 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
local uci = require("luci.model.uci").cursor()
--[[
Dialzone overview table
]]
if not arg[1] then
zonemap = Map("asterisk", "Dial Zones", [[
Dial zones hold patterns of dialed numbers to match.
Each zone has one or more trunks assigned. If the first trunk is
congested, Asterisk will try to use the next available connection.
If all trunks fail, then the following zones in the parent dialplan
are tried.
]])
local zones, znames = ast.dialzone.zones()
zonetbl = zonemap:section(Table, zones, "Zone Overview")
zonetbl.sectionhead = "Zone"
zonetbl.addremove = true
zonetbl.anonymous = false
zonetbl.extedit = luci.dispatcher.build_url(
"admin", "asterisk", "dialplans", "zones", "%s"
)
function zonetbl.cfgsections(self)
return znames
end
function zonetbl.parse(self)
for k, v in pairs(self.map:formvaluetable(
luci.cbi.REMOVE_PREFIX .. self.config
) or {}) do
if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end
uci:delete("asterisk", k)
uci:save("asterisk")
self.data[k] = nil
for i = 1,#znames do
if znames[i] == k then
table.remove(znames, i)
break
end
end
end
Table.parse(self)
end
zonetbl:option(DummyValue, "description", "Description")
zonetbl:option(DummyValue, "addprefix")
match = zonetbl:option(DummyValue, "matches")
function match.cfgvalue(self, s)
return table.concat(zones[s].matches, ", ")
end
trunks = zonetbl:option(DummyValue, "trunk")
trunks.template = "asterisk/cbi/cell"
function trunks.cfgvalue(self, s)
return ast.tools.hyperlinks(zones[s].trunks)
end
return zonemap
--[[
Zone edit form
]]
else
zoneedit = Map("asterisk", "Edit Dialzone")
entry = zoneedit:section(NamedSection, arg[1])
entry.title = "Zone %q" % arg[1];
back = entry:option(DummyValue, "_overview", "Back to dialzone overview")
back.value = ""
back.titleref = luci.dispatcher.build_url(
"admin", "asterisk", "dialplans", "zones"
)
desc = entry:option(Value, "description", "Description")
function desc.cfgvalue(self, s, ...)
return Value.cfgvalue(self, s, ...) or s
end
trunks = entry:option(MultiValue, "uses", "Used trunks")
trunks.widget = "checkbox"
uci:foreach("asterisk", "sip",
function(s)
if s.provider == "yes" then
trunks:value(
"SIP/%s" % s['.name'],
"SIP/%s (%s)" %{ s['.name'], s.host or 'n/a' }
)
end
end)
match = entry:option(DynamicList, "match", "Number matches")
intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)")
aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)")
ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)")
lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers")
lzone:value("", "no special treatment of local numbers")
for _, z in ipairs(ast.dialzone.zones()) do
lzone:value(z.name, "%q (%s)" %{ z.name, z.description })
end
--for _, v in ipairs(find_outgoing_contexts(zoneedit.uci)) do
-- lzone:value(unpack(v))
--end
lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)")
return zoneedit
end
| apache-2.0 |
Honsal/hszs_deathstreak | lua/zs_deathstreak/init.lua | 1 | 12676 | local DS_DMGUP = "dsDmgUp"
local DS_ARMORUP = "dsArmorUp"
local DS_SPEEDUP = "dsSpeedUp"
local DS_ATK_SPEEDUP = "dsAtkSpeedUp"
local DS_HEALTHUP = "dsHealthUp"
local DS_LIMIT_BARRICADEDAMAGE = 300
local DS_LIMIT_DAMAGE = 120
-- local DS_LIMIT_DISTANCE = 3600
ZombieClassTable = ZombieClassTable or {}
local DeathStreakEffect = function(name, value)
return {name, value}
end
local DSE = DeathStreakEffect
G_DSE = DSE
local InsertEffect = function(pl, dse)
for i, v in pairs(pl.zs_deathstreak.effect) do
if !istable(v) or table.Count(v) == 0 then
continue
end
if v[1] == dse[1] then
pl.zs_deathstreak.effect[i][2] = dse[2]
return
end
end
table.insert(pl.zs_deathstreak.effect, dse)
end
G_InsEft = InsertEffect
local AddEffect = function(pl)
local count = pl.zs_deathstreak.count
-- PrintMessage(3, "DTSCount: " .. count)
if count == 3 then
InsertEffect(pl, DSE(DS_DMGUP, 0.15))
elseif count == 5 then
InsertEffect(pl, DSE(DS_DMGUP, 0.25))
InsertEffect(pl, DSE(DS_ARMORUP, 1))
elseif count == 7 then
InsertEffect(pl, DSE(DS_DMGUP, 0.50))
InsertEffect(pl, DSE(DS_ARMORUP, 2))
InsertEffect(pl, DSE(DS_SPEEDUP, 0.15))
elseif count == 9 then
InsertEffect(pl, DSE(DS_ARMORUP, 4))
InsertEffect(pl, DSE(DS_SPEEDUP, 0.25))
InsertEffect(pl, DSE(DS_ATK_SPEEDUP, 0.10))
InsertEffect(pl, DSE(DS_HEALTHUP, 0.10))
elseif count == 11 then
InsertEffect(pl, DSE(DS_ATK_SPEEDUP, 0.25))
InsertEffect(pl, DSE(DS_HEALTHUP, 0.20))
elseif count == 13 then
InsertEffect(pl, DSE(DS_ARMORUP, 6))
InsertEffect(pl, DSE(DS_HEALTHUP, 0.55))
elseif count == 15 then
InsertEffect(pl, DSE(DS_DMGUP, 0.75))
InsertEffect(pl, DSE(DS_ARMORUP, 8))
InsertEffect(pl, DSE(DS_SPEEDUP, 0.45))
InsertEffect(pl, DSE(DS_ATK_SPEEDUP, 0.40))
InsertEffect(pl, DSE(DS_HEALTHUP, 0.60))
end
end
G_AddEffectZSDS = AddEffect
local SetWpnAtkSpd = function(wep, mul)
if wep.Primary and wep.Primary.Delay then
wep.Primary.Delay = wep.Primary.Delay * mul
end
if wep.Secondary and wep.Secondary.Delay then
wep.Secondary.Delay = wep.Secondary.Delay * mul
end
if wep.MeleeDelay then
wep.MeleeDelay = wep.MeleeDelay * mul
end
end
local ResetDeathStreak = function(pl)
if !pl.zs_deathstreak then
pl.zs_deathstreak = {}
pl.zs_deathstreak.count = 0
pl.zs_deathstreak.damage = 0
pl.zs_deathstreak.barricadeDamage =0
pl.zs_deathstreak.effect = {}
pl.zs_deathstreak.spawn = 0
else
pl.zs_deathstreak.count = 0
pl.zs_deathstreak.damage = 0
pl.zs_deathstreak.barricadeDamage = 0
pl.zs_deathstreak.effect = {}
pl.zs_deathstreak.spawn = 0
pl:ResetSpeed()
if pl:Team() == TEAM_ZOMBIE then
pl:GetZombieClassTable().Health = ZombieClassTable[pl:GetZombieClass()].Health
pl:SetMaxHealth(pl:GetZombieClassTable().Health)
end
local wep = pl:GetActiveWeapon()
if IsValid(wep) then
local stored = weapons.GetStored(wep:GetClass())
if istable(stored) then
if wep.Primary and wep.Primary.Delay then
wep.Primary.Delay = stored.Primary.Delay or weapons.GetStored(stored.Base).Primary.Delay
end
if wep.Secondary and wep.Secondary.Delay then
wep.Secondary.Delay = stored.Secondary.Delay or weapons.GetStored(stored.Base).Secondary.Delay
end
if wep.MeleeDelay then
wep.MeleeDelay = stored.MeleeDelay or weapons.GetStored(stored.Base).MeleeDelay
end
if wep.WalkSpeed then
wep.WalkSpeed = stored.WalkSpeed or weapons.GetStored(stored.Base).WalkSpeed
end
end
end
end
end
local ResetDeathstreak = ResetDeathStreak
local ResetDeathstreakAll = function()
if !ZombieClassTable or #ZombieClassTable == 0 then
ZombieClassTable = table.Copy(GAMEMODE.ZombieClasses)
else
local meta = FindMetaTable("Player")
GAMEMODE.ZombieClasses = table.Copy(ZombieClassTable)
local ZombieClasses = table.Copy(GAMEMODE.ZombieClasses)
meta.GetZombieClassTable = function(self)
return ZombieClasses[self:GetZombieClass()]
end
end
for _, v in pairs(player.GetAll()) do
ResetDeathStreak(v)
end
end
hook.Add("InitPostEntity", "zs_deathstreak.ResetDeathstreak", ResetDeathstreakAll)
hook.Add("RestartRound", "zs_deathstreak.ResetDeathstreak", ResetDeathstreakAll)
G_ResetDeathStreakAll = function()
if !ZombieClassTable or #ZombieClassTable == 0 then
ZombieClassTable = table.Copy(GAMEMODE.ZombieClasses)
else
local meta = FindMetaTable("Player")
GAMEMODE.ZombieClasses = table.Copy(ZombieClassTable)
local ZombieClasses = table.Copy(GAMEMODE.ZombieClasses)
meta.GetZombieClassTable = function(self)
return ZombieClasses[self:GetZombieClass()]
end
end
for _, v in pairs(player.GetAll()) do
ResetDeathStreak(v)
end
end
G_ResetDeathStreak = function(pl)
if pl.zs_deathstreak then
if pl.zs_deathstreak then
pl.zs_deathstreak = {}
pl.zs_deathstreak.count = 0
pl.zs_deathstreak.damage = 0
pl.zs_deathstreak.barricadeDamage = 0
pl.zs_deathstreak.effect = {}
pl.zs_deathstreak.spawn = 0
end
end
end
local ProcessDeathstreak = function(pl)
if !IsValid(pl) or !pl:IsPlayer() or pl:Team() ~= TEAM_UNDEAD then
return
end
if !pl.zs_deathstreak or (pl.zs_deathstreak.effect and !istable(pl.zs_deathstreak.effect)) or pl:GetZombieClassTable().Boss then
ResetDeathStreak(pl)
end
local count = pl.zs_deathstreak.count
local effect = pl.zs_deathstreak.effect
pl.zs_deathstreak.spawn = CurTime()
if pl.zs_deathstreak.count < 9 then
local mul = 1
local numundead = team.NumPlayers(TEAM_UNDEAD)
if GAMEMODE.OutnumberedHealthBonus >= numundead then
mul = 2
end
pl:GetZombieClassTable().Health = ZombieClassTable[pl:GetZombieClass()].Health * mul
end
for i, v in pairs(pl.zs_deathstreak.effect) do
if !istable(v) then
continue
end
local name, value = v[1], v[2]
if name == DS_SPEEDUP then
local mul = 1 + v[2]
local spd = pl:GetZombieClassTable().Speed
pl:SetSpeed(spd * mul)
local wep = pl:GetActiveWeapon()
if wep and IsValid(wep) then
if wep.WalkSpeed then
wep.WalkSpeed = wep.WalkSpeed * mul
end
end
elseif name == DS_ATK_SPEEDUP then
local mul = 1 - v[2]
local wep = pl:GetActiveWeapon()
if !wep or !IsValid(wep) then
timer.Simple(1, function()
if !wep or !IsValid(wep) then
SetWpnAtkSpd(wep, mul)
return
end
end)
else
SetWpnAtkSpd(wep, mul)
end
elseif name == DS_HEALTHUP then
local mul = 1 + v[2]
local numundead = team.NumPlayers(TEAM_UNDEAD)
if GAMEMODE.OutnumberedHealthBonus >= numundead then
mul = mul + 1
end
local originalHealth = ZombieClassTable[pl:GetZombieClass()].Health
pl:GetZombieClassTable().Health = originalHealth * mul
pl:SetMaxHealth(originalHealth * mul)
pl:SetHealth(pl:GetMaxHealth())
end
end
end
local PlayerDeathHandler = function(pl, attacker, inflictor, dmginfo, headshot, suicide)
if !pl.zs_deathstreak then
ResetDeathStreak(pl)
end
pl.zs_deathstreak.count = pl.zs_deathstreak.count + 1
AddEffect(pl)
end
hook.Add("HumanKilledZombie", "zs_deathstreak.PlayerDeathHandler", PlayerDeathHandler)
local ZombieKilledHuman = function(pl, attacker, inflictor, dmginfo, headshot, suicide)
if attacker.zs_deathstreak then
ResetDeathStreak(attacker)
end
end
hook.Add("ZombieKilledHuman", "zs_deathstreak.PlayerDeathHandler", ZombieKilledHuman)
local PlayerSpawnHandler = function(pl)
if !IsValid(pl) or !pl:IsPlayer() or pl:Team() ~= TEAM_ZOMBIE then
return
end
if pl.zs_deathstreak then
timer.Simple(1, function()
ProcessDeathstreak(pl)
end)
else
pl.zs_deathstreak = pl.zs_deathstreak or {}
pl.zs_deathstreak.count = pl.zs_deathstreak.count or 0
pl.zs_deathstreak.damage = pl.zs_deathstreak.damage or 0
pl.zs_deathstreak.barricadeDamage = pl.zs_deathstreak.barricadeDamage or 0
pl.zs_deathstreak.effect = pl.zs_deathstreak.effect or {}
end
end
hook.Add("PlayerSpawn", "zs_deathstreak.PlayerSpawnHandler", PlayerSpawnHandler)
local TakeDamageHandler = function(ent, dmginfo)
local attacker = dmginfo:GetAttacker()
if IsValid(ent) and !ent:IsPlayer() and ent:IsNailed() and IsValid(attacker) and attacker:IsPlayer() and attacker:Team() == TEAM_ZOMBIE then
attacker.zs_deathstreak.barricadeDamage = attacker.zs_deathstreak.barricadeDamage + dmginfo:GetDamage()
if attacker.zs_deathstreak.barricadeDamage >= DS_LIMIT_BARRICADEDAMAGE then
ResetDeathstreak(attacker)
end
end
if !IsValid(ent) or !ent:IsPlayer() or !IsValid(attacker) or !attacker:IsPlayer() then
return
end
if ent:Team() == TEAM_HUMAN and attacker:Team() == TEAM_ZOMBIE then
if attacker.zs_deathstreak.count > 0 then
local prevDmg = attacker.zs_deathstreak.damage or 0
attacker.zs_deathstreak.damage = prevDmg + (dmginfo:GetDamage() or 0)
if attacker.zs_deathstreak.damage >= DS_LIMIT_DAMAGE then
ResetDeathstreak(attacker)
end
end
if attacker.zs_deathstreak and attacker.zs_deathstreak.effect then
local ef = attacker.zs_deathstreak.effect
local dmgmul = 1
for i, v in pairs(ef) do
if istable(v) and v[1] == DS_DMGUP then
dmgmul = 1 + v[2]
end
end
dmginfo:ScaleDamage(dmgmul)
end
end
if ent:Team() == TEAM_ZOMBIE and attacker:Team() == TEAM_HUMAN then
if ent.zs_deathstreak then
if istable(ent.zs_deathstreak.effect) and table.Count(ent.zs_deathstreak.effect) > 0 then
local ef = ent.zs_deathstreak.effect
local minus = 0
for i, v in pairs(ef) do
if istable(v) and v[1] == DS_ARMORUP then
minus = v[2]
end
end
local infl = dmginfo:GetInflictor()
if infl:IsPlayer() then
infl = infl:GetActiveWeapon()
end
if infl and infl ~= NULL and IsValid(infl) then
if infl.ArmorThrough then
minus = math.max(0, minus - infl.ArmorThrough)
end
if infl.ArmorThroughRate then
minus = math.max(0, minus * (1 - infl.ArmorThroughRate))
end
end
dmginfo:SetDamage(dmginfo:GetDamage() - minus)
end
end
end
end
hook.Add("EntityTakeDamage", "zs_deathstreak.TakeDamageHandler", TakeDamageHandler)
local stop_dist_check = CreateConVar("hszs_deathstreak_stop_dist_check", "0")
local crDistanceCheck = coroutine.create(function()
while(!stop_dist_check:GetBool()) do
coroutine.yield()
local zombies = {}
for _, v in pairs(team.GetPlayers(TEAM_ZOMBIE)) do
coroutine.yield()
if (IsValid(v) and v.zs_deathstreak and v.zs_deathstreak.count > 0) then
table.insert(zombies, v)
end
end
-- local spawnpoints = ents.FindByClass("info_player_undead")
-- spawnpoints = table.Add(spawnpoints, ents.FindByClass("info_player_zombie"))
-- spawnpoints = table.Add(spawnpoints, ents.FindByClass("info_player_rebel"))
for _, z in pairs(zombies) do
coroutine.yield()
if (IsValid(z)) then
-- local valid = false
-- for _, v in pairs(spawnpoints) do
-- if math.sqrt((z:GetPos() - v:GetPos()):LengthSqr()) <= DS_LIMIT_DISTANCE + (z:GetPremium() and DS_LIMIT_DISTANCE * 0.1 or 0) then
-- valid = true
-- break
-- end
-- coroutine.yield()
-- end
-- if !valid then
-- ResetDeathstreak(z)
-- end
if (!z.zs_deathstreak.spawn) then
z.zs_deathstreak.spawn = 0
end
if (z.zs_deathstreak and z.zs_deathstreak.count >= 1 and z.zs_deathstreak.spawn + (30 + (z.deathstreakTimeAdder or 0)) <= CurTime() and z.zs_deathstreak.spawn ~= 0) then
ResetDeathstreak(z)
end
end
end
end
end)
local lastDistCheck = 0
local DistanceCheck = function()
coroutine.resume(crDistanceCheck)
-- if lastDistCheck + 1 <= CurTime() then
-- local zombies = {}
-- for _, v in pairs(team.GetPlayers(TEAM_ZOMBIE)) do
-- if v.zs_deathstreak and v.zs_deathstreak.count > 0 then
-- table.insert(zombies, v)
-- end
-- end
-- local spawnpoints = ents.FindByClass("info_player_undead")
-- spawnpoints = table.Add(spawnpoints, ents.FindByClass("info_player_zombie"))
-- spawnpoints = table.Add(spawnpoints, ents.FindByClass("info_player_rebel"))
-- for _, z in pairs(zombies) do
-- local valid = false
-- for _, v in pairs(spawnpoints) do
-- if z:GetPos():Distance(v:GetPos()) <= DS_LIMIT_DISTANCE + (z:GetPremium() and DS_LIMIT_DISTANCE * 0.1 or 0) then
-- valid = true
-- break
-- end
-- end
-- if !valid then
-- ResetDeathstreak(z)
-- end
-- if !z.zs_deathstreak.spawn then
-- z.zs_deathstreak.spawn = 0
-- end
-- if z.zs_deathstreak and z.zs_deathstreak.count >= 1 and z.zs_deathstreak.spawn + 30 <= CurTime() and z.zs_deathstreak.spawn ~= 0 then
-- ResetDeathstreak(z)
-- end
-- end
-- end
end
hook.Add("Think", "zs_deathstreak.DistanceCheck", DistanceCheck) | apache-2.0 |
vavrusa/luajit-libuv | test/timer_test.lua | 2 | 1041 | require 'uv/util/strict'
local loop = require 'uv.loop'
local timer = require 'uv.timer'
do
local s = ''
timer.set(5, function() s = s .. 'e' end)
timer.set(3, function() s = s .. 'c' end)
timer.set(1, function() s = s .. 'a' end)
timer.set(2, function() s = s .. 'b' end)
timer.set(4, function() s = s .. 'd' end)
timer.set(6, function() s = s .. 'f' end)
loop.run()
assert(s == 'abcdef')
end
local s = ''
loop.run(function()
timer.set(5, function() s = s .. 'e' end)
timer.set(3, function() s = s .. 'c' end)
timer.set(1, function() s = s .. 'a' end)
timer.set(2, function() s = s .. 'b' end)
timer.set(4, function() s = s .. 'd' end)
timer.set(6, function() s = s .. 'f' end)
end)
assert(s == 'abcdef')
do
local s = ''
timer.every(1, function(self)
s = s .. 'a'
if #s >= 5 then self:stop() end
end)
loop.run()
assert(s == 'aaaaa')
end
local s = ''
loop.run(function()
timer.every(1, function(self)
s = s .. 'a'
if #s >= 5 then self:stop() end
end)
end)
assert(s == 'aaaaa')
| mit |
EricssonResearch/scott-eu | simulation-ros/src/turtlebot2i/turtlebot2i_description/v-rep_model/warehouse_scene/vrep_scripts/lidar.lua | 1 | 5233 | -- This is a ROS enabled Hokuyo_04LX_UG01 model (although it can be used as a generic
-- ROS enabled laser scanner), based on the existing Hokuyo model. It performs instantaneous
-- scans and publishes ROS Laserscan msgs, along with the sensor's tf.
-- This script was modified to support the Hokuyo_04LX_UG01_Fast sensor
if (sim_call_type == sim.childscriptcall_initialization) then
-- Disable camera sensor (comment the lines below to enable)
object_fastHokuyo_sensor1 = sim.getObjectHandle('fastHokuyo_sensor1')
-- sim.setExplicitHandling(object_fastHokuyo_sensor1, 1)
object_fastHokuyo_sensor2 = sim.getObjectHandle('fastHokuyo_sensor2')
-- sim.setExplicitHandling(object_fastHokuyo_sensor2, 1)
modelHandle = sim.getObjectAssociatedWithScript(sim.handle_self)
object_name = sim.getObjectName(modelHandle)
sensor_number, sensor_name = sim.getNameSuffix(object_name)
robot_id = sim.getStringSignal("robot_id")
visionSensor1Handle = sim.getObjectHandle("fastHokuyo_sensor1")
visionSensor2Handle = sim.getObjectHandle("fastHokuyo_sensor2")
maxScanDistance = sim.getScriptSimulationParameter(sim.handle_self, 'maxScanDistance')
if maxScanDistance > 1000 then
maxScanDistance = 1000
end
if maxScanDistance < 0.1 then
maxScanDistance = 0.1
end
maxScanDistance_ = maxScanDistance * 0.9999
scanRange = sim.getScriptSimulationParameter(sim.handle_self, 'scanAngle')
if scanRange > 240 then
scanRange = 240
end
if scanRange < 2 then
scanRange = 2
end
minScanDistance_ = 0.12
scanRange = scanRange * math.pi/180
----------------------------- ROS STUFF --------------------------------
pubScan = simROS.advertise(robot_id..'/'..sensor_name..'/scan', 'sensor_msgs/LaserScan')
--pubScan = simROS.advertise(robot_id..'/'..sensor_name..'/scan_data_collection', 'sensor_msgs/LaserScan')
simROS.publisherTreatUInt8ArrayAsString(pubScan)
end
if (sim_call_type == sim.childscriptcall_cleanup) then
end
if (sim_call_type == sim.childscriptcall_sensing) then
ranges = {}
if notFirstHere then
r,t1,u1 = sim.readVisionSensor(visionSensor1Handle)
r,t2,u2 = sim.readVisionSensor(visionSensor2Handle)
if u1 then
for i = 0, u1[1]-1, 1 do
w = 2+4*i
dist = u1[w+4]
if (dist > maxScanDistance_) then
--table.insert(ranges, math.huge)
table.insert(ranges, maxScanDistance_)
elseif (dist < minScanDistance_) then
table.insert(ranges, 0.0) --considered as collision
else
table.insert(ranges, dist)
end
end
end
if u2 then
for i = 0, u2[1]-1, 1 do
w = 2+4*i
dist = u2[w+4]
if (dist > maxScanDistance_) then
--table.insert(ranges, math.huge)
table.insert(ranges, maxScanDistance_)
elseif (dist < minScanDistance_) then
table.insert(ranges, 0.0) --considered as collision
else
table.insert(ranges, dist)
end
end
end
-- Now send the data:
stepSize = scanRange / table.getn(ranges)
local ros_laser_data = {}
ros_laser_data["header"] = {seq=0, stamp=simROS.getTime(), frame_id = robot_id..'/'..sensor_name.."/scan"}
ros_laser_data["angle_min"] = -scanRange * 0.5
ros_laser_data["angle_max"] = scanRange * 0.5 - stepSize
ros_laser_data["angle_increment"] = stepSize
ros_laser_data["range_min"] = 0
ros_laser_data["range_max"] = maxScanDistance
ros_laser_data["ranges"] = ranges
simROS.publish(pubScan, ros_laser_data)
end
notFirstHere=true
-- measuredData now contains all the points that are closer than the sensor range
-- For each point there is the x, y and z coordinate (i.e. 3 number for each point)
-- Coordinates are expressed relative to the sensor frame.
-- You can access this data from outside via various mechanisms. The best is to first
-- pack the data, then to send it as a string. For example:
--
--
-- data=sim.packFloatTable(measuredData)
-- sim.setStringSignal("measuredDataAtThisTime",data)
--
-- Then in a different location:
-- data=sim.getStringSignal("measuredDataAtThisTime")
-- measuredData=sim.unpackFloatTable(data)
--
--
-- Of course you can also send the data via tubes, wireless (sim.tubeOpen, etc., sim.sendData, etc.)
--
-- Also, if you send the data via string signals, if you you cannot read the data in each simulation
-- step, then always append the data to an already existing signal data, e.g.
--
--
-- data=sim.packFloatTable(measuredData)
-- existingData=sim.getStringSignal("measuredDataAtThisTime")
-- if existingData then
-- data=existingData..data
-- end
-- sim.setStringSignal("measuredDataAtThisTime",data)
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Castle_Oztroja/npcs/Treasure_Coffer.lua | 17 | 3634 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Treasure Coffer
-- @zone 151
-- @pos
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1044,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(1044,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();
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local listAF = getAFbyZone(zone);
for nb = 1,table.getn(listAF),3 do
if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then
questItemNeeded = 2;
break
end
end
--------------------------------------
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 -- 0 or 1
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 2) then
for nb = 1,table.getn(listAF),3 do
if (mJob == listAF[nb]) then
player:addItem(listAF[nb + 2]);
player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]);
break
end
end
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(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
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1044);
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/Bibiki_Bay/npcs/Toh_Zonikki.lua | 19 | 4706 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Toh Zonikki
-- Type: Clamming NPC
-- @pos -371 -1 -421 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
require("scripts/zones/Bibiki_Bay/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- Local Variables
-----------------------------------
local clammingItems = { 1311, -- Oxblood
885, -- Turtle Shell
1193, -- HQ Crab Shell
1446, -- Lacquer Tree Log
4318, -- Bibiki Urchin
1586, -- Titanictus Shell
5124, -- Tropical Clam
690, -- Elm Log
887, -- Coral Fragment
703, -- Petrified Log
691, -- Maple Log
4468, -- Pamamas
3270, -- HQ Pugil Scales
888, -- Seashell
4328, -- Hobgoblin Bread
485, -- Broken Willow Rod
510, -- Goblin Armor
5187, -- Elshimo Coconut
507, -- Goblin Mail
881, -- Crab Shell
4325, -- Hobgoblin Pie
936, -- Rock Salt
4361, -- Nebimonite
864, -- Fish Scales
4484, -- Shall Shell
624, -- Pamtam Kelp
1654, -- Igneous Rock
17296, -- Pebble
5123, -- Jacknife
5122 -- Bibiki Slug
};
-----------------------------------
-- Local Functions
-----------------------------------
local function giveClammedItems(player)
for item = 1, table.getn(clammingItems) do
local clammedItemQty = player:getVar("ClammedItem_" .. clammingItems[item]);
if (clammedItemQty > 0) then
if (player:addItem(clammingItems[item],clammedItemQty)) then
player:messageSpecial(YOU_OBTAIN, clammingItems[item], clammedItemQty);
player:setVar("ClammedItem_" .. clammingItems[item], 0);
else
player:messageSpecial(WHOA_HOLD_ON_NOW);
break;
end
end
end
end;
local function owePlayerClammedItems(player)
for item = 1, table.getn(clammingItems) do
if (player:getVar("ClammedItem_" .. clammingItems[item]) > 0) then
return true;
end
end
return false;
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if ( player:hasKeyItem(CLAMMING_KIT)) then -- Player has clamming kit
if (player:getVar("ClammingKitBroken") == 1) then -- Broken bucket
player:startEvent(0x001E, 0, 0, 0, 0, 0, 0, 0, 0);
else --Bucket not broken
player:startEvent(0x001D, 0, 0, 0, 0, 0, 0, 0, 0);
end
else -- Player does not have clamming kit
if (owePlayerClammedItems(player)) then
player:messageSpecial(YOU_GIT_YER_BAG_READY);
giveClammedItems(player);
else
player:startEvent(0x001C, 500, 0, 0, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001C) then
local enoughMoney = 2; -- Not enough money
if (player:getGil() >= 500) then
enoughMoney = 1; --Player has enough Money
end
player:updateEvent(CLAMMING_KIT, enoughMoney, 0, 0, 0, 500, 0, 0);
elseif (csid == 0x001D) then
local clammingKitSize = player:getVar("ClammingKitSize");
player:updateEvent( player:getVar("ClammingKitWeight"), clammingKitSize, clammingKitSize, clammingKitSize + 50, 0, 0, 0, 0);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001C) then
if (option == 1) then -- Give 50pz clamming kit
player:setVar("ClammingKitSize", 50);
player:addKeyItem(CLAMMING_KIT);
player:delGil(500);
player:messageSpecial(KEYITEM_OBTAINED,CLAMMING_KIT);
end
elseif (csid == 0x001D) then
if (option == 2) then -- Give player clammed items
player:setVar("ClammingKitSize", 0);
player:setVar("ClammingKitWeight", 0);
player:delKeyItem(CLAMMING_KIT);
player:messageSpecial(YOU_RETURN_THE,CLAMMING_KIT);
giveClammedItems(player);
elseif (option == 3) then -- Get bigger kit
local clammingKitSize = player:getVar("ClammingKitSize") + 50;
player:setVar("ClammingKitSize", clammingKitSize);
player:messageSpecial(YOUR_CLAMMING_CAPACITY, 0, 0, clammingKitSize);
end
elseif ( csid == 0x001E) then -- Broken bucket
player:setVar("ClammingKitSize", 0);
player:setVar("ClammingKitBroken", 0);
player:setVar("ClammingKitWeight", 0);
player:delKeyItem(CLAMMING_KIT);
player:messageSpecial(YOU_RETURN_THE,CLAMMING_KIT);
end
end; | gpl-3.0 |
ngeiswei/ardour | share/scripts/s_thin_automation.lua | 2 | 1340 | ardour { ["type"] = "Snippet", name = "Thin Fader Automation" }
-- --TODO--
-- For a fully fledged EditorAction this script should
-- offer a dropdown to select automation of all parameters
-- (not just the fader)
-- see scripts/midi_cc_to_automation.lua and
-- scripts/mixer_settings_store.lua
-- Thinning Area should also be a numeric-entry or slider
function factory () return function ()
-- get selected tracks
rl = Editor:get_selection ().tracks:routelist ()
-- prepare undo operation
Session:begin_reversible_command ("Thin Automation")
local add_undo = false -- keep track if something has changed
-- iterate over selected tracks
for r in rl:iter () do
-- get the Fader (aka "amp") control
local ac = r:amp ():gain_control () -- ARDOUR:AutomationControl
local al = ac:alist () -- ARDOUR:AutomationList
-- get state for undo
local before = al:get_state ()
-- remove dense events
al:thin (50) -- threshold of area below curve
-- save undo
local after = al:get_state ()
Session:add_command (al:memento_command (before, after))
add_undo = true
::out::
end
-- all done, commit the combined Undo Operation
if add_undo then
-- the 'nil' Command here means to use the collected diffs added above
Session:commit_reversible_command (nil)
else
Session:abort_reversible_command ()
end
end end
| gpl-2.0 |
renyaoxiang/QSanguosha-For-Hegemony | lang/zh_CN/Package/StandardQunGeneral.lua | 2 | 8495 | --[[********************************************************************
Copyright (c) 2013-2015 Mogara
This file is part of QSanguosha-Hegemony.
This game is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3.0
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
See the LICENSE file for more details.
Mogara
*********************************************************************]]
-- translation for Standard General Package
return {
-- 群雄
["#huatuo"] = "神医",
["huatuo"] = "华佗",
["qingnang"] = "青囊",
[":qingnang"] = "出牌阶段限一次,你可以弃置一张手牌并选择一名已受伤的角色,令其回复1点体力。",
["jijiu"] = "急救",
[":jijiu"] = "你于回合外可以将一张红色牌当【桃】使用。",
["#lvbu"] = "武的化身",
["lvbu"] = "吕布",
["illustrator:lvbu"] = "LiuHeng",
["wushuang"] = "无双",
[":wushuang"] = "锁定技,每当你使用【杀】指定一个目标后,你将其抵消此【杀】的方式改为依次使用两张【闪】;" ..
"锁定技,每当你使用【决斗】指定一个目标后,或成为一名角色使用【决斗】的目标后,你将其执行此【决斗】中打出【杀】的效果改为依次打出两张【杀】。",
["@wushuang-slash-1"] = "%src 对你【决斗】,你须连续打出两张【杀】",
["@wushuang-slash-2"] = "%src 对你【决斗】,你须再打出一张【杀】",
["#diaochan"] = "绝世的舞姬",
["diaochan"] = "貂蝉",
["illustrator:diaochan"] = "LiuHeng",
["lijian"] = "离间",
[":lijian"] = "出牌阶段限一次,你可以弃置一张牌并选择两名其他男性角色,令其中的一名男性角色视为对另一名男性角色使用【决斗】。",
["biyue"] = "闭月",
[":biyue"] = "结束阶段开始时,你可以摸一张牌。",
["#yuanshao"] = "高贵的名门",
["yuanshao"] = "袁绍",
["illustrator:yuanshao"] = "SoniaTang",
["luanji"] = "乱击",
[":luanji"] = "你可以将两张花色相同的手牌当【万箭齐发】使用。",
["#yanliangwenchou"] = "虎狼兄弟",
["yanliangwenchou"] = "颜良&文丑",
["&yanliangwenchou"] = "颜良文丑",
["shuangxiong"] = "双雄",
[":shuangxiong"] = "摸牌阶段开始时,你可以放弃摸牌,判定,当判定牌生效后,你获得之,若如此做,你于此回合内可以将一张与之颜色不同的手牌当【决斗】使用。",
["#shuangxiong"] = "双雄(获得判定牌)",
["#jiaxu"] = "冷酷的毒士",
["jiaxu"] = "贾诩",
["wansha"] = "完杀",
[":wansha"] = "锁定技,不处于濒死状态的其他角色于你的回合内不能使用【桃】。",
["weimu"] = "帷幕",
[":weimu"] = "锁定技,每当你成为黑色锦囊牌的目标时,你取消自己。",
["luanwu"] = "乱武",
[":luanwu"] = "限定技,出牌阶段,你可以选择所有其他角色,这些角色各需对距离最小的另一名角色使用【杀】,否则失去1点体力。",
["@chaos"] = "乱武",
["@luanwu-slash"] = "请使用一张【杀】响应“乱武”",
["#WanshaOne"] = "%from 的“%arg”被触发,只有 %from 才能救 %from",
["#WanshaTwo"] = "%from 的“%arg”被触发,只有 %from 和 %to 才能救 %to",
["#pangde"] = "人马一体",
["pangde"] = "庞德",
["illustrator:pangde"] = "LiuHeng",
["mashu_pangde"] = "马术",
["mengjin"] = "猛进",
[":mengjin"] = "每当你使用的【杀】被目标角色使用的【闪】抵消时,你可以弃置其一张牌。",
["#zhangjiao"] = "天公将军",
["zhangjiao"] = "张角",
["illustrator:zhangjiao"] = "LiuHeng",
["leiji"] = "雷击",
[":leiji"] = "每当你使用或打出【闪】时,你可以令一名角色判定,若结果为黑桃,你对其造成2点雷电伤害。",
["leiji-invoke"] = "你可以发动“雷击”<br/> <b>操作提示</b>: 选择一名角色→点击确定<br/>",
["guidao"] = "鬼道",
[":guidao"] = "每当一名角色的判定牌生效前,你可以打出黑色牌替换之。",
["@guidao-card"] = CommonTranslationTable["@askforretrial"],
["~guidao"] = "选择一张黑色牌→点击确定",
["#caiwenji"] = "异乡的孤女",
["caiwenji"] = "蔡文姬",
["illustrator:caiwenji"] = "SoniaTang",
["beige"] = "悲歌",
[":beige"] = "每当一名角色受到【杀】造成的伤害后,若其存活,你可以弃置一张牌,令其判定,若结果为:红桃,其回复1点体力;方块,其摸两张牌;梅花,来源弃置两张牌;黑桃,来源叠置。",
["@beige"] = "你可以弃置一张牌发动“悲歌”",
["duanchang"] = "断肠",
[":duanchang"] = "锁定技,当你死亡时,你令杀死你的角色失去你选择的其一张武将牌的技能。",
["@duanchang"] = "断肠",
["#DuanchangLoseHeadSkills"] = "%from 的“%arg”被触发, %to 失去所有主将技能",
["#DuanchangLoseDeputySkills"] = "%from 的“%arg”被触发, %to 失去所有副将技能",
["#mateng"] = "驰骋西陲",
["mateng"] = "马腾",
["illustrator:mateng"] = "DH",
["mashu_mateng"] = "马术",
["xiongyi"] = "雄异",
[":xiongyi"] = "限定技,出牌阶段,你可以令与你势力相同的所有角色各摸三张牌,然后若你的势力是角色最少的势力,你回复1点体力。",
["@arise"] = "雄异",
["#kongrong"] = "凛然重义",
["kongrong"] = "孔融",
["illustrator:kongrong"] = "苍月白龙",
["mingshi"] = "名士",
[":mingshi"] = "锁定技,每当你受到伤害时,若来源有暗置的武将牌,你令此伤害-1。",
["lirang"] = "礼让",
[":lirang"] = "每当你的一张被弃置的牌置入弃牌堆后,你可以将之交给一名其他角色。",
["@lirang-distribute1"] = "礼让:你须将至少 1 张牌任意分配给其他角色",
["@lirang-distribute2"] = "礼让:你可将至多 %arg 张牌任意分配给其他角色",
["~lirang"] = "选择任意礼让牌和一名其他角色→点击确定",
["#lirang"] = "礼让",
["#Mingshi"] = "%from 的“<font color=\"yellow\"><b>名士</b></font>”被触发,伤害从 %arg 点减少至 %arg2 点",
["#jiling"] = "仲家的主将",
["jiling"] = "纪灵",
["illustrator:jiling"] = "樱花闪乱",
["shuangren"] = "双刃",
[":shuangren"] = "出牌阶段开始时,你可以与一名角色拼点:当你赢后,你视为对其或一名与其势力相同的其他角色使用【杀】;当你没赢后,你结束出牌阶段。",
["@shuangren"] = "你可以发动“双刃”",
["#tianfeng"] = "河北瑰杰",
["tianfeng"] = "田丰",
["illustrator:tianfeng"] = "地狱许",
["sijian"] = "死谏",
[":sijian"] = "每当你失去所有手牌后,你可以弃置一名其他角色的一张牌。",
["sijian-invoke"] = "你可以发动“死谏”<br/> <b>操作提示</b>: 选择一名有牌的其他角色→点击确定<br/>",
["suishi"] = "随势",
[":suishi"] = "锁定技,每当其他角色因受到伤害而进入濒死状态时,若来源与你势力相同,你摸一张牌;锁定技,每当其他与你势力相同的角色死亡时,你失去1点体力。",
["#panfeng"] = "联军上将",
["panfeng"] = "潘凤",
["illustrator:panfeng"] = "Yi章",
["kuangfu"] = "狂斧",
[":kuangfu"] = "每当你使用【杀】对目标角色造成伤害后,你可以选择一项:1.将其装备区里的一张牌置入你的装备区;2.弃置其装备区里的一张牌。",
["kuangfu:throw"] = "弃置该装备",
["kuangfu:move"] = "将该装备移动到自己的装备区",
["kuangfu_equip"] = "狂斧",
["kuangfu_equip:0"] = "武器牌",
["kuangfu_equip:1"] = "防具牌",
["kuangfu_equip:2"] = "+1坐骑",
["kuangfu_equip:3"] = "-1坐骑",
["kuangfu_equip:4"] = "宝物牌",
["#zoushi"] = "惑心之魅",
["zoushi"] = "邹氏",
["illustrator:zoushi"] = "Tuu.",
["huoshui"] = "祸水",
[":huoshui"] = "出牌阶段,你可以明置此武将牌;其他角色于你的回合内不能明置其武将牌。",
["qingcheng"] = "倾城",
[":qingcheng"] = "出牌阶段,你可以弃置一张装备牌并选择一名两张武将牌均明置的其他角色,暗置其一张武将牌。",
}
| gpl-3.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/assault_rattle_2.meta.lua | 6 | 3344 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"95 205 228 255",
"223 113 38 255",
"182 229 239 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 = -24,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = -13,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {
7,
0,
1,
6,
7,
2,
3,
4,
5,
6,
1,
2
},
original_poly = {
{
x = -30,
y = -3
},
{
x = 8,
y = -1
},
{
x = 10,
y = -3
},
{
x = 30,
y = -4
},
{
x = 30,
y = 5
},
{
x = 10,
y = 5
},
{
x = 9,
y = 3
},
{
x = -30,
y = 4
}
}
},
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 |
phcosta29/rstats | lib/vstruct/test/error.lua | 7 | 6118 | -- tests for error conditions
-- checks that vstruct properly raises an error (and raises the *correct* error)
-- when things go wrong
local test = require "vstruct.test.common"
local vstruct = require "vstruct"
local E = test.errortest
test.group "error conditions"
-- utility functions gone horribly wrong
E("missing-explode-1", "bad argument #1 to 'vstruct.explode' %(number expected, got nil%)", vstruct.explode)
E("invalid-explode-1", "bad argument #1 to 'vstruct.explode' %(number expected, got boolean%)", vstruct.explode, true, nil)
E("invalid-explode-2", "bad argument #2 to 'vstruct.explode' %(number expected, got boolean%)", vstruct.explode, 0, true)
E("missing-implode-1", "bad argument #1 to 'vstruct.implode' %(table expected, got nil%)", vstruct.implode)
E("invalid-implode-1", "bad argument #1 to 'vstruct.implode' %(table expected, got boolean%)", vstruct.implode, true, nil)
E("invalid-implode-2", "bad argument #2 to 'vstruct.implode' %(number expected, got boolean%)", vstruct.implode, { 0 }, true)
-- attempt to read/seek past bounds of file
-- seeking past the end is totally allowed when writing
-- when reading, you will get a different error when you try to do IO
E("invalid-seek-uf", "attempt to read past end of buffer", vstruct.read, "@8 u4", "1234")
E("invalid-seek-ub", "attempt to seek prior to start of file", vstruct.read, "@0 -4", "1234")
E("invalid-seek-pb", "attempt to seek prior to start of file", vstruct.write, "@0 -4", "1234", {})
-- invalid argument type
E("invalid-arg-u1", "bad argument #1 to 'vstruct.read' %(string expected, got nil%)", vstruct.read)
E("invalid-arg-p1", "bad argument #1 to 'vstruct.write' %(string expected, got nil%)", vstruct.write)
E("invalid-arg-c1", "bad argument #1 to 'vstruct.compile' %(string expected, got nil%)", vstruct.compile)
E("invalid-arg-u1", "bad argument #1 to 'vstruct.read' %(string expected, got number%)", vstruct.read, 0, "1234")
E("invalid-arg-p1", "bad argument #1 to 'vstruct.write' %(string expected, got number%)", vstruct.write, 0, {})
E("invalid-arg-c1", "bad argument #1 to 'vstruct.compile' %(string expected, got number%)", vstruct.compile, 0)
E("invalid-arg-u2", "bad argument #2 to 'vstruct.read' %(file or string expected, got number%)", vstruct.read, "@0", 0)
E("invalid-arg-p2", "bad argument #2 to 'vstruct.write' %(file or string expected, got number%)", vstruct.write, "@0", 0, {})
E("invalid-arg-u3", "bad argument #3 to 'vstruct.read' %(table expected, got string%)", vstruct.read, "@0", "", "1234")
E("invalid-arg-p3", "bad argument #3 to 'vstruct.write' %(table expected, got string%)", vstruct.write, "@0", nil, "1234")
E("invalid-arg-p3", "bad argument #3 to 'vstruct.write' %(table expected, got string%)", vstruct.write, "@0", "1234")
-- format string is ill-formed
-- note that the empty format string is well-formed, does nothing, and returns/accepts the empty table
E("invalid-format-number", "expected.*, got EOF", vstruct.compile, "4")
E("invalid-format-}", "expected.* or io specifier, got }", vstruct.compile, "}")
E("invalid-format-)", "expected.* or io specifier, got %)", vstruct.compile, ")")
E("invalid-format-]", "expected.* or io specifier, got %]", vstruct.compile, "]")
E("invalid-format-{", "expected.*, got EOF", vstruct.compile, "{")
E("invalid-format-(", "expected.*, got EOF", vstruct.compile, "(")
E("invalid-format-[", "expected.*, got EOF", vstruct.compile, "[")
E("invalid-format-*", "expected.*or io specifier, got %*", vstruct.compile, "*4")
E("invalid-format-no-size", "format requires a size", vstruct.compile, "u u4")
-- format string is well-formed but nonsensical
-- note that empty groups and tables and zero-length repeats make it easier to dynamically construct format strings, and are thus allowed
E("bad-format-no-support", "no support for format 'q'", vstruct.compile, "q1")
E("bad-format-small-bitpack", "bitpack contents do not match bitpack size", vstruct.compile, "[1|u4]")
E("bad-format-large-bitpack", "bitpack contents do not match bitpack size", vstruct.compile, "[1|u16]")
-- io format size checking occurs on a format-by-format basis
E("bad-format-size-missing-f", "only supports sizes 4", vstruct.compile, 'f')
E("bad-format-size-wrong-f", "only supports sizes 4", vstruct.compile, 'f1')
E("bad-format-fraction-p", "format requires a fractional%-part size", vstruct.compile, 'p4')
E("bad-format-x-bit", "invalid value to `x` format in bitpack: 0 or 1 required, got 2", vstruct.write, "[1|x8,2]", {})
E("bad-format-x-byte", "bad argument #1 to 'char'", vstruct.write, "x1,300", {})
-- note that s and z can be used either with or without a size specifier
local sized_formats = "abcimpux@+-"
local plain_formats = "<>="
for format in sized_formats:gmatch(".") do
E("bad-format-size-missing-"..format, "format requires a size", vstruct.compile, format)
end
for format in plain_formats:gmatch(".") do
E("bad-format-size-present-"..format, "is an endianness control, and does not have size", vstruct.compile, format.."1")
end
-- format string splicing
vstruct.compile("coord", "x:u1 y:u1 z:u1")
E("splice-wrong-syntax", "parsing format string at character 10.*expected value.*got splice", vstruct.read, "position:&coord", "000")
E("splice-wrong-name", "attempt to splice in format 'coords', which is not registered", vstruct.read, "&coords", "000")
-- input table doesn't match format string
E("bad-data-missing", "bad input while writing: no value for key 1", vstruct.write, "u4", {})
E("bad-data-missing-name", "bad input while writing: no value for key t", vstruct.write, "t:{ x:u4 }", {})
E("bad-data-missing-nested", "bad input while writing: no value for key t.x", vstruct.write, "t.x:u4", {})
-- these require a bunch of type-specific checks. I don't have a good way to do this yet and it's an open question whether I want to do it at all.
--E("bad-data-u-string", "placeholder", vstruct.write, "u4", { "string" })
--E("bad-data-u-numeric-string", "placeholder", vstruct.write, "u4", { "0" })
--E("bad-data-s-number", "placeholder", vstruct.write, "s4", { 0 })
--E("bad-data-z-number", "placeholder", vstruct.write, "z4", { 0 })
| gpl-3.0 |
actboy168/YDWE | Development/Component/plugin/w3x2lni/script/backend/cli/mpq.lua | 2 | 7057 | fs = require 'bee.filesystem'
require 'utility'
local stormlib = require 'ffi.stormlib'
local sleep = require 'ffi.sleep'
local makefile = require 'prebuilt.makefile'
local maketemplate = require 'prebuilt.maketemplate'
local prebuilt_metadata = require 'prebuilt.metadata'
local prebuilt_keydata = require 'prebuilt.keydata'
local prebuilt_search = require 'prebuilt.search'
local proto = require 'share.protocol'
local lang = require 'share.lang'
local core = require 'backend.sandbox_core'
local w3xparser = require 'w3xparser'
local messager = require 'share.messager'
local war3 = require 'share.war3'
local data_version = require 'share.data_version'
local command = require 'backend.command'
local base = require 'backend.base_path'
local root = require 'backend.w2l_path'
local w2l
local mpqs
local input
local output
local function task(f, ...)
for i = 1, 99 do
if pcall(f, ...) then
return true
end
sleep(10)
end
return false
end
local result = {}
local function extract_file(path, name)
local r = war3:extractfile(name, path / name)
result[name] = r or false
end
local function extract_mpq(name)
extract_file(output / 'mpq', name)
end
local function report_fail()
local tbl = {}
for name, res in pairs(result) do
if res == false and not name:match '^Custom_V1' then
table.insert(tbl, name)
end
end
table.sort(tbl)
for _, name in ipairs(tbl) do
w2l.messager.report(lang.report.OTHER, 9, lang.script.EXPORT_FILE_FAILED .. name)
end
end
local function extract()
for _, dir in ipairs {'', 'Custom_V1\\'} do
extract_mpq(dir .. 'Scripts\\Common.j')
extract_mpq(dir .. 'Scripts\\Blizzard.j')
extract_mpq(dir .. 'UI\\MiscData.txt')
extract_mpq(dir .. 'Units\\MiscGame.txt')
extract_mpq(dir .. 'Units\\MiscData.txt')
extract_mpq(dir .. 'Units\\AbilityMetaData.slk')
extract_mpq(dir .. 'Units\\DestructableMetaData.slk')
extract_mpq(dir .. 'Units\\AbilitybuffMetaData.slk')
extract_mpq(dir .. 'Units\\UpgradeMetaData.slk')
extract_mpq(dir .. 'Units\\UnitMetaData.slk')
extract_mpq(dir .. 'Units\\MiscMetaData.slk')
extract_mpq(dir .. 'Doodads\\DoodadMetaData.slk')
extract_mpq(dir .. 'UI\\UnitEditorData.txt')
for type, slks in pairs(w2l.info.slk) do
for _, name in ipairs(slks) do
extract_mpq(dir .. name)
end
end
for _, name in ipairs(w2l.info.txt) do
extract_mpq(dir .. name)
end
end
-- TODO: 应该放在上面的循环中?
extract_mpq('UI\\WorldEditStrings.txt')
extract_mpq('UI\\WorldEditGameStrings.txt')
extract_file(output, 'UI\\TriggerData.txt')
extract_file(output, 'UI\\TriggerStrings.txt')
end
local function create_metadata(w2l)
local defined_meta = w2l:parse_lni(io.load(root / 'script' / 'core' / 'defined' / 'metadata.ini'))
local meta = prebuilt_metadata(w2l, defined_meta, function (name)
return io.load(output / 'mpq' / name)
end)
fs.create_directories(output / 'prebuilt')
io.save(output / 'prebuilt' / 'metadata.ini', meta)
end
local lost_wes = {}
local reports = {}
local function get_w2l()
w2l = core()
w2l:set_messager(messager)
function messager.report(_, _, str, tip)
if str == lang.report.NO_WES_STRING then
lost_wes[tip] = true
else
reports[#reports+1] = str
end
end
end
local function sortpairs(t)
local keys = {}
for k in pairs(t) do
keys[#keys+1] = k
end
table.sort(keys)
local i = 0
return function ()
i = i + 1
local k = keys[i]
return k, t[k]
end
end
local function make_log(clock)
local lines = {}
lines[#lines+1] = lang.report.INPUT_PATH .. input:string()
lines[#lines+1] = lang.report.OUTPUT_PATH .. output:string()
lines[#lines+1] = lang.report.OUTPUT_MODE .. 'mpq'
lines[#lines+1] = lang.report.TAKES_TIME:format(clock)
if #reports > 0 then
for _, rep in ipairs(reports) do
lines[#lines+1] = rep
end
lines[#lines+1] = ''
end
if next(lost_wes) then
lines[#lines+1] = lang.script.UNEXIST_WES_IN_MPQ
for v in sortpairs(lost_wes) do
lines[#lines+1] = v
end
lines[#lines+1] = ''
end
local buf = table.concat(lines, '\r\n')
fs.create_directories(root / 'log')
io.save(root / 'log' / 'report.log', buf)
end
local function loader(name)
return war3:readfile(name)
end
local function input_war3(path)
if not path then
path = '.'
end
path = fs.path(path)
if not path:is_absolute() then
path = fs.absolute(path, base)
end
return fs.absolute(path)
end
return function ()
get_w2l()
w2l.messager.text(lang.script.INIT)
w2l.messager.progress(0)
fs.remove(root / 'log' / 'report.log')
input = input_war3(command[2])
if not war3:open(input) then
w2l.messager.text(lang.script.NEED_WAR3_DIR)
return
end
if not war3.name then
w2l.messager.text(lang.script.LOAD_WAR3_LANG_FAILED)
return
end
output = root / 'data' / war3.name
w2l.progress:start(0.1)
w2l.messager.text(lang.script.CLEAN_DIR)
if fs.exists(output) then
if not task(fs.remove_all, output) then
w2l.messager.text(lang.script.CREATE_DIR_FAILED:format(output:string()))
return
end
end
if not fs.exists(output) then
if not task(fs.create_directories, output) then
w2l.messager.text(lang.script.CREATE_DIR_FAILED:format(output:string()))
return
end
end
w2l.progress:finish()
w2l.progress:start(0.3)
w2l.messager.text(lang.script.EXPORT_MPQ)
extract()
report_fail()
create_metadata(w2l)
w2l.progress:finish()
w2l.cache_metadata = w2l:parse_lni(io.load(output / 'prebuilt' / 'metadata.ini'))
fs.create_directories(output / 'prebuilt')
local keydata = prebuilt_keydata(w2l, loader)
local search = prebuilt_search(w2l, loader)
io.save(output / 'prebuilt' / 'keydata.ini', keydata)
io.save(output / 'prebuilt' / 'search.ini', search)
w2l.cache_metadata = nil
io.save(output / 'version', table.concat(data_version, '\r\n'))
local config = require 'share.config'
config.global.data = war3.name
w2l.progress:start(0.4)
local slk = makefile(w2l, 'Melee')
w2l.progress:finish()
w2l.progress:start(0.65)
maketemplate(w2l, 'Melee', slk)
w2l.progress:finish()
w2l.progress:start(0.75)
local slk = makefile(w2l, 'Custom')
w2l.progress:finish()
w2l.progress:start(1.0)
maketemplate(w2l, 'Custom', slk)
w2l.progress:finish()
local clock = os.clock()
w2l.messager.text((lang.script.FINISH):format(clock))
w2l.messager.exit('success', lang.script.MPQ_EXTRACT_DIR:format(war3.name))
make_log(clock)
end
| gpl-3.0 |
coolflyreg/gs | 3rd/skynet-mingw/lualib/md5.lua | 62 | 1054 | ----------------------------------------------------------------------------
-- Modify version from https://github.com/keplerproject/md5
----------------------------------------------------------------------------
local core = require "md5.core"
----------------------------------------------------------------------------
-- @param k String with original message.
-- @return String with the md5 hash value converted to hexadecimal digits
function core.sumhexa (k)
k = core.sum(k)
return (string.gsub(k, ".", function (c)
return string.format("%02x", string.byte(c))
end))
end
local function get_ipad(c)
return string.char(c:byte() ~ 0x36)
end
local function get_opad(c)
return string.char(c:byte() ~ 0x5c)
end
function core.hmacmd5(data,key)
if #key>64 then
key=core.sum(key)
key=key:sub(1,16)
end
local ipad_s=key:gsub(".", get_ipad)..string.rep("6",64-#key)
local opad_s=key:gsub(".", get_opad)..string.rep("\\",64-#key)
local istr=core.sum(ipad_s..data)
local ostr=core.sumhexa(opad_s..istr)
return ostr
end
return core
| gpl-2.0 |
pallab-gain/janus-gateway | plugins/lua/echotest.lua | 2 | 8023 | -- This is a simple example of an echo test application built in Lua,
-- and conceived to be used in conjunction with the janus_lua.c plugin
--
-- Note: this example depends on lua-json to do JSON processing
-- (http://luaforge.net/projects/luajson/)
json = require('json')
-- We also import our own SDP helper utilities: you may have better ones
sdp = require('janus-sdp')
-- Let's also use our ugly stdout logger just for the fun of it: to add
-- some color to the text we use the ansicolors library
-- (https://github.com/kikito/ansicolors.lua)
colors = require "ansicolors"
logger = require('janus-logger')
-- Example details
name = "echotest.lua"
logger.prefix(colors("[%{blue}" .. name .. "%{reset}]"))
logger.print("Loading...")
-- State and properties
sessions = {}
tasks = {}
-- Just for fun, let's override the plugin info with our own
function getVersion()
return 12
end
function getVersionString()
return "0.0.12"
end
function getDescription()
return "This is echotest.lua, a Lua based clone of janus.plugin.echotest"
end
function getName()
return "Lua based EchoTest"
end
function getAuthor()
return "Lorenzo Miniero"
end
function getPackage()
return "janus.plugin.echolua"
end
-- Methods
function init(config)
-- This is where we initialize the plugin, for static properties
logger.print("Initializing...")
if config ~= nil then
logger.print("Configuration file provided (" .. config .. "), but we don't need it")
end
logger.print("Initialized")
-- Just for fun (and to showcase the feature), let's send an event to handlers:
-- notice how the first argument is 0, meaning this event is not tied to any session
local event = { event = "loaded", script = name }
local eventjson = json.encode(event)
notifyEvent(0, eventjson)
end
function destroy()
-- This is where we deinitialize the plugin, when Janus shuts down
logger.print("Deinitialized")
end
function createSession(id)
-- Keep track of a new session
logger.print("Created new session: " .. id)
sessions[id] = { id = id, lua = name }
end
function destroySession(id)
-- A Janus plugin session has gone
logger.print("Destroyed session: " .. id)
hangupMedia(id)
sessions[id] = nil
end
function querySession(id)
-- Return info on a session
logger.print("Queried session: " .. id)
local s = sessions[id]
if s == nil then
return nil
end
local info = { script = s["lua"], id = s["id"] }
local infojson = json.encode(info)
return infojson
end
function handleMessage(id, tr, msg, jsep)
-- Handle a message, synchronously or asynchronously, and return
-- something accordingly: if it's the latter, we'll do a coroutine
logger.print("Handling message for session: " .. id)
local s = sessions[id]
if s == nil then
return -1, "Session not found"
end
-- Decode the message JSON string to a table
local msgT = json.decode(msg)
-- Let's return a synchronous response if there's no jsep, asynchronous otherwise
if jsep == nil then
processRequest(id, msgT)
local response = { echotest = "response", result = "ok" }
local responsejson = json.encode(response)
return 0, responsejson
else
-- Decode the JSEP JSON string to a table too
local jsepT = json.decode(jsep)
-- We need a new coroutine here
local async = coroutine.create(function(id, tr, comsg, cojsep)
-- We'll only execute this when the scheduler resumes the task
logger.print("Handling async message for session: " .. id)
local s = sessions[id]
if s == nil then
logger.print("Can't handle async message: so such session")
return
end
local offer = sdp.parse(cojsep.sdp)
logger.print("Got offer: " .. sdp.render(offer))
local answer = sdp.generateAnswer(offer, { audio = true, video = true, data = true })
logger.print("Generated answer: " .. sdp.render(answer))
logger.print("Processing request: " .. dumpTable(comsg))
processRequest(id, comsg)
logger.print("Pushing event:")
local event = { echotest = "event", result = "ok" }
local jsonevent = json.encode(event)
logger.print(" -- " .. jsonevent)
local jsepanswer = { type = "answer", sdp = sdp.render(answer) }
local jsonjsep = json.encode(jsepanswer)
logger.print(" -- " .. jsonjsep)
pushEvent(id, tr, jsonevent, jsonjsep)
-- Just for fun (and to showcase the feature), let's send an event to handlers;
-- notice how we pass the id now, meaning this event is tied to a specific session
local event = { event = "processed", request = comsg }
local eventjson = json.encode(event)
notifyEvent(id, eventjson)
end)
-- Enqueue it: the scheduler will resume it later
tasks[#tasks+1] = { co = async, id = id, tr = tr, msg = msgT, jsep = jsepT }
-- Return explaining that this is will be handled asynchronously
pokeScheduler()
return 1, nil
end
end
function setupMedia(id)
-- WebRTC is now available
logger.print("WebRTC PeerConnection is up for session: " .. id)
-- Attach the session's stream to itself (echo test)
addRecipient(id, id)
end
function hangupMedia(id)
-- WebRTC not available anymore
logger.print("WebRTC PeerConnection is down for session: " .. id)
-- Detach the stream
removeRecipient(id, id)
-- Clear some flags
local s = sessions[id]
if s ~= nil then
s.audioCodec = nil
s.videoCodec = nil
end
end
function incomingData(id, buf, len)
-- Relaying RTP/RTCP in Lua makes no sense, but just for fun
-- we handle data channel messages ourselves to manipulate them
local edit = "[" .. name .. "] --> " .. buf
relayData(id, edit, string.len(edit));
end
function resumeScheduler()
-- This is the function responsible for resuming coroutines associated
-- with whatever is relevant to the Lua script, e.g., for this script,
-- with asynchronous requests: if you're handling async stuff yourself,
-- you're free not to use this and just return, but the C Lua plugin
-- expects this method to exist so it MUST be present, even if empty
logger.print("Resuming coroutines")
for index,task in ipairs(tasks) do
local success, result = coroutine.resume(task.co, task.id, task.tr, task.msg, task.jsep)
if not success then
logger.print(colors("[%{red}exception%{reset}]") .. " " .. dumpTable(result))
end
end
logger.print("Coroutines resumed")
tasks = {}
end
-- We use this internal method to process an API request
function processRequest(id, msg)
if msg == nil then
return -1
end
-- We implement most of the existing EchoTest API messages, here
if msg["audio"] == true then
configureMedium(id, "audio", "in", true)
configureMedium(id, "audio", "out", true)
elseif msg["audio"] == false then
configureMedium(id, "audio", "in", false)
configureMedium(id, "audio", "out", false)
end
if msg["video"] == true then
configureMedium(id, "video", "in", true)
configureMedium(id, "video", "out", true)
sendPli(id)
elseif msg["video"] == false then
configureMedium(id, "video", "in", false)
configureMedium(id, "video", "out", false)
end
if msg["data"] == true then
configureMedium(id, "data", "in", true)
configureMedium(id, "data", "out", true)
elseif msg["data"] == false then
configureMedium(id, "data", "in", false)
configureMedium(id, "data", "out", false)
end
if msg["bitrate"] ~= nil then
setBitrate(id, msg["bitrate"])
end
if msg["record"] == true then
local fnbase = msg["filename"]
if fnbase == nil then
fnbase = "lua-echotest-" .. id .. "-" .. require 'socket'.gettime()
end
startRecording(id,
"audio", "opus", "/tmp", fnbase .. "-audio",
"video", "vp8", "/tmp", fnbase .. "-video",
"data", "text", "/tmp", fnbase .. "-data"
)
elseif msg["record"] == false then
stopRecording(id, "audio", "video", "data")
end
return 0
end
-- Helper for logging tables
-- https://stackoverflow.com/a/27028488
function dumpTable(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dumpTable(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-- Done
logger.print("Loaded")
| gpl-3.0 |
iuser99/BoL | Common/SidasAutoCarryPlugin - Lissandra.lua | 2 | 1949 | --[[
SAC Lissandra plugin
Version 1.0
- Initial release
Version 1.1
- Herp-Derp skillshot fixes
Version 1.2
- Converted to iFoundation_v2
--]]
require "iFoundation_v2"
local SkillQ = Caster(_Q, 700, SPELL_LINEAR, 2250, 0.250, 100, true)
local SkillW = Caster(_W, 450, SPELL_SELF)
local SkillE = Caster(_E, 1025, SPELL_LINEAR, 853, 0.250, 100, true)
local SkillR = Caster(_R, 700, SPELL_TARGETED)
local eClaw = nil
local eClawRemoved = nil
function PluginOnLoad()
AutoCarry.SkillsCrosshair.range = 600
MainMenu = AutoCarry.MainMenu
PluginMenu = AutoCarry.PluginMenu
end
function PluginOnTick()
Target = AutoCarry.GetAttackTarget()
if eClaw ~= nil and not eClaw.valid then
eClaw = nil
end
-- AutoCarry
if Target and MainMenu.AutoCarry then
if DamageCalculation.CalculateRealDamage(Target) >= Target.health then
if SkillE:Ready() then SkillE:Cast(Target) end -- First cast
if SkillQ:Ready() then SkillQ:Cast(Target) end
if eClaw ~= nil and eClaw.valid then
if GetDistance(eClaw, Target) < 50 then
if SkillE:Ready() and not UnderTurret(Target) then
CastSpell(_E)
end -- second cast
end
end
if SkillW:Ready() then SkillW:Cast(Target) end
end
if ((eClaw == nil) or eClaw ~= nil and not eClaw.valid) and SkillE:Ready() then SkillE:Cast(Target) end
if SkillR:Ready() and (DamageCalculation.CalculateRealDamage(true, Target) >= Target.health or getDmg("R", Target, myHero) > Target.health) then SkillR:Cast(Target) end
if SkillQ:Ready() then SkillQ:Cast(Target) end
if SkillW:Ready() then SkillW:Cast(Target) end
end
-- LastHit
if MainMenu.LastHit then
Combat.LastHit(SkillE)
end
end
function PluginOnCreateObj(object)
if object.name:find("Lissandra_E_Missile.troy") then
eClaw = object
end
end
function PluginOnDeleteObj(object)
if object.name:find("Lissandra_E_Missile.troy") then
eClaw = nil
eClawRemoved = GetTickCount()
end
end | gpl-2.0 |
nasomi/darkstar | scripts/globals/items/divine_sword_+1.lua | 42 | 1080 | -----------------------------------------
-- ID: 16826
-- Item: Divine Sword +1
-- Additional Effect: Light Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-openvpn/luasrc/model/cbi/openvpn.lua | 15 | 3780 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local testfullps = luci.sys.exec("ps --help 2>&1 | grep BusyBox") --check which ps do we have
local psstring = (string.len(testfullps)>0) and "ps w" or "ps axfw" --set command we use to get pid
local m = Map("openvpn", translate("OpenVPN"))
local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") )
s.template = "cbi/tblsection"
s.template_addremove = "openvpn/cbi-select-input-add"
s.addremove = true
s.add_select_options = { }
s.extedit = luci.dispatcher.build_url(
"admin", "services", "openvpn", "basic", "%s"
)
uci:load("openvpn_recipes")
uci:foreach( "openvpn_recipes", "openvpn_recipe",
function(section)
s.add_select_options[section['.name']] =
section['_description'] or section['.name']
end
)
function s.getPID(section) -- Universal function which returns valid pid # or nil
local pid = sys.exec("%s | grep -w %s | grep openvpn | grep -v grep | awk '{print $1}'" % { psstring,section} )
if pid and #pid > 0 and tonumber(pid) ~= nil then
return tonumber(pid)
else
return nil
end
end
function s.parse(self, section)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if recipe and not s.add_select_options[recipe] then
self.invalid_cts = true
else
TypedSection.parse( self, section )
end
end
function s.create(self, name)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
name = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".text"
)
if string.len(name)>3 and not name:match("[^a-zA-Z0-9_]") then
uci:section(
"openvpn", "openvpn", name,
uci:get_all( "openvpn_recipes", recipe )
)
uci:delete("openvpn", name, "_role")
uci:delete("openvpn", name, "_description")
uci:save("openvpn")
luci.http.redirect( self.extedit:format(name) )
else
self.invalid_cts = true
end
end
s:option( Flag, "enabled", translate("Enabled") )
local active = s:option( DummyValue, "_active", translate("Started") )
function active.cfgvalue(self, section)
local pid = s.getPID(section)
if pid ~= nil then
return (sys.process.signal(pid, 0))
and translatef("yes (%i)", pid)
or translate("no")
end
return translate("no")
end
local updown = s:option( Button, "_updown", translate("Start/Stop") )
updown._state = false
updown.redirect = luci.dispatcher.build_url(
"admin", "services", "openvpn"
)
function updown.cbid(self, section)
local pid = s.getPID(section)
self._state = pid ~= nil and sys.process.signal(pid, 0)
self.option = self._state and "stop" or "start"
return AbstractValue.cbid(self, section)
end
function updown.cfgvalue(self, section)
self.title = self._state and "stop" or "start"
self.inputstyle = self._state and "reset" or "reload"
end
function updown.write(self, section, value)
if self.option == "stop" then
local pid = s.getPID(section)
if pid ~= nil then
sys.process.signal(pid,15)
end
else
luci.sys.call("/etc/init.d/openvpn start %s" % section)
end
luci.http.redirect( self.redirect )
end
local port = s:option( DummyValue, "port", translate("Port") )
function port.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "1194"
end
local proto = s:option( DummyValue, "proto", translate("Protocol") )
function proto.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "udp"
end
return m
| apache-2.0 |
nasomi/darkstar | scripts/zones/Metalworks/npcs/Naji.lua | 17 | 4914 | -----------------------------------
-- Area: Metalworks
-- NPC: Naji
-- Involved in Quests: The doorman (finish), Riding on the Clouds
-- Involved in Mission: Bastok 6-2
-- @pos 64 -14 -4 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 6) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman, WAR AF1
player:startEvent(0x02ee);
elseif (player:getCurrentMission(BASTOK) ~= 255) then
local currentMission = player:getCurrentMission(BASTOK);
if (currentMission == THE_ZERUHN_REPORT and player:hasKeyItem(ZERUHN_REPORT)) then
if (player:seenKeyItem(ZERUHN_REPORT)) then
player:startEvent(0x02C6,0);
else
player:startEvent(0x02C6,1);
end
elseif (currentMission == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then
player:startEvent(0x02c7);
elseif (currentMission == THE_EMISSARY and player:hasKeyItem(KINDRED_REPORT)) then
player:startEvent(0x02ca);
elseif (currentMission == THE_EMISSARY) then
if (player:hasKeyItem(LETTER_TO_THE_CONSULS_BASTOK) == false and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02c9);
else
player:showText(npc,GOOD_LUCK);
end
elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK) and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02d0);
elseif (currentMission == DARKNESS_RISING and player:getVar("MissionStatus") == 1) then
player:startEvent(0x02d1);
elseif (player:hasKeyItem(BURNT_SEAL)) then
player:startEvent(0x02d2);
elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02f9);
elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 3) then
player:startEvent(0x02fa);
else
player:startEvent(0x02bc);
end
elseif (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman
player:startEvent(0x02ee);
else
player:startEvent(0x02bc);
end
end;
-- 0x02c6 0x02c7 0x02bc 0x02c9 0x02ca 0x02cb 0x02cd 0x02d0 0x02d1 0x02ee 0x03f0 0x03f1 0x02f9
-- 0x02fa 0x030e 0x0325 0x034d 0x036d 0x03aa 0x03ab 0x03ac 0x03ad 0x03ae 0x03cb 0x03c9 0x03ca
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x02ee) then
if (player:getFreeSlotsCount(0) >= 1) then
player:addItem(16678);
player:messageSpecial(ITEM_OBTAINED, 16678); -- Razor Axe
player:delKeyItem(YASINS_SWORD);
player:setVar("theDoormanCS",0);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,THE_DOORMAN);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16678); -- Razor Axe
end
elseif (csid == 0x02C6) then
player:delKeyItem(ZERUHN_REPORT);
player:completeMission(BASTOK,THE_ZERUHN_REPORT);
elseif (csid == 0x02c9) then
player:addKeyItem(LETTER_TO_THE_CONSULS_BASTOK);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_BASTOK);
player:setVar("MissionStatus",1);
elseif (csid == 0x02d0 and option == 0 or csid == 0x02d1) then
player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK);
player:addKeyItem(NEW_FEIYIN_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL);
player:setVar("MissionStatus",10);
elseif (csid == 0x02d0 and option == 1) then
player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK);
player:setVar("MissionStatus",1);
elseif (csid == 0x02f9) then
player:setVar("MissionStatus",1);
elseif (csid == 0x02ca or csid == 0x02d2 or csid == 0x02fa) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
mkjanke/Focus-Points | focuspoints.lrdevplugin/SonyRX10M4Delegates.lua | 3 | 3826 | --[[
Copyright 2016 Whizzbang Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
A collection of delegate functions to be passed into the DefaultPointRenderer when
the camera is Sony RX10M4
--]]
local LrStringUtils = import "LrStringUtils"
require "Utils"
SonyDelegates = {}
--[[
-- metaData - the metadata as read by exiftool
--]]
function SonyDelegates.getAfPoints(photo, metaData)
local focusPoint = ExifUtils.findFirstMatchingValue(metaData, { "Focus Location" })
if focusPoint == nil then
return nil
end
local values = split(focusPoint, " ")
local imageWidth = LrStringUtils.trimWhitespace(values[1])
local imageHeight = LrStringUtils.trimWhitespace(values[2])
local x = LrStringUtils.trimWhitespace(values[3])
local y = LrStringUtils.trimWhitespace(values[4])
if imageWidth == nil or imageHeight == nil or x == nil or y == nil then
return nil
end
local pdafPointSize = imageWidth*0.039/2
local orgPhotoWidth, orgPhotoHeight = DefaultPointRenderer.getNormalizedDimensions(photo)
local xScale = orgPhotoWidth / imageWidth
local yScale = orgPhotoHeight / imageHeight
logInfo("Sony", "Focus location at [" .. math.ceil(x * xScale) .. ", " .. math.floor(y * yScale) .. "]")
local result = {
pointTemplates = DefaultDelegates.pointTemplates,
points = {
{
pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS,
x = x*xScale - (pdafPointSize/2),
y = y*yScale - (pdafPointSize/2),
width = pdafPointSize,
height = pdafPointSize
}
}
}
-- Let's see if we used any PDAF points
local numPdafPointsStr = ExifUtils.findFirstMatchingValue(metaData, { "Focal Plane AF Points Used" })
if numPdafPointsStr == nil then
return result
end
local numPdafPoints = LrStringUtils.trimWhitespace(numPdafPointsStr)
if numPdafPoints == nil then
return result
end
logDebug("Sony", "PDAF AF points used: " .. numPdafPoints)
local pdafDimensionsStr = ExifUtils.findFirstMatchingValue(metaData, { "Focal Plane AF Point Area" })
if pdafDimensionsStr == nil then
return result
end
local pdafDimensions = split(pdafDimensionsStr, " ")
local pdafWidth = LrStringUtils.trimWhitespace(pdafDimensions[1])
local pdafHeight = LrStringUtils.trimWhitespace(pdafDimensions[2])
if pdafWidth == nil or pdafHeight == nil then
return result
end
for i=1, numPdafPoints do
local pdafPointStr = ExifUtils.findFirstMatchingValue(metaData, { "Focal Plane AF Point Location " .. i })
if pdafPointStr == nil then
return result
end
local pdafPoint = split(pdafPointStr, " ")
local x = LrStringUtils.trimWhitespace(pdafPoint[1])
local y = LrStringUtils.trimWhitespace(pdafPoint[2])
if x == nil or y == nil then
return result
end
logDebug("Sony", "PDAF unscaled point at [" .. x .. ", " .. y .. "]")
local pdafX = (imageWidth*x/pdafWidth)*xScale
local pdafY = (imageHeight*y/pdafHeight)*yScale
logInfo("Sony", "PDAF point at [" .. math.floor(pdafX) .. ", " .. math.floor(pdafY) .. "]")
table.insert(result.points, {
pointType = DefaultDelegates.POINTTYPE_AF_INACTIVE,
x = pdafX-(pdafPointSize/2),
y = pdafY-(pdafPointSize/2),
width = pdafPointSize,
height = pdafPointSize
})
end
return result
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Caedarva_Mire/npcs/qm3.lua | 16 | 1188 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: ??? (Spawn Mahjlaef the Paintorn(ZNM T3))
-- @pos 695 -7 527 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(2594,1) and trade:getItemCount() == 1) then -- Trade Exorcism Treatise
player:tradeComplete();
SpawnMob(17101204,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Yughott_Grotto/npcs/Mining_Point.lua | 29 | 1099 | -----------------------------------
-- Area: Yughott Grotto
-- NPC: Mining Point
-----------------------------------
package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/mining");
require("scripts/zones/Yughott_Grotto/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startMining(player,player:getZoneID(),npc,trade,0x0064);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
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/coral_butterfly.lua | 18 | 1264 | -----------------------------------------
-- ID: 4580
-- Item: Coral Butterfly
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
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,4580);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
dageq/Dage-Aliraqi | plugins/ar-onservice.lua | 1 | 1359 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY Dage Aliraqi ▀▄ ▄▀
▀▄ ▄▀ BY Dage Aliraqi (@dageq) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY Dage Aliraqi ▀▄ ▄▀
▀▄ ▄▀ Kick bot : طرد بوت ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
local bot_id = our_id
local receiver = get_receiver(msg)
if matches[1] == 'طرد البوت' and is_admin1(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then
send_large_msg(receiver, 'This is not one of my groups.', ok_cb, false)
chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
end
end
return {
patterns = {
"^(طرد البوت)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Mhaura/npcs/Bihoro-Guhoro.lua | 17 | 1509 | -----------------------------------
-- Area: Mhaura
-- NPC: Bihoro-Guhoro
-- Involved in Quest: Riding on the Clouds
-- @pos -28 -8 41 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 7) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2ee);
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 |
minaevmike/rspamd | rules/http_headers.lua | 1 | 5753 | --[[
Copyright (c) 2015, Vsevolod Stakhov <vsevolod@highsecure.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local logger = require "rspamd_logger"
local ucl = require "ucl"
local spf_symbols = {
symbol_allow = 'R_SPF_ALLOW',
symbol_deny = 'R_SPF_FAIL',
symbol_softfail = 'R_SPF_SOFTFAIL',
symbol_neutral = 'R_SPF_NEUTRAL',
symbol_tempfail = 'R_SPF_DNSFAIL',
symbol_na = 'R_SPF_NA',
symbol_permfail = 'R_SPF_PERMFAIL',
}
local dkim_symbols = {
symbol_allow = 'R_DKIM_ALLOW',
symbol_deny = 'R_DKIM_REJECT',
symbol_tempfail = 'R_DKIM_TEMPFAIL',
symbol_na = 'R_DKIM_NA',
symbol_permfail = 'R_DKIM_PERMFAIL',
}
local dmarc_symbols = {
allow = 'DMARC_POLICY_ALLOW',
badpolicy = 'DMARC_BAD_POLICY',
dnsfail = 'DMARC_DNSFAIL',
na = 'DMARC_NA',
reject = 'DMARC_POLICY_REJECT',
softfail = 'DMARC_POLICY_SOFTFAIL',
quarantine = 'DMARC_POLICY_QUARANTINE',
}
local opts = rspamd_config:get_all_opt('dmarc')
if opts and opts['symbols'] then
for k,_ in pairs(dmarc_symbols) do
if opts['symbols'][k] then
dmarc_symbols[k] = opts['symbols'][k]
end
end
end
local opts = rspamd_config:get_all_opt('dkim')
if opts then
for k,_ in pairs(dkim_symbols) do
if opts[k] then
dkim_symbols[k] = opts[k]
end
end
end
local opts = rspamd_config:get_all_opt('spf')
if opts then
for k,_ in pairs(spf_symbols) do
if opts[k] then
spf_symbols[k] = opts[k]
end
end
end
-- Disable DKIM checks if passed via HTTP headers
rspamd_config:add_condition("R_DKIM_ALLOW", function(task)
local hdr = task:get_request_header('DKIM')
if hdr then
local parser = ucl.parser()
local res, err = parser:parse_string(tostring(hdr))
if not res then
logger.infox(task, "cannot parse DKIM header: %1", err)
return true
end
local obj = parser:get_object()
if obj['result'] then
if obj['result'] == 'pass' or obj['result'] == 'allow' then
task:insert_result(dkim_symbols['symbol_allow'], 1.0, 'http header')
elseif obj['result'] == 'fail' or obj['result'] == 'reject' then
task:insert_result(dkim_symbols['symbol_deny'], 1.0, 'http header')
elseif obj['result'] == 'tempfail' or obj['result'] == 'softfail' then
task:insert_result(dkim_symbols['symbol_tempfail'], 1.0, 'http header')
elseif obj['result'] == 'permfail' then
task:insert_result(dkim_symbols['symbol_permfail'], 1.0, 'http header')
elseif obj['result'] == 'na' then
task:insert_result(dkim_symbols['symbol_na'], 1.0, 'http header')
end
return false
end
end
return true
end)
-- Disable DKIM checks if passed via HTTP headers
rspamd_config:add_condition("R_SPF_ALLOW", function(task)
local hdr = task:get_request_header('SPF')
if hdr then
local parser = ucl.parser()
local res, err = parser:parse_string(tostring(hdr))
if not res then
logger.infox(task, "cannot parse SPF header: %1", err)
return true
end
local obj = parser:get_object()
if obj['result'] then
if obj['result'] == 'pass' or obj['result'] == 'allow' then
task:insert_result(spf_symbols['symbol_allow'], 1.0, 'http header')
elseif obj['result'] == 'fail' or obj['result'] == 'reject' then
task:insert_result(spf_symbols['symbol_deny'], 1.0, 'http header')
elseif obj['result'] == 'neutral' then
task:insert_result(spf_symbols['symbol_neutral'], 1.0, 'http header')
elseif obj['result'] == 'softfail' then
task:insert_result(spf_symbols['symbol_softfail'], 1.0, 'http header')
elseif obj['result'] == 'permfail' then
task:insert_result(spf_symbols['symbol_permfail'], 1.0, 'http header')
elseif obj['result'] == 'na' then
task:insert_result(spf_symbols['symbol_na'], 1.0, 'http header')
end
return false
end
end
return true
end)
rspamd_config:add_condition("DMARC_POLICY_ALLOW", function(task)
local hdr = task:get_request_header('DMARC')
if hdr then
local parser = ucl.parser()
local res, err = parser:parse_string(tostring(hdr))
if not res then
logger.infox(task, "cannot parse DMARC header: %1", err)
return true
end
local obj = parser:get_object()
if obj['result'] then
if obj['result'] == 'pass' or obj['result'] == 'allow' then
task:insert_result(dmarc_symbols['allow'], 1.0, 'http header')
elseif obj['result'] == 'fail' or obj['result'] == 'reject' then
task:insert_result(dmarc_symbols['reject'], 1.0, 'http header')
elseif obj['result'] == 'quarantine' then
task:insert_result(dmarc_symbols['quarantine'], 1.0, 'http header')
elseif obj['result'] == 'tempfail' then
task:insert_result(dmarc_symbols['dnsfail'], 1.0, 'http header')
elseif obj['result'] == 'softfail' or obj['result'] == 'none' then
task:insert_result(dmarc_symbols['softfail'], 1.0, 'http header')
elseif obj['result'] == 'permfail' or obj['result'] == 'badpolicy' then
task:insert_result(dmarc_symbols['badpolicy'], 1.0, 'http header')
elseif obj['result'] == 'na' then
task:insert_result(dmarc_symbols['na'], 1.0, 'http header')
end
return false
end
end
return true
end)
| apache-2.0 |
kbridgers/VOLTE4GFAX | package/feeds/ltq_gpon_onu/gpon-luci/files/tools/gpon.lua | 1 | 1448 |
-- module("luci.tools.gpon", package.seeall)
require("luci.util")
--- Trim a string.
-- @return Trimmed string
function trim(s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
function trim2(s)
return (string.gsub(s, "^\"(.-)\"$", "%1"))
end
--- Retrieves the output of the onu command.
-- @return String containing the current buffer
function cli(command)
local s = "/opt/lantiq/bin/onu " .. command
return trim(luci.util.exec(s))
end
--- Split the CLI string into a table.
-- @return Value Table
function split_val(s)
local t = {}
local s1, s2, s3, s4
repeat
s1, s2 = string.match(s, "(.-) (.+)")
if s1 then
s3, s4 = string.match(s1, "(.-)=(.+)")
if s3 and s4 then
t[s3] = s4
end
s = s2
else
s3, s4 = string.match(s, "(.-)=(.+)")
if s3 and s4 then
t[s3] = s4
end
end
until s1 == nil
return t
end
function return_val(s, val)
if s == nil then return "table is invalid" end
if val == nil then return "index is invalid" end
local v = tonumber(val)
if v == nil then
return val
end
if s[v] == nil then
return v
else
return s[v]
end
end
function decode_error_code(val)
local s = {}
s[-1]="oops"
return return_val(s, val)
end
function assign_value(t, v)
if t['errorcode'] == nil then
return "invalid response"
end
if tonumber(t['errorcode']) < 0 then
return decode_error_code(t['errorcode'])
end
if t[v] == nil then
return "value not found"
else
return t[v]
end
end
| gpl-2.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/have_a_pleasant.meta.lua | 7 | 1899 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"255 255 255 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/globals/abilities/altruism.lua | 28 | 1176 | -----------------------------------
-- Ability: Altruism
-- Increases the accuracy of your next White Magic spell.
-- Obtained: Scholar Level 75 Tier 2 Merit Points
-- Recast Time: Stratagem Charge
-- Duration: 1 white magic spell or 60 seconds, whichever occurs first
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_ALTRUISM) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:addStatusEffect(EFFECT_ALTRUISM,player:getMerit(MERIT_ALTRUISM),0,60);
return EFFECT_ALTRUISM;
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/effects/voidstorm.lua | 37 | 1334 | -----------------------------------
--
--
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR,math.floor(effect:getPower()/2));
target:addMod(MOD_DEX,math.floor(effect:getPower()/2));
target:addMod(MOD_VIT,math.floor(effect:getPower()/2));
target:addMod(MOD_AGI,math.floor(effect:getPower()/2));
target:addMod(MOD_INT,math.floor(effect:getPower()/2));
target:addMod(MOD_MND,math.floor(effect:getPower()/2));
target:addMod(MOD_CHR,math.floor(effect:getPower()/2));
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR,math.floor(effect:getPower()/2));
target:delMod(MOD_DEX,math.floor(effect:getPower()/2));
target:delMod(MOD_VIT,math.floor(effect:getPower()/2));
target:delMod(MOD_AGI,math.floor(effect:getPower()/2));
target:delMod(MOD_INT,math.floor(effect:getPower()/2));
target:delMod(MOD_MND,math.floor(effect:getPower()/2));
target:delMod(MOD_CHR,math.floor(effect:getPower()/2));
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Castle_Oztroja/npcs/_47w.lua | 17 | 1266 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47w (Handle)
-- Notes: Opens door _473 from behind
-- @pos -41.377 -17.084 17.036 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)
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if (player:getXPos() > -43) then
if (DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
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);
end; | gpl-3.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c2700055.lua | 1 | 1946 | --P-037 Increasing Evil Frieza
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
ds.EnableBattleAttribute(c)
ds.AddPlayProcedure(c,COLOR_COLORLESS,0,6)
ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,CHARACTER_FRIEZA,SPECIAL_TRAIT_FRIEZA_CLAN)
--xeno-evolve
ds.EnableXenoEvolve(c,aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_FRIEZA),COLOR_COLORLESS,0,6)
--triple strike
ds.EnableTripleStrike(c)
--confirm
ds.AddSingleAutoPlay(c,0,nil,scard.conftg,scard.confop,DS_EFFECT_FLAG_CARD_CHOOSE,ds.evoplcon)
end
scard.dragon_ball_super_card=true
scard.combo_cost=1
function scard.conffilter(c,e)
return not c:IsPublic() and c:IsCanBeSkillTarget(e)
end
function scard.conftg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_HAND) and chkc:IsControler(1-tp) and aux.NOT(chkc.IsPublic) end
if chk==0 then return Duel.IsExistingTarget(aux.NOT(Card.IsPublic),tp,0,LOCATION_HAND,1,nil) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
if not Duel.SelectYesNo(tp,aux.Stringid(sid,1)) then return end
local g=Duel.GetMatchingGroup(scard.conffilter,tp,0,LOCATION_HAND,nil,e)
local count=g:GetCount()
if count>1 then count=2 end
repeat
local tc=g:RandomSelect(tp,1):GetFirst()
Duel.SetTargetCard(tc)
g:RemoveCard(tc)
count=count-1
until count==0 or not Duel.SelectYesNo(tp,aux.Stringid(sid,2))
end
function scard.confop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if not g then return end
local sg=g:Filter(Card.IsRelateToSkill,nil,e)
for tc in aux.Next(sg) do
Duel.ConfirmCards(1-tc:GetControler(),tc)
if tc:IsBattle() then
if Duel.PlayStep(tc,0,tp,1-tp,false,false,DS_POS_FACEUP_ACTIVE) then
--negate skill
ds.GainSkillNegateSkill(e:GetHandler(),tc,3,0,1,true)
Duel.PlayComplete()
end
elseif tc:IsExtra() then
Duel.SendtoDrop(tc,DS_REASON_SKILL)
end
end
Duel.ShuffleHand(1-tp)
end
| gpl-3.0 |
thesabbir/luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/leds.lua | 52 | 3065 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("system", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Configuration"), translate("Customizes the behaviour of the device <abbr title=\"Light Emitting Diode\">LED</abbr>s if possible."))
local sysfs_path = "/sys/class/leds/"
local leds = {}
local fs = require "nixio.fs"
local util = require "nixio.util"
if fs.access(sysfs_path) then
leds = util.consume((fs.dir(sysfs_path)))
end
if #leds == 0 then
return m
end
s = m:section(TypedSection, "led", "")
s.anonymous = true
s.addremove = true
function s.parse(self, ...)
TypedSection.parse(self, ...)
os.execute("/etc/init.d/led enable")
end
s:option(Value, "name", translate("Name"))
sysfs = s:option(ListValue, "sysfs", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Name"))
for k, v in ipairs(leds) do
sysfs:value(v)
end
s:option(Flag, "default", translate("Default state")).rmempty = false
trigger = s:option(ListValue, "trigger", translate("Trigger"))
local triggers = fs.readfile(sysfs_path .. leds[1] .. "/trigger")
for t in triggers:gmatch("[%w-]+") do
trigger:value(t, translate(t:gsub("-", "")))
end
delayon = s:option(Value, "delayon", translate ("On-State Delay"))
delayon:depends("trigger", "timer")
delayoff = s:option(Value, "delayoff", translate ("Off-State Delay"))
delayoff:depends("trigger", "timer")
dev = s:option(ListValue, "_net_dev", translate("Device"))
dev.rmempty = true
dev:value("")
dev:depends("trigger", "netdev")
function dev.cfgvalue(self, section)
return m.uci:get("system", section, "dev")
end
function dev.write(self, section, value)
m.uci:set("system", section, "dev", value)
end
function dev.remove(self, section)
local t = trigger:formvalue(section)
if t ~= "netdev" and t ~= "usbdev" then
m.uci:delete("system", section, "dev")
end
end
for k, v in pairs(luci.sys.net.devices()) do
if v ~= "lo" then
dev:value(v)
end
end
mode = s:option(MultiValue, "mode", translate("Trigger Mode"))
mode.rmempty = true
mode:depends("trigger", "netdev")
mode:value("link", translate("Link On"))
mode:value("tx", translate("Transmit"))
mode:value("rx", translate("Receive"))
usbdev = s:option(ListValue, "_usb_dev", translate("USB Device"))
usbdev:depends("trigger", "usbdev")
usbdev.rmempty = true
usbdev:value("")
function usbdev.cfgvalue(self, section)
return m.uci:get("system", section, "dev")
end
function usbdev.write(self, section, value)
m.uci:set("system", section, "dev", value)
end
function usbdev.remove(self, section)
local t = trigger:formvalue(section)
if t ~= "netdev" and t ~= "usbdev" then
m.uci:delete("system", section, "dev")
end
end
for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer") do
local id = p:match("%d+-%d+")
local mf = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/manufacturer") or "?"
local pr = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/product") or "?"
usbdev:value(id, "%s (%s - %s)" %{ id, mf, pr })
end
return m
| apache-2.0 |
nasomi/darkstar | scripts/commands/givexp.lua | 27 | 1213 | ---------------------------------------------------------------------------------------------------
-- func: @givexp <amount> <player>
-- desc: Gives the GM or target player experience points.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function onTrigger(player, amount, target)
if (amount == nil or amount <= 0) then
player:PrintToPlayer("You must enter a valid amount.");
player:PrintToPlayer( "@givexp <amount> <player>" );
return;
end
if (target == nil) then
player:addExp(amount);
-- print( 'Exp amount: ' .. tostring( amount ) );
else
local targ = GetPlayerByName(target);
if (targ ~= nil) then
targ:addExp(amount);
-- print( 'Exp amount: ' .. tostring( amount ) );
player:PrintToPlayer( string.format( "Gave %i exp to player '%s' ", amount, target ) );
else
player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) );
player:PrintToPlayer( "@givexp <amount> <player>" );
end
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Galzweesh.lua | 34 | 1034 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Galzweesh
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0292);
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/Metalworks/npcs/Unlucky_Rat.lua | 34 | 2137 | -----------------------------------
-- Area: Metalworks
-- NPC: Unlucky Rat
-- Starts & Finishes Quest: Mean Machine
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local MeanMachine = player:getQuestStatus(BASTOK,MEAN_MACHINE);
if (MeanMachine == QUEST_ACCEPTED) then
local FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
count = trade:getItemCount();
SlimeOil = trade:hasItemQty(637,1);
if (SlimeOil == true and count == 1) then
player:startEvent(0x022d);
end
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE, 4731);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local MeanMachine = player:getQuestStatus(BASTOK,MEAN_MACHINE);
local Fame = player:getFameLevel(BASTOK);
if (MeanMachine == QUEST_AVAILABLE and Fame >= 2) then
player:startEvent(0x022c);
elseif (MeanMachine == QUEST_ACCEPTED) then
player:startEvent(0x022f);
else
player:startEvent(0x0226);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x022c) then
player:addQuest(BASTOK,MEAN_MACHINE);
elseif (csid == 0x022d) then
player:completeQuest(BASTOK,MEAN_MACHINE);
player:addFame(BASTOK,BAS_FAME*120);
player:tradeComplete();
player:addItem(4869);
player:messageSpecial(ITEM_OBTAINED,4869);
end
end;
| gpl-3.0 |
appaquet/torch-android | src/3rdparty/nnx/SpatialUpSampling.lua | 6 | 2520 | local SpatialUpSampling, parent = torch.class('nn.SpatialUpSampling', 'nn.Module')
local help_desc = [[
Applies a 2D up-sampling over an input image composed of
several input planes. The input tensor in forward(input) is
expected to be a 3D tensor (nInputPlane x width x height).
The number of output planes will be the same as nInputPlane.
The upsampling is done using the simple nearest neighbor
technique. For interpolated (bicubic) upsampling, use
nn.SpatialReSampling().
If the input image is a 3D tensor nInputPlane x width x height,
the output image size will be nInputPlane x owidth x oheight where
owidth = width*dW
oheight = height*dH ]]
function SpatialUpSampling:__init(...)
parent.__init(self)
-- get args
xlua.unpack_class(self, {...}, 'nn.SpatialUpSampling', help_desc,
{arg='dW', type='number', help='stride width', req=true},
{arg='dH', type='number', help='stride height', req=true},
{arg='yDim', type='number', help='image y dimension', default=2},
{arg='xDim', type='number', help='image x dimension', default=3}
)
if self.yDim+1 ~= self.xDim then
error('nn.SpatialUpSampling: yDim must be equals to xDim-1')
end
self.outputSize = torch.LongStorage(4)
self.inputSize = torch.LongStorage(4)
end
function SpatialUpSampling:updateOutput(input)
self.inputSize:fill(1)
for i = 1,self.yDim-1 do
self.inputSize[1] = self.inputSize[1] * input:size(i)
end
self.inputSize[2] = input:size(self.yDim)
self.inputSize[3] = input:size(self.xDim)
for i = self.xDim+1,input:nDimension() do
self.inputSize[4] = self.inputSize[4] * input:size(i)
end
self.outputSize[1] = self.inputSize[1]
self.outputSize[2] = self.inputSize[2] * self.dH
self.outputSize[3] = self.inputSize[3] * self.dW
self.outputSize[4] = self.inputSize[4]
self.output:resize(self.outputSize)
input.nn.SpatialUpSampling_updateOutput(self, input:reshape(self.inputSize))
local outputSize2 = input:size()
outputSize2[self.yDim] = outputSize2[self.yDim] * self.dH
outputSize2[self.xDim] = outputSize2[self.xDim] * self.dW
self.output = self.output:reshape(outputSize2)
return self.output
end
function SpatialUpSampling:updateGradInput(input, gradOutput)
self.gradInput:resize(self.inputSize)
input.nn.SpatialUpSampling_updateGradInput(self, input,
gradOutput:reshape(self.outputSize))
self.gradInput = self.gradInput:reshape(input:size())
return self.gradInput
end
| bsd-3-clause |
haka-security/haka | modules/protocol/http/test/request-modif.lua | 2 | 1128 | -- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
require("protocol/http")
haka.rule {
on = haka.dissectors.http.events.request,
eval = function (http, request)
print("HTTP REQUEST")
debug.pprint(request, { hide = { debug.hide_underscore, debug.hide_function } })
-- We change a part of the request
request.version = "2.0"
-- We change an existing header
request.headers["Host"] = "haka.powered.tld"
-- We destroy one
request.headers["User-Agent"] = nil
-- We create a new one
request.headers["Haka"] = "Done"
-- We create a new one and we remove it
request.headers["Haka2"] = "Done"
request.headers["Haka2"] = nil
print("HTTP MODIFIED REQUEST")
debug.pprint(request, { hide = { debug.hide_underscore, debug.hide_function } })
end
}
haka.rule {
on = haka.dissectors.http.events.response,
eval = function (http, response)
print("HTTP RESPONSE")
debug.pprint(response, { hide = { debug.hide_underscore, debug.hide_function } })
end
}
| mpl-2.0 |
nicholas-leonard/nn | StochasticGradient.lua | 65 | 1921 | local StochasticGradient = torch.class('nn.StochasticGradient')
function StochasticGradient:__init(module, criterion)
self.learningRate = 0.01
self.learningRateDecay = 0
self.maxIteration = 25
self.shuffleIndices = true
self.module = module
self.criterion = criterion
self.verbose = true
end
function StochasticGradient:train(dataset)
local iteration = 1
local currentLearningRate = self.learningRate
local module = self.module
local criterion = self.criterion
local shuffledIndices = torch.randperm(dataset:size(), 'torch.LongTensor')
if not self.shuffleIndices then
for t = 1,dataset:size() do
shuffledIndices[t] = t
end
end
print("# StochasticGradient: training")
while true do
local currentError = 0
for t = 1,dataset:size() do
local example = dataset[shuffledIndices[t]]
local input = example[1]
local target = example[2]
currentError = currentError + criterion:forward(module:forward(input), target)
module:updateGradInput(input, criterion:updateGradInput(module.output, target))
module:accUpdateGradParameters(input, criterion.gradInput, currentLearningRate)
if self.hookExample then
self.hookExample(self, example)
end
end
currentError = currentError / dataset:size()
if self.hookIteration then
self.hookIteration(self, iteration, currentError)
end
if self.verbose then
print("# current error = " .. currentError)
end
iteration = iteration + 1
currentLearningRate = self.learningRate/(1+iteration*self.learningRateDecay)
if self.maxIteration > 0 and iteration > self.maxIteration then
print("# StochasticGradient: you have reached the maximum number of iterations")
print("# training error = " .. currentError)
break
end
end
end
| bsd-3-clause |
nasomi/darkstar | scripts/zones/Port_Bastok/npcs/Numa.lua | 36 | 1824 | -----------------------------------
-- Area: Port Bastok
-- NPC: Numa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NUMA_SHOP_DIALOG);
stock = {
0x30A9, 5079,1, --Cotton Hachimaki
0x3129, 7654,1, --Cotton Dogi
0x31A9, 4212,1, --Cotton Tekko
0x3229, 6133,1, --Cotton Sitabaki
0x32A9, 3924,1, --Cotton Kyahan
0x3395, 3825,1, --Silver Obi
0x30A8, 759,2, --Hachimaki
0x3128, 1145,2, --Kenpogi
0x31A8, 630,2, --Tekko
0x3228, 915,2, --Sitabaki
0x32A8, 584,2, --Kyahan
0x02C0, 132,2, --Bamboo Stick
0x025D, 180,3, --Pickaxe
0x16EB, 13500,3, --Toolbag (Ino)
0x16EC, 18000,3, --Toolbag (Shika)
0x16ED, 18000,3 --Toolbag (Cho)
}
showNationShop(player, BASTOK, 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.