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 |
|---|---|---|---|---|---|
renyaoxiang/QSanguosha-For-Hegemony | lua/ai/basara-ai.lua | 2 | 10937 | --[[********************************************************************
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
*********************************************************************]]
sgs.ai_skill_invoke["userdefine:halfmaxhp"] = function(self)
return not self:needKongcheng(self.player, true) or self.player:getPhase() == sgs.Player_Play
end
sgs.ai_skill_invoke["userdefine:changetolord"] = function(self)
return math.random() < 0.8
end
sgs.ai_skill_choice.CompanionEffect = function(self, choice, data)
if ( self:isWeak() or self:needKongcheng(self.player, true) ) and string.find(choice, "recover") then return "recover"
else return "draw" end
end
sgs.ai_skill_invoke["userdefine:FirstShowReward"] = function(self, choice, data)
if self.room:getMode() == "jiange_defense" then return false end
return true
end
sgs.ai_skill_choice.heg_nullification = function(self, choice, data)
local effect = data:toCardEffect()
if effect.card:isKindOf("AOE") or effect.card:isKindOf("GlobalEffect") then
if self:isFriendWith(effect.to) then return "all"
elseif self:isFriend(effect.to) then return "single"
elseif self:isEnemy(effect.to) then return "all"
end
end
return "all"
end
sgs.ai_skill_choice["GameRule:TriggerOrder"] = function(self, choices, data)
local canShowHead = string.find(choices, "GameRule_AskForGeneralShowHead")
local canShowDeputy = string.find(choices, "GameRule_AskForGeneralShowDeputy")
local firstShow = ("luanji|qianhuan"):split("|")
local bothShow = ("luanji+shuangxiong|luanji+huoshui|huoji+jizhi|luoshen+fangzhu|guanxing+jizhi"):split("|")
local followShow = ("qianhuan|duoshi|rende|cunsi|jieyin|xiongyi|shouyue|hongfa"):split("|")
local notshown, shown, allshown, f, e, eAtt = 0, 0, 0, 0, 0, 0
for _,p in sgs.qlist(self.room:getAlivePlayers()) do
if not p:hasShownOneGeneral() then
notshown = notshown + 1
end
if p:hasShownOneGeneral() then
shown = shown + 1
if self:evaluateKingdom(p) == self.player:getKingdom() then
f = f + 1
else
e = e + 1
if self:isWeak(p) and p:getHp() == 1 and self.player:distanceTo(p) <= self.player:getAttackRange() then eAtt= eAtt + 1 end
end
end
if p:hasShownAllGenerals() then
allshown = allshown + 1
end
end
local showRate = math.random() + shown/20
local firstShowReward = false
if sgs.GetConfig("RewardTheFirstShowingPlayer", true) then
if shown == 0 then
firstShowReward = true
end
end
if (firstShowReward or self:willShowForAttack()) and not self:willSkipPlayPhase() then
for _, skill in ipairs(bothShow) do
if self.player:hasSkills(skill) then
if canShowHead and showRate > 0.7 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.7 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
end
if firstShowReward and not self:willSkipPlayPhase() then
for _, skill in ipairs(firstShow) do
if self.player:hasSkill(skill) and not self.player:hasShownOneGeneral() then
if self.player:inHeadSkills(skill) and canShowHead and showRate > 0.8 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.8 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
if not self.player:hasShownOneGeneral() then
if canShowHead and showRate > 0.9 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.9 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
if self.player:inHeadSkills("baoling") then
if (self.player:hasSkill("luanwu") and self.player:getMark("@chaos") ~= 0)
or (self.player:hasSkill("xiongyi") and self.player:getMark("@arise") ~= 0) then
canShowHead = false
end
end
if self.player:inHeadSkills("baoling") then
if (self.player:hasSkill("mingshi") and allshown >= (self.room:alivePlayerCount() - 1))
or (self.player:hasSkill("luanwu") and self.player:getMark("@chaos") == 0)
or (self.player:hasSkill("xiongyi") and self.player:getMark("@arise") == 0) then
if canShowHead then
return "GameRule_AskForGeneralShowHead"
end
end
end
if self.player:hasSkill("guixiu") and not self.player:hasShownSkill("guixiu") then
if self:isWeak() or (shown > 0 and eAtt > 0 and e - f < 3 and not self:willSkipPlayPhase() ) then
if self.player:inHeadSkills("guixiu") and canShowHead then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
for _,p in ipairs(self.friends) do
if p:hasShownSkill("jieyin") then
if canShowHead and self.player:getGeneral():isMale() then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and self.player:getGeneral():isFemale() and self.player:getGeneral2():isMale() then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
if self.player:getMark("CompanionEffect") > 0 then
if self:isWeak() or (shown > 0 and eAtt > 0 and e - f < 3 and not self:willSkipPlayPhase()) then
if canShowHead then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
if self.player:getMark("HalfMaxHpLeft") > 0 then
if self:isWeak() and self:willShowForDefence() then
if canShowHead and showRate > 0.6 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate >0.6 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
if self.player:hasTreasure("JadeSeal") then
if not self.player:hasShownOneGeneral() then
if canShowHead then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
for _, skill in ipairs(followShow) do
if ((shown > 0 and e < notshown) or self.player:hasShownOneGeneral()) and self.player:hasSkill(skill) then
if self.player:inHeadSkills(skill) and canShowHead and showRate > 0.6 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.6 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
for _, skill in ipairs(followShow) do
if not self.player:hasShownOneGeneral() then
for _,p in sgs.qlist(self.room:getOtherPlayers(player)) do
if p:hasShownSkill(skill) and p:getKingdom() == self.player:getKingdom() then
if canShowHead and canShowDeputy and showRate > 0.2 then
local cho = { "GameRule_AskForGeneralShowHead", "GameRule_AskForGeneralShowDeputy"}
return cho[math.random(1, #cho)]
elseif canShowHead and showRate > 0.2 then
return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.2 then
return "GameRule_AskForGeneralShowDeputy"
end
end
end
end
end
local skillTrigger = false
local skillnames = choices:split("+")
table.removeOne(skillnames, "GameRule_AskForGeneralShowHead")
table.removeOne(skillnames, "GameRule_AskForGeneralShowDeputy")
table.removeOne(skillnames, "cancel")
if #skillnames ~= 0 then
skillTrigger = true
end
if skillTrigger then
if string.find(choices, "jieming") then return "jieming" end
if string.find(choices, "wangxi") and string.find(choices, "fankui") then
local from = data:toDamage().from
if from and from:isNude() then return "wangxi" end
end
if string.find(choices, "fankui") and string.find(choices, "ganglie") then return "fankui" end
if string.find(choices, "wangxi") and string.find(choices, "ganglie") then return "ganglie" end
if string.find(choices, "luoshen") and string.find(choices, "guanxing") then return "guanxing" end
if string.find(choices, "wangxi") and string.find(choices, "fangzhu") then return "fangzhu" end
if table.contains(skillnames, "tiandu") then
local judge = data:toJudge()
if judge.card:isKindOf("Peach") or judge.card:isKindOf("Analeptic") then
return "tiandu"
end
end
local except = {}
for _, skillname in ipairs(skillnames) do
local invoke = self:askForSkillInvoke(skillname, data)
if invoke == true then
return skillname
elseif invoke == false then
table.insert(except, skillname)
end
end
if string.find(choices, "cancel") and not canShowHead and not canShowDeputy and not self.player:hasShownOneGeneral() then
return "cancel"
end
table.removeTable(skillnames, except)
if #skillnames > 0 then return skillnames[math.random(1, #skillnames)] end
end
return "cancel"
end
sgs.ai_skill_choice["GameRule:TurnStart"] = function(self, choices, data)
local choice = sgs.ai_skill_choice["GameRule:TriggerOrder"](self, choices, data)
if choice == "cancel" then
local canShowHead = string.find(choices, "GameRule_AskForGeneralShowHead")
local canShowDeputy = string.find(choices, "GameRule_AskForGeneralShowDeputy")
local showRate = math.random()
if canShowHead and showRate > 0.8 then
if self.player:isDuanchang() then return "GameRule_AskForGeneralShowHead" end
for _, p in ipairs(self.enemies) do
if p:hasShownSkills("mingshi|huoshui") then return "GameRule_AskForGeneralShowHead" end
end
elseif canShowDeputy and showRate > 0.8 then
if self.player:isDuanchang() then return "GameRule_AskForGeneralShowDeputy" end
for _, p in ipairs(self.enemies) do
if p:hasShownSkills("mingshi|huoshui") then return "GameRule_AskForGeneralShowDeputy" end
end
end
if not self.player:hasShownOneGeneral() then
local gameProcess = sgs.gameProcess():split(">>")
if self.player:getKingdom() == gameProcess[1] and (self.player:getLord() or sgs.shown_kingdom[self.player:getKingdom()] < self.player:aliveCount() / 2) then
if canShowHead and showRate > 0.6 then return "GameRule_AskForGeneralShowHead"
elseif canShowDeputy and showRate > 0.6 then return "GameRule_AskForGeneralShowDeputy" end
end
end
end
return choice
end
sgs.ai_skill_invoke.GameRule_AskForArraySummon = function(self, data)
return self:willShowForDefence() or self:willShowForAttack()
end
sgs.ai_skill_invoke.SiegeSummon = true
sgs.ai_skill_invoke["SiegeSummon!"] = false
sgs.ai_skill_invoke.FormationSummon = true
sgs.ai_skill_invoke["FormationSummon!"] = false
sgs.ai_skill_choice["GuanxingShowGeneral"] = function(self, choices, data)
if self.room:alivePlayerCount() >= 5 then
local cho = { "show_head_general", "show_deputy_general"}
return cho[math.random(1, #cho)]
end
return "show_both_generals"
end
| gpl-3.0 |
thesabbir/luci | applications/luci-app-siitwizard/luasrc/model/cbi/siitwizard.lua | 68 | 9836 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local uci = require "luci.model.uci".cursor()
local bit = require "nixio".bit
local ip = require "luci.ip"
-------------------- Init --------------------
--
-- Find link-local address
--
function find_ll()
local _, r
for _, r in ipairs(ip.routes({ family = 6, dest = "fe80::/64" })) do
if r.dest:higher("fe80:0:0:0:ff:fe00:0:0") then
return (r.dest - "fe80::")
end
end
return ip.IPv6("::")
end
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000"
local ipv4_pool = uci:get("siit", "ipv4", "pool") or "172.16.0.0/12"
local ipv4_netsz = uci:get("siit", "ipv4", "netsize") or "24"
--
-- Find IPv4 allocation pool
--
local gv4_net = ip.IPv4(ipv4_pool)
--
-- Generate ULA
--
local ula = ip.IPv6("::/64")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(ip.IPv6(prefix))
end
ula = ula:add(find_ll())
-------------------- View --------------------
f = SimpleForm("siitwizward", "SIIT-Wizzard",
"This wizzard helps to setup SIIT (IPv4-over-IPv6) translation according to RFC2765.")
f:field(DummyValue, "info_ula", "Mesh ULA address").value = ula:string()
f:field(DummyValue, "ipv4_pool", "IPv4 allocation pool").value =
"%s (%i hosts)" %{ gv4_net:string(), 2 ^ ( 32 - gv4_net:prefix() ) - 2 }
f:field(DummyValue, "ipv4_size", "IPv4 LAN network prefix").value =
"%i bit (%i hosts)" %{ ipv4_netsz, 2 ^ ( 32 - ipv4_netsz ) - 2 }
mode = f:field(ListValue, "mode", "Operation mode")
mode:value("client", "Client")
mode:value("gateway", "Gateway")
dev = f:field(ListValue, "device", "Wireless device")
uci:foreach("wireless", "wifi-device",
function(section)
dev:value(section[".name"])
end)
lanip = f:field(Value, "ipaddr", "LAN IPv4 subnet")
function lanip.formvalue(self, section)
local val = self.map:formvalue(self:cbid(section))
local net = ip.IPv4("%s/%i" %{ val, ipv4_netsz })
if net then
if gv4_net:contains(net) then
if not net:minhost():equal(net:host()) then
self.error = { [section] = true }
f.errmessage = "IPv4 address is not the first host of " ..
"subnet, expected " .. net:minhost():string()
end
else
self.error = { [section] = true }
f.errmessage = "IPv4 address is not within the allocation pool"
end
else
self.error = { [section] = true }
f.errmessage = "Invalid IPv4 address given"
end
return val
end
dns = f:field(Value, "dns", "DNS server for LAN clients")
dns.value = "141.1.1.1"
-------------------- Control --------------------
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
end
return true
end
function mode.write(self, section, value)
--
-- Find LAN IPv4 range
--
local lan_net = ip.IPv4(
( lanip:formvalue(section) or "172.16.0.1" ) .. "/" .. ipv4_netsz
)
if not lan_net then return end
--
-- Find wifi interface, dns server and hostname
--
local device = dev:formvalue(section)
local dns_server = dns:formvalue(section) or "141.1.1.1"
local hostname = "siit-" .. lan_net:host():string():gsub("%.","-")
--
-- Configure wifi device
--
local wifi_device = dev:formvalue(section)
local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net"
local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be"
local wifi_channel = uci:get("siit", "wifi", "channel") or "1"
-- nuke old device definition
uci:delete_all("wireless", "wifi-iface",
function(s) return s.device == wifi_device end )
uci:delete_all("network", "interface",
function(s) return s['.name'] == wifi_device end )
-- create wifi device definition
uci:tset("wireless", wifi_device, {
disabled = 0,
channel = wifi_channel,
-- txantenna = 1,
-- rxantenna = 1,
-- diversity = 0
})
uci:section("wireless", "wifi-iface", nil, {
encryption = "none",
mode = "adhoc",
txpower = 10,
sw_merge = 1,
network = wifi_device,
device = wifi_device,
ssid = wifi_essid,
bssid = wifi_bssid,
})
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
-- wan mtu
uci:set("network", "wan", "mtu", 1240)
-- lan settings
uci:tset("network", "lan", {
mtu = 1240,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string(),
proto = "static"
})
-- use full siit subnet
siit_route = ip.IPv6(siit_prefix .. "/96")
-- v4 <-> siit route
uci:delete_all("network", "route",
function(s) return s.interface == "siit0" end)
uci:section("network", "route", nil, {
interface = "siit0",
target = gv4_net:network():string(),
netmask = gv4_net:mask():string()
})
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
-- lan settings
uci:tset("network", "lan", {
mtu = 1240,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string()
})
-- derive siit subnet from lan config
siit_route = ip.IPv6(
siit_prefix .. "/" .. (96 + lan_net:prefix())
):add(lan_net[2])
-- ipv4 <-> siit route
uci:delete_all("network", "route",
function(s) return s.interface == "siit0" end)
-- XXX: kind of a catch all, gv4_net would be better
-- but does not cover non-local v4 space
uci:section("network", "route", nil, {
interface = "siit0",
target = "0.0.0.0",
netmask = "0.0.0.0"
})
end
-- setup the firewall
uci:delete_all("firewall", "zone",
function(s) return (
s['.name'] == "siit0" or s.name == "siit0" or
s.network == "siit0" or s['.name'] == wifi_device or
s.name == wifi_device or s.network == wifi_device
) end)
uci:delete_all("firewall", "forwarding",
function(s) return (
s.src == wifi_device and s.dest == "siit0" or
s.dest == wifi_device and s.src == "siit0" or
s.src == "lan" and s.dest == "siit0" or
s.dest == "lan" and s.src == "siit0"
) end)
uci:section("firewall", "zone", "siit0", {
name = "siit0",
network = "siit0",
input = "ACCEPT",
output = "ACCEPT",
forward = "ACCEPT"
})
uci:section("firewall", "zone", wifi_device, {
name = wifi_device,
network = wifi_device,
input = "ACCEPT",
output = "ACCEPT",
forward = "ACCEPT"
})
uci:section("firewall", "forwarding", nil, {
src = wifi_device,
dest = "siit0"
})
uci:section("firewall", "forwarding", nil, {
src = "siit0",
dest = wifi_device
})
uci:section("firewall", "forwarding", nil, {
src = "lan",
dest = "siit0"
})
uci:section("firewall", "forwarding", nil, {
src = "siit0",
dest = "lan"
})
-- firewall include
uci:delete_all("firewall", "include",
function(s) return s.path == "/etc/firewall.user" end)
uci:section("firewall", "include", nil, {
path = "/etc/firewall.user"
})
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "none"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = "siit0",
target = siit_route:string()
})
-- create wifi network interface
uci:section("network", "interface", wifi_device, {
proto = "static",
mtu = 1400,
ip6addr = ula:string()
})
-- nuke old olsrd interfaces
uci:delete_all("olsrd", "Interface",
function(s) return s.interface == wifi_device end)
-- configure olsrd interface
uci:foreach("olsrd", "olsrd",
function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end)
uci:section("olsrd", "Interface", nil, {
ignore = 0,
interface = wifi_device,
Ip6AddrType = "unique-local"
})
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s) return true end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
-- txtinfo v6 & olsrd nameservice
uci:foreach("olsrd", "LoadPlugin",
function(s)
if s.library == "olsrd_txtinfo.so.0.1" then
uci:set("olsrd", s['.name'], "accept", "::1")
elseif s.library == "olsrd_nameservice.so.0.3" then
uci:set("olsrd", s['.name'], "name", hostname)
end
end)
-- lan dns
uci:tset("dhcp", "lan", {
dhcp_option = "6," .. dns_server,
start = bit.band(lan_net:minhost():add(1)[2][2], 0xFF),
limit = ( 2 ^ ( 32 - lan_net:prefix() ) ) - 3
})
-- hostname
uci:foreach("system", "system",
function(s)
uci:set("system", s['.name'], "hostname", hostname)
end)
uci:save("wireless")
uci:save("firewall")
uci:save("network")
uci:save("system")
uci:save("olsrd")
uci:save("dhcp")
end
return f
| apache-2.0 |
nasomi/darkstar | scripts/zones/Buburimu_Peninsula/npcs/Logging_Point.lua | 29 | 1116 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Silke.lua | 34 | 1243 | -----------------------------------
-- Area: Bastok Markets (S)
-- NPC: Silke
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SILKE_SHOP_DIALOG);
stock = {0x17ab,29925, -- Animus Augeo Schema
0x17ac,29925, -- Animus Minuo Schema
0x17ad,36300} -- Adloquim Schema
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
thesabbir/luci | modules/luci-base/luasrc/http/protocol/conditionals.lua | 68 | 3024 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
local method = req.env and req.env.REQUEST_METHOD or "GET"
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if method == "GET" or method == "HEAD" then
return false, 304, {
["ETag"] = etag;
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
| apache-2.0 |
znek/xupnpd | src/plugins/xupnpd_youtube.lua | 2 | 20373 | -- Copyright (C) 2011-2013 Anton Burdinuk
-- clark15b@gmail.com
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- sysmer add support api v3 (need install curl with ssl)
-- 20150524 AnLeAl changes:
-- in url fetch, added docs section
-- 20150527 AnLeAl changes:
-- fixed for video get when less than 50
-- returned ui config for user amount video
-- add possibility get more than 50 videos
-- 20150527 MejGun changes:
-- code refactoring for feed update
-- 20150530 AnLeAl changes:
-- small code cleanup
-- added 'channel/mostpopular' for youtube mostpopular videos (it's only 30 from api), also region code from ui working
-- added favorites/username to get favorites
-- added search function
-- 20150531 AnLeAl changes:
-- fixed error when only first feed can get all videos for cfg.youtube_video_count and other no more 50
-- ui help updated
-- curl settings from cycles was moved to variables
-- 20170321 vidok changes:
-- added vlc descrambler
-- added youtube_preferred_resolution parameter
-- README
-- This is YouTube api v3 plugin for xupnpd.
-- For now only search username supported.
-- Quickstart:
-- 1. Place this file into xupnpd plugin directory.
-- 2. Go to google developers console: https://developers.google.com/youtube/registering_an_application?hl=ru
-- 3. You need API Key, choose Browser key: https://developers.google.com/youtube/registering_an_application?hl=ru#Create_API_Keys
-- 4. Don't use option: only allow referrals from domains.
-- 5. Replace '***' with your new key in section '&key=***' in this file. Save file.
-- 6. Restart xupnpd, remove any old feeds that was made for youtube earlier. Add new one based on username.
-- 7. Enjoy!
-- 18 - 360p (MP4,h.264/AVC)
-- 22 - 720p (MP4,h.264/AVC) hd
-- 37 - 1080p (MP4,h.264/AVC) hd
-- 82 - 360p (MP4,h.264/AVC) stereo3d
-- 83 - 480p (MP4,h.264/AVC) hq stereo3d
-- 84 - 720p (MP4,h.264/AVC) hd stereo3d
-- 85 - 1080p (MP4,h.264/AVC) hd stereo3d
cfg.youtube_preferred_resolution=1080
cfg.youtube_fmt=37
cfg.youtube_region='*'
cfg.youtube_video_count=100
-- cfg.youtube_api_key=123
youtube_api_url='https://www.googleapis.com/youtube/v3/'
function youtube_updatefeed(feed,friendly_name)
local function isempty(s)
return s == nil or s == ''
end
local rc=false
local feed_url=nil
local feed_urn=nil
local tfeed=split_string(feed,'/')
local feed_name='youtube_'..string.lower(string.gsub(feed,"[/ :\'\"]",'_'))
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=youtube\n')
--------------------------------------------------------------------------------------------------
--local getopt = '/mnt/sda1/iptv/curl/curl -k '
local count = 0
local totalres = 0
local numA = 50 -- show 50 videos per page 0..50 from youtube api v3
local pagetokenA = ''
local nextpageA = ''
local allpages = math.ceil(cfg.youtube_video_count/numA) -- check how much pages per 50 videos there can be
local lastpage = allpages - 1
local maxA = '&maxResults=' .. numA
if cfg.youtube_video_count < numA then
maxA = '&maxResults=' .. cfg.youtube_video_count
numA = cfg.youtube_video_count
end
local keyA = '&key=***' -- change *** to your youtube api key from: https://console.developers.google.com
local cA = ''
local iA = ''
local userA = tfeed[1]
local uploads = ''
local region = ''
local enough = false
-- Get what exactly user wants to get.
if tfeed[1]=='channel' and tfeed[2]=='mostpopular' then
if cfg.youtube_region and cfg.youtube_region~='*' then uploads='®ionCode='..cfg.youtube_region end
iA = youtube_api_url..'videos?part=snippet&chart=mostPopular'
elseif tfeed[1]=='favorites' then
cA = youtube_api_url..'channels?part=contentDetails&forUsername='
iA = youtube_api_url..'playlistItems?part=snippet&playlistId='
userA = tfeed[2]
local jsonA = cA .. userA .. keyA
--local url_data = io.popen(getopt .. jsonA)
--local user_data = url_data:read('*all')
--url_data:close()
local user_data = http.download(jsonA)
local x=json.decode(user_data)
uploads = x['items'][1]['contentDetails']['relatedPlaylists']['favorites']
x=nil
elseif tfeed[1]=='playlist' then
uploads = tfeed[2]
iA = youtube_api_url..'playlistItems?part=snippet&playlistId='
elseif tfeed[1]=='channel' then
cA = youtube_api_url..'channels?part=contentDetails&id='
iA = youtube_api_url..'playlistItems?part=snippet&playlistId='
local channel_id = tfeed[2]
local jsonA = cA .. channel_id .. keyA
--local url_data = io.popen(getopt .. jsonA)
--local user_data = url_data:read('*all')
--url_data:close()
local user_data = http.download(jsonA)
local x=json.decode(user_data)
uploads = x['items'][1]['contentDetails']['relatedPlaylists']['uploads']
x=nil
elseif tfeed[1]=='search' then
-- feed_urn='videos?vq='..util.urlencode(tfeed[2])..'&alt=json'
if cfg.youtube_region and cfg.youtube_region~='*' then region='®ionCode='..cfg.youtube_region end
iA = youtube_api_url..'search?type=video&part=snippet&order=date&q=' .. util.urlencode(tfeed[2]) .. '&videoDefinition=high&videoDimension=2d' .. region
uploads = ''
else
cA = youtube_api_url..'channels?part=contentDetails&forUsername='
iA = youtube_api_url..'playlistItems?part=snippet&playlistId='
userA = tfeed[1]
local jsonA = cA .. userA .. keyA
--local url_data = io.popen(getopt .. jsonA)
--local user_data = url_data:read('*all')
--url_data:close()
local user_data = http.download(jsonA)
local x=json.decode(user_data)
uploads = x['items'][1]['contentDetails']['relatedPlaylists']['uploads']
x=nil
end
while true do
local jsonA = iA .. uploads .. maxA .. pagetokenA .. keyA
--local url_data = io.popen(getopt .. jsonA)
--local item_data = url_data:read('*all')
--url_data:close()
local item_data = http.download(jsonA)
if item_data == nil then
if cfg.debug>0 then print('YouTube feed \''..feed_name..'\' NOT updated') end
return rc
end
local x=json.decode(item_data)
if isempty(x['pageInfo']) then
break
end
totalres = x['pageInfo']['totalResults']
local realpages = math.ceil(totalres/numA)
local prelastpage = realpages - 1
local items = nil
local title = nil
local url = nil
local img = nil
local countx = 0
for key,value in pairs(x['items']) do
count = count + 1
if count > cfg.youtube_video_count then
enough = true
break
end
if tfeed[1]=='channel' and tfeed[2]=='mostpopular' then
items = value['id']
elseif tfeed[1]=='search' then
items = value['id']['videoId']
else
items = value['snippet']['resourceId']['videoId']
end
title = value['snippet']['title']
url = 'https://www.youtube.com/watch?v=' .. items .. '&feature=youtube_gdata'
img = 'http://i.ytimg.com/vi/' .. items .. '/mqdefault.jpg'
dfd:write('#EXTINF:0 logo=',img,' ,',title,'\n',url,'\n')
end
if isempty(x['nextPageToken']) or enough then
break
else
nextpageA = x['nextPageToken']
pagetokenA = '&pageToken=' .. nextpageA
end
x=nil
-- enough=nil
end
dfd:close()
---------------------------------------------------------------------------------------------------------
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('YouTube feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
return rc
end
function youtube_sendurl(youtube_url,range)
local url=nil
if plugin_sendurl_from_cache(youtube_url,range) then return end
url=youtube_get_video_url(youtube_url)
if url then
if cfg.debug>0 then print('YouTube Real URL: '..url) end
plugin_sendurl(youtube_url,url,range)
else
if cfg.debug>0 then print('YouTube clip is not found') end
plugin_sendfile('www/corrupted.mp4')
end
end
-- Helper to search and extract code from javascript stream
function js_extract( js, pattern )
--js.i = 0 -- Reset to beginning
--for line in buf_iter, js do
for line in string.gmatch(js.stream,"(.-};)\r?\n" ) do
local ex = string.match( line, pattern )
if ex then
return ex
end
end
if cfg.debug>0 then print("Youtube.js_extract(pattern="..pattern.."). Couldn't process youtube video URL." ) end
return nil
end
-- Descramble the URL signature using the javascript code that does that
-- in the web page
function js_descramble( sig, js_url )
--print("Youtube.js_descramble stream="..stream)
-- Fetch javascript code
local js = { stream = plugin_download(js_url) }
--print("Youtube.js_descramble js.stream="..js.stream)
if not js.stream then
if cfg.debug>0 then print("Youtube.js_descramble("..sig..", "..js_url.."). Couldn't process youtube video JS URL." ) end
return sig
end
-- Look for the descrambler function's name
-- c&&a.set("signature",br(c));
local descrambler = js_extract( js, "%.set%(\"signature\",([^)]-)%(" )
--print("Youtube.js_descramble descrambler = "..descrambler)
if not descrambler then
if cfg.debug>0 then print ( "Youtube.js_descramble. ("..js.."). Couldn't extract youtube video URL signature descrambling function name" ) end
js.stream=nil
return sig
end
-- Fetch the code of the descrambler function
-- Go=function(a){a=a.split("");Fo.sH(a,2);Fo.TU(a,28);Fo.TU(a,44);Fo.TU(a,26);Fo.TU(a,40);Fo.TU(a,64);Fo.TR(a,26);Fo.sH(a,1);return a.join("")};
local rules = js_extract( js, "^"..descrambler.."=function%([^)]*%){(.-)};" )
--print("Youtube.js_descramble rules = "..rules)
if not rules then
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't extract youtube video URL signature descrambling rules" ) end
js.stream=nil
return sig
end
-- Get the name of the helper object providing transformation definitions
local helper = string.match( rules, ";(..)%...%(" )
--print("Youtube.js_descramble helper = "..helper)
if not helper then
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't extract youtube video URL signature transformation helper name" ) end
js.stream=nil
return sig
end
-- Fetch the helper object code
-- var Fo={TR:function(a){a.reverse()},TU:function(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c},sH:function(a,b){a.splice(0,b)}};
local transformations = js_extract( js, "[ ,]"..helper.."={(.-)};" )
--print("Youtube.js_descramble transformations = "..transformations)
js.stream=nil
if not transformations then
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't extract youtube video URL signature transformation code" ) end
return sig
end
-- Parse the helper object to map available transformations
local trans = {}
for meth,code in string.gmatch( transformations, "(..):function%([^)]*%){([^}]*)}" ) do
-- a=a.reverse()
if string.match( code, "%.reverse%(" ) then
trans[meth] = "reverse"
-- a.splice(0,b)
elseif string.match( code, "%.splice%(") then
trans[meth] = "slice"
-- var c=a[0];a[0]=a[b%a.length];a[b]=c
elseif string.match( code, "var c=" ) then
trans[meth] = "swap"
else
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't parse unknown youtube video URL signature transformation") end
end
end
-- Parse descrambling rules, map them to known transformations
-- and apply them on the signature
local missing = false
for meth,idx in string.gmatch( rules, "..%.(..)%([^,]+,(%d+)%)" ) do
idx = tonumber( idx )
if trans[meth] == "reverse" then
sig = string.reverse( sig )
elseif trans[meth] == "slice" then
sig = string.sub( sig, idx + 1 )
elseif trans[meth] == "swap" then
if idx > 1 then
sig = string.gsub( sig, "^(.)("..string.rep( ".", idx - 1 )..")(.)(.*)$", "%3%2%1%4" )
elseif idx == 1 then
sig = string.gsub( sig, "^(.)(.)", "%2%1" )
end
else
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't apply unknown youtube video URL signature transformation. missing = true") end
missing = true
end
end
if missing then
if cfg.debug>0 then print ( "Youtube.js_descramble. Couldn't process youtube video URL. missing=true" ) end
end
--print("Youtube.js_descramble sig = "..sig)
return sig
end
-- decode URL
function unescape (s)
s = string.gsub(s,"%%(%x%x)", function (h)
return string.char(tonumber(h, 16))
end)
return s
end
-- Parse and pick our video URL
function pick_url( url_map, fmt, js_url )
local path = nil
for stream in string.gmatch( url_map, "[^,]+" ) do
-- Apparently formats are listed in quality order,
-- so we can afford to simply take the first one
local itag = string.match( stream, "itag=(%d+)" )
if not fmt or not itag or tonumber( itag ) == tonumber( fmt ) then
local url = string.match( stream, "url=([^&,]+)" )
if url then
-- url = vlc.strings.decode_uri( url )
url = unescape (url)
--print( "Youtube.pick_url unescape url="..url)
local sig = string.match( stream, "sig=([^&,]+)" )
if not sig then
-- Scrambled signature
sig = string.match( stream, "s=([^&,]+)" )
if sig then
if cfg.debug>0 then print( "Youtube.pick_url Found "..string.len( sig ).."-character scrambled signature for youtube video URL, attempting to descramble... " ) end
if js_url then
sig = js_descramble( sig, js_url )
else
if cfg.debug>0 then print("Youtube.pick_url "..js_url..". Couldn't process youtube video URL" ) end
end
end
end
local signature = ""
if sig then
signature = "&signature="..sig
end
--print( "Youtube.pick_url signature="..signature)
path = url..signature
--print( "Youtube.pick_url path="..path)
break
end
end
end
return path
end
function youtube_get_best_fmt(urls,fmt)
if fmt>81 and fmt<86 then -- 3d
local i=fmt while(i>81) do
if urls[i] then return urls[i] end
i=i-1
end
local t={ [82]=18, [83]=18, [84]=22, [85]=37 }
fmt=t[fmt]
end
local t={ 37,22,18 }
local t2={ [18]=true, [22]=true, [37]=true }
for i=1,3,1 do
local u=urls[ t[i] ]
if u and t2[fmt] and t[i]<=fmt then return u end
end
return urls[18]
end
-- Pick the most suited format available
function get_fmt( fmt_list )
local prefres = cfg.youtube_preferred_resolution
if prefres < 0 then
return nil
end
local fmt = nil
for itag,height in string.gmatch( fmt_list, "(%d+)/%d+x(%d+)/[^,]+" ) do
-- Apparently formats are listed in quality
-- order, so we take the first one that works,
-- or fallback to the lowest quality
fmt = itag
-- remove WebM itag=43
if tonumber(height) <= prefres and fmt~='43' then
break
end
end
return fmt
end
function youtube_get_video_url(youtube_url)
local clip_page=plugin_download(youtube_url)
if clip_page then
local line=string.match(clip_page,'ytplayer.config%s*=%s*({.-});')
clip_page=nil
local js_url = string.match( line, "\"js\": *\"(.-)\"" )
if js_url then
js_url = string.gsub( js_url, "\\/", "/" )
-- Resolve JS URL
if string.match( js_url, "^/[^/]" ) then
local authority = string.match( youtube_url, "://([^/]*)/" )
js_url = "//"..authority..js_url
end
js_url = string.gsub( js_url, "^//", string.match( youtube_url, ".-://" ) )
end
fmt_list = string.match( line, "\"fmt_list\": *\"(.-)\"" )
if fmt_list then
fmt_list = string.gsub( fmt_list, "\\/", "/" )
fmt = get_fmt( fmt_list )
end
-- print ("fmt\r\n"..fmt)
url_map = string.match( line, "\"url_encoded_fmt_stream_map\": *\"(.-)\"" )
if url_map then
-- FIXME: do this properly
url_map = string.gsub( url_map, "\\u0026", "&" )
path = pick_url( url_map, fmt, js_url )
end
-- print ("path\r\n"..path)
if not path then
-- If this is a live stream, the URL map will be empty
-- and we get the URL from this field instead
local hlsvp = string.match( line, "\"hlsvp\": *\"(.-)\"" )
if hlsvp then
hlsvp = string.gsub( hlsvp, "\\/", "/" )
path = hlsvp
end
end
else
if cfg.debug>0 then print('YouTube clip is not found') end
return nil
end
return path;
end
function youtube_old_get_video_url(youtube_url)
local url=nil
local clip_page=plugin_download(youtube_url)
if clip_page then
local s=json.decode(string.match(clip_page,'ytplayer.config%s*=%s*({.-});'))
clip_page=nil
local stream_map=nil
-- s.args.adaptive_fmts
-- itag 137: 1080p
-- itag 136: 720p
-- itag 135: 480p
-- itag 134: 360p
-- itag 133: 240p
-- itag 160: 144
-- local player_url=nil if s.assets then player_url=s.assets.js end if player_url and string.sub(player_url,1,2)=='//' then player_url='http:'..player_url end
if s.args then stream_map=s.args.url_encoded_fmt_stream_map end
local fmt=string.match(youtube_url,'&fmt=(%w+)$')
if not fmt then fmt=cfg.youtube_fmt end
if stream_map then
local urls={}
for i in string.gmatch(stream_map,'([^,]+)') do
local item={}
for j in string.gmatch(i,'([^&]+)') do
local name,value=string.match(j,'(%w+)=(.+)')
if name then
--print(name,util.urldecode(value))
item[name]=util.urldecode(value)
end
end
local sig=item['sig'] or item['s']
local u=item['url']
if sig then u=u..'&signature='..sig end
--print(item['itag'],u)
urls[tonumber(item['itag'])]=u
--print('\n')
end
url=youtube_get_best_fmt(urls,tonumber(fmt))
--print('old url='..url)
end
return url
else
if cfg.debug>0 then print('YouTube clip is not found') end
return nil
end
end
plugins['youtube']={}
plugins.youtube.name="YouTube"
plugins.youtube.desc="<i>username</i>, favorites/<i>username</i>, playlist/<i>idplaylist</i>, search/<i>search_string</i>"..
"<br/><b>YouTube channels</b>: channel/mostpopular, channel/<i>idchannel</i>"
plugins.youtube.sendurl=youtube_sendurl
plugins.youtube.updatefeed=youtube_updatefeed
plugins.youtube.getvideourl=youtube_get_video_url
plugins.youtube.ui_config_vars=
{
{ "select", "youtube_fmt", "int" },
{ "select", "youtube_region" },
{ "input", "youtube_video_count", "int" }
-- { "input", "youtube_api_key", "int" }
}
--youtube_updatefeed('channel/top_rated','')
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/mobs/Eo_zdei.lua | 18 | 2695 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- MOB: Eo'Zdei
-- Animation Sub 0 Pot Form
-- Animation Sub 1 Pot Form (reverse eye position)
-- Animation Sub 2 Bar Form
-- Animation Sub 3 Ring Form
-----------------------------------
require("scripts/zones/Grand_Palace_of_HuXzoi/MobIDs");
require("scripts/globals/status");
-----------------------------------
-- OnMobSpawn Action
-- Set AnimationSub to 0, put it in pot form
-----------------------------------
function onMobSpawn(mob)
mob:AnimationSub(0);
onPath(mob);
end;
function onPath(mob)
local spawnPos = mob:getSpawnPos();
mob:pathThrough({spawnPos.x, spawnPos.y, spawnPos.z});
local pos = mob:getPos();
if (spawnPos.x == pos.x and spawnPos.z == pos.z) then
mob:setPos(spawnPos.x, spawnPos.y, spawnPos.z, mob:getRotPos() + 16);
end
end;
-----------------------------------
-- onMobFight Action
-- Randomly change forms
-----------------------------------
function onMobFight(mob)
local randomTime = math.random(15,45);
local changeTime = mob:getLocalVar("changeTime");
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > randomTime) then
mob:AnimationSub(math.random(2,3));
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > randomTime) then
mob:AnimationSub(math.random(2,3));
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 2 and mob:getBattleTime() - changeTime > randomTime) then
local aniChance = math.random(0,1);
if (aniChance == 0) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
else
mob:AnimationSub(3)
mob:setLocalVar("changeTime", mob:getBattleTime());
end
elseif (mob:AnimationSub() == 3 and mob:getBattleTime() - changeTime > randomTime) then
mob:AnimationSub(math.random(0,2));
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end;
-----------------------------------
-- onMobDeath Action
-- Jailer of Temperance pop
-----------------------------------
function onMobDeath(mob,killer)
mob = mob:getID();
PH = GetServerVariable("[SEA]Jailer_of_Temperance_PH");
if (PH == mob) then
-- printf("%u is a PH",mob);
-- printf("JoT will pop");
-- We need to set Jailer of Temperance spawn point to where the PH spawns (The platform in the room).
mobSpawnPoint = GetMobByID(mob):getSpawnPos();
GetMobByID(Jailer_of_Temperance):setSpawn(mobSpawnPoint.x, mobSpawnPoint.y, mobSpawnPoint.z);
-- The jailer spawns instantly, so don't need to set respawn time
SpawnMob(Jailer_of_Temperance,300):updateEnmity(killer);
DeterMob(mob, true);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/items/keen_zaghnal.lua | 37 | 1120 | -----------------------------------------
-- ID: 18067
-- Equip: Keen Zaghnal
-- Enchantment: Accuracy +3
-- Enchantment will wear off if weapon is unequipped.
-- Effect lasts for 30 minutes
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
if (target:getEquipID(SLOT_MAIN) ~= 18067) then
target:delStatusEffect(EFFECT_ACCURACY_BOOST,18067);
end
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_ACCURACY_BOOST,0,0,1800,18067);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_ACC, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_ACC, 3);
end; | gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-ocserv/luasrc/model/cbi/ocserv/main.lua | 22 | 6871 | -- Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
local o_sha = s:taboption("general", DummyValue, "sha_hash", translate("Server's certificate SHA1 hash"),
translate("That value should be communicated to the client to verify the server's certificate"))
local o_pki = s:taboption("general", DummyValue, "pkid", translate("Server's Public Key ID"),
translate("An alternative value to be communicated to the client to verify the server's certificate; this value only depends on the public key"))
local fd = io.popen("/usr/bin/certtool -i --infile /etc/ocserv/server-cert.pem", "r")
if fd then local ln
local found_sha = false
local found_pki = false
local complete = 0
while complete < 2 do
local ln = fd:read("*l")
if not ln then
break
elseif ln:match("SHA%-?1 fingerprint:") then
found_sha = true
elseif found_sha then
local hash = ln:match("([a-f0-9]+)")
o_sha.default = hash and hash:upper()
complete = complete + 1
found_sha = false
elseif ln:match("Public Key I[Dd]:") then
found_pki = true
elseif found_pki then
local hash = ln:match("([a-f0-9]+)")
o_pki.default = hash and "sha1:" .. hash:upper()
complete = complete + 1
found_pki = false
end
end
fd:close()
end
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local compr = s:taboption("general", Flag, "compression", translate("Enable compression"),
translate("Enable compression"))
compr.default = "1"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[Networking options]]--
local parp = s:taboption("general", Flag, "proxy_arp", translate("Enable proxy arp"),
translate("Provide addresses to clients from a subnet of LAN; if enabled the network below must be a subnet of LAN. Note that the first address of the specified subnet will be reserved by ocserv, so it should not be in use. If you have a network in LAN covering 192.168.1.0/24 use 192.168.1.192/26 to reserve the upper 62 addresses."))
parp.default = "0"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"),
translate("The IPv4 subnet address to provide to clients; this should be some private network different than the LAN addresses unless proxy ARP is enabled. Leave empty to attempt auto-configuration."))
ipaddr.datatype = "ip4addr"
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"),
translate("The mask of the subnet above."))
nm.datatype = "ip4addr"
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"),
translate("The IPv6 subnet address to provide to clients; leave empty to attempt auto-configuration."))
ip6addr.datatype = "ip6addr"
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4. Typically you should include the address of this device"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
s.datatype = "ipaddr"
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
| apache-2.0 |
nasomi/darkstar | scripts/zones/Bastok_Mines/npcs/Roh_Latteh.lua | 34 | 2602 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Roh Latteh
-- Involved in Quest: Mom, The Adventurer?
-- Finishes Quest: The Signpost Marks the Spot
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,MOM_THE_ADVENTURER) ~= QUEST_AVAILABLE and player:getVar("MomTheAdventurer_Event") == 1) then
if (trade:hasItemQty(13454,1) and trade:getItemCount() == 1) then -- Trade Copper Ring
player:startEvent(0x005f);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local HasPainting = player:hasKeyItem(PAINTING_OF_A_WINDMILL);
if (player:getQuestStatus(BASTOK,THE_SIGNPOST_MARKS_THE_SPOT) == QUEST_ACCEPTED and HasPainting == true) then
player:startEvent(0x0060);
else
player:startEvent(0x001d);
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 == 0x005f) then
player:addKeyItem(LETTER_FROM_ROH_LATTEH);
player:messageSpecial(KEYITEM_OBTAINED, LETTER_FROM_ROH_LATTEH);
player:setVar("MomTheAdventurer_Event",2);
player:tradeComplete();
elseif (csid == 0x0060) then
local freeInventory = player:getFreeSlotsCount();
if (freeInventory > 0) then
player:completeQuest(BASTOK,THE_SIGNPOST_MARKS_THE_SPOT);
player:delKeyItem(PAINTING_OF_A_WINDMILL);
player:addTitle(TREASURE_SCAVENGER);
player:addFame(BASTOK,BAS_FAME*50);
player:addItem(12601);
player:messageSpecial(ITEM_OBTAINED,12601); -- Linen Robe
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12601);
end
end
end; | gpl-3.0 |
actboy168/YDWE | Development/Component/script/ydwe/plugin.lua | 2 | 2956 | local uni = require 'ffi.unicode'
plugin = {}
plugin.loaders = {}
plugin.blacklist = { 'YDTileLimitBreaker', 'YDCustomObjectId', 'YDWeHelper' }
local getdevpath
if fs.ydwe_path() == fs.ydwe_devpath() then
function getdevpath(path)
return path
end
else
function getdevpath(path)
return fs.absolute(fs.relative(path, fs.ydwe_path()), fs.ydwe_devpath())
end
end
function plugin:load(plugin_config_path)
log.trace("Load plugin config " .. plugin_config_path:string())
local plugin_config = sys.ini_load(plugin_config_path)
if not plugin_config then
log.error("Cannot found plugin config.")
return
end
local plugin_name = plugin_config['Info']['PluginName']
if plugin_name == '' then
log.error("Cannot plugin name.")
return
end
for _, v in pairs(plugin.blacklist) do
if v == plugin_name then
log.trace("Blacklist.")
return
end
end
if self.loaders[plugin_name] then
log.error(plugin_name .. " already exists.")
return
end
if 0 == tonumber(plugin_config['Load']['Enable']) then
log.debug("Disable " .. plugin_name .. ".")
return
end
local plugin_loader_path = plugin_config['Load']['Loader']
if plugin_loader_path == '' then
log.error("Cannot find " .. plugin_name .. "'s loader.")
return
end
plugin_loader_path = getdevpath(plugin_config_path:parent_path()) / plugin_loader_path
if not fs.exists(plugin_loader_path) then
log.error(plugin_name .. "'loader does not exist.")
return
end
local s, r = pcall(dofile, plugin_loader_path:string())
if not s then
log.error("Error in initialize " .. plugin_name .. "'s loader: ".. r)
return
end
self.loaders[plugin_name] = r
local plugin_dll_path = plugin_config['Load']['Dll']
if plugin_dll_path == '' then
log.error("Cannot find " .. plugin_name .. "'s dll.")
return
end
plugin_dll_path = plugin_config_path:parent_path() / plugin_dll_path
if not fs.exists(plugin_dll_path) then
log.error(plugin_name .. "'dll does not exist. " .. plugin_dll_path:string())
return
end
s, r = pcall(self.loaders[plugin_name].load, plugin_dll_path)
if not s then
log.error("Error in load " .. plugin_name .. ": ".. r)
self.loaders[plugin_name] = nil
return
end
if not r then
self.loaders[plugin_name] = nil
return
end
log.debug(plugin_name .. " loaded successfully.")
return
end
function plugin:load_directory(plugin_dir)
for full_path in plugin_dir:list_directory() do
if full_path:extension():string() == ".plcfg" then
self:load(full_path)
end
end
end
function plugin:load_all()
for full_path in (fs.ydwe_path() / "plugin"):list_directory() do
if fs.is_directory(full_path) then
self:load_directory(full_path)
elseif full_path:extension():string() == ".plcfg" then
self:load(full_path)
end
end
end
function plugin:unload_all()
for name, loader in pairs(self.loaders) do
log.trace("Unload plugin " .. name .. ".")
pcall(loader.unload)
end
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Behemoths_Dominion/npcs/qm1.lua | 17 | 1434 | -----------------------------------
-- Area: Behemoth's Dominion
-- NPC: ???
-- Involved In Quest: The Talekeeper's Gift
-- @pos 211 4 -79 127
-----------------------------------
package.loaded["scripts/zones/Behemoths_Dominion/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Behemoths_Dominion/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("theTalekeeperGiftCS") == 3 and player:getVar("theTalekeepersGiftKilledNM") < 3) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17297446,180):updateClaim(player);
SpawnMob(17297447,180):updateClaim(player);
SpawnMob(17297448,180):updateClaim(player);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/spells/katon_san.lua | 17 | 1616 | -----------------------------------------
-- Spell: Katon: San
-- Deals fire damage to an enemy and lowers its resistance against water.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_KATON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_KATON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod
if(caster:getMerit(MERIT_KATON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(MERIT_KATON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(MERIT_KATON_SAN) - 5;
end;
if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees
bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_WATERRES);
return dmg;
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Monarch_Linn/mobs/Mammet-19_Epsilon.lua | 27 | 2679 | -----------------------------------
-- Area: Monarch Linn
-- NPC: Mammet-19 Epsilon
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:SetMagicCastingEnabled(false);
mob:addMod(MOD_REGAIN, 30);
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local form = mob:AnimationSub();
-- Mammets seem to be able to change to any given form, per YouTube videos
-- Added a random chance to change forms every 3 seconds if 60 seconds have passed, just to make things less formulaic.
-- May be able to change forms more often. Witnessed one at ~50 seconds, most were 60-80.
-- Believe it or not, these changes may be too slow @ 50% chance. Probability is a pain.
-- L40 means their "weapons" are 40 DMG by default.
if ((mob:getBattleTime() > mob:getLocalVar('changeTime') + 60 or mob:getLocalVar('changeTime') == 0) and math.random(0,1) == 1
and not mob:hasStatusEffect(EFFECT_FOOD)) then
changeForm(mob)
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
end;
function changeForm(mob)
local newform = math.random(0,2);
if (mob:AnimationSub() == newform) then
newform = 3;
end
-- setDamage works beautifully, but setDelay doesn't seem to be working. Increased DMG turned off.
if (newform == 0) then -- Hand Form, ~3s delay
mob:SetMagicCastingEnabled(false);
mob:setDelay(2400);
mob:setDamage(40);
elseif (newform == 1) then -- Sword Form, ~2s delay, melee hits for ~50-100 vs WHM/BLM w/o buffs, 40 DMG seems to work.
mob:SetMagicCastingEnabled(false);
mob:setDelay(1500);
mob:setDamage(40);
elseif (newform == 2) then -- Polearm Form, ~3-3.5s delay, melee hits for ~100-150. Takes about 70-80 DMG to make this happen.
mob:SetMagicCastingEnabled(false);
mob:setDelay(3250);
mob:setDamage(75);
elseif (newform == 3) then -- Staff Form, ~4s delay, ~10 seconds between spell ends and next cast
mob:setMobMod(MOBMOD_MAGIC_COOL, 10);
mob:SetMagicCastingEnabled(true);
mob:setDelay(3700);
mob:setDamage(40);
end
mob:AnimationSub(newform);
mob:setLocalVar('changeTime', mob:getBattleTime());
end; | gpl-3.0 |
amirhacker135/mmkingtm1 | plugins/lock_eng.lua | 14 | 3154 |
local function run(msg, matches)
if msg.to.type == 'chat' then
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_eng'] then
lock_eng = data[tostring(msg.to.id)]['settings']['lock_eng']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_eng == "yes" then
send_large_msg(chat, 'English Is not Allow Here !')
chat_del_user(chat, user, ok_cb, true)
end
end
end
return {
usage ={
"lock adds: If User Send A Link Then Removed From Bot.",
"unlock adds: Adds Is Enabled.",
},
patterns = {
"(a)",
"(b)",
"(c)",
"(d)",
"(e)",
"(f)",
"(g)",
"(h)",
"(i)",
"(j)",
"(k)",
"(l)",
"(m)",
"(n)",
"(o)",
"(p)",
"(q)",
"(r)",
"(s)",
"(t)",
"(u)",
"(v)",
"(w)",
"(x)",
"(y)",
"(z)",
},
run = run
}
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
Etehadmarg/margbot | plugins/trivia.lua | 647 | 6784 | do
-- Trivia plugin developed by Guy Spronck
-- Returns the chat hash for storing information
local function get_hash(msg)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':trivia'
end
if msg.to.type == 'user' then
hash = 'user:'..msg.from.id..':trivia'
end
return hash
end
-- Sets the question variables
local function set_question(msg, question, answer)
local hash =get_hash(msg)
if hash then
redis:hset(hash, "question", question)
redis:hset(hash, "answer", answer)
redis:hset(hash, "time", os.time())
end
end
-- Returns the current question
local function get_question( msg )
local hash = get_hash(msg)
if hash then
local question = redis:hget(hash, 'question')
if question ~= "NA" then
return question
end
end
return nil
end
-- Returns the answer of the last question
local function get_answer(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'answer')
else
return nil
end
end
-- Returns the time of the last question
local function get_time(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'time')
else
return nil
end
end
-- This function generates a new question if available
local function get_newquestion(msg)
local timediff = 601
if(get_time(msg)) then
timediff = os.time() - get_time(msg)
end
if(timediff > 600 or get_question(msg) == nil)then
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
else
return 'Please wait ' .. 600 - timediff .. ' seconds before requesting a new question. \nUse !triviaquestion to see the current question.'
end
end
-- This function generates a new question when forced
local function force_newquestion(msg)
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
end
-- This function adds a point to the player
local function give_point(msg)
local hash = get_hash(msg)
if hash then
local score = tonumber(redis:hget(hash, msg.from.id) or 0)
redis:hset(hash, msg.from.id, score+1)
end
end
-- This function checks for a correct answer
local function check_answer(msg, answer)
if(get_answer(msg)) then -- Safety for first time use
if(get_answer(msg) == "NA")then
-- Question has not been set, give a new one
--get_newquestion(msg)
return "No question set, please use !trivia first."
elseif (get_answer(msg) == answer:lower()) then -- Question is set, lets check the answer
set_question(msg, "NA", "NA") -- Correct, clear the answer
give_point(msg) -- gives out point to player for correct answer
return msg.from.print_name .. " has answered correctly! \nUse !trivia to get a new question."
else
return "Sorry " .. msg.from.print_name .. ", but '" .. answer .. "' is not the correct answer!"
end
else
return "No question set, please use !trivia first."
end
end
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function get_user_score(msg, user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local hash = 'chat:'..msg.to.id..':trivia'
user_info.score = tonumber(redis:hget(hash, user_id) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
-- Function to print score
local function trivia_scores(msg)
if msg.to.type == 'chat' then
-- Users on chat
local hash = 'chat:'..msg.to.id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_user_score(msg, user_id, msg.to.id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.score and b.score then
return a.score > b.score
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.score..'\n'
end
return text
else
return "This function is only available in group chats."
end
end
local function run(msg, matches)
if(matches[1] == "!triviascore" or matches[1] == "!triviascores") then
-- Output all scores
return trivia_scores(msg)
elseif(matches[1] == "!triviaquestion")then
return "Question: " .. get_question(msg)
elseif(matches[1] == "!triviaskip") then
if is_sudo(msg) then
return force_newquestion(msg)
end
elseif(matches[1] ~= "!trivia") then
return check_answer(msg, matches[1])
end
return get_newquestion(msg)
end
return {
description = "Trivia plugin for Telegram",
usage = {
"!trivia to obtain a new question.",
"!trivia [answer] to answer the question.",
"!triviaquestion to show the current question.",
"!triviascore to get a scoretable of all players.",
"!triviaskip to skip a question (requires sudo)"
},
patterns = {"^!trivia (.*)$",
"^!trivia$",
"^!triviaquestion$",
"^!triviascore$",
"^!triviascores$",
"^!triviaskip$"},
run = run
}
end
| gpl-2.0 |
nasomi/darkstar | scripts/globals/items/dish_of_spaghetti_melanzane.lua | 35 | 1401 | -----------------------------------------
-- ID: 5213
-- Item: dish_of_spaghetti_melanzane
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 25
-- Health Cap 100
-- Vitality 2
-- Store TP 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5213);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 25);
target:addMod(MOD_FOOD_HP_CAP, 100);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_STORETP, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 25);
target:delMod(MOD_FOOD_HP_CAP, 100);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_STORETP, 4);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/dark_bass.lua | 18 | 1331 | -----------------------------------------
-- ID: 4428
-- Item: dark_bass
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
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,4428);
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 |
nasomi/darkstar | scripts/zones/Qufim_Island/npcs/Singing_Blade_IM.lua | 30 | 3053 | -----------------------------------
-- Area: Qufim Island
-- NPC: Singing Blade, I.M.
-- Type: Border Conquest Guards
-- @pos 179.093 -21.575 -15.282 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Qufim_Island/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = QUFIMISLAND;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Halbeeya.lua | 34 | 1033 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Halbeeya
-- 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(0x029E);
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 |
Hello23-Ygopro/ygopro-ds | expansions/script/c27002122.lua | 1 | 2100 | --BT2-108 The Infinite Force Meta-Cooler Core
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
ds.EnableBattleAttribute(c)
ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZA_CLAN,CHARACTER_METACOOLER_CORE)
ds.AddPlayProcedure(c,COLOR_YELLOW,2,5)
--power up
ds.AddActivateBattleSkill(c,0,DS_LOCATION_BATTLE,scard.powop,scard.powcost,ds.hinttg)
--play
ds.AddSingleAutoPlay(c,1,nil,scard.pltg,scard.plop,DS_EFFECT_FLAG_CARD_CHOOSE,scard.plcon)
ds.AddSingleAutoAttack(c,1,nil,scard.pltg,scard.plop,DS_EFFECT_FLAG_CARD_CHOOSE,scard.plcon)
end
scard.dragon_ball_super_card=true
scard.combo_cost=1
--power up
function scard.costfilter(c)
return c:IsCharacter(CHARACTER_METACOOLER) and c:IsAbleToDropAsCost()
end
function scard.powcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(ds.BattleAreaFilter(scard.costfilter),tp,DS_LOCATION_BATTLE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TODROP)
local g=Duel.SelectMatchingCard(tp,ds.BattleAreaFilter(scard.costfilter),tp,DS_LOCATION_BATTLE,0,1,1,nil)
Duel.SendtoDrop(g,REASON_COST)
end
function scard.powop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToSkill(e) or c:IsFacedown() then return end
ds.GainSkillUpdatePower(c,c,2,5000)
end
--play
function scard.plcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetStackGroup():IsExists(Card.IsCode,1,nil,CARD_BIG_GETE_STAR)
end
function scard.plfilter(c,e,tp)
return c:IsCharacter(CHARACTER_METACOOLER) and c:IsCanBePlayed(e,0,tp,false,false)
end
function scard.pltg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(DS_LOCATION_DROP) and chkc:IsControler(tp) and ds.DropAreaFilter(scard.plfilter)(chkc,e,tp) end
if chk==0 then return true end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
local ct=Duel.GetLocationCount(tp,DS_LOCATION_BZONE)
if ct>2 then ct=2 end
Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_PLAY)
Duel.SelectTarget(tp,ds.DropAreaFilter(scard.plfilter),tp,DS_LOCATION_DROP,0,0,ct,nil,e,tp)
end
scard.plop=ds.ChoosePlayOperation(DS_POS_FACEUP_ACTIVE)
| gpl-3.0 |
appaquet/torch-android | src/3rdparty/nn/Add.lua | 61 | 1699 | local Add, parent = torch.class('nn.Add', 'nn.Module')
function Add:__init(inputSize,scalar)
parent.__init(self)
local size = inputSize
if scalar then size=1 end
self.scalar = scalar
self.bias = torch.Tensor(size)
self.gradBias = torch.Tensor(size)
self._ones = torch.Tensor{1}
self:reset()
end
function Add:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.bias:size(1))
end
self.bias:uniform(-stdv, stdv)
end
function Add:updateOutput(input)
self.output:resizeAs(input):copy(input)
if self.scalar then
self.output:add(self.bias[1]);
else
if input:isSameSizeAs(self.bias) then
self.output:add(self.bias)
else
local batchSize = input:size(1)
if self._ones:size(1) ~= batchSize then
self._ones:resize(batchSize):fill(1)
end
local bias = self.bias:view(-1)
local output = self.output:view(batchSize, -1)
output:addr(1, self._ones, bias)
end
end
return self.output
end
function Add:updateGradInput(input, gradOutput)
if self.gradInput then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
return self.gradInput
end
end
function Add:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if self.gradBias:size(1) == 1 then
self.gradBias[1] = self.gradBias[1] + scale*gradOutput:sum();
else
if input:isSameSizeAs(self.bias) then
self.gradBias:add(scale, gradOutput)
else
local gradOutput = gradOutput:view(input:size(1), -1)
self.gradBias:view(-1):addmv(scale, gradOutput:t(), self._ones)
end
end
end
| bsd-3-clause |
nasomi/darkstar | scripts/zones/Dynamis-Valkurm/bcnms/dynamis_Valkurm.lua | 16 | 1855 | -----------------------------------
-- Area: dynamis_Valkurm
-- Name: dynamis_Valkurm
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[DynaValkurm]UniqueID",player:getDynamisUniqueID(1286));
SetServerVariable("[DynaValkurm]Boss_Trigger",0);
SetServerVariable("[DynaValkurm]Already_Received",0);
local RNDpositionTable=TimerStatueRandomPos;
local X=0;
local Y=0;
local Z=0;
local statueID = {16937287,16937262,16937237,16937212};
--spawn random timer statue
local statueRND = math.random(1,4);
local SpawnStatueID= statueID[statueRND];
--printf("timer_statue_ID = %u",SpawnStatueID);
local F={2,4,6,8};
--printf("position_type = %u",statueRND);
X=RNDpositionTable[F[statueRND]][1];
--printf("X = %u",X);
Y=RNDpositionTable[F[statueRND]][2];
--printf("Y = %u",Y);
Z=RNDpositionTable[F[statueRND]][3];
--printf("Z = %u",Z);
SpawnMob(SpawnStatueID);
GetMobByID(SpawnStatueID):setPos(X,Y,Z);
GetMobByID(SpawnStatueID):setSpawn(X,Y,Z);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("DynamisID",GetServerVariable("[DynaValkurm]UniqueID"));
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then
player:setVar("dynaWaitxDay",realDay);
end
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
SetServerVariable("[DynaValkurm]UniqueID",0);
end
end; | gpl-3.0 |
EricssonResearch/scott-eu | simulated-enviroment/logistics_multiple_robots_ShelfBody.lua | 1 | 7779 | --**************************
-- Actions for the YouBot Kuka Robot
-- @author Klaus Raizer
-- @date 08-02-2017
--
-- Description: Controls information comming from
-- This script calls a lua script located at the same folder.
--**************************
if (sim_call_type==sim_childscriptcall_initialization) then
simSetThreadSwitchTiming(100) -- Default timing for automatic thread switching
maximum_number_of_products_per_collumn=10 --Arbitrary parameter
shelf_bound_box_radius = 0.6 --NOTE: must be carefull not to put other products too close to this shelf.
positionSensorGreenHandle=simGetObjectHandle('PositionSensorGreen')
positionSensorRedHandle=simGetObjectHandle('PositionSensorRed')
positionSensorYellowHandle=simGetObjectHandle('PositionSensorYellow')
proximitySensorInputGreenHandle=simGetObjectHandle('proximitySensorInputGreen')
proximitySensorInputRedHandle=simGetObjectHandle('proximitySensorInputRed')
proximitySensorInputYellowHandle=simGetObjectHandle('proximitySensorInputYellow')
end
if (sim_call_type==sim_childscriptcall_actuation) then
--[[ local listOfProducts=getListOfProducts()
print("listOfProducts: ")
local n=table.getn(listOfProducts)
print("n: ",n)
for i=1,n,1 do
print(listOfProducts[i])
end]]--
end
if (sim_call_type==sim_childscriptcall_sensing) then
end
if (sim_call_type==sim_childscriptcall_cleanup) then
end
-- Shelf functions
-- http://www.coppeliarobotics.com/helpFiles/en/accessingGeneralObjects.htm
-- List all products on this shelf
getListOfProducts = function ()
shelfHandle=simGetObjectAssociatedWithScript(sim_handle_self)
shelfName=simGetObjectName(shelfHandle)
objects = simGetObjectsInTree(sim_handle_scene,0,0)
numberOfObjectsOfTypeShape=table.getn(objects)
cp=1
cs=1
products={}
shelves={}
for i=1,numberOfObjectsOfTypeShape,1 do
objectName=simGetObjectName(objects[i])
-- p=simGetObjectPosition(objects[i],shelfHandle) -- relative position
--distance=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3])
if string.match(objectName, "product") then
products[cp]=objects[i]
cp=cp+1
--elseif (objectName=="ShelfBody") then--string.match(objectName, "ShelfBody") then
elseif (string.match(objectName, "ShelfBody")) and not (string.match(objectName, "ForPathPlanning")) then
shelves[cs]=objects[i]
cs=cs+1
end
end
shelfContent={}
counter=1
for p=1,cp-1,1 do
product=products[p]
closestShelf=shelves[1]
p=simGetObjectPosition(product,closestShelf) -- relative position
distance=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3])
for s=1,cs-1,1 do
p=simGetObjectPosition(product,shelves[s]) -- relative position
distance_new=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3])
if(distance_new<distance)then
closestShelf=shelves[s]
distance=distance_new
end
end
--print('closestShelf: ',simGetObjectName(closestShelf))
if(closestShelf==shelfHandle and distance <= shelf_bound_box_radius)then
shelfContent[counter]=simGetObjectName(product)
--print(shelfName,' ',simGetObjectName(shelfContent[counter]))
counter=counter+1
end
end
return shelfContent
end
-- Return a list with all current pickable products
getListOfPickableProducts = function(inInts, inFloats, inStrings, inBuff)
psg=simGetObjectPosition(positionSensorGreenHandle,-1) -- position in space of the green sensor
psr=simGetObjectPosition(positionSensorRedHandle,-1) -- position in space of the red sensor
psy=simGetObjectPosition(positionSensorYellowHandle,-1) -- position in space of the yellow sensor
shelfContent=getListOfProducts()
pickable={"None", "None", "None"}
for i = 1,table.getn(shelfContent),1 do
--print(shelfContent[i])
p=simGetObjectPosition(simGetObjectHandle(shelfContent[i]),-1)
-- for this product to be pickable, it should be bellow (in z) its sensor
if(string.match(shelfContent[i], "Yellow"))then
if(p[3]<psr[3])then
pickable[1]=shelfContent[i]
end
elseif(string.match(shelfContent[i], "Red"))then
if(p[3]<psg[3])then
pickable[2]=shelfContent[i]
end
elseif(string.match(shelfContent[i], "Green"))then
if(p[3]<psy[3])then
pickable[3]=shelfContent[i]
end
else print('Product ID error in child script.')
end
end
return {1}, {}, pickable, ""
end
---------------------------
-- Adds Product to Shelf
-- Returns {1},{},{},"" if successful and {0},{},{},"" if it fails
addProduct=function(inInts, inFloats, inStrings, inBuff)
productType = inStrings[1]
--[[
local initial_t = simGetSimulationTime()
local dt=0
while(dt<1000)do
t=simGetSimulationTime()
if(t~=nil)then
dt=t-initial_t
end
--print("dt: ",dt)
end
]]-- --locks the simulation
--simWait(1000, true) -- only works with threaded scripts
if((productType=='productGreen') or (productType=='productRed') or (productType=='productYellow'))then
greenPosition={.30,.1,.50}
redPosition={.30,0,.50}
yellowPosition={.30,-.1,.50}
if(productType=='productGreen')then
h=proximitySensorInputGreenHandle
position=greenPosition
elseif(productType=='productRed')then
h=proximitySensorInputRedHandle
position=redPosition
elseif(productType=='productYellow')then
h=proximitySensorInputYellowHandle
position=yellowPosition
end
--Check if there is enough room for it
counter_of_product_type=0;
shelfContent=getListOfProducts()
-- print('======')
for i = 1,table.getn(shelfContent),1 do
-- print("-> ",shelfContent[i])
if(string.match(shelfContent[i], productType))then
counter_of_product_type=counter_of_product_type+1;
end
end
-- print('======')
--print("counter_of_product_type(",productType,"): ",counter_of_product_type)
if(counter_of_product_type<maximum_number_of_products_per_collumn)then
-- Check if position is free before creating a new one
local res,dist,pt,obj=simHandleProximitySensor(h)
if obj then
local fullnm=simGetObjectName(obj)
local suffix,nm=simGetNameSuffix(fullnm)
print("Couldn't create a new ",nm,". There is already ",fullnm," in this position. ")
return {0},{},{},""
else
string_to_avoid_dynamic_naming=productType .. '#'
objectHandle=simGetObjectHandle(string_to_avoid_dynamic_naming)
copiedObjectHandles=simCopyPasteObjects({objectHandle},1)
shelfHandle=simGetObjectAssociatedWithScript(sim_handle_self)
copiedObjectHandle=copiedObjectHandles[1]
simSetObjectOrientation(copiedObjectHandle,shelfHandle,{0,0,0})
simSetObjectPosition(copiedObjectHandle,shelfHandle,position)
simSetObjectInt32Parameter(copiedObjectHandle,sim_shapeintparam_static,0)
end
else
print("Product creation error. There are too many (",counter_of_product_type,") ",productType," units in this shelf.")
return {0},{},{"full shelf"},""
end
else
print('Product creation error. Product type ',productType,' does not exist.')
return {0},{},{"product not found"},""
end
return {1},{},{"True"},"";
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Port_San_dOria/npcs/Bricorsant.lua | 36 | 1376 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Bricorsant
-- 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(0x23a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
thesabbir/luci | modules/luci-mod-freifunk/luasrc/controller/freifunk/freifunk.lua | 59 | 5943 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.freifunk.freifunk", package.seeall)
function index()
local uci = require "luci.model.uci".cursor()
local page
-- Frontend
page = node()
page.lock = true
page.target = alias("freifunk")
page.subindex = true
page.index = false
page = node("freifunk")
page.title = _("Freifunk")
page.target = alias("freifunk", "index")
page.order = 5
page.setuser = "nobody"
page.setgroup = "nogroup"
page.i18n = "freifunk"
page.index = true
page = node("freifunk", "index")
page.target = template("freifunk/index")
page.title = _("Overview")
page.order = 10
page.indexignore = true
page = node("freifunk", "contact")
page.target = template("freifunk/contact")
page.title = _("Contact")
page.order = 15
page = node("freifunk", "status")
page.target = template("freifunk/public_status")
page.title = _("Status")
page.order = 20
page.i18n = "base"
page.setuser = false
page.setgroup = false
entry({"freifunk", "status.json"}, call("jsonstatus"))
entry({"freifunk", "status", "zeroes"}, call("zeroes"), "Testdownload")
if nixio.fs.access("/usr/sbin/luci-splash") then
assign({"freifunk", "status", "splash"}, {"splash", "publicstatus"}, _("Splash"), 40)
end
page = assign({"freifunk", "olsr"}, {"admin", "status", "olsr"}, _("OLSR"), 30)
page.setuser = false
page.setgroup = false
if nixio.fs.access("/etc/config/luci_statistics") then
assign({"freifunk", "graph"}, {"admin", "statistics", "graph"}, _("Statistics"), 40)
end
-- backend
assign({"mini", "freifunk"}, {"admin", "freifunk"}, _("Freifunk"), 5)
entry({"admin", "freifunk"}, alias("admin", "freifunk", "index"), _("Freifunk"), 5)
page = node("admin", "freifunk")
page.target = template("freifunk/adminindex")
page.title = _("Freifunk")
page.order = 5
page = node("admin", "freifunk", "basics")
page.target = cbi("freifunk/basics")
page.title = _("Basic Settings")
page.order = 5
page = node("admin", "freifunk", "basics", "profile")
page.target = cbi("freifunk/profile")
page.title = _("Profile")
page.order = 10
page = node("admin", "freifunk", "basics", "profile_expert")
page.target = cbi("freifunk/profile_expert")
page.title = _("Profile (Expert)")
page.order = 20
page = node("admin", "freifunk", "Index-Page")
page.target = cbi("freifunk/user_index")
page.title = _("Index Page")
page.order = 50
page = node("admin", "freifunk", "contact")
page.target = cbi("freifunk/contact")
page.title = _("Contact")
page.order = 15
entry({"freifunk", "map"}, template("freifunk-map/frame"), _("Map"), 50)
entry({"freifunk", "map", "content"}, template("freifunk-map/map"), nil, 51)
entry({"admin", "freifunk", "profile_error"}, template("freifunk/profile_error"))
end
function zeroes()
local string = require "string"
local http = require "luci.http"
local zeroes = string.rep(string.char(0), 8192)
local cnt = 0
local lim = 1024 * 1024 * 1024
http.prepare_content("application/x-many-zeroes")
while cnt < lim do
http.write(zeroes)
cnt = cnt + #zeroes
end
end
function jsonstatus()
local root = {}
local sys = require "luci.sys"
local uci = require "luci.model.uci"
local util = require "luci.util"
local http = require "luci.http"
local json = require "luci.json"
local ltn12 = require "luci.ltn12"
local version = require "luci.version"
local webadmin = require "luci.tools.webadmin"
local cursor = uci.cursor_state()
local ffzone = webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and cursor:get("firewall", ffzone, "network")
local ffwifs = ffznet and util.split(ffznet, " ") or {}
local sysinfo = util.ubus("system", "info") or { }
local boardinfo = util.ubus("system", "board") or { }
local loads = sysinfo.load or { 0, 0, 0 }
local memory = sysinfo.memory or {
total = 0,
free = 0,
shared = 0,
buffered = 0
}
local swap = sysinfo.swap or {
total = 0,
free = 0
}
root.protocol = 1
root.system = {
uptime = { sysinfo.uptime or 0 },
loadavg = { loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0 },
sysinfo = {
boardinfo.system or "?",
boardinfo.model or "?",
memory.total,
0, -- former cached memory
memory.buffered,
memory.free,
0, -- former bogomips
swap.total,
0, -- former cached swap
swap.free
},
hostname = boardinfo.hostname
}
root.firmware = {
luciname=version.luciname,
luciversion=version.luciversion,
distname=version.distname,
distversion=version.distversion
}
root.freifunk = {}
cursor:foreach("freifunk", "public", function(s)
root.freifunk[s[".name"]] = s
end)
cursor:foreach("system", "system", function(s)
root.geo = {
latitude = s.latitude,
longitude = s.longitude
}
end)
root.network = {}
root.wireless = {devices = {}, interfaces = {}, status = {}}
local wifs = root.wireless.interfaces
local netdata = luci.sys.net.deviceinfo() or {}
for _, vif in ipairs(ffwifs) do
root.network[vif] = cursor:get_all("network", vif)
root.wireless.devices[vif] = cursor:get_all("wireless", vif)
cursor:foreach("wireless", "wifi-iface", function(s)
if s.device == vif and s.network == vif then
wifs[#wifs+1] = s
if s.ifname then
local iwinfo = luci.sys.wifi.getiwinfo(s.ifname)
if iwinfo then
root.wireless.status[s.ifname] = { }
local _, f
for _, f in ipairs({
"channel", "txpower", "bitrate", "signal", "noise",
"quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname"
}) do
root.wireless.status[s.ifname][f] = iwinfo[f]
end
end
end
end
end)
end
http.prepare_content("application/json")
ltn12.pump.all(json.Encoder(root):source(), http.write)
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/Cavernous_Maw.lua | 17 | 1236 | -----------------------------------
-- Area: Abyssea - Tahrongi
-- NPC: Cavernous Maw
-- @pos -31.000, 47.000, -681.000 45
-- Teleports Players to Tahrongi Canyon
-----------------------------------
package.loaded["scripts/zones/Abyssea-Tahrongi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Abyssea-Tahrongi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00C8);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00C8 and option ==1) then
player:setPos(-28,46,-680,76,117);
end
end; | gpl-3.0 |
amirhoseinhastam1/1 | plugins/anti_spam.lua | 923 | 3750 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
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'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Upper_Jeuno/npcs/Mejuone.lua | 37 | 1157 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Mejuone
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MEJUONE_SHOP_DIALOG);
stock = {0x11C1,62, -- Gysahl Greens
0x0348,7, -- Chocobo Feather
0x439B,9} -- Dart
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
renyaoxiang/QSanguosha-For-Hegemony | extension-doc/11-Fundamentals.lua | 15 | 9150 | --[[
大家好我是 William915。
从这个文件开始讲解AI的编写方法。
三国杀的 AI 由太阳神上与 hypercross 共同编写。
之后经过他们及 donle,宇文天启和本人的发展。
本文档针对的 AI 稳定版本为 V0.7 Patch 2(20120201,c11f5ace8)。
在论坛上可以看到反馈 AI 的问题的帖子远比反映程序的问题的帖子要多得多,这表明了 AI 的复杂性。
熟悉 AI 发展历史的朋友一定知道有那么一段时间 AI 常常会改好了这个又坏了那个,
这是因为影响 AI 表现的因素太多。
一言以蔽之,AI 编写与修改是牵一发而动全身的。
目前的 AI 架构还不完善,随着架构的逐步完善文档也会逐步的调整。
而架构的完善,需要你们和我们的共同努力。
也许您已经知道在开始编写 MOD 和 LUA 扩展之前需要一定的准备。
AI 也是如此,这些准备包括:
+ 熟悉三国杀本身的源代码(知道如何去检索自己需要的东西就够了),
包括sanguosha_wrap.cxx文件。
+ 熟悉 MOD 或 LUA 扩展的源代码并作适当修改(下面将具体介绍)。
可以说,没有源代码作参考是很难编写 AI 的。
+ 熟悉 smart-ai 中的各个函数的用法。(下面将具体介绍)
+ 阅读 lua/ai 文件夹下的各个 AI 文件以对 AI 编写形成一个大致的概念。
如果您对 AI 还不熟悉,又想比较快上手,那么最好的方法是参考已有的 AI。
其实在编写 Lua 扩展的时候也是一样,照葫芦画瓢是最好的方法。
++ AI 需要做什么?
AI 所做的事情只有一件:作决定。
如果您想知道有哪些地方需要编写 AI,只要想一下游戏过程中什么地方您需要作决定就行了。
已有的 AI 文件提供了大部分情况下作决定的策略。
因此大家只需要把精力集中在与扩展的武将的技能相关的决定上就可以了。
对于 MOD 的编写者,当然还需要为扩展的卡牌编写相应的策略。
随着下面介绍的逐步深入,相信大家对于 AI 的这一特点会有更深的体会。
在编写 AI 之前,还要知道:现在的 AI 是基于技能的,而不是基于武将的。
因此,我们不需要给姜维觉醒后获得的观星额外写 AI,只要把诸葛亮的观星 AI 写好就行了。
++ 为 AI 而修改技能代码
实际上如果在写技能时没有为 AI 考虑的话,有一些技能的 AI 甚至根本无法编写。
因为 AI 所能获得的信息是很有限的。
最常用的传递信息给 AI 的方法是通过 data 参数。例如 src/package/thicket.cpp 第 124 行附近颂威的代码:
foreach(ServerPlayer *p, players){
QVariant who = QVariant::fromValue(p);
if(p->hasLordSkill("songwei") && player->askForSkillInvoke("songwei", who)){
...
对照 serverplayer.h 可以看到,askForSkillInvoke 里面的第 2 个参数就是 data,
这个 data 就是给 AI 用的。
上面的代码如果写成 lua,则是这样:
]]
for _, p in sgs.qlist(players) do
local who = sgs.QVariant()
who:setValue(p)
if p:hasLordSkill("songwei") and player:askForSkillInvoke("songwei", who) then
-- ...
end
end
--正是因为在编写技能时传入了 data,我们在 thicket-ai.lua 中才能根据 data 判断是否需要颂威(第 55 至 58 行)。
sgs.ai_skill_invoke.songwei = function(self, data)
local who = data:toPlayer() -- 将 data (QVariant 类型)转换为 ServerPlayer* 类型
return self:isFriend(who) -- 如果是对友方,则发动颂威
end
--[[
因此,在开始编写 AI 之前,请相应修改您的程序代码以便 AI 正常工作。
给 AI 传递数据的另外一个方法是通过 tag。例子可见鬼才,不再赘述。
++ 如何载入自己写的 AI?
方法很简单,只要找到您的扩展包的名字,例如为 extension。
则只要在 lua/ai 文件夹下新增一个文件 extension-ai.lua 并把相应的 AI 代码放到这一文件内即可。
对于扩展包的名字,cpp 扩展应查找形如这样的代码:
ThicketPackage::ThicketPackage():Package("thicket")
而 lua 扩展则应根据第一行:]]
module("extensions.moligaloo", package.seeall)
--[[上面两个例子相应的 AI 文件名分别应该为 thicket-ai.lua 和 moligaloo-ai.lua
++ 万一需要修改已有的 AI 文件?
虽然这次 AI 架构的编写力求做到对所有的扩展都不需要修改 smart-ai.lua。
但是有一些情况可能还是需要修改已有的 AI 文件。
例如有一个像奇才一样的技能,那么在目前的版本里只能通过修改 SmartAI.getDistanceLimit 来实现。
但是这并不意味着需要修改 smart-ai.lua 文件。
事实上,您只要在自己的 AI 文档里头重新写一遍 SmartAI.getDistanceLimit 就可以了。
这时原来的 getDistanceLimit 会被您所写的覆盖掉。
强烈不建议为了某个技能而直接修改已有的 AI 文件(包括但不限于 smart-ai.lua)。
直接修改已有的 AI 文件会使得以后新版本发布时您的 AI 的更新过程变得十分繁琐。
zombie_mode-ai.lua 提供了一个修改 SmartAI.useTrickCard 函数的实例。
++ Lua 基础知识
Lua 语言的基础知识可以通过查阅 manual.luaer.cn 获得。
下面重点介绍一些与 AI 编写关系比较紧密的和容易混淆的 Lua 知识。
如果你还没有编写过 AI,可以先跳过这一部分。
首先要记住Lua是大小写敏感的。SmartAI 跟 smartai 不是同一个东西。
点,冒号与方括号:
这是最容易混淆的地方之一。这三种符号都用于对 Lua 里头的表作索引。下面三种写法是等价的:]]
example:blah(foo),
example.blah(example, foo)
example["blah"](example, foo)
--[[
nil, false 与 0:
任何一个变量在初始化之前都是 nil。当一个函数没有返回任何值的时候,返回值也是 nil。
C 中的 NULL 在 LUA 中被映射为 nil。
nil,false 与 0 在 Lua 里头两两不等。]]
if a then blah end
--[[上面的代码当 a 为 nil 和 false 的时候,blah 不会执行。
但是当 a 为 0 的时候,blah 会被执行。
给熟悉 C 的朋友提个醒:
Lua 里头没有 switch,没有 continue,没有 goto,请不要在代码里使用这些关键字。
Lua 里头没有函数重载的说法,以下两种写法是等价的:]]
function blah(a, b, c) end
blah = function(a, b, c) end
--因此如果有下面的代码:
function blah(a,b,c) blahblah end
function blah(a,b) ... end
--[[则相当于给全局变量 blah 赋了两次值。结果第一行代码没有任何作用,blahblah 也不会被执行。
这正是上面说的“万一需要修改已有的 AI 文件”部分的原理。
表(table)与列表(QList)
这是两个完全不同的类型,但是很容易混淆。Lua 所能直接处理的是前者,但是通过调用room里头的函数获得的往往是后者。
两者的转换可以通过下面代码来进行,这种转换是单向的:]]
Table = sgs.QList2Table(QList)
--[[两者的差别列出如下:
表t 列表l
索引 t[i] l:at(i-1)
长度 #t l:length()
插入 table.insert(t,foo) l:append(foo)
迭代算子 ipairs(t) sgs.qlist(l)
++ AI 中用到的表
在 AI 编写中主要会用到两个表,一个是sgs,该表含有大量由 SWIG 提供的成员函数,另外一个表是 SmartAI。
在具体的 AI 代码中出现的 self,实际上都是在操作 SmartAI 这个表。
sgs 表的常用元素:
sgs.Sanguosha 指向 Engine 对象
sgs.qlist(l) 是 QList 对象的迭代算子
sgs.reverse(t) 将一个表的元素反序,得到反序后新的表。
例如 t == {a, b, c} 则 sgs.reverse(t) == {c, b, a}
sgs.QList2Table(l) 将一个列表转换为表。
SmartAI 表的常用元素:
SmartAI.player 指向 AI 对应的 ServerPlayer 对象
SmartAI.room 指向 AI 所在的房间(Room 对象)
SmartAI.role 是 AI 对应身份的字符串
(主公为 "lord",忠臣为 "loyalist",反贼为 "rebel",内奸为 "renegade")
SmartAI.friends_noself 是一个包含 AI 的所有友方 ServerPlayer 对象指针的表(不包括自身)
SmartAI.friends 是一个包含 AI 的所有友方 ServerPlayer 对象指针的表(包括自身)
SmartAI.enemies 是一个包含 AI 的所有敌方 ServerPlayer 对象指针的表(包括自身)
这两个表的其它重要元素将在后续文档中介绍。
++ 调试 AI 的基本方法。
为了调试 AI,您必须通过点击“启动服务器”然后点击“启动游戏”的方式来启动游戏,不能通过“单机启动”。
调试 AI 的基本方法是通过在服务器端输出信息。输出信息的基本方法有三种:]]
self:log(message)
self.room:output(message)
self.room:writeToConsole(message)
--[[其中前两种是等价的。与第三种的区别在于,前两种仅当 config.ini 中有 DebugOutput=true 时才会输出。
后一种无论什么情况都会输出。这里的 message 是一个字符串。
加入以下代码,则可以了解函数被调用的过程。]]
self:log(debug.traceback())
-- 还有一个重要的用于调试的函数是 assert,将在 15-Activate.lua 介绍。
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Davoi/npcs/Lootblox.lua | 19 | 7228 | -----------------------------------
-- Area: Davoi
-- NPC: Lootblox
-- Type: Standard NPC
-- @pos 218.073 -0.982 -20.746 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Davoi/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local buying = false;
local exchange;
local gil = trade:getGil();
if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND) == true) then
if (count == 1 and gil == TIMELESS_HOURGLASS_COST) then -- Hourglass purchase
player:startEvent(134);
elseif (gil == 0) then
if (count == 1 and trade:hasItemQty(4236,1)) then -- Bringing back a Timeless Hourglass
player:startEvent(153);
-- Currency Exchanges
elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1452,CURRENCY_EXCHANGE_RATE)) then -- Single -> Hundred
player:startEvent(135,CURRENCY_EXCHANGE_RATE);
elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1453,CURRENCY_EXCHANGE_RATE)) then -- Hundred -> Ten thousand
player:startEvent(136,CURRENCY_EXCHANGE_RATE);
elseif (count == 1 and trade:hasItemQty(1454,1)) then -- Ten thousand -> 100 Hundreds
player:startEvent(138,1454,1453,CURRENCY_EXCHANGE_RATE);
-- Currency Shop
elseif (count == 25 and trade:hasItemQty(1453,25)) then -- Behemoth Horn (833)
buying = true;
exchange = {25, 833};
elseif (count == 7 and trade:hasItemQty(1453,7)) then -- Goblin Grease (1520)
buying = true;
exchange = {7,1520};
elseif (count == 8 and trade:hasItemQty(1453,8)) then -- Griffon Hide (1516)
buying = true;
exchange = {8, 1516};
elseif (count == 23 and trade:hasItemQty(1453,23)) then -- Griffon Leather (1459)
buying = true;
exchange = {23, 1459};
elseif (count == 28 and trade:hasItemQty(1453,28)) then -- Mammoth Tusk (1458)
buying = true;
exchange = {28,1458};
elseif (count == 6 and trade:hasItemQty(1453,6)) then -- Relic Iron (1466)
buying = true;
exchange = {6, 1466};
elseif (count == 5 and trade:hasItemQty(1453,5)) then -- Twincoon (1295)
buying = true;
exchange = {5, 1295};
end
end
end
-- Handle the shop trades.
-- Item obtained dialog appears before CS. Could be fixed with a non-local variable and onEventFinish, but meh.
if (buying == true) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,exchange[2]);
else
player:startEvent(137,1453,exchange[1],exchange[2]);
player:tradeComplete();
player:addItem(exchange[2]);
player:messageSpecial(ITEM_OBTAINED,exchange[2]);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND) == true) then
player:startEvent(133, 1452, CURRENCY_EXCHANGE_RATE, 1453, CURRENCY_EXCHANGE_RATE, 1454, TIMELESS_HOURGLASS_COST, 4236, TIMELESS_HOURGLASS_COST);
--[[else
player:startEvent(130);
end]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 133) then
if (option == 11) then -- Main menu, and many others. Param1 = map bitmask, param2 = player's gil
player:updateEvent(getDynamisMapList(player), player:getGil());
elseif (option == 10) then -- Final line of the ancient currency explanation. "I'll trade you param3 param2s for a param1."
player:updateEvent(1454, 1453, CURRENCY_EXCHANGE_RATE);
-- Map sales handling.
elseif (option >= MAP_OF_DYNAMIS_SANDORIA and option <= MAP_OF_DYNAMIS_TAVNAZIA) then
-- The returned option is actually the keyitem ID, making this much easier.
-- The prices are set in the menu's dialog, so they cannot be (visibly) changed.
if (option == MAP_OF_DYNAMIS_BEAUCEDINE) then -- 15k gil
player:delGil(15000);
elseif (option == MAP_OF_DYNAMIS_XARCABARD or option == MAP_OF_DYNAMIS_TAVNAZIA) then -- 20k gil
player:delGil(20000);
else -- All others 10k
player:delGil(10000);
end
player:addKeyItem(option);
player:updateEvent(getDynamisMapList(player),player:getGil());
-- Ancient Currency shop menu
elseif (option == 2) then -- Hundreds sales menu Page 1 (price1 item1 price2 item2 price3 item3 price4 item4)
player:updateEvent(25,883,7,1520,8,1516,23,1459);
elseif (option == 3) then -- Hundreds sales menu Page 2 (price1 item1 price2 item2 price3 item3)
player:updateEvent(28,1458,6,1466,5,1295);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 134) then -- Buying an Hourglass
if (player:getFreeSlotsCount() == 0 or player:hasItem(4236) == true) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4236);
else
player:tradeComplete();
player:addItem(4236);
player:messageSpecial(ITEM_OBTAINED,4236);
end
elseif (csid == 153) then -- Bringing back an hourglass for gil.
player:tradeComplete();
player:addGil(TIMELESS_HOURGLASS_COST);
player:messageSpecial(GIL_OBTAINED,TIMELESS_HOURGLASS_COST);
elseif (csid == 135) then -- Trading Singles for a Hundred
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1453);
else
player:tradeComplete();
player:addItem(1453);
player:messageSpecial(ITEM_OBTAINED,1453);
end
elseif (csid == 136) then -- Trading 100 Hundreds for Ten thousand
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1454);
else
player:tradeComplete();
player:addItem(1454);
player:messageSpecial(ITEM_OBTAINED,1454);
end
elseif (csid == 138) then -- Trading Ten thousand for 100 Hundreds
if (player:getFreeSlotsCount() <= 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1453);
else
player:tradeComplete();
player:addItem(1453,CURRENCY_EXCHANGE_RATE);
if (CURRENCY_EXCHANGE_RATE >= 100) then -- Turns out addItem cannot add > stackSize, so we need to addItem twice for quantities > 99.
player:addItem(1453,CURRENCY_EXCHANGE_RATE - 99);
end
player:messageSpecial(ITEMS_OBTAINED,1453,CURRENCY_EXCHANGE_RATE);
end
end
end; | gpl-3.0 |
icplus/OP-SDK | package/ramips/ui/luci-mtk/src/modules/base/luasrc/ip.lua | 86 | 18154 | --[[
LuCI ip calculation libarary
(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
--- LuCI IP calculation library.
module( "luci.ip", package.seeall )
require "nixio"
local bit = nixio.bit
local util = require "luci.util"
--- Boolean; true if system is little endian
LITTLE_ENDIAN = not util.bigendian()
--- Boolean; true if system is big endian
BIG_ENDIAN = not LITTLE_ENDIAN
--- Specifier for IPv4 address family
FAMILY_INET4 = 0x04
--- Specifier for IPv6 address family
FAMILY_INET6 = 0x06
local function __bless(x)
return setmetatable( x, {
__index = luci.ip.cidr,
__add = luci.ip.cidr.add,
__sub = luci.ip.cidr.sub,
__lt = luci.ip.cidr.lower,
__eq = luci.ip.cidr.equal,
__le =
function(...)
return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
end
} )
end
local function __array16( x, family )
local list
if type(x) == "number" then
list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
elseif type(x) == "string" then
if x:find(":") then x = IPv6(x) else x = IPv4(x) end
if x then
assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
list = { unpack(x[2]) }
end
elseif type(x) == "table" and type(x[2]) == "table" then
assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
list = { unpack(x[2]) }
elseif type(x) == "table" then
list = { unpack(x) }
end
assert( list, "Invalid operand" )
return list
end
local function __mask16(bits)
return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
end
local function __not16(bits)
return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
end
local function __maxlen(family)
return ( family == FAMILY_INET4 ) and 32 or 128
end
local function __sublen(family)
return ( family == FAMILY_INET4 ) and 30 or 127
end
--- Convert given short value to network byte order on little endian hosts
-- @param x Unsigned integer value between 0x0000 and 0xFFFF
-- @return Byte-swapped value
-- @see htonl
-- @see ntohs
function htons(x)
if LITTLE_ENDIAN then
return bit.bor(
bit.rshift( x, 8 ),
bit.band( bit.lshift( x, 8 ), 0xFF00 )
)
else
return x
end
end
--- Convert given long value to network byte order on little endian hosts
-- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
-- @return Byte-swapped value
-- @see htons
-- @see ntohl
function htonl(x)
if LITTLE_ENDIAN then
return bit.bor(
bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
htons( bit.rshift( x, 16 ) )
)
else
return x
end
end
--- Convert given short value to host byte order on little endian hosts
-- @class function
-- @name ntohs
-- @param x Unsigned integer value between 0x0000 and 0xFFFF
-- @return Byte-swapped value
-- @see htonl
-- @see ntohs
ntohs = htons
--- Convert given short value to host byte order on little endian hosts
-- @class function
-- @name ntohl
-- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
-- @return Byte-swapped value
-- @see htons
-- @see ntohl
ntohl = htonl
--- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
-- netmask is given as second argument and the IP address is encoded in CIDR
-- notation then the netmask parameter takes precedence. If neither a CIDR
-- encoded prefix nor a netmask parameter is given, then a prefix length of
-- 32 bit is assumed.
-- @param address IPv4 address in dotted quad or CIDR notation
-- @param netmask IPv4 netmask in dotted quad notation (optional)
-- @return luci.ip.cidr instance or nil if given address was invalid
-- @see IPv6
-- @see Hex
function IPv4(address, netmask)
address = address or "0.0.0.0/0"
local obj = __bless({ FAMILY_INET4 })
local data = {}
local prefix = address:match("/(.+)")
address = address:gsub("/.+","")
address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
if netmask then
prefix = obj:prefix(netmask)
elseif prefix then
prefix = tonumber(prefix)
if not prefix or prefix < 0 or prefix > 32 then return nil end
else
prefix = 32
end
local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
b1 = tonumber(b1)
b2 = tonumber(b2)
b3 = tonumber(b3)
b4 = tonumber(b4)
if b1 and b1 <= 255 and
b2 and b2 <= 255 and
b3 and b3 <= 255 and
b4 and b4 <= 255 and
prefix
then
table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
table.insert(obj, prefix)
return obj
end
end
--- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
-- If an optional netmask is given as second argument and the IP address is
-- encoded in CIDR notation then the netmask parameter takes precedence.
-- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
-- prefix length of 128 bit is assumed.
-- @param address IPv6 address in full/compressed/mixed or CIDR notation
-- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
-- @return luci.ip.cidr instance or nil if given address was invalid
-- @see IPv4
-- @see Hex
function IPv6(address, netmask)
address = address or "::/0"
local obj = __bless({ FAMILY_INET6 })
local data = {}
local prefix = address:match("/(.+)")
address = address:gsub("/.+","")
address = address:gsub("^%[(.*)%]$", "%1")
if netmask then
prefix = obj:prefix(netmask)
elseif prefix then
prefix = tonumber(prefix)
if not prefix or prefix < 0 or prefix > 128 then return nil end
else
prefix = 128
end
local borderl = address:sub(1, 1) == ":" and 2 or 1
local borderh, zeroh, chunk, block, i
if #address > 45 then return nil end
repeat
borderh = address:find(":", borderl, true)
if not borderh then break end
block = tonumber(address:sub(borderl, borderh - 1), 16)
if block and block <= 0xFFFF then
data[#data+1] = block
else
if zeroh or borderh - borderl > 1 then return nil end
zeroh = #data + 1
end
borderl = borderh + 1
until #data == 7
chunk = address:sub(borderl)
if #chunk > 0 and #chunk <= 4 then
block = tonumber(chunk, 16)
if not block or block > 0xFFFF then return nil end
data[#data+1] = block
elseif #chunk > 4 then
if #data == 7 or #chunk > 15 then return nil end
borderl = 1
for i=1, 4 do
borderh = chunk:find(".", borderl, true)
if not borderh and i < 4 then return nil end
borderh = borderh and borderh - 1
block = tonumber(chunk:sub(borderl, borderh))
if not block or block > 255 then return nil end
if i == 1 or i == 3 then
data[#data+1] = block * 256
else
data[#data] = data[#data] + block
end
borderl = borderh and borderh + 2
end
end
if zeroh then
if #data == 8 then return nil end
while #data < 8 do
table.insert(data, zeroh, 0)
end
end
if #data == 8 and prefix then
table.insert(obj, data)
table.insert(obj, prefix)
return obj
end
end
--- Transform given hex-encoded value to luci.ip.cidr instance of specified
-- address family.
-- @param hex String containing hex encoded value
-- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
-- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
-- @param swap Bool indicating whether to swap byteorder on low endian host
-- @return luci.ip.cidr instance or nil if given value was invalid
-- @see IPv4
-- @see IPv6
function Hex( hex, prefix, family, swap )
family = ( family ~= nil ) and family or FAMILY_INET4
swap = ( swap == nil ) and true or swap
prefix = prefix or __maxlen(family)
local len = __maxlen(family)
local tmp = ""
local data = { }
local i
for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
if swap and LITTLE_ENDIAN then
for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
else
tmp = tmp .. hex
end
hex = tmp
for i = 1, ( len / 4 ), 4 do
local n = tonumber( hex:sub( i, i+3 ), 16 )
if n then
data[#data+1] = n
else
return nil
end
end
return __bless({ family, data, prefix })
end
--- LuCI IP Library / CIDR instances
-- @class module
-- @cstyle instance
-- @name luci.ip.cidr
cidr = util.class()
--- Test whether the instance is a IPv4 address.
-- @return Boolean indicating a IPv4 address type
-- @see cidr.is6
function cidr.is4( self )
return self[1] == FAMILY_INET4
end
--- Test whether this instance is an IPv4 RFC1918 private address
-- @return Boolean indicating whether this instance is an RFC1918 address
function cidr.is4rfc1918( self )
if self[1] == FAMILY_INET4 then
return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or
((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or
(self[2][1] == 0xC0A8)
end
return false
end
--- Test whether this instance is an IPv4 link-local address (Zeroconf)
-- @return Boolean indicating whether this instance is IPv4 link-local
function cidr.is4linklocal( self )
if self[1] == FAMILY_INET4 then
return (self[2][1] == 0xA9FE)
end
return false
end
--- Test whether the instance is a IPv6 address.
-- @return Boolean indicating a IPv6 address type
-- @see cidr.is4
function cidr.is6( self )
return self[1] == FAMILY_INET6
end
--- Test whether this instance is an IPv6 link-local address
-- @return Boolean indicating whether this instance is IPv6 link-local
function cidr.is6linklocal( self )
if self[1] == FAMILY_INET6 then
return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF)
end
return false
end
--- Return a corresponding string representation of the instance.
-- If the prefix length is lower then the maximum possible prefix length for the
-- corresponding address type then the address is returned in CIDR notation,
-- otherwise the prefix will be left out.
function cidr.string( self )
local str
if self:is4() then
str = string.format(
"%d.%d.%d.%d",
bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
)
if self[3] < 32 then
str = str .. "/" .. self[3]
end
elseif self:is6() then
str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
if self[3] < 128 then
str = str .. "/" .. self[3]
end
end
return str
end
--- Test whether the value of the instance is lower then the given address.
-- This function will throw an exception if the given address has a different
-- family than this instance.
-- @param addr A luci.ip.cidr instance to compare against
-- @return Boolean indicating whether this instance is lower
-- @see cidr.higher
-- @see cidr.equal
function cidr.lower( self, addr )
assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
local i
for i = 1, #self[2] do
if self[2][i] ~= addr[2][i] then
return self[2][i] < addr[2][i]
end
end
return false
end
--- Test whether the value of the instance is higher then the given address.
-- This function will throw an exception if the given address has a different
-- family than this instance.
-- @param addr A luci.ip.cidr instance to compare against
-- @return Boolean indicating whether this instance is higher
-- @see cidr.lower
-- @see cidr.equal
function cidr.higher( self, addr )
assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
local i
for i = 1, #self[2] do
if self[2][i] ~= addr[2][i] then
return self[2][i] > addr[2][i]
end
end
return false
end
--- Test whether the value of the instance is equal to the given address.
-- This function will throw an exception if the given address is a different
-- family than this instance.
-- @param addr A luci.ip.cidr instance to compare against
-- @return Boolean indicating whether this instance is equal
-- @see cidr.lower
-- @see cidr.higher
function cidr.equal( self, addr )
assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
local i
for i = 1, #self[2] do
if self[2][i] ~= addr[2][i] then
return false
end
end
return true
end
--- Return the prefix length of this CIDR instance.
-- @param mask Override instance prefix with given netmask (optional)
-- @return Prefix length in bit
function cidr.prefix( self, mask )
local prefix = self[3]
if mask then
prefix = 0
local stop = false
local obj = type(mask) ~= "table"
and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
if not obj then return nil end
local _, word
for _, word in ipairs(obj[2]) do
if word == 0xFFFF then
prefix = prefix + 16
else
local bitmask = bit.lshift(1, 15)
while bit.band(word, bitmask) == bitmask do
prefix = prefix + 1
bitmask = bit.lshift(1, 15 - (prefix % 16))
end
break
end
end
end
return prefix
end
--- Return a corresponding CIDR representing the network address of this
-- instance.
-- @param bits Override prefix length of this instance (optional)
-- @return CIDR instance containing the network address
-- @see cidr.host
-- @see cidr.broadcast
-- @see cidr.mask
function cidr.network( self, bits )
local data = { }
bits = bits or self[3]
local i
for i = 1, math.floor( bits / 16 ) do
data[#data+1] = self[2][i]
end
if #data < #self[2] then
data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
for i = #data + 1, #self[2] do
data[#data+1] = 0
end
end
return __bless({ self[1], data, __maxlen(self[1]) })
end
--- Return a corresponding CIDR representing the host address of this
-- instance. This is intended to extract the host address from larger subnet.
-- @return CIDR instance containing the network address
-- @see cidr.network
-- @see cidr.broadcast
-- @see cidr.mask
function cidr.host( self )
return __bless({ self[1], self[2], __maxlen(self[1]) })
end
--- Return a corresponding CIDR representing the netmask of this instance.
-- @param bits Override prefix length of this instance (optional)
-- @return CIDR instance containing the netmask
-- @see cidr.network
-- @see cidr.host
-- @see cidr.broadcast
function cidr.mask( self, bits )
local data = { }
bits = bits or self[3]
for i = 1, math.floor( bits / 16 ) do
data[#data+1] = 0xFFFF
end
if #data < #self[2] then
data[#data+1] = __mask16(bits)
for i = #data + 1, #self[2] do
data[#data+1] = 0
end
end
return __bless({ self[1], data, __maxlen(self[1]) })
end
--- Return CIDR containing the broadcast address of this instance.
-- @return CIDR instance containing the netmask, always nil for IPv6
-- @see cidr.network
-- @see cidr.host
-- @see cidr.mask
function cidr.broadcast( self )
-- IPv6 has no broadcast addresses (XXX: assert() instead?)
if self[1] == FAMILY_INET4 then
local data = { unpack(self[2]) }
local offset = math.floor( self[3] / 16 ) + 1
if offset <= #data then
data[offset] = bit.bor( data[offset], __not16(self[3]) )
for i = offset + 1, #data do data[i] = 0xFFFF end
return __bless({ self[1], data, __maxlen(self[1]) })
end
end
end
--- Test whether this instance fully contains the given CIDR instance.
-- @param addr CIDR instance to test against
-- @return Boolean indicating whether this instance contains the given CIDR
function cidr.contains( self, addr )
assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
if self:prefix() <= addr:prefix() then
return self:network() == addr:network(self:prefix())
end
return false
end
--- Add specified amount of hosts to this instance.
-- @param amount Number of hosts to add to this instance
-- @param inplace Boolen indicating whether to alter values inplace (optional)
-- @return CIDR representing the new address or nil on overflow error
-- @see cidr.sub
function cidr.add( self, amount, inplace )
local pos
local data = { unpack(self[2]) }
local shorts = __array16( amount, self[1] )
for pos = #data, 1, -1 do
local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
if ( data[pos] + add ) > 0xFFFF then
data[pos] = ( data[pos] + add ) % 0xFFFF
if pos > 1 then
data[pos-1] = data[pos-1] + ( add - data[pos] )
else
return nil
end
else
data[pos] = data[pos] + add
end
end
if inplace then
self[2] = data
return self
else
return __bless({ self[1], data, self[3] })
end
end
--- Substract specified amount of hosts from this instance.
-- @param amount Number of hosts to substract from this instance
-- @param inplace Boolen indicating whether to alter values inplace (optional)
-- @return CIDR representing the new address or nil on underflow error
-- @see cidr.add
function cidr.sub( self, amount, inplace )
local pos
local data = { unpack(self[2]) }
local shorts = __array16( amount, self[1] )
for pos = #data, 1, -1 do
local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
if ( data[pos] - sub ) < 0 then
data[pos] = ( sub - data[pos] ) % 0xFFFF
if pos > 1 then
data[pos-1] = data[pos-1] - ( sub + data[pos] )
else
return nil
end
else
data[pos] = data[pos] - sub
end
end
if inplace then
self[2] = data
return self
else
return __bless({ self[1], data, self[3] })
end
end
--- Return CIDR containing the lowest available host address within this subnet.
-- @return CIDR containing the host address, nil if subnet is too small
-- @see cidr.maxhost
function cidr.minhost( self )
if self[3] <= __sublen(self[1]) then
-- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
return self:network():add(1, true)
end
end
--- Return CIDR containing the highest available host address within the subnet.
-- @return CIDR containing the host address, nil if subnet is too small
-- @see cidr.minhost
function cidr.maxhost( self )
if self[3] <= __sublen(self[1]) then
local i
local data = { unpack(self[2]) }
local offset = math.floor( self[3] / 16 ) + 1
data[offset] = bit.bor( data[offset], __not16(self[3]) )
for i = offset + 1, #data do data[i] = 0xFFFF end
data = __bless({ self[1], data, __maxlen(self[1]) })
-- Last address in reserved for Broadcast Address in IPv4
if data[1] == FAMILY_INET4 then data:sub(1, true) end
return data
end
end
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Temenos/mobs/Goblin_Theurgist.lua | 16 | 1151 | -----------------------------------
-- Area: Temenos N T
-- NPC: Goblin_Theurgist
-----------------------------------
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)
GetMobByID(16928831):updateEnmity(target);
GetMobByID(16928832):updateEnmity(target);
GetMobByID(16928834):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if (IsMobDead(16928831)==true and IsMobDead(16928832)==true and IsMobDead(16928833)==true and IsMobDead(16928834)==true and IsMobDead(16928835)==true ) then
GetNPCByID(16928768+39):setPos(-599,85,438);
GetNPCByID(16928768+39):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+456):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
RhenaudTheLukark/CreateYourFrisk | Assets/Mods/Examples/Lua/Waves/COMBINED.lua | 2 | 2204 | -- The bouncing bullets attack from the documentation example.
-- Sets a bullet's color as a string, then checks it in OnHit to achieve different types of bullet effects in one wave.
spawntimer = 0
bullets = {}
colors = {"regular", "cyan", "orange", "green"}
function Update()
spawntimer = spawntimer + 1
if spawntimer%20 == 0 then
local posx = 30 - math.random(60)
local posy = Arena.height/2
local bulletType = colors[math.random(#colors)]
local bullet = CreateProjectile("bullet", posx, posy)
if bulletType == "cyan" then
bullet.sprite.color = {0/255, 162/255, 232/255}
elseif bulletType == "orange" then
bullet.sprite.color = {255/255, 154/255, 34/255}
elseif bulletType == "green" then
bullet.sprite.color = {64/255, 252/255, 64/255}
end
bullet.SetVar('color', bulletType)
bullet.SetVar('velx', 1 - 2*math.random())
bullet.SetVar('vely', 0)
table.insert(bullets, bullet)
end
for i=1,#bullets do
local bullet = bullets[i]
-- Note this new if check. We're going to remove bullets, and we can't move bullets that were removed.
if bullet.isactive then
local velx = bullet.GetVar('velx')
local vely = bullet.GetVar('vely')
local newposx = bullet.x + velx
local newposy = bullet.y + vely
if(bullet.x > -Arena.width/2 and bullet.x < Arena.width/2) then
if(bullet.y < -Arena.height/2 + 8) then
newposy = -Arena.height/2 + 8
vely = 4
end
end
vely = vely - 0.04
bullet.MoveTo(newposx, newposy)
bullet.SetVar('vely', vely)
end
end
end
function OnHit(bullet)
local color = bullet.GetVar("color")
local damage = 5
if color == "regular" then
Player.Hurt(damage)
elseif color == "cyan" and Player.isMoving then
Player.Hurt(damage)
elseif color == "orange" and not Player.isMoving then
Player.Hurt(damage)
elseif color == "green" then
Player.Heal(1)
bullet.Remove()
end
end | gpl-3.0 |
nasomi/darkstar | scripts/zones/Qulun_Dome/mobs/Za_Dha_Adamantking.lua | 27 | 1182 | -----------------------------------
-- Area: Qulun Dome
-- NM: Za Dha Adamantking
-----------------------------------
require("scripts/globals/titles");
require("scripts/zones/Qulun_Dome/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
--TODO: Addtionaleffect:Slow on melee attacks
mob:showText(mob,QUADAV_KING_ENGAGE);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:addTitle(ADAMANTKING_USURPER);
mob:showText(mob,QUADAV_KING_DEATH);
-- Set Za_Dha_Adamantking's Window Open Time
local wait = 48 * 3600
SetServerVariable("[POP]Za_Dha_Adamantking", os.time(t) + wait); -- 2 days
-- Set Diamond_Quadav's spawnpoint and respawn time (21-24 hours)
local Diamond_Quadav = 17383442;
DeterMob(Diamond_Quadav, false);
GetMobByID(Diamond_Quadav):setRespawnTime(math.random((75600),(86400))); -- 21 to 24 hours
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Turbulent_Storm.lua | 21 | 1898 | -----------------------------------
-- Area: The Eldieme Necropolis [S]
-- NPC: Turbulent Storm
-- Note: Starts Quest "The Fighting Fourth"
-- @pos 422.461 -48.000 175
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCampaignAllegiance() > 0) then
if (player:getCampaignAllegiance() == 2) then
player:startEvent(9);
else
-- message for other nations missing
player:startEvent(9);
end
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == true) then
player:startEvent(8);
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == false) then
player:startEvent(7);
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 == 0x0007 and option == 0) then
player:addKeyItem(BLUE_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED,BLUE_RECOMMENDATION_LETTER);
end
end; | gpl-3.0 |
bmddota/barebones | game/dota_addons/barebones/scripts/vscripts/libraries/selection.lua | 10 | 6644 | SELECTION_VERSION = "1.00"
--[[
Lua-controlled Selection Library by Noya
Installation:
- "require" this file inside your code in order to add the new API functions to the PlayerResource global
- Additionally, ensure your game scripts custom_net_tables.txt has a "selection" entry
- Finally, ensure that you have the following files correctly added and included in your panorama content folder
selection.xml, and include line on custom_ui_manifest.xml, on layout/custom_game/ folder
selection folder containing selection.js and selection_filter.js, on /scripts/ folder
Usage:
- Functions with unit_args can recieve an Entity Index, a NPC Handle, or a table of each type.
- Functions with unit can recieve an Entity Index or NPC Handle
* Create a new selection for the player
PlayerResource:NewSelection(playerID, unit_args)
* Add units to the current selection of the player
PlayerResource:AddToSelection(playerID, unit_args)
* Remove units by index from the player selection group
PlayerResource:RemoveFromSelection(playerID, unit_args)
* Returns the list of units by entity index that are selected by the player
PlayerResource:GetSelectedEntities(playerID)
* Deselect everything, selecting the main hero (which can be redirected to another entity)
PlayerResource:ResetSelection(playerID)
* Get the index of the first selected unit of the player
PlayerResource:GetMainSelectedEntity(playerID)
* Check if a unit is selected or not by a player, returns bool
PlayerResource:IsUnitSelected(playerID, unit_args)
* Force a refresh of the current selection on all players, useful after abilities are removed
PlayerResource:RefreshSelection()
* Redirects the selection of the main hero to another entity of choice
PlayerResource:SetDefaultSelectionEntity(playerID, unit)
* Redirects the selection of any entity to another entity of choice
hero:SetSelectionOverride(unit)
* Use -1 to reset to default
PlayerResource:SetDefaultSelectionEntity(playerID, -1)
hero:SetSelectionOverride(-1)
Notes:
- Enemy units that you don't control can't be added to the selection group of a player
- This library requires "libraries/timers.lua" to be present in your vscripts directory.
--]]
function CDOTA_PlayerResource:NewSelection(playerID, unit_args)
local player = self:GetPlayer(playerID)
if player then
local entities = Selection:GetEntIndexListFromTable(unit_args)
CustomGameEventManager:Send_ServerToPlayer(player, "selection_new", {entities = entities})
end
end
function CDOTA_PlayerResource:AddToSelection(playerID, unit_args)
local player = self:GetPlayer(playerID)
if player then
local entities = Selection:GetEntIndexListFromTable(unit_args)
CustomGameEventManager:Send_ServerToPlayer(player, "selection_add", {entities = entities})
end
end
function CDOTA_PlayerResource:RemoveFromSelection(playerID, unit_args)
local player = self:GetPlayer(playerID)
if player then
local entities = Selection:GetEntIndexListFromTable(unit_args)
CustomGameEventManager:Send_ServerToPlayer(player, "selection_remove", {entities = entities})
end
end
function CDOTA_PlayerResource:ResetSelection(playerID)
local player = self:GetPlayer(playerID)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "selection_reset", {})
end
end
function CDOTA_PlayerResource:GetSelectedEntities(playerID)
return Selection.entities[playerID] or {}
end
function CDOTA_PlayerResource:GetMainSelectedEntity(playerID)
local selectedEntities = self:GetSelectedEntities(playerID)
return selectedEntities and selectedEntities["0"]
end
function CDOTA_PlayerResource:IsUnitSelected(playerID, unit)
if not unit then return false end
local entIndex = type(unit)=="number" and unit or IsValidEntity(unit) and unit:GetEntityIndex()
if not entIndex then return false end
local selectedEntities = self:GetSelectedEntities(playerID)
for _,v in pairs(selectedEntities) do
if v==entIndex then
return true
end
end
return false
end
function CDOTA_PlayerResource:RefreshSelection()
Timers:CreateTimer(0.03, function()
FireGameEvent("dota_player_update_selected_unit", {})
end)
end
function CDOTA_PlayerResource:SetDefaultSelectionEntity(playerID, unit)
if not unit then unit = -1 end
local entIndex = type(unit)=="number" and unit or unit:GetEntityIndex()
local hero = self:GetSelectedHeroEntity(playerID)
if hero then
hero:SetSelectionOverride(unit)
end
end
function CDOTA_BaseNPC:SetSelectionOverride(reselect_unit)
local unit = self
local reselectIndex = type(reselect_unit)=="number" and reselect_unit or reselect_unit:GetEntityIndex()
CustomNetTables:SetTableValue("selection", tostring(unit:GetEntityIndex()), {entity = reselectIndex})
end
------------------------------------------------------------------------
-- Internal
------------------------------------------------------------------------
require('libraries/timers')
if not Selection then
Selection = class({})
end
function Selection:Init()
Selection.entities = {} --Stores the selected entities of each playerID
CustomGameEventManager:RegisterListener("selection_update", Dynamic_Wrap(Selection, 'OnUpdate'))
end
function Selection:OnUpdate(event)
local playerID = event.PlayerID
Selection.entities[playerID] = event.entities
end
-- Internal function to build an entity index list out of various inputs
function Selection:GetEntIndexListFromTable(unit_args)
local entities = {}
if type(unit_args)=="number" then
table.insert(entities, unit_args) -- Entity Index
-- Check contents of the table
elseif type(unit_args)=="table" then
if unit_args.IsCreature then
table.insert(entities, unit_args:GetEntityIndex()) -- NPC Handle
else
for _,arg in pairs(unit_args) do
-- Table of entity index values
if type(arg)=="number" then
table.insert(entities, arg)
-- Table of npc handles
elseif type(arg)=="table" then
if arg.IsCreature then
table.insert(entities, arg:GetEntityIndex())
end
end
end
end
end
return entities
end
if not Selection.entities then Selection:Init() end | apache-2.0 |
nasomi/darkstar | scripts/globals/spells/valor_minuet_ii.lua | 18 | 1591 | -----------------------------------------
-- Spell: Valor Minuet II
-- Grants Attack bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 10;
if (sLvl+iLvl > 85) then
power = power + math.floor((sLvl+iLvl-85) / 6);
end
if (power >= 32) then
power = 32;
end
local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINUET_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 2)) then
spell:setMsg(75);
end
return EFFECT_MINUET;
end; | gpl-3.0 |
shakfu/start-vm | config/artful/awesome/vicious/contrib/batpmu_linux.lua | 4 | 2402 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { open = io.open }
local setmetatable = setmetatable
local math = {
min = math.min,
floor = math.floor
}
local string = {
find = string.find,
match = string.match,
format = string.format
}
-- }}}
-- Batpmu: provides state, charge and remaining time for a requested battery using PMU
-- vicious.contrib.batpmu
local batpmu_linux = {}
-- {{{ Battery widget type
local function worker(format, batid)
local battery_state = {
["full"] = "↯",
["unknown"] = "⌁",
["00000013"] = "+",
["00000011"] = "-"
}
-- Get /proc/pmu/battery* state
local f = io.open("/proc/pmu/" .. batid)
-- Handler for incompetent users
if not f then return {battery_state["unknown"], 0, "N/A"} end
local statefile = f:read("*all")
f:close()
-- Get /proc/pmu/info data
local f = io.open("/proc/pmu/info")
local infofile = f:read("*all")
f:close()
-- Check if the battery is present
if infofile == nil or string.find(infofile, "Battery count[%s]+:[%s]0") then
return {battery_state["unknown"], 0, "N/A"}
end
-- Get capacity and charge information
local capacity = string.match(statefile, "max_charge[%s]+:[%s]([%d]+).*")
local remaining = string.match(statefile, "charge[%s]+:[%s]([%d]+).*")
-- Calculate percentage
local percent = math.min(math.floor(remaining / capacity * 100), 100)
-- Get timer information
local timer = string.match(statefile, "time rem%.[%s]+:[%s]([%d]+).*")
if timer == "0" then return {battery_state["full"], percent, "N/A"} end
-- Get state information
local state = string.match(statefile, "flags[%s]+:[%s]([%d]+).*")
local state = battery_state[state] or battery_state["unknown"]
-- Calculate remaining (charging or discharging) time
local hoursleft = math.floor(tonumber(timer) / 3600)
local minutesleft = math.floor((tonumber(timer) / 60) % 60)
local time = string.format("%02d:%02d", hoursleft, minutesleft)
return {state, percent, time}
end
-- }}}
return setmetatable(batpmu_linux, { __call = function(_, ...) return worker(...) end })
| mit |
blankoworld/quinoa | bin/parser.lua | 1 | 1367 | #!/usr/bin/env lua
--[[ LICENSE
Makefly, a static weblog engine using a BSD Makefile
Copyright (C) 2012 DOSSMANN Olivier
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
--[[ USE
lua parser.lua var1=value1 var2=value2 <in >out
This permits to replace ${var1} by "value1" in a string.
Could be used as this: % lua test.lua "un cochon=un chat" <<<'Oh ! ${un cochon} !'
Result: Oh ! un chat !
--]]
function replace(file, table)
local s = file:read("*a")
return s:gsub("$(%b{})", function(s)
return table[s:sub(2,-2)]
end)
end
function parseargs(...)
local out = {}
for _, v in ipairs({...}) do
local key = v:match("(.-)=")
local val = v:match("=(.*)")
out[key] = val
end
return out
end
io.write((replace(io.stdin, parseargs(...))))
| agpl-3.0 |
nasomi/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Rasdinice.lua | 36 | 1113 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Rasdinice
-- @zone 80
-- @pos -8 1 35
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 11637); -- (Couldn't find default text so i threw this in) Perhaps you should first attend to more pressing matters...
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/rolanberry_pie.lua | 35 | 1274 | -----------------------------------------
-- ID: 4414
-- Item: rolanberry_pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 50
-- Agility -1
-- Intelligence 2
-----------------------------------------
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,4414);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 50);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_INT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 50);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_INT, 2);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Selbina/npcs/Elfriede.lua | 17 | 1956 | -----------------------------------
-- Area: Selbina
-- NPC: Elfriede
-- Involved In Quest: The Tenshodo Showdown
-- @pos 61 -15 10 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("theTenshodoShowdownCS") == 3) then
if (trade:hasItemQty(4569,1) and trade:getItemCount() == 1) then -- Trade Quadav Stew
player:startEvent(0x2714,0,TENSHODO_ENVELOPE,4569);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local theTenshodoShowdownCS = player:getVar("theTenshodoShowdownCS");
if (theTenshodoShowdownCS == 2) then
player:startEvent(0x2712,0,TENSHODO_ENVELOPE,4569); -- During Quest "The Tenshodo Showdown"
player:setVar("theTenshodoShowdownCS",3);
elseif (theTenshodoShowdownCS == 3) then
player:startEvent(0x2713,0,0,4569);
else
player:startEvent(0x0019); -- Standard dialog
end
end;
-- 0x0019 0x2712 0x2713 0x2714 4569
-----------------------------------
-- 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 == 0x2714) then
player:tradeComplete();
player:setVar("theTenshodoShowdownCS",4);
player:delKeyItem(TENSHODO_ENVELOPE);
player:addKeyItem(SIGNED_ENVELOPE);
player:messageSpecial(KEYITEM_OBTAINED,SIGNED_ENVELOPE);
end
end; | gpl-3.0 |
coolflyreg/gs | common/lualib/EventHandler.lua | 1 | 1089 |
EventHandler = class("EventHandler")
EventHandler.__index = EventHandler
EventHandler.handlers = {}
function EventHandler:add(func)
if (func == nil or type(func) ~= "function") then return false end
if (self:indexOfHandler(func) > 0) then return false end
local list = self.handlers
list[#list + 1] = func
return true
end
function EventHandler:remove(func)
local index = self:indexOfHandler(func)
if (index == 0) then return end
local list = self.handlers
table.remove(list, index)
end
function EventHandler:clear()
local list = self.handlers
while (#list > 0) do
list[1] = nil
end
end
function EventHandler:indexOfHandler(handler) -- Integer 0,1,2.....
local list = self.handlers
local i = 1
for i = 1, #list do
if (list[i] == handler) then return i end
end
return 0
end
function EventHandler:raiseEvent(event, args)
local list = self.handlers
for i = 1, #list do
if (list[i] ~= nil) then
list[i](event, args)
end
end
end | gpl-2.0 |
moodlIMyIl/WASLTSHAKE | bot.lua | 16 | 5685 | package.path = package.path..';.luarocks/share/lua/5.2/?.lua;.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath..';.luarocks/lib/lua/5.2/?.so'
http = require('socket.http')
https = require('ssl.https')
url = require('socket.url')
json = require('dkjson')
require("config")
require("extra")
function bot_run()
bot = nil
while not bot do
bot = send_req(send_api.."/getMe")
end
bot = bot.result
local runlog = bot.first_name.." [@"..bot.username.."]\nis run in: "..os.date("%F - %H:%M:%S")
print(runlog)
send_msg(sudo_id, runlog)
plugin = dofile('plugin.lua')
last_update = last_update or 0
last_cron = last_cron or os.time()
startbot = true
end
function send_req(url)
local dat, res = https.request(url)
local tab = json.decode(dat)
if res ~= 200 then return false end
if not tab.ok then return false end
return tab
end
function bot_updates(offset)
local url = send_api.."/getUpdates?timeout=10"
if offset then
url = url.."&offset="..offset
end
return send_req(url)
end
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = json.decode(s)
return data
end
function save_data(filename, data)
local s = json.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
function send_msg(chat_id, text, use_markdown)
local text_len = string.len(text)
local num_msg = math.ceil(text_len / 3000)
if num_msg <= 1 then
local send = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&disable_web_page_preview=true"
if use_markdown then
send = send.."&parse_mode=Markdown"
end
return send_req(send)
else
text = text:gsub("*","")
text = text:gsub("`","")
text = text:gsub("_","")
local f = io.open("large_msg.txt", 'w')
f:write(text)
f:close()
local send = send_api.."/sendDocument"
local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@large_msg.txt"'
return io.popen(curl_command):read("*all")
end
end
function send_document(chat_id, name)
local send = send_api.."/sendDocument"
local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@'..name..'"'
return io.popen(curl_command):read("*all")
end
function send_key(chat_id, text, keyboard, resize, mark)
local response = {}
response.keyboard = keyboard
response.resize_keyboard = resize
response.one_time_keyboard = false
response.selective = false
local responseString = json.encode(response)
if mark then
sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&disable_web_page_preview=true&reply_markup="..url.escape(responseString)
else
sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&parse_mode=Markdown&disable_web_page_preview=true&reply_markup="..url.escape(responseString)
end
return send_req(sended)
end
function string:input()
if not self:find(' ') then
return false
end
return self:sub(self:find(' ')+1)
end
function msg_receive(msg)
if msg.date < os.time() - 5 then return end
if not msg.text then
msg.text = msg.caption or ''
end
if string.match(msg.text:lower(), '^[@'..bot.username..']*') then
blocks = load_data("blocks.json")
if blocks[tostring(msg.from.id)] then
return
end
flood = load_data("flood.json")
if not flood[tostring(msg.from.id)] then
flood[tostring(msg.from.id)] = {f=0,d=msg.date}
save_data("flood.json", flood)
end
if flood[tostring(msg.from.id)].f > 5 then
if flood[tostring(msg.from.id)].d > msg.date - 2 then
if msg.from.id == sudo_id or msg.from.id == bot.id then
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("flood.json", flood)
else
chats = load_data("chats.json")
requests = load_data("requests.json")
blocks[tostring(msg.from.id)] = true
save_data("blocks.json", blocks)
send_msg(msg.from.id, "_You are_ *Blocked* _for spaming_", true)
send_msg(admingp, msg.from.id.." _for spaming_ *Blocked*", true)
if requests[tostring(msg.from.id)] then
requests[tostring(msg.from.id)] = false
save_data("requests.json", requests)
elseif chats.id == tonumber(msg.from.id) then
chats.id = 0
save_data("chats.json", chats)
end
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("flood.json", flood)
return
end
else
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("flood.json", flood)
end
else
flood[tostring(msg.from.id)].f = flood[tostring(msg.from.id)].f+1
save_data("flood.json", flood)
end
local success, result = pcall(
function()
return plugin.launch(msg)
end
)
if not success then
print(msg.text, result)
return
end
if type(result) == 'table' then
msg = result
elseif result ~= true then
return
end
end
end
function query_receive(msg)
local success, result = pcall(
function()
return plugin.inline(msg)
end
)
if not success then
return
end
if type(result) == 'table' then
msg = result
elseif result ~= true then
return
end
end
bot_run()
while startbot do
local res = bot_updates(last_update+1)
if res then
for i,v in ipairs(res.result) do
last_update = v.update_id
if v.edited_message then
msg_receive(v.edited_message)
elseif v.message then
msg_receive(v.message)
elseif v.inline_query then
query_receive(v.inline_query)
end
end
else
print("error while")
end
if last_cron < os.time() - 30 then
if plugin.cron then
local res, err = pcall(
function()
plugin.cron()
end
)
if not res then print('error: '..err) end
end
last_cron = os.time()
end
end | apache-2.0 |
nasomi/darkstar | scripts/zones/Northern_San_dOria/npcs/Emeige_AMAN.lua | 65 | 1182 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Emeige A.M.A.N.
-- Type: Mentor Recruiter
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local var = 0;
if (player:getMentor() == 0) then
if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then
var = 1;
end
elseif (player:getMentor() >= 1) then
var = 2;
end
player:startEvent(0x02E3, var);
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 == 0x02E3 and option == 0) then
player:setMentor(1);
end
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/PsoXja/npcs/_09h.lua | 17 | 1223 | -----------------------------------
-- Area: Pso'Xja
-- NPC: Avatars Gate
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 9) then
player:startEvent(0x0005);
else
player:messageSpecial(DOOR_LOCKED);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x0005) then
player:setVar("COP_Tenzen_s_Path",10);
end
end; | gpl-3.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/bomb_armed_1.meta.lua | 22 | 2111 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"96 225 1 255",
"171 205 228 255",
"147 232 58 255",
"255 0 0 255",
"223 64 38 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
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 18,
y = -2
},
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 |
sugao516/gltron-code | levels/4squares.lua | 1 | 5477 | directions = { random = -1, up = 2, down = 0, right = 1, left = 3 }
level = {
version = 71,
-- the sizes in the level are all in the [0,1] range and can be
-- scaled to the appropriate arena size
scalable = 1,
-- collision detection takes place against these lines
boundary = {
{ { x = 0, y = 1 }, { x = 0.375, y = 1 } },
{ { x = 0, y = 1 }, { x = 0, y = 0.625 } },
{ { x = 0, y = 0 }, { x = 0, y = 0.375 } },
{ { x = 0, y = 0 }, { x = 0.375, y = 0 } },
{ { x = 0, y = 0.375 }, { x = 0.125, y = 0.375 } },
{ { x = 0.125, y = 0.375 }, { x = 0.125, y = 0.625 } },
{ { x = 0.125, y = 0.625 }, { x = 0, y = 0.625 } },
{ { x = 0.125, y = 0.375 }, { x = 0.125, y = 0.625 } },
{ { x = 0.125, y = 0.375 }, { x = 0.125, y = 0.625 } },
{ { x = 0, y = 0 }, { x = 0, y = 0.375 } },
{ { x = 0.375, y = 0 }, { x = 0.375, y = 0.125 } },
{ { x = 0.375, y = 0.125 }, { x = 0.625, y = 0.125 } },
{ { x = 0.625, y = 0.125 }, { x = 0.625, y = 0 } },
{ { x = 0.625, y = 0 }, { x = 1, y = 0 } },
{ { x = 1, y = 0 }, { x = 1, y = 0.375 } },
{ { x = 1, y = 0.375 }, { x = 0.875, y = 0.375 } },
{ { x = 0.875, y = 0.625 }, { x = 0.875, y = 0.375 } },
{ { x = 0.875, y = 0.625 }, { x = 1, y = 0.625 } },
{ { x = 1, y = 1 }, { x = 1, y = 0.625 } },
{ { x = 0.625, y = 1 }, { x = 1, y = 1 } },
{ { x = 0.625, y = 1 }, { x = 0.625, y = 0.875 } },
{ { x = 0.375, y = 0.875 }, { x = 0.625, y = 0.875 } },
{ { x = 0.375, y = 0.875 }, { x = 0.375, y = 1 } },
{ { x = 0.25, y = 0.375 }, { x = 0.375, y = 0.375 } },
{ { x = 0.375, y = 0.375 }, { x = 0.375, y = 0.25 } },
{ { x = 0.375, y = 0.25 }, { x = 0.625, y = 0.25 } },
{ { x = 0.625, y = 0.25 }, { x = 0.625, y = 0.375 } },
{ { x = 0.625, y = 0.375 }, { x = 0.75, y = 0.375 } },
{ { x = 0.75, y = 0.375 }, { x = 0.75, y = 0.625 } },
{ { x = 0.75, y = 0.625 }, { x = 0.625, y = 0.625 } },
{ { x = 0.625, y = 0.625 }, { x = 0.625, y = 0.75 } },
{ { x = 0.625, y = 0.75 }, { x = 0.375, y = 0.75 } },
{ { x = 0.375, y = 0.75 }, { x = 0.375, y = 0.625 } },
{ { x = 0.375, y = 0.625 }, { x = 0.25, y = 0.625 } },
{ { x = 0.25, y = 0.375 }, { x = 0.25, y = 0.625 } },
},
-- spawn points
-- (they don't have to be sorted, they will be randomized anyway)
spawn = {
{ x = .25, y = .5, dir = directions.random },
{ x = .5, y = .25, dir = directions.random },
{ x = .5, y = .75, dir = directions.random },
{ x = .75, y = .5, dir = directions.random }
},
-- floor geometry is used to generate reflections, and
-- as a background for the 2d map
floor = {
-- uv = 4, normal = 2, position = 1
vertexformat = 5,
shading = {
lit = 0, -- no lighting, only diffuse texture is applied
textures = {
diffuse = {
file = "gltron_floor.png",
-- 0: nearest, 1: linear: 2: linear_mipmap_nearest
-- 3: linear_mipmap_linear
min_filter = 3,
mag_filter = 1,
-- 0: clamp, 1: clamp to edge, 2: repeat
wrap_s = 2,
wrap_t = 2
}
}
},
vertices = {
{ pos = { x = 0, y = 0, z = 0 }, uv = { u = 0, v = 0 } },
{ pos = { x = 1, y = 0, z = 0 }, uv = { u = 40, v = 0 } },
{ pos = { x = 1, y = 1, z = 0 }, uv = { u = 40, v = 40 } },
{ pos = { x = 0, y = 1, z = 0 }, uv = { u = 0, v = 40 } }
},
indices = {
{ 0, 1, 2 },
{ 0, 2, 3 }
}
},
arena = {
-- uv = 4, normal = 2, position = 1
vertexformat = 5,
shading = {
lit = 0, -- no lighting, only diffuse texture is applied
textures = {
diffuse = {
file = "walls.png",
-- 0: nearest, 1: linear: 2: linear_mipmap_nearest
-- 3: linear_mipmap_linear
min_filter = 3,
mag_filter = 1,
-- 0: clamp, 1: clamp to edge, 2: repeat
wrap_s = 1,
wrap_t = 1
}
}
},
vertices = {
-- wall
{ pos = { x = 0, y = 0, z = 0 }, uv = { u = 0, v = 0 } },
{ pos = { x = 0, y = 1, z = 0 }, uv = { u = 0.25, v = 0 } },
{ pos = { x = 0, y = 1, z = 0.125 }, uv = { u = 0.25, v = 1 } },
{ pos = { x = 0, y = 0, z = 0.125 }, uv = { u = 0, v = 1 } },
-- wall
{ pos = { x = 0, y = 1, z = 0 }, uv = { u = 0.25, v = 0 } },
{ pos = { x = 1, y = 1, z = 0 }, uv = { u = 0.5, v = 0 } },
{ pos = { x = 1, y = 1, z = 0.125 }, uv = { u = 0.5, v = 1 } },
{ pos = { x = 0, y = 1, z = 0.125 }, uv = { u = 0.25, v = 1 } },
-- wall
{ pos = { x = 1, y = 1, z = 0 }, uv = { u = 0.5, v = 0 } },
{ pos = { x = 1, y = 0, z = 0 }, uv = { u = 0.75, v = 0 } },
{ pos = { x = 1, y = 0, z = 0.125 }, uv = { u = 0.75, v = 1 } },
{ pos = { x = 1, y = 1, z = 0.125 }, uv = { u = 0.5, v = 1 } },
-- wall
{ pos = { x = 1, y = 0, z = 0 }, uv = { u = 0.75, v = 0 } },
{ pos = { x = 0, y = 0, z = 0 }, uv = { u = 1, v = 0 } },
{ pos = { x = 0, y = 0, z = 0.125 }, uv = { u = 1, v = 1 } },
{ pos = { x = 1, y = 0, z = 0.125 }, uv = { u = 0.75, v = 1 } }
},
indices = {
{ 0, 1, 2 }, { 0, 2, 3 },
{ 4, 5, 6 }, { 4, 6, 7 }, { 8, 9, 10 }, { 8, 10, 11 },
{ 12, 13, 14 }, { 12, 14, 15 }
}
}
}
| gpl-2.0 |
shangjiyu/luci-with-extra | applications/luci-app-ddns/luasrc/model/cbi/ddns/detail.lua | 11 | 54059 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Copyright 2013 Manuel Munz <freifunk at somakoma dot de>
-- Copyright 2014-2016 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local NX = require "nixio"
local NXFS = require "nixio.fs"
local SYS = require "luci.sys"
local UTIL = require "luci.util"
local HTTP = require "luci.http"
local DISP = require "luci.dispatcher"
local WADM = require "luci.tools.webadmin"
local DTYP = require "luci.cbi.datatypes"
local CTRL = require "luci.controller.ddns" -- this application's controller
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- takeover arguments -- #######################################################
local section = arg[1]
-- html constants -- ###########################################################
local font_red = "<font color='red'>"
local font_off = "</font>"
local bold_on = "<strong>"
local bold_off = "</strong>"
-- error text constants -- #####################################################
local err_ipv6_plain = translate("IPv6 not supported") .. " - " ..
translate("please select 'IPv4' address version")
local err_ipv6_basic = bold_on ..
font_red ..
translate("IPv6 not supported") ..
font_off ..
"<br />" .. translate("please select 'IPv4' address version") ..
bold_off
local err_ipv6_other = bold_on ..
font_red ..
translate("IPv6 not supported") ..
font_off ..
"<br />" .. translate("please select 'IPv4' address version in") .. " " ..
[[<a href="]] ..
DISP.build_url("admin", "services", "ddns", "detail", section) ..
"?tab.dns." .. section .. "=basic" ..
[[">]] ..
translate("Basic Settings") ..
[[</a>]] ..
bold_off
function err_tab_basic(self)
return translate("Basic Settings") .. " - " .. self.title .. ": "
end
function err_tab_adv(self)
return translate("Advanced Settings") .. " - " .. self.title .. ": "
end
function err_tab_timer(self)
return translate("Timer Settings") .. " - " .. self.title .. ": "
end
-- read services/services_ipv6 files -- ########################################
local services4 = { } -- IPv4 --
local fd4 = io.open("/etc/ddns/services", "r")
if fd4 then
local ln, s, t
repeat
ln = fd4:read("*l")
s = ln and ln:match('^%s*".*') -- only handle lines beginning with "
s = s and s:gsub('"','') -- remove "
t = s and UTIL.split(s,"(%s+)",nil,true) -- split on whitespaces
if t then services4[t[1]]=t[2] end
until not ln
fd4:close()
end
local services6 = { } -- IPv6 --
local fd6 = io.open("/etc/ddns/services_ipv6", "r")
if fd6 then
local ln, s, t
repeat
ln = fd6:read("*l")
s = ln and ln:match('^%s*".*') -- only handle lines beginning with "
s = s and s:gsub('"','') -- remove "
t = s and UTIL.split(s,"(%s+)",nil,true) -- split on whitespaces
if t then services6[t[1]]=t[2] end
until not ln
fd6:close()
end
-- multi-used functions -- ####################################################
-- function to verify settings around ip_source
-- will use dynamic_dns_lucihelper to check if
-- local IP can be read
local function _verify_ip_source()
-- section is globally defined here be calling agrument (see above)
local _arg
local _ipv6 = usev6:formvalue(section)
local _source = (_ipv6 == "1")
and src6:formvalue(section)
or src4:formvalue(section)
local command = CTRL.luci_helper .. [[ -]]
if (_ipv6 == "1") then command = command .. [[6]] end
if _source == "network" then
_arg = (_ipv6 == "1")
and ipn6:formvalue(section)
or ipn4:formvalue(section)
command = command .. [[n ]] .. _arg
elseif _source == "web" then
_arg = (_ipv6 == "1")
and iurl6:formvalue(section)
or iurl4:formvalue(section)
command = command .. [[u ]] .. _arg
-- proxy only needed for checking url
_arg = (pxy) and pxy:formvalue(section) or ""
if (_arg and #_arg > 0) then
command = command .. [[ -p ]] .. _arg
end
elseif _source == "interface" then
command = command .. [[i ]] .. ipi:formvalue(section)
elseif _source == "script" then
command = command .. [[s ]] .. ips:formvalue(section)
end
command = command .. [[ -- get_local_ip]]
return (SYS.call(command) == 0)
end
-- function to check if option is used inside url or script
-- return -1 on error, 0 NOT required, 1 required
local function _option_used(option, urlscript)
local surl -- search string for url
local ssh -- search string for script
local required -- option used inside url or script
if option == "domain" then surl, ssh = '%[DOMAIN%]', '%$domain'
elseif option == "username" then surl, ssh = '%[USERNAME%]', '%$username'
elseif option == "password" then surl, ssh = '%[PASSWORD%]', '%$password'
elseif option == "param_enc" then surl, ssh = '%[PARAMENC%]', '%$param_enc'
elseif option == "param_opt" then surl, ssh = '%[PARAMOPT%]', '%$param_opt'
else
error("undefined option")
return -1 -- return on error
end
local required = false
-- handle url
if urlscript:find('http') then
required = ( urlscript:find(surl) )
-- handle script
else
if not urlscript:find("/") then
-- might be inside ddns-scripts directory
urlscript = "/usr/lib/ddns/" .. urlscript
end
-- problem with script exit here
if not NXFS.access(urlscript) then return -1 end
local f = io.input(urlscript)
-- still problem with script exit here
if not f then return -1 end
for l in f:lines() do
repeat
if l:find('^#') then break end -- continue on comment lines
required = ( l:find(surl) or l:find(ssh) )
until true
if required then break end
end
f:close()
end
return (required and 1 or 0)
end
-- function to verify if option is valid
local function _option_validate(self, value)
-- section is globally defined here be calling agrument (see above)
local fusev6 = usev6:formvalue(section) or "0"
local fsvc4 = svc4:formvalue(section) or "-"
local fsvc6 = svc6:formvalue(section) or "-"
local urlsh, used
-- IP-Version dependent custom service selected
if (fusev6 == "0" and fsvc4 == "-") or
(fusev6 == "1" and fsvc6 == "-") then
-- read custom url
urlsh = uurl:formvalue(section) or ""
-- no url then read custom script
if (#urlsh == 0) then
urlsh = ush:formvalue(section) or ""
end
-- IPv4 read from services4 table
elseif (fusev6 == "0") then
urlsh = services4[fsvc4] or ""
-- IPv6 read from services6 table
else
urlsh = services6[fsvc6] or ""
end
-- problem with url or script exit here
-- error handled somewhere else
if (#urlsh == 0) then return "" end
used = _option_used(self.option, urlsh)
-- on error or not used return empty sting
if used < 1 then return "" end
-- needed but no data then return error
if not value or (#value == 0) then
return nil, err_tab_basic(self) .. translate("missing / required")
end
return value
end
-- cbi-map definition -- #######################################################
local m = Map("ddns")
m.title = CTRL.app_title_back()
m.description = CTRL.app_description()
m.redirect = DISP.build_url("admin", "services", "ddns")
m.on_after_commit = function(self)
if self.changed then -- changes ?
local pid = DDNS.get_pid(section)
if pid > 0 then -- running ?
local tmp = NX.kill(pid, 1) -- send SIGHUP
end
end
end
-- provider switch was requested, save and reload page
if m:formvalue("cbid.ddns.%s._switch" % section) then -- section == arg[1]
local fsvc
local fusev6 = m:formvalue("cbid.ddns.%s.use_ipv6" % section) or "0"
if fusev6 == "1" then
fsvc = m:formvalue("cbid.ddns.%s.ipv6_service_name" % section) or ""
else
fsvc = m:formvalue("cbid.ddns.%s.ipv4_service_name" % section) or ""
end
if fusev6 ~= (m:get(section, "use_ipv6") or "0") then -- IPv6 was changed
m:set(section, "use_ipv6", fusev6) -- save it
end
if fsvc ~= "-" then -- NOT "custom"
m:set(section, "service_name", fsvc) -- save it
else -- else
m:del(section, "service_name") -- delete it
end
m.uci:save(m.config)
-- reload page
HTTP.redirect( DISP.build_url("admin", "services", "ddns", "detail", section) )
return
end
-- read application settings -- ################################################
-- log directory
local logdir = m.uci:get(m.config, "global", "ddns_logdir") or "/var/log/ddns"
-- cbi-section definition -- ###################################################
local ns = m:section( NamedSection, section, "service",
translate("Details for") .. ([[: <strong>%s</strong>]] % section),
translate("Configure here the details for selected Dynamic DNS service.") )
ns.instance = section -- arg [1]
ns:tab("basic", translate("Basic Settings"), nil )
ns:tab("advanced", translate("Advanced Settings"), nil )
ns:tab("timer", translate("Timer Settings"), nil )
ns:tab("logview", translate("Log File Viewer"), nil )
-- TAB: Basic #####################################################################################
-- enabled -- #################################################################
en = ns:taboption("basic", Flag, "enabled",
translate("Enabled"),
translate("If this service section is disabled it could not be started." .. "<br />" ..
"Neither from LuCI interface nor from console") )
en.orientation = "horizontal"
-- IPv4/IPv6 - lookup_host -- #################################################
luh = ns:taboption("basic", Value, "lookup_host",
translate("Lookup Hostname"),
translate("Hostname/FQDN to validate, if IP update happen or necessary") )
luh.rmempty = false
luh.placeholder = "myhost.example.com"
function luh.validate(self, value)
if not value
or not (#value > 0)
or not DTYP.hostname(value) then
return nil, err_tab_basic(self) .. translate("invalid FQDN / required - Sample") .. ": 'myhost.example.com'"
else
return UTIL.trim(value)
end
end
function luh.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- use_ipv6 -- ################################################################
usev6 = ns:taboption("basic", ListValue, "use_ipv6",
translate("IP address version"),
translate("Defines which IP address 'IPv4/IPv6' is send to the DDNS provider") )
usev6.widget = "radio"
usev6.default = "0"
usev6:value("0", translate("IPv4-Address") )
function usev6.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section) or "0"
if DDNS.has_ipv6 or (value == "1" and not DDNS.has_ipv6) then
self:value("1", translate("IPv6-Address") )
end
if value == "1" and not DDNS.has_ipv6 then
self.description = err_ipv6_basic
end
return value
end
function usev6.validate(self, value)
if (value == "1" and DDNS.has_ipv6) or value == "0" then
return value
end
return nil, err_tab_basic(self) .. err_ipv6_plain
end
function usev6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 - service_name -- #####################################################
svc4 = ns:taboption("basic", ListValue, "ipv4_service_name",
translate("DDNS Service provider") .. " [IPv4]" )
svc4.default = "-"
svc4:depends("use_ipv6", "0") -- only show on IPv4
function svc4.cfgvalue(self, section)
local v = DDNS.read_value(self, section, "service_name")
if v and (#v > 0) then
for s, u in UTIL.kspairs(services4) do
if v == s then return v end
end
end
return "-"
end
function svc4.validate(self, value)
if usev6:formvalue(section) ~= "1" then -- do only on IPv4
return value
else
return "" -- suppress validate error
end
end
function svc4.write(self, section, value)
if usev6:formvalue(section) ~= "1" then -- do only IPv4 here
self.map:del(section, self.option) -- to be shure
if value ~= "-" then -- and write "service_name
self.map:del(section, "update_url") -- delete update_url
self.map:del(section, "update_script") -- delete update_script
return self.map:set(section, "service_name", value)
else
return self.map:del(section, "service_name")
end
end
end
function svc4.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv6 - service_name -- #####################################################
svc6 = ns:taboption("basic", ListValue, "ipv6_service_name",
translate("DDNS Service provider") .. " [IPv6]" )
svc6.default = "-"
svc6:depends("use_ipv6", "1") -- only show on IPv6
if not DDNS.has_ipv6 then
svc6.description = err_ipv6_basic
end
function svc6.cfgvalue(self, section)
local v = DDNS.read_value(self, section, "service_name")
if v and (#v > 0) then
for s, u in UTIL.kspairs(services4) do
if v == s then return v end
end
end
return "-"
end
function svc6.validate(self, value)
if usev6:formvalue(section) == "1" then -- do only on IPv6
if DDNS.has_ipv6 then return value end
return nil, err_tab_basic(self) .. err_ipv6_plain
else
return "" -- suppress validate error
end
end
function svc6.write(self, section, value)
if usev6:formvalue(section) == "1" then -- do only when IPv6
self.map:del(section, self.option) -- delete "ipv6_service_name" helper
if value ~= "-" then -- and write "service_name
self.map:del(section, "update_url") -- delete update_url
self.map:del(section, "update_script") -- delete update_script
return self.map:set(section, "service_name", value)
else
return self.map:del(section, "service_name")
end
end
end
function svc6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - change Provider -- #############################################
svs = ns:taboption("basic", Button, "_switch")
svs.title = translate("Really change DDNS provider?")
svs.inputtitle = translate("Change provider")
svs.inputstyle = "apply"
-- IPv4/IPv6 - update_url -- ##################################################
uurl = ns:taboption("basic", Value, "update_url",
translate("Custom update-URL"),
translate("Update URL to be used for updating your DDNS Provider." .. "<br />" ..
"Follow instructions you will find on their WEB page.") )
function uurl.validate(self, value)
local fush = ush:formvalue(section)
local fusev6 = usev6:formvalue(section)
if (fusev6 ~= "1" and svc4:formvalue(section) ~= "-") or
(fusev6 == "1" and svc6:formvalue(section) ~= "-") then
return "" -- suppress validate error
elseif not value or (#value == 0) then
if not fush or (#fush == 0) then
return nil, err_tab_basic(self) .. translate("missing / required")
else
return "" -- suppress validate error / update_script is given
end
elseif (#fush > 0) then
return nil, err_tab_basic(self) .. translate("either url or script could be set")
end
local url = DDNS.parse_url(value)
if not url.scheme == "http" then
return nil, err_tab_basic(self) .. translate("must start with 'http://'")
elseif not url.query then
return nil, err_tab_basic(self) .. "<QUERY> " .. translate("missing / required")
elseif not url.host then
return nil, err_tab_basic(self) .. "<HOST> " .. translate("missing / required")
elseif SYS.call([[nslookup ]] .. url.host .. [[ >/dev/null 2>&1]]) ~= 0 then
return nil, err_tab_basic(self) .. translate("can not resolve host: ") .. url.host
end
return value
end
function uurl.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - update_script -- ###############################################
ush = ns:taboption("basic", Value, "update_script",
translate("Custom update-script"),
translate("Custom update script to be used for updating your DDNS Provider.") )
function ush.validate(self, value)
local fuurl = uurl:formvalue(section)
local fusev6 = usev6:formvalue(section)
if (fusev6 ~= "1" and svc4:formvalue(section) ~= "-") or
(fusev6 == "1" and svc6:formvalue(section) ~= "-") then
return "" -- suppress validate error
elseif not value or (#value == 0) then
if not fuurl or (#fuurl == 0) then
return nil, err_tab_basic(self) .. translate("missing / required")
else
return "" -- suppress validate error / update_url is given
end
elseif (#fuurl > 0) then
return nil, err_tab_basic(self) .. translate("either url or script could be set")
elseif not NXFS.access(value) then
return nil, err_tab_basic(self) .. translate("File not found")
end
return value
end
function ush.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - domain -- ######################################################
dom = ns:taboption("basic", Value, "domain",
translate("Domain"),
translate("Replaces [DOMAIN] in Update-URL") )
dom.placeholder = "myhost.example.com"
function dom.validate(self, value)
return _option_validate(self, value)
end
function dom.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - username -- ####################################################
user = ns:taboption("basic", Value, "username",
translate("Username"),
translate("Replaces [USERNAME] in Update-URL (URL-encoded)") )
function user.validate(self, value)
return _option_validate(self, value)
end
function user.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - password -- ####################################################
pw = ns:taboption("basic", Value, "password",
translate("Password"),
translate("Replaces [PASSWORD] in Update-URL (URL-encoded)") )
pw.password = true
function pw.validate(self, value)
return _option_validate(self, value)
end
function pw.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - param_enc -- ###################################################
pe = ns:taboption("basic", Value, "param_enc",
translate("Optional Encoded Parameter"),
translate("Optional: Replaces [PARAMENC] in Update-URL (URL-encoded)") )
function pe.validate(self, value)
return _option_validate(self, value)
end
function pe.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - param_enc -- ###################################################
po = ns:taboption("basic", Value, "param_opt",
translate("Optional Parameter"),
translate("Optional: Replaces [PARAMOPT] in Update-URL (NOT URL-encoded)") )
function po.validate(self, value)
return _option_validate(self, value)
end
function po.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- handled service dependent show/display -- ##################################
-- IPv4 --
local cv4 = svc4:cfgvalue(section)
if cv4 ~= "-" then
svs:depends ("ipv4_service_name", "-" ) -- show only if "-"
ush:depends ("ipv4_service_name", "?")
uurl:depends("ipv4_service_name", "?")
else
uurl:depends("ipv4_service_name", "-")
ush:depends ("ipv4_service_name", "-")
dom:depends("ipv4_service_name", "-" )
user:depends("ipv4_service_name", "-" )
pw:depends("ipv4_service_name", "-" )
pe:depends("ipv4_service_name", "-" )
po:depends("ipv4_service_name", "-" )
end
for s, u in UTIL.kspairs(services4) do
svc4:value(s) -- fill DropDown-List
if cv4 ~= s then
svs:depends("ipv4_service_name", s )
else
dom:depends ("ipv4_service_name", ((_option_used(dom.option, u) == 1) and s or "?") )
user:depends("ipv4_service_name", ((_option_used(user.option, u) == 1) and s or "?") )
pw:depends ("ipv4_service_name", ((_option_used(pw.option, u) == 1) and s or "?") )
pe:depends ("ipv4_service_name", ((_option_used(pe.option, u) == 1) and s or "?") )
po:depends ("ipv4_service_name", ((_option_used(po.option, u) == 1) and s or "?") )
end
end
svc4:value("-", translate("-- custom --") )
-- IPv6 --
local cv6 = svc6:cfgvalue(section)
if cv6 ~= "-" then
svs:depends ("ipv6_service_name", "-" )
uurl:depends("ipv6_service_name", "?")
ush:depends ("ipv6_service_name", "?")
else
uurl:depends("ipv6_service_name", "-")
ush:depends ("ipv6_service_name", "-")
dom:depends("ipv6_service_name", "-" )
user:depends("ipv6_service_name", "-" )
pw:depends("ipv6_service_name", "-" )
pe:depends("ipv6_service_name", "-" )
po:depends("ipv6_service_name", "-" )
end
for s, u in UTIL.kspairs(services6) do
svc6:value(s) -- fill DropDown-List
if cv6 ~= s then
svs:depends("ipv6_service_name", s )
else
dom:depends ("ipv6_service_name", ((_option_used(dom.option, u) == 1) and s or "?") )
user:depends("ipv6_service_name", ((_option_used(user.option, u) == 1) and s or "?") )
pw:depends ("ipv6_service_name", ((_option_used(pw.option, u) == 1) and s or "?") )
pe:depends ("ipv6_service_name", ((_option_used(pe.option, u) == 1) and s or "?") )
po:depends ("ipv6_service_name", ((_option_used(po.option, u) == 1) and s or "?") )
end
end
svc6:value("-", translate("-- custom --") )
-- IPv4/IPv6 - use_https -- ###################################################
if DDNS.has_ssl or ( ( m:get(section, "use_https") or "0" ) == "1" ) then
https = ns:taboption("basic", Flag, "use_https",
translate("Use HTTP Secure") )
https.orientation = "horizontal"
function https.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if not DDNS.has_ssl and value == "1" then
self.description = bold_on .. font_red ..
translate("HTTPS not supported") .. font_off .. "<br />" ..
translate("please disable") .. " !" .. bold_off
else
self.description = translate("Enable secure communication with DDNS provider")
end
return value
end
function https.validate(self, value)
if (value == "1" and DDNS.has_ssl ) or value == "0" then return value end
return nil, err_tab_basic(self) .. translate("HTTPS not supported") .. " !"
end
function https.write(self, section, value)
if value == "1" then
return self.map:set(section, self.option, value)
else
self.map:del(section, "cacert")
return self.map:del(section, self.option)
end
end
end
-- IPv4/IPv6 - cacert -- ######################################################
if DDNS.has_ssl then
cert = ns:taboption("basic", Value, "cacert",
translate("Path to CA-Certificate"),
translate("directory or path/file") .. "<br />" ..
translate("or") .. bold_on .. " IGNORE " .. bold_off ..
translate("to run HTTPS without verification of server certificates (insecure)") )
cert:depends("use_https", "1")
cert.placeholder = "/etc/ssl/certs"
cert.forcewrite = true
function cert.validate(self, value)
if https:formvalue(section) ~= "1" then
return "" -- suppress validate error if NOT https
end
if value then -- otherwise errors in datatype check
if DTYP.directory(value)
or DTYP.file(value)
or (value == "IGNORE")
or (#value == 0) then
return value
end
end
return nil, err_tab_basic(self) ..
translate("file or directory not found or not 'IGNORE'") .. " !"
end
function cert.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
end
-- TAB: Advanced #################################################################################
-- IPv4 - ip_source -- ########################################################
src4 = ns:taboption("advanced", ListValue, "ipv4_source",
translate("IP address source") .. " [IPv4]",
translate("Defines the source to read systems IPv4-Address from, that will be send to the DDNS provider") )
src4:depends("use_ipv6", "0") -- IPv4 selected
src4.default = "network"
src4:value("network", translate("Network"))
src4:value("web", translate("URL"))
src4:value("interface", translate("Interface"))
src4:value("script", translate("Script"))
function src4.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_source")
end
function src4.validate(self, value)
if usev6:formvalue(section) == "1" then
return "" -- ignore on IPv6 selected
elseif not _verify_ip_source() then
return nil, err_tab_adv(self) ..
translate("can not detect local IP. Please select a different Source combination")
else
return value
end
end
function src4.write(self, section, value)
if usev6:formvalue(section) == "1" then
return true -- ignore on IPv6 selected
elseif value == "network" then
self.map:del(section, "ip_url") -- delete not need parameters
self.map:del(section, "ip_interface")
self.map:del(section, "ip_script")
elseif value == "web" then
self.map:del(section, "ip_network") -- delete not need parameters
self.map:del(section, "ip_interface")
self.map:del(section, "ip_script")
elseif value == "interface" then
self.map:del(section, "ip_network") -- delete not need parameters
self.map:del(section, "ip_url")
self.map:del(section, "ip_script")
elseif value == "script" then
self.map:del(section, "ip_network")
self.map:del(section, "ip_url") -- delete not need parameters
self.map:del(section, "ip_interface")
end
self.map:del(section, self.option) -- delete "ipv4_source" helper
return self.map:set(section, "ip_source", value) -- and write "ip_source
end
function src4.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv6 - ip_source -- ########################################################
src6 = ns:taboption("advanced", ListValue, "ipv6_source",
translate("IP address source") .. " [IPv6]",
translate("Defines the source to read systems IPv6-Address from, that will be send to the DDNS provider") )
src6:depends("use_ipv6", 1) -- IPv6 selected
src6.default = "network"
src6:value("network", translate("Network"))
src6:value("web", translate("URL"))
src6:value("interface", translate("Interface"))
src6:value("script", translate("Script"))
if not DDNS.has_ipv6 then
src6.description = err_ipv6_other
end
function src6.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_source")
end
function src6.validate(self, value)
if usev6:formvalue(section) ~= "1" then
return "" -- ignore on IPv4 selected
elseif not DDNS.has_ipv6 then
return nil, err_tab_adv(self) .. err_ipv6_plain
elseif not _verify_ip_source() then
return nil, err_tab_adv(self) ..
translate("can not detect local IP. Please select a different Source combination")
else
return value
end
end
function src6.write(self, section, value)
if usev6:formvalue(section) ~= "1" then
return true -- ignore on IPv4 selected
elseif value == "network" then
self.map:del(section, "ip_url") -- delete not need parameters
self.map:del(section, "ip_interface")
self.map:del(section, "ip_script")
elseif value == "web" then
self.map:del(section, "ip_network") -- delete not need parameters
self.map:del(section, "ip_interface")
self.map:del(section, "ip_script")
elseif value == "interface" then
self.map:del(section, "ip_network") -- delete not need parameters
self.map:del(section, "ip_url")
self.map:del(section, "ip_script")
elseif value == "script" then
self.map:del(section, "ip_network")
self.map:del(section, "ip_url") -- delete not need parameters
self.map:del(section, "ip_interface")
end
self.map:del(section, self.option) -- delete "ipv4_source" helper
return self.map:set(section, "ip_source", value) -- and write "ip_source
end
function src6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 - ip_network (default "wan") -- #######################################
ipn4 = ns:taboption("advanced", ListValue, "ipv4_network",
translate("Network") .. " [IPv4]",
translate("Defines the network to read systems IPv4-Address from") )
ipn4:depends("ipv4_source", "network")
ipn4.default = "wan"
WADM.cbi_add_networks(ipn4)
function ipn4.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_network")
end
function ipn4.validate(self, value)
if usev6:formvalue(section) == "1"
or src4:formvalue(section) ~= "network" then
-- ignore if IPv6 selected OR
-- ignore everything except "network"
return ""
else
return value
end
end
function ipn4.write(self, section, value)
if usev6:formvalue(section) == "1"
or src4:formvalue(section) ~= "network" then
-- ignore if IPv6 selected OR
-- ignore everything except "network"
return true
else
-- set also as "interface" for monitoring events changes/hot-plug
self.map:set(section, "interface", value)
self.map:del(section, self.option) -- delete "ipv4_network" helper
return self.map:set(section, "ip_network", value) -- and write "ip_network"
end
end
function ipn4.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv6 - ip_network (default "wan6") -- ######################################
ipn6 = ns:taboption("advanced", ListValue, "ipv6_network",
translate("Network") .. " [IPv6]" )
ipn6:depends("ipv6_source", "network")
ipn6.default = "wan6"
WADM.cbi_add_networks(ipn6)
if DDNS.has_ipv6 then
ipn6.description = translate("Defines the network to read systems IPv6-Address from")
else
ipn6.description = err_ipv6_other
end
function ipn6.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_network")
end
function ipn6.validate(self, value)
if usev6:formvalue(section) ~= "1"
or src6:formvalue(section) ~= "network" then
-- ignore if IPv4 selected OR
-- ignore everything except "network"
return ""
elseif DDNS.has_ipv6 then
return value
else
return nil, err_tab_adv(self) .. err_ipv6_plain
end
end
function ipn6.write(self, section, value)
if usev6:formvalue(section) ~= "1"
or src6:formvalue(section) ~= "network" then
-- ignore if IPv4 selected OR
-- ignore everything except "network"
return true
else
-- set also as "interface" for monitoring events changes/hotplug
self.map:set(section, "interface", value)
self.map:del(section, self.option) -- delete "ipv6_network" helper
return self.map:set(section, "ip_network", value) -- and write "ip_network"
end
end
function ipn6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 - ip_url (default "checkip.dyndns.com") -- ############################
iurl4 = ns:taboption("advanced", Value, "ipv4_url",
translate("URL to detect") .. " [IPv4]",
translate("Defines the Web page to read systems IPv4-Address from") )
iurl4:depends("ipv4_source", "web")
iurl4.default = "http://checkip.dyndns.com"
function iurl4.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_url")
end
function iurl4.validate(self, value)
if usev6:formvalue(section) == "1"
or src4:formvalue(section) ~= "web" then
-- ignore if IPv6 selected OR
-- ignore everything except "web"
return ""
elseif not value or #value == 0 then
return nil, err_tab_adv(self) .. translate("missing / required")
end
local url = DDNS.parse_url(value)
if not (url.scheme == "http" or url.scheme == "https") then
return nil, err_tab_adv(self) .. translate("must start with 'http://'")
elseif not url.host then
return nil, err_tab_adv(self) .. "<HOST> " .. translate("missing / required")
elseif SYS.call([[nslookup ]] .. url.host .. [[>/dev/null 2>&1]]) ~= 0 then
return nil, err_tab_adv(self) .. translate("can not resolve host: ") .. url.host
else
return value
end
end
function iurl4.write(self, section, value)
if usev6:formvalue(section) == "1"
or src4:formvalue(section) ~= "web" then
-- ignore if IPv6 selected OR
-- ignore everything except "web"
return true
else
self.map:del(section, self.option) -- delete "ipv4_url" helper
return self.map:set(section, "ip_url", value) -- and write "ip_url"
end
end
function iurl4.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv6 - ip_url (default "checkipv6.dyndns.com") -- ##########################
iurl6 = ns:taboption("advanced", Value, "ipv6_url",
translate("URL to detect") .. " [IPv6]" )
iurl6:depends("ipv6_source", "web")
iurl6.default = "http://checkipv6.dyndns.com"
if DDNS.has_ipv6 then
iurl6.description = translate("Defines the Web page to read systems IPv6-Address from")
else
iurl6.description = err_ipv6_other
end
function iurl6.cfgvalue(self, section)
return DDNS.read_value(self, section, "ip_url")
end
function iurl6.validate(self, value)
if usev6:formvalue(section) ~= "1"
or src6:formvalue(section) ~= "web" then
-- ignore if IPv4 selected OR
-- ignore everything except "web"
return ""
elseif not DDNS.has_ipv6 then
return nil, err_tab_adv(self) .. err_ipv6_plain
elseif not value or #value == 0 then
return nil, err_tab_adv(self) .. translate("missing / required")
end
local url = DDNS.parse_url(value)
if not (url.scheme == "http" or url.scheme == "https") then
return nil, err_tab_adv(self) .. translate("must start with 'http://'")
elseif not url.host then
return nil, err_tab_adv(self) .. "<HOST> " .. translate("missing / required")
elseif SYS.call([[nslookup ]] .. url.host .. [[>/dev/null 2>&1]]) ~= 0 then
return nil, err_tab_adv(self) .. translate("can not resolve host: ") .. url.host
else
return value
end
end
function iurl6.write(self, section, value)
if usev6:formvalue(section) ~= "1"
or src6:formvalue(section) ~= "web" then
-- ignore if IPv4 selected OR
-- ignore everything except "web"
return true
else
self.map:del(section, self.option) -- delete "ipv6_url" helper
return self.map:set(section, "ip_url", value) -- and write "ip_url"
end
end
function iurl6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 + IPv6 - ip_interface -- ##############################################
ipi = ns:taboption("advanced", ListValue, "ip_interface",
translate("Interface"),
translate("Defines the interface to read systems IP-Address from") )
ipi:depends("ipv4_source", "interface") -- IPv4
ipi:depends("ipv6_source", "interface") -- or IPv6
for _, v in pairs(SYS.net.devices()) do
-- show only interface set to a network
-- and ignore loopback
net = WADM.iface_get_network(v)
if net and net ~= "loopback" then
ipi:value(v)
end
end
function ipi.validate(self, value)
local fusev6 = usev6:formvalue(section)
if (fusev6 ~= "1" and src4:formvalue(section) ~= "interface")
or (fusev6 == "1" and src6:formvalue(section) ~= "interface") then
return ""
else
return value
end
end
function ipi.write(self, section, value)
local fusev6 = usev6:formvalue(section)
if (fusev6 ~= "1" and src4:formvalue(section) ~= "interface")
or (fusev6 == "1" and src6:formvalue(section) ~= "interface") then
return true
else
-- get network from device to
-- set also as "interface" for monitoring events changes/hotplug
local net = WADM.iface_get_network(value)
self.map:set(section, "interface", net)
return self.map:set(section, self.option, value)
end
end
function ipi.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 + IPv6 - ip_script -- #################################################
ips = ns:taboption("advanced", Value, "ip_script",
translate("Script"),
translate("User defined script to read systems IP-Address") )
ips:depends("ipv4_source", "script") -- IPv4
ips:depends("ipv6_source", "script") -- or IPv6
ips.placeholder = "/path/to/script.sh"
function ips.validate(self, value)
local fusev6 = usev6:formvalue(section)
local split
if value then split = UTIL.split(value, " ") end
if (fusev6 ~= "1" and src4:formvalue(section) ~= "script")
or (fusev6 == "1" and src6:formvalue(section) ~= "script") then
return ""
elseif not value or not (#value > 0) or not NXFS.access(split[1], "x") then
return nil, err_tab_adv(self) ..
translate("not found or not executable - Sample: '/path/to/script.sh'")
else
return value
end
end
function ips.write(self, section, value)
local fusev6 = usev6:formvalue(section)
if (fusev6 ~= "1" and src4:formvalue(section) ~= "script")
or (fusev6 == "1" and src6:formvalue(section) ~= "script") then
return true
else
return self.map:set(section, self.option, value)
end
end
function ips.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4 - interface - default "wan" -- ########################################
-- event network to monitor changes/hotplug/dynamic_dns_updater.sh
-- only needs to be set if "ip_source"="web" or "script"
-- if "ip_source"="network" or "interface" we use their network
eif4 = ns:taboption("advanced", ListValue, "ipv4_interface",
translate("Event Network") .. " [IPv4]",
translate("Network on which the ddns-updater scripts will be started") )
eif4:depends("ipv4_source", "web")
eif4:depends("ipv4_source", "script")
eif4.default = "wan"
WADM.cbi_add_networks(eif4)
function eif4.cfgvalue(self, section)
return DDNS.read_value(self, section, "interface")
end
function eif4.validate(self, value)
local fsrc4 = src4:formvalue(section) or ""
if usev6:formvalue(section) == "1"
or fsrc4 == "network"
or fsrc4 == "interface" then
return "" -- ignore IPv6, network, interface
else
return value
end
end
function eif4.write(self, section, value)
local fsrc4 = src4:formvalue(section) or ""
if usev6:formvalue(section) == "1"
or fsrc4 == "network"
or fsrc4 == "interface" then
return true -- ignore IPv6, network, interface
else
self.map:del(section, self.option) -- delete "ipv4_interface" helper
return self.map:set(section, "interface", value) -- and write "interface"
end
end
function eif4.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv6 - interface - default "wan6" -- #######################################
-- event network to monitor changes/hotplug
-- only needs to be set if "ip_source"="web" or "script"
-- if "ip_source"="network" or "interface" we use their network
eif6 = ns:taboption("advanced", ListValue, "ipv6_interface",
translate("Event Network") .. " [IPv6]" )
eif6:depends("ipv6_source", "web")
eif6:depends("ipv6_source", "script")
eif6.default = "wan6"
WADM.cbi_add_networks(eif6)
if not DDNS.has_ipv6 then
eif6.description = err_ipv6_other
else
eif6.description = translate("Network on which the ddns-updater scripts will be started")
end
function eif6.cfgvalue(self, section)
return DDNS.read_value(self, section, "interface")
end
function eif6.validate(self, value)
local fsrc6 = src6:formvalue(section) or ""
if usev6:formvalue(section) ~= "1"
or fsrc6 == "network"
or fsrc6 == "interface" then
return "" -- ignore IPv4, network, interface
elseif not DDNS.has_ipv6 then
return nil, err_tab_adv(self) .. err_ipv6_plain
else
return value
end
end
function eif6.write(self, section, value)
local fsrc6 = src6:formvalue(section) or ""
if usev6:formvalue(section) ~= "1"
or fsrc6 == "network"
or fsrc6 == "interface" then
return true -- ignore IPv4, network, interface
else
self.map:del(section, self.option) -- delete "ipv6_interface" helper
return self.map:set(section, "interface", value) -- and write "interface"
end
end
function eif6.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- IPv4/IPv6 - bind_network -- ################################################
if DDNS.has_bindnet or ( ( m:get(section, "bind_network") or "" ) ~= "" ) then
bnet = ns:taboption("advanced", ListValue, "bind_network",
translate("Bind Network") )
bnet:depends("ipv4_source", "web")
bnet:depends("ipv6_source", "web")
bnet.default = ""
bnet:value("", translate("-- default --"))
WADM.cbi_add_networks(bnet)
function bnet.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if not DDNS.has_bindnet and value ~= "" then
self.description = bold_on .. font_red ..
translate("Binding to a specific network not supported") .. font_off .. "<br />" ..
translate("please set to 'default'") .. " !" .. bold_off
else
self.description = translate("OPTIONAL: Network to use for communication") ..
"<br />" .. translate("Casual users should not change this setting")
end
return value
end
function bnet.validate(self, value)
if ( (value ~= "") and DDNS.has_bindnet ) or (value == "") then return value end
return nil, err_tab_adv(self) .. translate("Binding to a specific network not supported") .. " !"
end
function bnet.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
end
-- IPv4 + IPv6 - force_ipversion -- ###########################################
-- optional to force wget/curl and host to use only selected IP version
-- command parameter "-4" or "-6"
if DDNS.has_forceip or ( ( m:get(section, "force_ipversion") or "0" ) ~= "0" ) then
fipv = ns:taboption("advanced", Flag, "force_ipversion",
translate("Force IP Version") )
fipv.orientation = "horizontal"
function fipv.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if not DDNS.has_forceip and value ~= "0" then
self.description = bold_on .. font_red ..
translate("Force IP Version not supported") .. font_off .. "<br />" ..
translate("please disable") .. " !" .. bold_off
else
self.description = translate("OPTIONAL: Force the usage of pure IPv4/IPv6 only communication.")
end
return value
end
function fipv.validate(self, value)
if (value == "1" and DDNS.has_forceip) or value == "0" then return value end
return nil, err_tab_adv(self) .. translate("Force IP Version not supported")
end
end
-- IPv4 + IPv6 - dns_server -- ################################################
-- optional DNS Server to use resolving my IP
if DDNS.has_dnsserver or ( ( m:get(section, "dns_server") or "" ) ~= "" ) then
dns = ns:taboption("advanced", Value, "dns_server",
translate("DNS-Server"),
translate("OPTIONAL: Use non-default DNS-Server to detect 'Registered IP'.") .. "<br />" ..
translate("Format: IP or FQDN"))
dns.placeholder = "mydns.lan"
function dns.validate(self, value)
-- if .datatype is set, then it is checked before calling this function
if not value or (#value == 0) then
return "" -- ignore on empty
elseif not DDNS.has_dnsserver then
return nil, err_tab_adv(self) .. translate("Specifying a DNS-Server is not supported")
elseif not DTYP.host(value) then
return nil, err_tab_adv(self) .. translate("use hostname, FQDN, IPv4- or IPv6-Address")
else
local ipv6 = usev6:formvalue(section) or "0"
local force = fipv:formvalue(section) or "0"
local command = CTRL.luci_helper .. [[ -]]
if (ipv6 == 1) then command = command .. [[6]] end
if (force == 1) then command = command .. [[f]] end
command = command .. [[d ]] .. value .. [[ -- verify_dns]]
local ret = SYS.call(command)
if ret == 0 then return value -- everything OK
elseif ret == 2 then return nil, err_tab_adv(self) .. translate("nslookup can not resolve host")
elseif ret == 3 then return nil, err_tab_adv(self) .. translate("nc (netcat) can not connect")
elseif ret == 4 then return nil, err_tab_adv(self) .. translate("Forced IP Version don't matched")
else return nil, err_tab_adv(self) .. translate("unspecific error")
end
end
end
function dns.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
end
-- IPv4 + IPv6 - force_dnstcp -- ##############################################
if DDNS.has_bindhost or ( ( m:get(section, "force_dnstcp") or "0" ) ~= "0" ) then
tcp = ns:taboption("advanced", Flag, "force_dnstcp",
translate("Force TCP on DNS") )
tcp.orientation = "horizontal"
function tcp.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if not DDNS.has_bindhost and value ~= "0" then
self.description = bold_on .. font_red ..
translate("DNS requests via TCP not supported") .. font_off .. "<br />" ..
translate("please disable") .. " !" .. bold_off
else
self.description = translate("OPTIONAL: Force the use of TCP instead of default UDP on DNS requests.")
end
return value
end
function tcp.validate(self, value)
if (value == "1" and DDNS.has_bindhost ) or value == "0" then
return value
end
return nil, err_tab_adv(self) .. translate("DNS requests via TCP not supported")
end
end
-- IPv4 + IPv6 - proxy -- #####################################################
-- optional Proxy to use for http/https requests [user:password@]proxyhost[:port]
if DDNS.has_proxy or ( ( m:get(section, "proxy") or "" ) ~= "" ) then
pxy = ns:taboption("advanced", Value, "proxy",
translate("PROXY-Server") )
pxy.placeholder="user:password@myproxy.lan:8080"
function pxy.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if not DDNS.has_proxy and value ~= "" then
self.description = bold_on .. font_red ..
translate("PROXY-Server not supported") .. font_off .. "<br />" ..
translate("please remove entry") .. "!" .. bold_off
else
self.description = translate("OPTIONAL: Proxy-Server for detection and updates.") .. "<br />" ..
translate("Format") .. ": " .. bold_on .. "[user:password@]proxyhost:port" .. bold_off .. "<br />" ..
translate("IPv6 address must be given in square brackets") .. ": " ..
bold_on .. " [2001:db8::1]:8080" .. bold_off
end
return value
end
function pxy.validate(self, value)
-- if .datatype is set, then it is checked before calling this function
if not value or (#value == 0) then
return "" -- ignore on empty
elseif DDNS.has_proxy then
local ipv6 = usev6:formvalue(section) or "0"
local force = fipv:formvalue(section) or "0"
local command = CRTL.luci_helper .. [[ -]]
if (ipv6 == 1) then command = command .. [[6]] end
if (force == 1) then command = command .. [[f]] end
command = command .. [[p ]] .. value .. [[ -- verify_proxy]]
local ret = SYS.call(command)
if ret == 0 then return value
elseif ret == 2 then return nil, err_tab_adv(self) .. translate("nslookup can not resolve host")
elseif ret == 3 then return nil, err_tab_adv(self) .. translate("nc (netcat) can not connect")
elseif ret == 4 then return nil, err_tab_adv(self) .. translate("Forced IP Version don't matched")
elseif ret == 5 then return nil, err_tab_adv(self) .. translate("proxy port missing")
else return nil, err_tab_adv(self) .. translate("unspecific error")
end
else
return nil, err_tab_adv(self) .. translate("PROXY-Server not supported")
end
end
function pxy.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
end
-- use_syslog -- ##############################################################
slog = ns:taboption("advanced", ListValue, "use_syslog",
translate("Log to syslog"),
translate("Writes log messages to syslog. Critical Errors will always be written to syslog.") )
slog.default = "2"
slog:value("0", translate("No logging"))
slog:value("1", translate("Info"))
slog:value("2", translate("Notice"))
slog:value("3", translate("Warning"))
slog:value("4", translate("Error"))
function slog.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- use_logfile -- #############################################################
logf = ns:taboption("advanced", Flag, "use_logfile",
translate("Log to file"),
translate("Writes detailed messages to log file. File will be truncated automatically.") .. "<br />" ..
translate("File") .. [[: "]] .. logdir .. [[/]] .. section .. [[.log"]] )
logf.orientation = "horizontal"
logf.default = "1" -- if not defined write to log by default
-- TAB: Timer ####################################################################################
-- check_interval -- ##########################################################
ci = ns:taboption("timer", Value, "check_interval",
translate("Check Interval") )
ci.template = "ddns/detail_value"
ci.default = "10"
function ci.validate(self, value)
if not DTYP.uinteger(value)
or tonumber(value) < 1 then
return nil, err_tab_timer(self) .. translate("minimum value 5 minutes == 300 seconds")
end
local secs = DDNS.calc_seconds(value, cu:formvalue(section))
if secs >= 300 then
return value
else
return nil, err_tab_timer(self) .. translate("minimum value 5 minutes == 300 seconds")
end
end
function ci.write(self, section, value)
-- remove when default
local secs = DDNS.calc_seconds(value, cu:formvalue(section))
if secs ~= 600 then --default 10 minutes
return self.map:set(section, self.option, value)
else
self.map:del(section, "check_unit")
return self.map:del(section, self.option)
end
end
function ci.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- check_unit -- ##############################################################
cu = ns:taboption("timer", ListValue, "check_unit", "not displayed, but needed otherwise error",
translate("Interval to check for changed IP" .. "<br />" ..
"Values below 5 minutes == 300 seconds are not supported") )
cu.template = "ddns/detail_lvalue"
cu.default = "minutes"
cu:value("seconds", translate("seconds"))
cu:value("minutes", translate("minutes"))
cu:value("hours", translate("hours"))
--cu:value("days", translate("days"))
function cu.write(self, section, value)
-- remove when default
local secs = DDNS.calc_seconds(ci:formvalue(section), value)
if secs ~= 600 then --default 10 minutes
return self.map:set(section, self.option, value)
else
return true
end
end
function cu.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- force_interval (modified) -- ###############################################
fi = ns:taboption("timer", Value, "force_interval",
translate("Force Interval") )
fi.template = "ddns/detail_value"
fi.default = "72" -- see dynamic_dns_updater.sh script
--fi.rmempty = false -- validate ourselves for translatable error messages
function fi.validate(self, value)
if not DTYP.uinteger(value)
or tonumber(value) < 0 then
return nil, err_tab_timer(self) .. translate("minimum value '0'")
end
local force_s = DDNS.calc_seconds(value, fu:formvalue(section))
if force_s == 0 then
return value
end
local ci_value = ci:formvalue(section)
if not DTYP.uinteger(ci_value) then
return "" -- ignore because error in check_interval above
end
local check_s = DDNS.calc_seconds(ci_value, cu:formvalue(section))
if force_s >= check_s then
return value
end
return nil, err_tab_timer(self) .. translate("must be greater or equal 'Check Interval'")
end
function fi.write(self, section, value)
-- simulate rmempty=true remove default
local secs = DDNS.calc_seconds(value, fu:formvalue(section))
if secs ~= 259200 then --default 72 hours == 3 days
return self.map:set(section, self.option, value)
else
self.map:del(section, "force_unit")
return self.map:del(section, self.option)
end
end
function fi.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- force_unit -- ##############################################################
fu = ns:taboption("timer", ListValue, "force_unit", "not displayed, but needed otherwise error",
translate("Interval to force updates send to DDNS Provider" .. "<br />" ..
"Setting this parameter to 0 will force the script to only run once" .. "<br />" ..
"Values lower 'Check Interval' except '0' are not supported") )
fu.template = "ddns/detail_lvalue"
fu.default = "hours"
--fu.rmempty = false -- want to control write process
--fu:value("seconds", translate("seconds"))
fu:value("minutes", translate("minutes"))
fu:value("hours", translate("hours"))
fu:value("days", translate("days"))
function fu.write(self, section, value)
-- simulate rmempty=true remove default
local secs = DDNS.calc_seconds(fi:formvalue(section), value)
if secs ~= 259200 and secs ~= 0 then --default 72 hours == 3 days
return self.map:set(section, self.option, value)
else
return true
end
end
function fu.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- retry_count -- #############################################################
rc = ns:taboption("timer", Value, "retry_count")
rc.title = translate("Error Retry Counter")
rc.description = translate("On Error the script will stop execution after given number of retrys")
.. "<br />"
.. translate("The default setting of '0' will retry infinite.")
rc.default = "0"
function rc.validate(self, value)
if not DTYP.uinteger(value) then
return nil, err_tab_timer(self) .. translate("minimum value '0'")
else
return value
end
end
function rc.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- retry_interval -- ##########################################################
ri = ns:taboption("timer", Value, "retry_interval",
translate("Error Retry Interval") )
ri.template = "ddns/detail_value"
ri.default = "60"
function ri.validate(self, value)
if not DTYP.uinteger(value)
or tonumber(value) < 1 then
return nil, err_tab_timer(self) .. translate("minimum value '1'")
else
return value
end
end
function ri.write(self, section, value)
-- simulate rmempty=true remove default
local secs = DDNS.calc_seconds(value, ru:formvalue(section))
if secs ~= 60 then --default 60seconds
return self.map:set(section, self.option, value)
else
self.map:del(section, "retry_unit")
return self.map:del(section, self.option)
end
end
function ri.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- retry_unit -- ##############################################################
ru = ns:taboption("timer", ListValue, "retry_unit", "not displayed, but needed otherwise error",
translate("On Error the script will retry the failed action after given time") )
ru.template = "ddns/detail_lvalue"
ru.default = "seconds"
--ru.rmempty = false -- want to control write process
ru:value("seconds", translate("seconds"))
ru:value("minutes", translate("minutes"))
--ru:value("hours", translate("hours"))
--ru:value("days", translate("days"))
function ru.write(self, section, value)
-- simulate rmempty=true remove default
local secs = DDNS.calc_seconds(ri:formvalue(section), value)
if secs ~= 60 then --default 60seconds
return self.map:set(section, self.option, value)
else
return true -- will be deleted by retry_interval
end
end
function ru.parse(self, section, novld)
DDNS.value_parse(self, section, novld)
end
-- TAB: LogView ##################################################################################
lv = ns:taboption("logview", DummyValue, "_logview")
lv.template = "ddns/detail_logview"
lv.inputtitle = translate("Read / Reread log file")
lv.rows = 50
function lv.cfgvalue(self, section)
local lfile=logdir .. "/" .. section .. ".log"
if NXFS.access(lfile) then
return lfile .. "\n" .. translate("Please press [Read] button")
end
return lfile .. "\n" .. translate("File not found or empty")
end
return m
| apache-2.0 |
nasomi/darkstar | scripts/zones/Lebros_Cavern/instances/wamoura_farm_raid.lua | 37 | 3946 | -----------------------------------
--
-- Assault: Wamoura Farm Raid
--
-----------------------------------
require("scripts/zones/Lebros_Cavern/IDs");
-----------------------------------
-- afterInstanceRegister
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(Lebros.text.ASSAULT_27_START, 27);
player:messageSpecial(Lebros.text.TIME_TO_COMPLETE, instance:getTimeLimit());
end;
-----------------------------------
-- onInstanceCreated
-----------------------------------
function onInstanceCreated(instance)
for i,v in pairs(Lebros.mobs[27]) do
SpawnMob(v, instance);
end
end;
-----------------------------------
-- onInstanceTimeUpdate
-----------------------------------
function onInstanceTimeUpdate(instance, elapsed)
local players = instance:getChars();
local lastTimeUpdate = instance:getLastTimeUpdate();
local remainingTimeLimit = (instance:getTimeLimit()) * 60 - (elapsed / 1000);
local wipeTime = instance:getWipeTime();
local message = 0;
if (remainingTimeLimit < 0) then
instance:fail();
return;
end
if (wipeTime == 0) then
local wipe = true;
for i,v in pairs(players) do
if v:getHP() ~= 0 then
wipe = false;
break;
end
end
if (wipe) then
for i,v in pairs(players) do
v:messageSpecial(Lebros.text.PARTY_FALLEN, 3);
end
instance:setWipeTime(elapsed);
end
else
if (elapsed - wipeTime) / 1000 > 180 then
instance:fail();
return;
else
for i,v in pairs(players) do
if v:getHP() ~= 0 then
instance:setWipeTime(0);
break;
end
end
end
end
if (lastTimeUpdate == 0 and elapsed > 20 * 60000) then
message = 600;
elseif (lastTimeUpdate == 600 and remainingTimeLimit < 300) then
message = 300;
elseif (lastTimeUpdate == 300 and remainingTimeLimit < 60) then
message = 60;
elseif (lastTimeUpdate == 60 and remainingTimeLimit < 30) then
message = 30;
elseif (lastTimeUpdate == 30 and remainingTimeLimit < 10) then
message = 10;
end
if (message ~= 0) then
for i,v in pairs(players) do
if (timeRemaining >= 60) then
v:messageSpecial(Lebros.text.TIME_REMAINING_MINUTES, timeRemaining / 60);
else
v:messageSpecial(Lebros.text.TIME_REMAINING_SECONDS, timeRemaining);
end
end
instance:setLastTimeUpdate(message);
end
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Lebros.text.MISSION_FAILED,10,10);
v:startEvent(0x66);
end
end;
-----------------------------------
-- onInstanceProgressUpdate
-----------------------------------
function onInstanceProgressUpdate(instance, progress)
if (progress >= 15) then
instance:complete();
end
end;
-----------------------------------
-- onInstanceComplete
-----------------------------------
function onInstanceComplete(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Lebros.text.RUNE_UNLOCKED, 7, 8);
end
local rune = instance:getEntity(bit.band(Lebros.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC);
local box = instance:getEntity(bit.band(Lebros.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC);
rune:setPos(414.29, -40.64, 301.523, 247);
rune:setStatus(STATUS_NORMAL);
box:setPos(410.41, -41.12, 300.743, 243);
box:setStatus(STATUS_NORMAL);
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Port_Jeuno/npcs/_6ua.lua | 17 | 1388 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Door: Departures Exit (for Bastok)
-- @zone 246
-- @pos -61 7 -54
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then
player:startEvent(0x0024);
else
player:startEvent(0x002c);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0024) then
Z = player:getZPos();
if (Z >= -61 and Z <= -58) then
player:delGil(200);
end
end
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Selbina/npcs/Jimaida.lua | 17 | 1301 | -----------------------------------
-- Area: Selbina
-- NPC: Jimaida
-- Involved in Quests: Under the sea
-- @pos -15 -2 -16 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("underTheSeaVar") == 2) then
player:startEvent(0x0021); -- During quest "Under the sea" - 2nd dialog
else
player:startEvent(0x0098); -- Standard dialog
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 == 0x0021) then
player:setVar("underTheSeaVar",3);
end
end;
| gpl-3.0 |
Ingenious-Gaming/Starfall | lua/starfall/libs_sh/angles.lua | 3 | 3630 | SF.Angles = {}
--- Angle Type
-- @shared
local ang_methods, ang_metamethods = SF.Typedef( "Angle" )
local wrap, unwrap = SF.CreateWrapper( ang_metamethods, true, false, debug.getregistry().Angle )
SF.DefaultEnvironment.Angle = function ( ... )
return wrap( Angle( ... ) )
end
SF.Angles.Wrap = wrap
SF.Angles.Unwrap = unwrap
SF.Angles.Methods = ang_methods
SF.Angles.Metatable = ang_metamethods
--- __newindex metamethod
function ang_metamethods.__newindex ( t, k, v )
if type( k ) == "number" and k >= 1 and k <= 3 then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
elseif k == "p" or k == "y" or k == "r" then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
else
rawset( t, k, v )
end
end
--- __index metamethod
function ang_metamethods.__index ( t, k )
if type( k ) == "number" and k >= 1 and k <= 3 then
return unwrap( t )[ k ]
elseif k == "p" or k == "y" or k == "r" then
return unwrap( t )[ k ]
end
return ang_metamethods.__methods[ k ]
end
--- tostring metamethod.
-- @return string representing the angle.
function ang_metamethods:__tostring ()
return unwrap( self ):__tostring()
end
--- __mul metamethod ang1 * ang2.
-- @param a Angle to multiply by.
-- @return resultant angle.
function ang_metamethods:__mul ( n )
SF.CheckType( n, "number" )
return SF.WrapObject( unwrap( self ):__mul( n ) )
end
--- __unm metamethod -ang.
-- @return resultant angle.
function ang_metamethods:__unm ()
return SF.WrapObject( unwrap( self ):__unm() )
end
--- __eq metamethod ang1 == ang2.
-- @param a Angle to check against.
-- @return bool
function ang_metamethods:__eq ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
return SF.WrapObject( unwrap( self ):__eq( unwrap( a ) ) )
end
--- __add metamethod ang1 + ang2.
-- @param a Angle to add.
-- @return resultant angle.
function ang_metamethods:__add ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
return SF.WrapObject( unwrap( self ):__add( unwrap( a ) ) )
end
--- __sub metamethod ang1 - ang2.
-- @param a Angle to subtract.
-- @return resultant angle.
function ang_metamethods:__sub ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
return SF.WrapObject( unwrap( self ):__sub( unwrap( a ) ) )
end
--- Return the Forward Vector ( direction the angle points ).
-- @return vector normalised.
function ang_methods:getForward ()
return SF.WrapObject( unwrap( self ):Forward() )
end
--- Returns if p,y,r are all 0.
-- @return boolean
function ang_methods:isZero ()
return unwrap( self ):IsZero()
end
--- Normalise angles eg (0,181,1) -> (0,-179,1).
-- @return nil
function ang_methods:normalize ()
unwrap( self ):Normalize()
end
--- Return the Right Vector relative to the angle dir.
-- @return vector normalised.
function ang_methods:getRight ()
return SF.WrapObject( unwrap( self ):Right() )
end
--- Rotates the angle around the specified axis by the specified degrees.
-- @param v Axis
-- @param r Number of degrees.
-- @return nil
function ang_methods:rotateAroundAxis ( v, r )
SF.CheckType( v, SF.Types[ "Vector" ] )
SF.CheckType( r, "number" )
unwrap( self ):RotateAroundAxis( SF.UnwrapObject( v ), r )
end
--- Copies p,y,r from second angle to the first.
-- @param a Angle to copy from.
-- @return nil
function ang_methods:set ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
unwrap( self ):Set( unwrap( a ) )
end
--- Return the Up Vector relative to the angle dir.
-- @return vector normalised.
function ang_methods:getUp ()
return SF.WrapObject( unwrap( self ):Up() )
end
--- Sets p,y,r to 0. This is faster than doing it manually.
-- @return nil
function ang_methods:setZero ()
unwrap( self ):Zero()
end
| bsd-3-clause |
EricssonResearch/scott-eu | simulation-ros/src/turtlebot2i/turtlebot2i_description/v-rep_model/warehouse_scene/vrep_scripts/Scene_Builder_test1.lua | 1 | 4528 | --**************************
-- Scene builder
-- @author Klaus Raizer
-- @date 2019-01-30
-- PROGRAMATICALLY ADD COMPONENTS TO YOUR SCENE
--**************************
function sysCall_init()
-- Initialization ------------------------
--sim.setBoolParameter(sim.boolparam_display_enabled,false)-- Disables rendering to increase simulation speed
simRemoteApi.start(20000) -- Start the remote API
simRemoteApi.start(20001) -- Start the remote API
-- Building the scene ------------------------
addModel('Floor10x15m',{2,0,0},{0,0,0})
--addModel('Floor10x10m',{2,0,0},{0,0,0})
--addModel('Floor10x10m',{10,0,0},{0,0,0})
addModel('dockstation',{-5.25,-4.000,0.063},{0,0,math.pi/2})
addModel('turtlebot2i',{-4.5,-3.5,0.063},{0,0,math.pi/2}) --Position for testing the performance of the robot
--addModel('turtlebot2i',{-1.5, 2.0,0.063},{0,0,0}) --Position for testing the mrcnn
--addModel('turtlebot2i_with_zone',{-1.0, 2.5,0.063},{0,0,0}) --Position for taking screenshoot
--addModel('Standing_Bill',{ 0.0, 2.0,0},{0,0,math.pi/2}) -- for taking screenshoot
--addModel('ConveyorBelt',{1.0,4.0,0.113},{0,0,math.pi/2}) -- for taking screenshoot
addModel('Shelf_simple',{-4.0, -4.0,0.063},{0,0,math.pi/2}) -- TODO: check why Shelf_simple rotation here is not compatible with what happens in the sim
addModel('ConcreteBox2',{-3.5, 2.0,0.5},{0,0,0})
addModel('ConcreteBox2',{-5.0,-0.5,0.5},{0,0,0})
addModel('ConcreteBox2',{-3.5,-2.5,0.5},{0,0,0})
addModel('ConveyorBelt_simple',{2.5,-2.50,0.113},{0,0,-math.pi/2})
--addModel('ConveyorBelt_simple',{4.0,-4.00,0.113},{0,0,-math.pi/2})
-- [[
--8 static objects:
addModel('ConcreteBox',{2.5, 3.5,0.5},{0,0,0})
addModel('80cmHighPillar100cm',{-0.5, 3.0,0.25},{0,0,0})
addModel('ConcreteBox1',{ 7.0, 1.5,0.5},{0,0,math.pi/2})
addModel('ConcreteBox2',{ 6.0,-0.5,0.5},{0,0,0})
addModel('ConcreteBox2',{ 8.0,-0.5,0.5},{0,0,0})
addModel('80cmHighPillar100cm',{-0.5, -2.5,0.25},{0,0,0})
addModel('ConcreteBox1',{ 1.0, -1.5,0.5},{0,0,0})
addModel('ConcreteBox1',{ 1.0, -3.5,0.5},{0,0,0}) --]]
-- [[
--5 walking humans:
--addModel('walkingBill_round',{-1.5, 1.0,0},{0,0,math.pi/2})
--addModel('walkingBill_round',{ 1.0, 4.5,0},{0,0,0})
addModel('Walking_Bill',{-1.5, 1.0,0},{0,0,math.pi/2})
addModel('Walking_Bill',{ 1.0, 4.5,0},{0,0,0})
addModel('Walking_Bill',{ 8.5, -1.5,0},{0,0, math.pi/2})
addModel('Walking_Bill',{ 5.5, 1.5,0},{0,0, 0})
addModel('Walking_Bill',{ 0.0, -1.0,0},{0,0, 0})
addModel('Working_Bill',{ 8.5, 4.0,0},{0,0,math.pi/2})
addModel('Working_Bill',{ 1.0, 1.0,0},{0,0,0})--]]
-------------------------Wall section bellow-------------------------------
addModel('80cmHighWall1000cm',{ 9.5, 0,.4},{0,0,0})
addModel('80cmHighWall1000cm',{ -5.5, 0,.4},{0,0,0})--dont have any effect on map
addModel('80cmHighWall1500cm',{ 2.0, 5,.4},{0,0,math.pi/2})
addModel('80cmHighWall1500cm',{ 2.0,-5,.4},{0,0,math.pi/2})
addModel('80cmHighWall100cm',{ -3.0, 4.5,.4},{0,0,0})
addModel('80cmHighWall750cm',{ -3.0, -1.25,.4},{0,0,0})
addModel('80cmHighWall750cm',{ 0.75, 0.00,.4},{0,0,math.pi/2})
addModel('80cmHighWall100cm',{ 6.0, 3.5,.4},{0,0,0})
addModel('80cmHighWall100cm',{ 4.5, 4.5,.4},{0,0,0})
addModel('80cmHighWall500cm',{ 4.5, 0.5,.4},{0,0,0})
addModel('80cmHighWall200cm',{ 4.5, -4.0,.4},{0,0,0})
addModel('80cmHighWall200cm',{ 8.5, 3.0,.4},{0,0,math.pi/2})
addModel('80cmHighWall200cm',{ 5.5, 3.0,.4},{0,0,math.pi/2})
addModel('80cmHighWall200cm',{ 8.5, -2.0,.4},{0,0,math.pi/2})
addModel('80cmHighWall200cm',{ 5.5, -2.0,.4},{0,0,math.pi/2})
end
function addModel(name,position,orientation)
scenePath = sim.getStringParameter(sim.stringparam_scene_path) -- retrieve scene path
file = '/vrep_models/'..name..'.ttm'
objectHandle=sim.loadModel(scenePath..file)
result=sim.setObjectPosition(objectHandle,-1,position)
result=sim.setObjectOrientation(objectHandle,-1,orientation)
return objectHandle
end
function sysCall_actuation()
-- put your actuation code here
--
-- For example:
--
-- local position=sim.getObjectPosition(handle,-1)
-- position[1]=position[1]+0.001
-- sim.setObjectPosition(handle,-1,position)
end
function sysCall_sensing()
-- put your sensing code here
end
function sysCall_cleanup()
-- do some clean-up here
end
| apache-2.0 |
haka-security/haka | modules/protocol/http/test/uri-split.lua | 5 | 3224 | -- 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/.
local http = require('protocol/http')
local function count_table(tab)
local index = 0
for k, _ in pairs(tab) do
index = index + 1
end
return index
end
local function dump_table(tab)
for k, v in pairs(tab) do
if type(v) == 'table' then
dump_table(v)
else
print('[' .. k .. '] = [' .. v .. ']')
end
end
end
local function compare_table(tab1, tab2)
local verif = true
if (tab1 and tab2) then
if type(tab1) ~= 'table' or type(tab2) ~= 'table' then return false end
if count_table(tab1) ~= count_table(tab2) then return false end
for k, v in pairs(tab1) do
if type(v) == 'table' then
verif = compare_table(v, tab2[k])
elseif tab2[k] ~= v then
return false
end
end
return verif
else
return false
end
end
TestUriSplit = {}
local _test = {
['test1'] = {
'HTTP://example.com/foo',
{
scheme = 'HTTP',
authority = 'example.com',
path = '/foo',
host = 'example.com',
}
},
['test2'] = {
'http://myname:mypass@www.example.com:8888/a/b/page?a=1&b=2#frag',
{
scheme = 'http',
authority = 'myname:mypass@www.example.com:8888',
host = 'www.example.com',
user = 'myname',
pass = 'mypass',
port = '8888',
args = {a = '1', b = '2'},
path = '/a/b/page',
fragment = 'frag',
userinfo = 'myname:mypass',
query = 'a=1&b=2',
}
},
['test3'] = {
'www.example.com:8888/foo',
{
authority = 'www.example.com:8888',
host = 'www.example.com',
port = '8888',
path = '/foo',
}
},
['test4'] = {
'/page?a=1',
{
args = {a = '1'},
path = '/page',
query = 'a=1',
}
},
['test5'] = {
'/page?a=1&b=2',
{
args = {a = '1', b='2'},
path = '/page',
query = 'a=1&b=2',
}
},
['test6'] = {
'/page?a=1&a=2',
{
args = {a = '1', a='2'},
path = '/page',
query = 'a=1&a=2',
}
},
['test7'] = {
'http://www.example.com/#',
{
scheme = 'http',
authority = 'www.example.com',
host = 'www.example.com',
path = '/',
}
},
['test8'] = {
'/',
{
path = '/',
}
},
['test9'] = {
'www.example.com/',
{
authority = 'www.example.com',
host = 'www.example.com',
path = '/',
}
}
}
for k, v in pairs(_test) do
TestUriSplit[k] = function (self)
local split = http.uri.split(v[1])
assertTrue(compare_table(split, v[2]))
end
end
TestCookieSplit = {}
local _cookie = {
['test1'] = { 'a=3;b=5', {a = '3', b='5'} },
['test2'] = { 'a=3', {a = '3'} },
['test3'] = { 'login=administrateur;password=pass;utm__z=0124645648645646', {login = 'administrateur', password='pass', utm__z='0124645648645646'} },
['test4'] = { '', { } },
['test5'] = { 'a=2%3bb=c', { a = '2%3bb=c'} },
['test6'] = { 'a=t t;b=c', { a = 't t'; b='c'} },
['test7'] = { 'a=2;;b=3', {a='2', b='3'} },
['test8'] = { ';a=2', {a = '2'} },
['test9'] = { 'a=2;', {a = '2'} }
}
for k, v in pairs(_cookie) do
TestCookieSplit[k] = function (self)
local split = http.cookies.split(v[1])
assertTrue(compare_table(split, v[2]))
end
end
addTestSuite('TestUriSplit', 'TestCookieSplit')
| mpl-2.0 |
nasomi/darkstar | scripts/zones/Bastok_Markets/npcs/Fatimah.lua | 53 | 2085 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Fatimah
-- Type: Goldsmithing Adv. Synthesis Image Support
-- @pos -193.849 -7.824 -56.372 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,6);
local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING);
local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then
player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0,0,0); -- Event doesn't work
else
player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),28674,0,0);
end
else
player:startEvent(0x012E);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING);
if (csid == 0x012E and option == 1) then
if (player:getGil() >= Cost) then
player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,0);
player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,480);
player:delGil(Cost);
else
player:messageSpecial(NOT_HAVE_ENOUGH_GIL);
end
end
end; | gpl-3.0 |
kaustubhcs/torch-toolbox | Adversarial/adversarial-fast.lua | 2 | 1247 | require('nn')
-- "Explaining and harnessing adversarial examples"
-- Ian Goodfellow, 2015
local function adversarial_fast(model, loss, x, y, std, intensity)
assert(loss.__typename == 'nn.ClassNLLCriterion')
local intensity = intensity or 1
-- consider x as batch
local batch = false
if x:dim() == 3 then
x = x:view(1, x:size(1), x:size(2), x:size(3))
batch = true
end
-- consider y as tensor
if type(y) == 'number' then
y = torch.Tensor({y}):typeAs(x)
end
-- compute output
local y_hat = model:updateOutput(x)
-- use predication as label if not provided
local _, target = nil, y
if target == nil then
_, target = y_hat:max(y_hat:dim())
end
-- find gradient of input (inplace)
local cost = loss:backward(y_hat, target)
local x_grad = model:updateGradInput(x, cost)
local noise = x_grad:sign():mul(intensity/255)
-- normalize noise intensity
if type(std) == 'number' then
noise:div(std)
else
for c = 1, 3 do
noise[{{},{c},{},{}}]:div(std[c])
end
end
if batch then
x = x:view(x:size(2), x:size(3), x:size(4))
end
-- return adversarial examples (inplace)
return x:add(noise)
end
return adversarial_fast
| bsd-3-clause |
ldrumm/chronos | update_rockspec.lua | 1 | 2873 | #!/usr/bin/env lua
print("enter a new version:")
version = string.match(io.read(), "v?([%d]+.[%d]+-[%d]+)")
assert(version ~= nil)
rockspec = {
package = "chronos",
version = version,
source = {
url = "https://github.com/ldrumm/chronos/archive/v" .. version .. ".zip",
dir= "chronos-" .. version,
tag = "v" .. version
},
description = {
summary = "High resolution monotonic timers",
detailed = [[
Wrappers around a number of platform-specific monotonic timers. The
highest resolution timer on each platform is used. This is typically
clock_gettime, gettimeofday, QueryPerformanceCounter, or similar
depending on the capabilities of the host. On a modern Linux system,
nanosecond precision is achievable.
]],
homepage = "https://github.com/ldrumm/chronos",
license = "MIT/X11"
},
dependencies = {
"lua >= 5.1"
},
build = {
platforms = {
unix = {
modules = {
chronos = {
sources = "src/chronos.c",
libraries = {"rt"},
},
},
},
macosx = {
modules = {
chronos = "src/chronos.c",
}
},
},
type = "builtin",
modules = {
chronos = "src/chronos.c",
}
}
}
do
local function writerockspec(file, rockspec, indent)
local comma = indent and "," or ""
indent = indent or 0
for k, v in pairs(rockspec) do
if type(v) == "table" then
file:write("\n")
file:write(string.rep("\t", indent) .. string.format("%s = {\n", k))
writerockspec(file, v, indent + 1)
file:write(string.rep("\t", indent) .. string.format("}%s\n", comma))
else
if(type(k) == "string") then
file:write(string.rep("\t", indent) .. string.format("%s = %q%s\n", k, v, comma))
elseif(type(k) == "number") then
file:write(string.rep("\t", indent) .. string.format("%q%s\n", v, comma))
else
file:write("rockspec can't contain key of type:" .. type(k))
end
end
end
end
local update_git
while update_git == nil do
print(string.format("Do 'git add . && commit -a && git tag v%s'?[yes/NO]", version))
update_git = io.read() == "yes"
end
local out = io.open(string.format("rockspecs/%s-%s.rockspec", rockspec.package, version ), "w")
writerockspec(out, rockspec)
out:flush()
if update_git then
os.execute(string.format('git add . && git commit -a && git tag v%s', version))
end
end
| mit |
nasomi/darkstar | scripts/zones/Windurst_Waters/npcs/Upih_Khachla.lua | 30 | 2226 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Upih Khachla
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
onHalloweenTrade(player,trade,npc);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,UPIHKHACHLA_SHOP_DIALOG);
stock = {
0x43A1, 1107,1, --Grenade
0x1010, 837,1, --Potion
0x03B7, 108,1, --Wijnruit
0x027C, 119,2, --Chamomile
0x1037, 736,2, --Echo Drops
0x1020, 4445,2, --Ether
0x1034, 290,3, --Antidote
0x0764, 3960,3, --Desalinator
0x026E, 44,3, --Dried Marjoram
0x1036, 2387,3, --Eye Drops
0x025D, 180,3, --Pickaxe
0x0765, 3960,3, --Salinator
0x03FC, 276,3, --Sickle
0x04D9, 354,3 --Twinkle Powder
}
rank = getNationRank(WINDURST);
if (rank ~= 1) then
table.insert(stock,0x03fe); --Thief's Tools
table.insert(stock,3643);
table.insert(stock,3);
end
if (rank == 3) then
table.insert(stock,0x03ff); --Living Key
table.insert(stock,5520);
table.insert(stock,3);
end
showNationShop(player, WINDURST, 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 |
nasomi/darkstar | scripts/globals/spells/gravity_ii.lua | 18 | 1087 | -----------------------------------------
-- Spell: Gravity II
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- Pull base stats.
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
local power = 60; -- 60% reduction
-- Duration, including resistance. Unconfirmed.
local duration = 180 * applyResistanceEffect(caster,spell,target,dINT,35,0,EFFECT_WEIGHT);
if (duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if (target:addStatusEffect(EFFECT_WEIGHT,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(284);
end
return EFFECT_WEIGHT;
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/items/serving_of_newt_flambe.lua | 35 | 1565 | -----------------------------------------
-- ID: 4329
-- Item: serving_of_newt_flambe
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 4
-- Mind -3
-- Attack % 18
-- Attack Cap 65
-- Virus Resist 5
-- Curse Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4329);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_VIRUSRES, 5);
target:addMod(MOD_CURSERES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_VIRUSRES, 5);
target:delMod(MOD_CURSERES, 5);
end;
| gpl-3.0 |
actboy168/YDWE | Development/Component/compiler/script/jasshelper.lua | 2 | 2531 | fs = require 'bee.filesystem'
local stormlib = require 'ffi.stormlib'
local jasshelper = {}
jasshelper.path = fs.ydwe_path() / "compiler" / "jasshelper"
local config = [[
[jasscompiler]
%q
"%s$COMMONJ $BLIZZARDJ $WAR3MAPJ"
]]
function jasshelper:prepare_common_j(map_path, version)
if fs.exists(map_path / 'common.j') then
return map_path / 'common.j'
elseif fs.exists(map_path / 'scripts' / 'common.j') then
return map_path / 'scripts' / 'common.j'
else
return fs.ydwe_devpath() / "compiler" / "jass" / tostring(version) / "common.j"
end
end
function jasshelper:prepare_blizzard_j(map_path, version)
if fs.exists(map_path / 'blizzard.j') then
return map_path / 'blizzard.j'
elseif fs.exists(map_path / 'scripts' / 'blizzard.j') then
return map_path / 'scripts' / 'blizzard.j'
else
return fs.ydwe_devpath() / "compiler" / "jass" / tostring(version) / "blizzard.j"
end
end
function jasshelper:createConfig(op)
if op.option.pjass == '1' then
io.save(fs.ydwe_path() / 'jasshelper.conf', config:format('../pjass/pjass-classic.exe', ''))
else
if op.option.runtime_version == 24 then
io.save(fs.ydwe_path() / 'jasshelper.conf', config:format('../pjass/pjass-latest.exe', ''))
else
io.save(fs.ydwe_path() / 'jasshelper.conf', config:format('../pjass/pjass-latest.exe', '+rb '))
end
end
end
function jasshelper:compile(op)
log.trace("JassHelper compilation start.")
self:createConfig(op)
local common_j_path = self:prepare_common_j(op.map_path, op.option.runtime_version)
local blizzard_j_path = self:prepare_blizzard_j(op.map_path, op.option.runtime_version)
local parameter = {}
-- 需要做vJass编译?
if op.option.enable_jasshelper then
-- debug选项(--debug)
if op.option.enable_jasshelper_debug then
parameter[#parameter + 1] = "--debug"
end
-- (关闭)优化选项(--nooptimize)
if not op.option.enable_jasshelper_optimization then
parameter[#parameter + 1] = "--nooptimize"
end
else
-- 不编译vJass选项(--nopreprocessor)
parameter[#parameter + 1] = "--nopreprocessor"
end
local ok = not not sys.spawn_wait {
(self.path / "jasshelper.exe"):string(),
parameter,
"--scriptonly",
common_j_path:string(),
blizzard_j_path:string(),
op.input:string(),
op.output:string(),
cwd = fs.ydwe_path():string(),
}
fs.remove(fs.ydwe_path() / 'jasshelper.conf')
return ok
end
return jasshelper
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#1.lua | 17 | 1280 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: HomePoint#1
-- @pos -21.129 0.001 -20.944 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 65);
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
irboy/000LOGIN000 | plugins/plugins.lua | 1 | 7876 | do
-- #Begin plugins.lua by @Y0BINARI
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled, msg)
local tmp = '\n'..msg_caption
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '|✖️|>'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '|✔|>'
end
nact = nact+1
end
if not only_enabled or status == '|✔|>'then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
text = '<code>'..text..'</code>\n\n'..nsum..' <b>📂plugins installed</b>\n\n'..nact..' <i>✔️plugins enabled</i>\n\n'..nsum-nact..' <i>❌plugins disabled</i>'..tmp
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
local function list_plugins(only_enabled, msg)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '*|✖️|>*'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '*|✔|>*'
end
nact = nact+1
end
if not only_enabled or status == '*|✔|>*'then
-- get the name
v = string.match (v, "(.*)%.lua")
-- text = text..v..' '..status..'\n'
end
end
text = "\n_🔃All Plugins Reloaded_\n\n"..nact.." *✔️Plugins Enabled*\n"..nsum.." *📂Plugins Installed*\n"..msg_caption
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'md')
end
local function reload_plugins(checks, msg)
plugins = {}
load_plugins()
return list_plugins(true, msg)
end
local function enable_plugin( plugin_name, msg )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
local text = '<b>'..plugin_name..'</b> <i>is enabled.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
return
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins(true, msg)
else
local text = '<b>'..plugin_name..'</b> <i>does not exists.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
end
local function disable_plugin( name, msg )
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
local text = '<b>'..name..'</b> <i>not enabled.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
return
end
-- Check if plugins exists
if not plugin_exists(name) then
local text = '<b>'..name..'</b> <i>does not exists.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
else
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true, msg)
end
end
local function disable_plugin_on_chat(receiver, plugin, msg)
if not plugin_exists(plugin) then
return "_Plugin doesn't exists_"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
local text = '<b>'..plugin..'</b> <i>disabled on this chat.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
local function reenable_plugin_on_chat(receiver, plugin, msg)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return '_This plugin is not disabled_'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
local text = '<b>'..plugin..'</b> <i>is enabled again.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
local function run(msg, matches)
local Chash = "cmd_lang:"..msg.to.id
local Clang = redis:get(Chash)
-- Show the available plugins
if is_sudo(msg) then
if (matches[1]:lower() == 'plist' and not Clang) or (matches[1]:lower() == 'لیست پلاگین' and Clang) then --after changed to moderator mode, set only sudo
return list_all_plugins(false, msg)
end
end
-- Re-enable a plugin for this chat
if (matches[1]:lower() == 'pl' and not Clang) or (matches[1]:lower() == 'پلاگین' and Clang) then
if matches[2] == '+' and ((matches[4] == 'chat' and not Clang) or (matches[4] == 'گروه' and not Clang)) then
if is_mod(msg) then
local receiver = msg.chat_id_
local plugin = matches[3]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin, msg)
end
end
-- Enable a plugin
if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[3]
print("enable: "..matches[3])
return enable_plugin(plugin_name, msg)
end
-- Disable a plugin on a chat
if matches[2] == '-' and ((matches[4] == 'chat' and not Clang) or (matches[4] == 'گروه' and not Clang)) then
if is_mod(msg) then
local plugin = matches[3]
local receiver = msg.chat_id_
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin, msg)
end
end
-- Disable a plugin
if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[3] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[3])
return disable_plugin(matches[3], msg)
end
-- Reload all the plugins!
if matches[2] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true, msg)
end
end
if (matches[1]:lower() == 'reload' and not Clang) or (matches[1]:lower() == 'بارگذاری' and Clang) and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true, msg)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!pl - [plugin] chat : disable plugin only this chat.",
"!pl + [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plist : list all plugins.",
"!pl + [plugin] : enable plugin.",
"!pl - [plugin] : disable plugin.",
"!pl * : reloads all plugins." },
},
patterns = {
"^[!/#]([Pp]list)$",
"^[!/#]([Pp]l) (+) ([%w_%.%-]+)$",
"^[!/#]([Pp]l) (-) ([%w_%.%-]+)$",
"^[!/#]([Pp]l) (+) ([%w_%.%-]+) (chat)",
"^[!/#]([Pp]l) (-) ([%w_%.%-]+) (chat)",
"^[!/#]([Pp]l) (*)$",
"^[!/#]([Rr]eload)$",
"^(لیست پلاگین)$",
"^(پلاگین) (+) ([%w_%.%-]+)$",
"^(پلاگین) (-) ([%w_%.%-]+)$",
"^(پلاگین) (+) ([%w_%.%-]+) (گروه)",
"^(پلاگین) (-) ([%w_%.%-]+) (گروه)",
"^(پلاگین) (*)$",
"^(بارگذاری)$",
},
run = run,
moderated = true, -- set to moderator mode
privileged = true
}
end
| gpl-3.0 |
mbsg/openwrt-extra | luci/applications/luci-app-xware3/luasrc/model/cbi/xware3.lua | 2 | 2856 | 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", "启用 迅雷远程下载")
s:option(Value, "prog_path", "Xware3主程序路径", "<br />Xware3主程序所在路径,例如:/mnt/sda1/xware3。请确认已经将Xware3的主程序etm_xware复制到该目录下。")
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下载目录所在的“挂载点”。")
s.anonymous = true
local devices = {}
util.consume((fs.glob("/mnt/sd??*")), devices)
device = s:option(DynamicList, "available_mounts", "挂载点")
for i, dev in ipairs(devices) do
device:value(dev)
end
return m
| gpl-2.0 |
shangjiyu/luci-with-extra | applications/luci-app-pbx/luasrc/model/cbi/pbx-calls.lua | 117 | 18881 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-calls"
voipmodulename = "pbx-voip"
googlemodulename = "pbx-google"
usersmodulename = "pbx-users"
allvalidaccounts = {}
nallvalidaccounts = 0
validoutaccounts = {}
nvalidoutaccounts = 0
validinaccounts = {}
nvalidinaccounts = 0
allvalidusers = {}
nallvalidusers = 0
validoutusers = {}
nvalidoutusers = 0
-- Checks whether the entered extension is valid syntactically.
function is_valid_extension(exten)
return (exten:match("[#*+0-9NXZ]+$") ~= nil)
end
m = Map (modulename, translate("Call Routing"),
translate("This is where you indicate which Google/SIP accounts are used to call what \
country/area codes, which users can use what SIP/Google accounts, how incoming \
calls are routed, what numbers can get into this PBX with a password, and what \
numbers are blacklisted."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null")
end
-- Add Google accounts to all valid accounts, and accounts valid for incoming and outgoing calls.
m.uci:foreach(googlemodulename, "gtalk_jabber",
function(s1)
-- Add this provider to list of valid accounts.
if s1.username ~= nil and s1.name ~= nil then
allvalidaccounts[s1.name] = s1.username
nallvalidaccounts = nallvalidaccounts + 1
if s1.make_outgoing_calls == "yes" then
-- Add provider to the associative array of valid outgoing accounts.
validoutaccounts[s1.name] = s1.username
nvalidoutaccounts = nvalidoutaccounts + 1
end
if s1.register == "yes" then
-- Add provider to the associative array of valid outgoing accounts.
validinaccounts[s1.name] = s1.username
nvalidinaccounts = nvalidinaccounts + 1
end
end
end)
-- Add SIP accounts to all valid accounts, and accounts valid for incoming and outgoing calls.
m.uci:foreach(voipmodulename, "voip_provider",
function(s1)
-- Add this provider to list of valid accounts.
if s1.defaultuser ~= nil and s1.host ~= nil and s1.name ~= nil then
allvalidaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host
nallvalidaccounts = nallvalidaccounts + 1
if s1.make_outgoing_calls == "yes" then
-- Add provider to the associative array of valid outgoing accounts.
validoutaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host
nvalidoutaccounts = nvalidoutaccounts + 1
end
if s1.register == "yes" then
-- Add provider to the associative array of valid outgoing accounts.
validinaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host
nvalidinaccounts = nvalidinaccounts + 1
end
end
end)
-- Add Local User accounts to all valid users, and users allowed to make outgoing calls.
m.uci:foreach(usersmodulename, "local_user",
function(s1)
-- Add user to list of all valid users.
if s1.defaultuser ~= nil then
allvalidusers[s1.defaultuser] = true
nallvalidusers = nallvalidusers + 1
if s1.can_call == "yes" then
validoutusers[s1.defaultuser] = true
nvalidoutusers = nvalidoutusers + 1
end
end
end)
----------------------------------------------------------------------------------------------------
-- If there are no accounts configured, or no accounts enabled for outgoing calls, display a warning.
-- Otherwise, display the usual help text within the section.
if nallvalidaccounts == 0 then
text = translate("NOTE: There are no Google or SIP provider accounts configured.")
elseif nvalidoutaccounts == 0 then
text = translate("NOTE: There are no Google or SIP provider accounts enabled for outgoing calls.")
else
text = translate("If you have more than one account that can make outgoing calls, you \
should enter a list of phone numbers and/or prefixes in the following fields for each \
provider listed. Invalid prefixes are removed silently, and only 0-9, X, Z, N, #, *, \
and + are valid characters. The letter X matches 0-9, Z matches 1-9, and N matches 2-9. \
For example to make calls to Germany through a provider, you can enter 49. To make calls \
to North America, you can enter 1NXXNXXXXXX. If one of your providers can make \"local\" \
calls to an area code like New York's 646, you can enter 646NXXXXXX for that \
provider. You should leave one account with an empty list to make calls with \
it by default, if no other provider's prefixes match. The system will automatically \
replace an empty list with a message that the provider dials all numbers not matched by another \
provider's prefixes. Be as specific as possible (i.e. 1NXXNXXXXXX is better than 1). Please note \
all international dial codes are discarded (e.g. 00, 011, 010, 0011). Entries can be made in a \
space-separated list, and/or one per line by hitting enter after every one.")
end
s = m:section(NamedSection, "outgoing_calls", "call_routing", translate("Outgoing Calls"), text)
s.anonymous = true
for k,v in pairs(validoutaccounts) do
patterns = s:option(DynamicList, k, v)
-- If the saved field is empty, we return a string
-- telling the user that this provider would dial any exten.
function patterns.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {translate("Dials numbers unmatched elsewhere")}
else
return value
end
end
-- Write only valid extensions into the config file.
function patterns.write(self, section, value)
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
val = luci.util.trim(value[index])
if is_valid_extension(val) == true then
newvalue[nindex] = val
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
----------------------------------------------------------------------------------------------------
-- If there are no accounts configured, or no accounts enabled for incoming calls, display a warning.
-- Otherwise, display the usual help text within the section.
if nallvalidaccounts == 0 then
text = translate("NOTE: There are no Google or SIP provider accounts configured.")
elseif nvalidinaccounts == 0 then
text = translate("NOTE: There are no Google or SIP provider accounts enabled for incoming calls.")
else
text = translate("For each provider enabled for incoming calls, here you can restrict which users to\
ring on incoming calls. If the list is empty, the system will indicate that all users \
enabled for incoming calls will ring. Invalid usernames will be rejected \
silently. Also, entering a username here overrides the user's setting to not receive \
incoming calls. This way, you can make certain users ring only for specific providers. \
Entries can be made in a space-separated list, and/or one per line by hitting enter after \
every one.")
end
s = m:section(NamedSection, "incoming_calls", "call_routing", translate("Incoming Calls"), text)
s.anonymous = true
for k,v in pairs(validinaccounts) do
users = s:option(DynamicList, k, v)
-- If the saved field is empty, we return a string telling the user that
-- this provider would ring all users configured for incoming calls.
function users.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {translate("Rings users enabled for incoming calls")}
else
return value
end
end
-- Write only valid user names.
function users.write(self, section, value)
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
trimuser = luci.util.trim(value[index])
if allvalidusers[trimuser] == true then
newvalue[nindex] = trimuser
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
----------------------------------------------------------------------------------------------------
-- If there are no user accounts configured, no user accounts enabled for outgoing calls,
-- display a warning. Otherwise, display the usual help text within the section.
if nallvalidusers == 0 then
text = translate("NOTE: There are no local user accounts configured.")
elseif nvalidoutusers == 0 then
text = translate("NOTE: There are no local user accounts enabled for outgoing calls.")
else
text = translate("For each user enabled for outgoing calls you can restrict what providers the user \
can use for outgoing calls. By default all users can use all providers. To show up in the list \
below the user should be allowed to make outgoing calls in the \"User Accounts\" page. Enter VoIP \
providers in the format username@some.host.name, as listed in \"Outgoing Calls\" above. It's \
easiest to copy and paste the providers from above. Invalid entries, including providers not \
enabled for outgoing calls, will be rejected silently. Entries can be made in a space-separated \
list, and/or one per line by hitting enter after every one.")
end
s = m:section(NamedSection, "providers_user_can_use", "call_routing",
translate("Providers Used for Outgoing Calls"), text)
s.anonymous = true
for k,v in pairs(validoutusers) do
providers = s:option(DynamicList, k, k)
-- If the saved field is empty, we return a string telling the user
-- that this user uses all providers enavled for outgoing calls.
function providers.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {translate("Uses providers enabled for outgoing calls")}
else
newvalue = {}
-- Convert internal names to user@host values.
for i,v in ipairs(value) do
newvalue[i] = validoutaccounts[v]
end
return newvalue
end
end
-- Cook the new values prior to entering them into the config file.
-- Also, enter them only if they are valid.
function providers.write(self, section, value)
cookedvalue = {}
cindex = 1
for index, field in ipairs(value) do
cooked = string.gsub(luci.util.trim(value[index]), "%W", "_")
if validoutaccounts[cooked] ~= nil then
cookedvalue[cindex] = cooked
cindex = cindex + 1
end
end
DynamicList.write(self, section, cookedvalue)
end
end
----------------------------------------------------------------------------------------------------
s = m:section(TypedSection, "callthrough_numbers", translate("Call-through Numbers"),
translate("Designate numbers that are allowed to call through this system and which user's \
privileges they will have."))
s.anonymous = true
s.addremove = true
num = s:option(DynamicList, "callthrough_number_list", translate("Call-through Numbers"),
translate("Specify numbers individually here. Press enter to add more numbers. \
You will have to experiment with what country and area codes you need to add \
to the number."))
num.datatype = "uinteger"
p = s:option(ListValue, "enabled", translate("Enabled"))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
user = s:option(Value, "defaultuser", translate("User Name"),
translate("The number(s) specified above will be able to dial out with this user's providers. \
Invalid usernames, including users not enabled for outgoing calls, are dropped silently. \
Please verify that the entry was accepted."))
function user.write(self, section, value)
trimuser = luci.util.trim(value)
if allvalidusers[trimuser] == true then
Value.write(self, section, trimuser)
end
end
pwd = s:option(Value, "pin", translate("PIN"),
translate("Your PIN disappears when saved for your protection. It will be changed \
only when you enter a value different from the saved one. Leaving the PIN \
empty is possible, but please beware of the security implications."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
----------------------------------------------------------------------------------------------------
s = m:section(TypedSection, "callback_numbers", translate("Call-back Numbers"),
translate("Designate numbers to whom the system will hang up and call back, which provider will \
be used to call them, and which user's privileges will be granted to them."))
s.anonymous = true
s.addremove = true
num = s:option(DynamicList, "callback_number_list", translate("Call-back Numbers"),
translate("Specify numbers individually here. Press enter to add more numbers. \
You will have to experiment with what country and area codes you need to add \
to the number."))
num.datatype = "uinteger"
p = s:option(ListValue, "enabled", translate("Enabled"))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
delay = s:option(Value, "callback_hangup_delay", translate("Hang-up Delay"),
translate("How long to wait before hanging up. If the provider you use to dial automatically forwards \
to voicemail, you can set this value to a delay that will allow you to hang up before your call gets \
forwarded and you get billed for it."))
delay.datatype = "uinteger"
delay.default = 0
user = s:option(Value, "defaultuser", translate("User Name"),
translate("The number(s) specified above will be able to dial out with this user's providers. \
Invalid usernames, including users not enabled for outgoing calls, are dropped silently. \
Please verify that the entry was accepted."))
function user.write(self, section, value)
trimuser = luci.util.trim(value)
if allvalidusers[trimuser] == true then
Value.write(self, section, trimuser)
end
end
pwd = s:option(Value, "pin", translate("PIN"),
translate("Your PIN disappears when saved for your protection. It will be changed \
only when you enter a value different from the saved one. Leaving the PIN \
empty is possible, but please beware of the security implications."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
provider = s:option(Value, "callback_provider", translate("Call-back Provider"),
translate("Enter a VoIP provider to use for call-back in the format username@some.host.name, as listed in \
\"Outgoing Calls\" above. It's easiest to copy and paste the providers from above. Invalid entries, including \
providers not enabled for outgoing calls, will be rejected silently."))
function provider.write(self, section, value)
cooked = string.gsub(luci.util.trim(value), "%W", "_")
if validoutaccounts[cooked] ~= nil then
Value.write(self, section, value)
end
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "blacklisting", "call_routing", translate("Blacklisted Numbers"),
translate("Enter phone numbers that you want to decline calls from automatically. \
You should probably omit the country code and any leading zeroes, but please \
experiment to make sure you are blocking numbers from your desired area successfully."))
s.anonymous = true
b = s:option(DynamicList, "blacklist1", translate("Dynamic List of Blacklisted Numbers"),
translate("Specify numbers individually here. Press enter to add more numbers."))
b.cast = "string"
b.datatype = "uinteger"
b = s:option(Value, "blacklist2", translate("Space-Separated List of Blacklisted Numbers"),
translate("Copy-paste large lists of numbers here."))
b.template = "cbi/tvalue"
b.rows = 3
return m
| apache-2.0 |
nasomi/darkstar | scripts/zones/Castle_Oztroja/npcs/_47u.lua | 17 | 1256 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47u (Handle)
-- Notes: Opens door _474 from behind
-- @pos -60 24 -77 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() < -72) 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/items/cup_of_windurstian_tea.lua | 35 | 1210 | -----------------------------------------
-- ID: 4493
-- Item: cup_of_windurstian_tea
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Vitality -2
-- Charisma 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4493);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -2);
target:addMod(MOD_CHR, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -2);
target:delMod(MOD_CHR, 1);
end;
| gpl-3.0 |
nicholas-leonard/nn | VolumetricMaxPooling.lua | 9 | 2555 | local VolumetricMaxPooling, parent = torch.class('nn.VolumetricMaxPooling', 'nn.Module')
VolumetricMaxPooling.__version = 2
function VolumetricMaxPooling:__init(kT, kW, kH, dT, dW, dH, padT, padW, padH)
parent.__init(self)
dT = dT or kT
dW = dW or kW
dH = dH or kH
self.kT = kT
self.kH = kH
self.kW = kW
self.dT = dT
self.dW = dW
self.dH = dH
self.padT = padT or 0
self.padW = padW or 0
self.padH = padH or 0
self.ceil_mode = false
self.indices = torch.LongTensor()
end
function VolumetricMaxPooling:ceil()
self.ceil_mode = true
return self
end
function VolumetricMaxPooling:floor()
self.ceil_mode = false
return self
end
function VolumetricMaxPooling:updateOutput(input)
local dims = input:dim()
self.itime = input:size(dims-2)
self.iheight = input:size(dims-1)
self.iwidth = input:size(dims)
self.indices = self.indices or torch.LongTensor()
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.indices = torch.CudaLongTensor and self.indices:cudaLong() or self.indices
else
self.indices = self.indices:long()
end
input.THNN.VolumetricMaxPooling_updateOutput(
input:cdata(),
self.output:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.ceil_mode
)
return self.output
end
function VolumetricMaxPooling:updateGradInput(input, gradOutput)
input.THNN.VolumetricMaxPooling_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.ceil_mode
)
return self.gradInput
end
function VolumetricMaxPooling:empty()
self:clearState()
end
function VolumetricMaxPooling:clearState()
if self.indices then self.indices:set() end
return parent.clearState(self)
end
function VolumetricMaxPooling:read(file, version)
parent.read(self, file)
if version < 2 then
self.ceil_mode = false
end
end
function VolumetricMaxPooling:__tostring__()
local s = string.format('%s(%dx%dx%d, %d,%d,%d', torch.type(self),
self.kT, self.kW, self.kH, self.dT, self.dW, self.dH)
if (self.padT or self.padW or self.padH) and
(self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padT.. ',' .. self.padW .. ','.. self.padH
end
s = s .. ')'
return s
end
| bsd-3-clause |
EnjoyHacking/nn | MixtureTable.lua | 23 | 5638 | local MixtureTable, parent = torch.class('nn.MixtureTable', 'nn.Module')
function MixtureTable:__init(dim)
parent.__init(self)
self.dim = dim
self.size = torch.LongStorage()
self.batchSize = 0
self.size2 = torch.LongStorage()
self.backwardSetup = false
self.gradInput = {}
end
function MixtureTable:updateOutput(input)
local gaterInput, expertInputs = table.unpack(input)
-- buffers
self._gaterView = self.gaterView or input[1].new()
self._expert = self._expert or input[1].new()
self._expertView = self._expertView or input[1].new()
self.dimG = 2
local batchSize = gaterInput:size(1)
if gaterInput:dim() < 2 then
self.dimG = 1
self.dim = self.dim or 1
batchSize = 1
end
self.dim = self.dim or 2
if self.table or torch.type(expertInputs) == 'table' then
-- expertInputs is a Table :
self.table = true
if gaterInput:size(self.dimG) ~= #expertInputs then
error"Should be one gater output per expert"
end
local expertInput = expertInputs[1]
if self.batchSize ~= batchSize then
self.size:resize(expertInput:dim()+1):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInput)
self.backwardSetup = false
self.batchSize = batchSize
end
self._gaterView:view(gaterInput, self.size)
self.output:zero()
-- multiply accumulate gater outputs by their commensurate expert
for i,expertInput in ipairs(expertInputs) do
local gate = self._gaterView:select(self.dim,i):expandAs(expertInput)
self.output:addcmul(expertInput, gate)
end
else
-- expertInputs is a Tensor :
if self.batchSize ~= batchSize then
self.size:resize(expertInputs:dim()):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInputs:select(self.dim, 1))
self.gradInput[2] = self._gradInput
self.batchSize = batchSize
self.backwardSetup = false
end
self._gaterView:view(gaterInput, self.size)
self._expert:cmul(self._gaterView:expandAs(expertInputs), expertInputs)
self.output:sum(self._expert, self.dim)
self.output:resizeAs(expertInputs:select(self.dim, 1))
end
return self.output
end
function MixtureTable:updateGradInput(input, gradOutput)
local gaterInput, expertInputs = table.unpack(input)
nn.utils.recursiveResizeAs(self.gradInput, input)
local gaterGradInput, expertGradInputs = table.unpack(self.gradInput)
-- buffers
self._sum = self._sum or input[1].new()
self._gradInput = self._gradInput or {input[1].new(), {}}
self._expertView2 = self._expertView2 or input[1].new()
self._expert2 = self._expert2 or input[1].new()
if self.table then
if not self.backwardSetup then
for i,expertInput in ipairs(expertInputs) do
local expertGradInput = expertGradInputs[i] or expertInput:clone()
expertGradInput:resizeAs(expertInput)
expertGradInputs[i] = expertGradInput
end
gaterGradInput:resizeAs(gaterInput)
self.backwardSetup = true
end
-- like CMulTable, but with broadcasting
for i,expertGradInput in ipairs(expertGradInputs) do
-- gater updateGradInput
self._expert:cmul(gradOutput, expertInputs[i])
if self.dimG == 1 then
self._expertView:view(self._expert, -1)
else
self._expertView:view(self._expert, gradOutput:size(1), -1)
end
self._sum:sum(self._expertView, self.dimG)
if self.dimG == 1 then
gaterGradInput[i] = self._sum:select(self.dimG,1)
else
gaterGradInput:select(self.dimG,i):copy(self._sum:select(self.dimG,1))
end
-- expert updateGradInput
local gate = self._gaterView:select(self.dim,i):expandAs(expertGradInput)
expertGradInput:cmul(gate, gradOutput)
end
else
if not self.backwardSetup then
self.size2:resize(expertInputs:dim())
self.size2:copy(expertInputs:size())
self.size2[self.dim] = 1
gaterGradInput:resizeAs(gaterInput)
self.backwardSetup = true
end
-- gater updateGradInput
self._expertView:view(gradOutput, self.size2)
local gradOutput = self._expertView:expandAs(expertInputs)
self._expert:cmul(gradOutput, expertInputs)
local expert = self._expert:transpose(self.dim, self.dimG)
if not expert:isContiguous() then
self._expert2:resizeAs(expert)
self._expert2:copy(expert)
expert = self._expert2
end
if self.dimG == 1 then
self._expertView2:view(expert, gaterInput:size(1), -1)
else
self._expertView2:view(expert, gaterInput:size(1), gaterInput:size(2), -1)
end
gaterGradInput:sum(self._expertView2, self.dimG+1)
gaterGradInput:resizeAs(gaterInput)
-- expert updateGradInput
expertGradInputs:cmul(self._gaterView:expandAs(expertInputs), gradOutput)
end
return self.gradInput
end
function MixtureTable:type(type, tensorCache)
self._gaterView = nil
self._expert = nil
self._expertView = nil
self._sum = nil
self._gradInput = nil
self._expert2 = nil
self._expertView2 = nil
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
nasomi/darkstar | scripts/zones/Southern_San_dOria/npcs/Valderotaux.lua | 17 | 1752 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Valderotaux
-- General Info NPC
-- @pos 97 0.1 113 230
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local lakesideMin = player:getQuestStatus(JEUNO,LAKESIDE_MINUET);
local lakeProg = player:getVar("Lakeside_Minuet_Progress");
if (lakeProg == 1) then
player:startEvent(0x0378); -- Dance for the drunks!
player:setVar("Lakeside_Minuet_Progress",2);
elseif (lakeProg >= 2) then
player:startEvent(0x0379); -- Immediate regret of failure!
else
player:startEvent(0x03A);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Port_San_dOria/npcs/Maunadolace.lua | 38 | 1043 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Maunadolace
-- Type: Standard NPC
-- @zone: 232
-- @pos -22.800 -9.3 -148.645
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02c9);
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 |
shangjiyu/luci-with-extra | applications/luci-app-adblock/luasrc/controller/adblock.lua | 1 | 2165 | -- Copyright 2016 Hannu Nyman
-- Copyright 2017 Dirk Brenken (dev@brenken.org)
-- This is free software, licensed under the Apache License, Version 2.0
module("luci.controller.adblock", package.seeall)
local fs = require("nixio.fs")
local util = require("luci.util")
local template = require("luci.template")
local i18n = require("luci.i18n")
function index()
if not nixio.fs.access("/etc/config/adblock") then
return
end
entry({"admin", "services", "adblock"}, firstchild(), _("Adblock"), 30).dependent = false
entry({"admin", "services", "adblock", "tab_from_cbi"}, cbi("adblock/overview_tab"), _("Overview"), 10).leaf = true
entry({"admin", "services", "adblock", "logfile"}, call("logread"), _("View Logfile"), 20).leaf = true
entry({"admin", "services", "adblock", "advanced"}, firstchild(), _("Advanced"), 100)
entry({"admin", "services", "adblock", "advanced", "blacklist"}, cbi("adblock/blacklist_tab"), _("Edit Blacklist"), 110).leaf = true
entry({"admin", "services", "adblock", "advanced", "whitelist"}, cbi("adblock/whitelist_tab"), _("Edit Whitelist"), 120).leaf = true
entry({"admin", "services", "adblock", "advanced", "configuration"}, cbi("adblock/configuration_tab"), _("Edit Configuration"), 130).leaf = true
entry({"admin", "services", "adblock", "advanced", "query"}, call("query"), _("Query domains"), 140).leaf = true
entry({"admin", "services", "adblock", "advanced", "result"}, call("queryData"), nil, 150).leaf = true
end
function logread()
local logfile = util.trim(util.exec("logread -e 'adblock'"))
template.render("adblock/logread", {title = i18n.translate("Adblock Logfile"), content = logfile})
end
function query()
template.render("adblock/query", {title = i18n.translate("Adblock Domain Query")})
end
function queryData(domain)
if domain and domain:match("^[a-zA-Z0-9%-%._]+$") then
luci.http.prepare_content("text/plain")
local cmd = "/etc/init.d/adblock query %q 2>&1"
local util = io.popen(cmd % domain)
if util then
while true do
local line = util:read("*l")
if not line then
break
end
luci.http.write(line)
luci.http.write("\n")
end
util:close()
end
end
end
| apache-2.0 |
nasomi/darkstar | scripts/zones/Northern_San_dOria/npcs/Telmoda.lua | 17 | 1622 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Telmoda
-- 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)
Telmoda_Madaline = player:getVar("Telmoda_Madaline_Event");
if (Telmoda_Madaline ~= 1) then
player:setVar(player,"Telmoda_Madaline_Event",1);
player:startEvent(0x0213);
else
player:startEvent(0x0268);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
shangjiyu/luci-with-extra | modules/luci-base/luasrc/sys/zoneinfo/tzoffset.lua | 6 | 3332 | -- Licensed to the public under the Apache License 2.0.
module "luci.sys.zoneinfo.tzoffset"
OFFSET = {
gmt = 0, -- GMT
eat = 10800, -- EAT
cet = 3600, -- CET
wat = 3600, -- WAT
cat = 7200, -- CAT
eet = 7200, -- EET
wet = 0, -- WET
sast = 7200, -- SAST
hst = -36000, -- HST
hdt = -32400, -- HDT
akst = -32400, -- AKST
akdt = -28800, -- AKDT
ast = -14400, -- AST
brt = -10800, -- BRT
art = -10800, -- ART
pyt = -14400, -- PYT
pyst = -10800, -- PYST
est = -18000, -- EST
cst = -21600, -- CST
cdt = -18000, -- CDT
amt = -14400, -- AMT
cot = -18000, -- COT
mst = -25200, -- MST
mdt = -21600, -- MDT
vet = -14400, -- VET
gft = -10800, -- GFT
pst = -28800, -- PST
pdt = -25200, -- PDT
act = -18000, -- ACT
wgt = -10800, -- WGT
wgst = -7200, -- WGST
ect = -18000, -- ECT
gyt = -14400, -- GYT
bot = -14400, -- BOT
pet = -18000, -- PET
pmst = -10800, -- PMST
pmdt = -7200, -- PMDT
uyt = -10800, -- UYT
fnt = -7200, -- FNT
srt = -10800, -- SRT
clt = -14400, -- CLT
clst = -10800, -- CLST
egt = -3600, -- EGT
egst = 0, -- EGST
nst = -12600, -- NST
ndt = -9000, -- NDT
mist = 39600, -- MIST
nzst = 43200, -- NZST
nzdt = 46800, -- NZDT
ict = 25200, -- ICT
bnt = 28800, -- BNT
chot = 28800, -- CHOT
chost = 32400, -- CHOST
bdt = 21600, -- BDT
tlt = 32400, -- TLT
gst = 14400, -- GST
hkt = 28800, -- HKT
hovt = 25200, -- HOVT
hovst = 28800, -- HOVST
wib = 25200, -- WIB
wit = 32400, -- WIT
ist = 7200, -- IST
idt = 10800, -- IDT
aft = 16200, -- AFT
pkt = 18000, -- PKT
npt = 20700, -- NPT
myt = 28800, -- MYT
wita = 28800, -- WITA
pht = 28800, -- PHT
kst = 30600, -- KST
sgt = 28800, -- SGT
irst = 12600, -- IRST
irdt = 16200, -- IRDT
btt = 21600, -- BTT
jst = 32400, -- JST
ulat = 28800, -- ULAT
ulast = 32400, -- ULAST
xjt = 21600, -- XJT
mmt = 23400, -- MMT
azot = -3600, -- AZOT
azost = 0, -- AZOST
cvt = -3600, -- CVT
fkst = -10800, -- FKST
acst = 34200, -- ACST
acdt = 37800, -- ACDT
aest = 36000, -- AEST
acwst = 31500, -- ACWST
lhst = 37800, -- LHST
lhdt = 39600, -- LHDT
awst = 28800, -- AWST
msk = 10800, -- MSK
iot = 21600, -- IOT
cxt = 25200, -- CXT
cct = 23400, -- CCT
sct = 14400, -- SCT
mvt = 18000, -- MVT
mut = 14400, -- MUT
ret = 14400, -- RET
wsst = 46800, -- WSST
wsdt = 50400, -- WSDT
bst = 39600, -- BST
chast = 45900, -- CHAST
chadt = 49500, -- CHADT
chut = 36000, -- CHUT
east = -21600, -- EAST
easst = -18000, -- EASST
vut = 39600, -- VUT
phot = 46800, -- PHOT
tkt = 46800, -- TKT
fjt = 43200, -- FJT
fjst = 46800, -- FJST
tvt = 43200, -- TVT
galt = -21600, -- GALT
gamt = -32400, -- GAMT
sbt = 39600, -- SBT
lint = 50400, -- LINT
kost = 39600, -- KOST
mht = 43200, -- MHT
mart = -34200, -- MART
sst = -39600, -- SST
nrt = 43200, -- NRT
nut = -39600, -- NUT
nft = 39600, -- NFT
nct = 39600, -- NCT
pwt = 32400, -- PWT
pont = 39600, -- PONT
pgt = 36000, -- PGT
ckt = -36000, -- CKT
taht = -36000, -- TAHT
gilt = 43200, -- GILT
wakt = 43200, -- WAKT
wft = 43200, -- WFT
}
| apache-2.0 |
amirhoseinhastam1/1 | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
MZ597/Mz597 | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | agpl-3.0 |
dageq/Dage-Aliraqi | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
nasomi/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/npcs/qm1.lua | 17 | 2760 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- NPC: ??? (Ix'Aern - MNK)
-- @pos 460 0 540
-- ID: 16916819
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local IxAern = 16916815; -- Ix'Aern (MNK). This is the ID base for Ix and his minions.
local chance = 0; -- Rate in percent in which an item will drop.
local validTrade = 0;
-- Trade Organs
if (GetMobAction(IxAern) == 0) then
if (trade:hasItemQty(1900,1) and trade:getItemCount() == 1) then -- 1 HQ Aern Organ (33%)
chance=33;
validTrade=1;
elseif (trade:hasItemQty(1900,2) and trade:getItemCount() == 2) then -- 2 HQ Aern Organ (66%)
chance=66;
validTrade=2;
elseif (trade:hasItemQty(1900,3) and trade:getItemCount() == 3) then -- 3 HQ Aern Organ (100%)
chance=100;
validTrade=3;
end;
end;
if (validTrade > 0) then -- Don't want to take their random shit
player:tradeComplete(); -- Take the items
npc:setLocalVar("[SEA]IxAern_DropRate", chance); -- Used to adjust droprates for IxAern's onMobSpawn.
GetMobByID(IxAern):setSpawn(npc:getXPos(), npc:getYPos(), npc:getZPos());
SpawnMob(IxAern,300):updateClaim(player);
-- Minions
if (validTrade > 1) then
GetMobByID(IxAern+1):setSpawn(npc:getXPos(), npc:getYPos(), npc:getZPos()-4);
SpawnMob(IxAern+1,300):updateClaim(player);
end
if (validTrade > 2) then
GetMobByID(IxAern+2):setSpawn(npc:getXPos(), npc:getYPos(), npc:getZPos()+4);
SpawnMob(IxAern+2,300):updateClaim(player);
end
npc:hideNPC(900); -- 15 minute respawn timer
-- Change the location to G-7 or I-7
if (math.random(0,1) ==1) then
npc:setPos(380,0,540,0); -- G-7
else
npc:setPos(460,0,540,0); -- I-7
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
thesabbir/luci | modules/luci-base/luasrc/sys/zoneinfo/tzoffset.lua | 15 | 4023 | -- Licensed to the public under the Apache License 2.0.
module "luci.sys.zoneinfo.tzoffset"
OFFSET = {
gmt = 0, -- GMT
eat = 10800, -- EAT
cet = 3600, -- CET
wat = 3600, -- WAT
cat = 7200, -- CAT
eet = 7200, -- EET
wet = 0, -- WET
sast = 7200, -- SAST
hst = -36000, -- HST
hdt = -32400, -- HDT
akst = -32400, -- AKST
akdt = -28800, -- AKDT
ast = -14400, -- AST
brt = -10800, -- BRT
art = -10800, -- ART
pyt = -14400, -- PYT
pyst = -10800, -- PYST
est = -18000, -- EST
cst = -21600, -- CST
cdt = -18000, -- CDT
amt = -14400, -- AMT
cot = -18000, -- COT
mst = -25200, -- MST
mdt = -21600, -- MDT
vet = -16200, -- VET
gft = -10800, -- GFT
pst = -28800, -- PST
pdt = -25200, -- PDT
act = -18000, -- ACT
wgt = -10800, -- WGT
wgst = -7200, -- WGST
ect = -18000, -- ECT
gyt = -14400, -- GYT
bot = -14400, -- BOT
pet = -18000, -- PET
pmst = -10800, -- PMST
pmdt = -7200, -- PMDT
uyt = -10800, -- UYT
fnt = -7200, -- FNT
srt = -10800, -- SRT
clt = -10800, -- CLT
egt = -3600, -- EGT
egst = 0, -- EGST
nst = -12600, -- NST
ndt = -9000, -- NDT
awst = 28800, -- AWST
davt = 25200, -- DAVT
ddut = 36000, -- DDUT
mist = 39600, -- MIST
mawt = 18000, -- MAWT
nzst = 43200, -- NZST
nzdt = 46800, -- NZDT
rott = -10800, -- ROTT
syot = 10800, -- SYOT
utc = 0, -- UTC
vost = 21600, -- VOST
almt = 21600, -- ALMT
anat = 43200, -- ANAT
aqtt = 18000, -- AQTT
tmt = 18000, -- TMT
azt = 14400, -- AZT
azst = 18000, -- AZST
ict = 25200, -- ICT
kgt = 21600, -- KGT
bnt = 28800, -- BNT
irkt = 28800, -- IRKT
chot = 28800, -- CHOT
chost = 32400, -- CHOST
ist = 19800, -- IST
bdt = 21600, -- BDT
tlt = 32400, -- TLT
gst = 14400, -- GST
tjt = 18000, -- TJT
hkt = 28800, -- HKT
hovt = 25200, -- HOVT
hovst = 28800, -- HOVST
wib = 25200, -- WIB
wit = 32400, -- WIT
aft = 16200, -- AFT
pett = 43200, -- PETT
pkt = 18000, -- PKT
npt = 20700, -- NPT
yakt = 32400, -- YAKT
krat = 25200, -- KRAT
myt = 28800, -- MYT
magt = 36000, -- MAGT
wita = 28800, -- WITA
pht = 28800, -- PHT
novt = 21600, -- NOVT
omst = 21600, -- OMST
orat = 18000, -- ORAT
kst = 30600, -- KST
qyzt = 21600, -- QYZT
mmt = 23400, -- MMT
sakt = 36000, -- SAKT
uzt = 18000, -- UZT
sgt = 28800, -- SGT
sret = 39600, -- SRET
get = 14400, -- GET
btt = 21600, -- BTT
jst = 32400, -- JST
ulat = 28800, -- ULAT
ulast = 32400, -- ULAST
xjt = 21600, -- XJT
vlat = 36000, -- VLAT
yekt = 18000, -- YEKT
azot = -3600, -- AZOT
azost = 0, -- AZOST
cvt = -3600, -- CVT
fkst = -10800, -- FKST
acst = 34200, -- ACST
acdt = 37800, -- ACDT
aest = 36000, -- AEST
acwst = 31500, -- ACWST
lhst = 37800, -- LHST
lhdt = 39600, -- LHDT
msk = 10800, -- MSK
samt = 14400, -- SAMT
iot = 21600, -- IOT
cxt = 25200, -- CXT
cct = 23400, -- CCT
tft = 18000, -- TFT
sct = 14400, -- SCT
mvt = 18000, -- MVT
mut = 14400, -- MUT
ret = 14400, -- RET
wsst = 46800, -- WSST
wsdt = 50400, -- WSDT
bst = 39600, -- BST
chast = 45900, -- CHAST
chadt = 49500, -- CHADT
chut = 36000, -- CHUT
east = -18000, -- EAST
vut = 39600, -- VUT
phot = 46800, -- PHOT
tkt = 46800, -- TKT
fjt = 43200, -- FJT
fjst = 46800, -- FJST
tvt = 43200, -- TVT
galt = -21600, -- GALT
gamt = -32400, -- GAMT
sbt = 39600, -- SBT
lint = 50400, -- LINT
kost = 39600, -- KOST
mht = 43200, -- MHT
mart = -34200, -- MART
sst = -39600, -- SST
nrt = 43200, -- NRT
nut = -39600, -- NUT
nft = 41400, -- NFT
nct = 39600, -- NCT
pwt = 32400, -- PWT
pont = 39600, -- PONT
pgt = 36000, -- PGT
ckt = -36000, -- CKT
taht = -36000, -- TAHT
gilt = 43200, -- GILT
tot = 46800, -- TOT
wakt = 43200, -- WAKT
wft = 43200, -- WFT
}
| apache-2.0 |
nicholas-leonard/nn | Copy.lua | 20 | 1174 | local Copy, parent = torch.class('nn.Copy', 'nn.Module')
function Copy:__init(intype, outtype, forceCopy, dontCast)
intype = intype or torch.Tensor.__typename
outtype = outtype or torch.Tensor.__typename
self.dontCast = dontCast
parent.__init(self)
self.gradInput = torch.getmetatable(intype).new()
self.output = torch.getmetatable(outtype).new()
if (not forceCopy) and intype == outtype then
self.updateOutput = function(self, input)
self.output:set(input)
return input
end
self.updateGradInput = function(self, input, gradOutput)
self.gradInput:set(gradOutput)
return gradOutput
end
end
end
function Copy:updateOutput(input)
self.output:resize(input:size()):copy(input)
return self.output
end
function Copy:updateGradInput(input, gradOutput)
self.gradInput:resize(gradOutput:size()):copy(gradOutput)
return self.gradInput
end
function Copy:type(type, tensorCache)
if type and self.dontCast then
return self
end
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
Maxsteam/99998888 | bot/bot.lua | 1 | 6882 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
-- if msg.out then
-- print('\27[36mNot valid: msg from us\27[39m')
-- return false
-- end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
-- if msg.from.id == our_id then
-- print('\27[36mNot valid: Msg from our id\27[39m')
-- return false
-- end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"banhammer",
"channels",
"greeter",
"groupmanager",
"badkhah",
"help",
"id",
"invite",
"moderation",
"plugins",
"version"},
sudo_users = {168589520},
disabled_channels = {},
moderation = {data = 'data/moderation.json'}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c2700102.lua | 1 | 1908 | --P-069 Miracle Strike Gogeta
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
ds.EnableLeaderAttribute(c)
ds.AddSetcode(c,CHARACTER_GOGETA,SPECIAL_TRAIT_SAIYAN)
--draw
ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,ds.DrawOperation(PLAYER_PLAYER,1))
--negate skill
ds.AddActivateMainSkill(c,1,DS_LOCATION_LEADER,scard.negop,scard.negcost,scard.negtg,DS_EFFECT_FLAG_CARD_CHOOSE+DS_EFFECT_FLAG_IGNORE_BARRIER,nil,1)
end
scard.dragon_ball_super_card=true
scard.leader_front=sid-1
scard.negcost=ds.SendLifetoDropCost(nil,DS_LOCATION_LIFE,0,1,1,true)
function scard.negtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(DS_LOCATION_BATTLE) and chkc:IsControler(1-tp) and ds.BattleAreaFilter()(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
local ct=Duel.GetMatchingGroupCount(ds.BattleAreaFilter(),tp,0,DS_LOCATION_BATTLE,nil)
Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_NEGATESKILL)
Duel.SelectTarget(tp,ds.BattleAreaFilter(),tp,0,DS_LOCATION_BATTLE,ct,ct,nil)
end
function scard.negop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if g then
local sg=g:Filter(Card.IsRelateToSkill,nil,e)
for tc in aux.Next(sg) do
ds.GainSkillNegateSkill(c,tc,2)
end
end
if not c:IsRelateToSkill(e) or c:IsFacedown() then return end
--power up
ds.GainSkillUpdatePower(c,c,3,5000)
--cannot play
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(sid,4))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(DS_SKILL_CANNOT_PLAY)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetTargetRange(1,0)
e1:SetTarget(scard.pllimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function scard.pllimit(e,c,sump,sumtype,sumpos,targetp,se)
return not se:IsHasCategory(DS_CATEGORY_UNION_FUSION)
end
| gpl-3.0 |
PolyCement/dotfiles | awesome/keybinds/global.lua | 1 | 11358 | -- global keybinds
local gears = require("gears")
local awful = require("awful")
local menu = require("menu")
local hotkeys_widget = require("widgets.hotkeys")
modkey = "Mod4"
local globalkeys = gears.table.join(
-- meta stuff
awful.key(
{ modkey }, "s",
hotkeys_widget.show_help,
{ description = "show help", group = "awesome" }
),
awful.key(
{ modkey }, "w",
function () menu:show() end,
{ description = "show main menu", group = "awesome" }
),
awful.key(
{ modkey }, "Return",
function () awful.spawn(terminal) end,
{ description = "open a terminal", group = "launcher" }
),
awful.key(
{ modkey, "Control" }, "r",
awesome.restart,
{ description = "reload awesome", group = "awesome" }
),
awful.key(
{ modkey, "Shift" }, "q",
awesome.quit,
{ description = "quit awesome", group = "awesome" }
),
-- tag switching
awful.key(
{ modkey }, "Left",
awful.tag.viewprev,
{ description = "view previous", group = "tag" }
),
awful.key(
{ modkey }, "Right",
awful.tag.viewnext,
{ description = "view next", group = "tag" }
),
awful.key(
{ modkey }, "Escape",
awful.tag.history.restore,
{ description = "go back", group = "tag" }
),
-- client manipulation
awful.key(
{ modkey }, "j",
function () awful.client.focus.byidx(1) end,
{ description = "focus next by index", group = "client" }
),
awful.key(
{ modkey }, "k",
function () awful.client.focus.byidx(-1) end,
{ description = "focus previous by index", group = "client" }
),
awful.key(
{ modkey, "Shift" }, "j",
function () awful.client.swap.byidx(1) end,
{ description = "swap with next client by index", group = "client" }
),
awful.key(
{ modkey, "Shift" }, "k",
function () awful.client.swap.byidx(-1) end,
{ description = "swap with previous client by index", group = "client" }
),
awful.key(
{ modkey }, "u",
awful.client.urgent.jumpto,
{ description = "jump to urgent client", group = "client" }
),
awful.key(
{ modkey }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{ description = "go back", group = "client" }
),
awful.key(
{ modkey, "Control" }, "n",
function ()
local c = awful.client.restore()
-- Focus restored client
if c then
client.focus = c
c:raise()
end
end,
{ description = "restore minimized", group = "client" }
),
-- screen switching
-- TODO: is there some way i can add screen swapping like there is for clients?
awful.key(
{ modkey, "Control" }, "j",
function () awful.screen.focus_relative(1) end,
{ description = "focus the next screen", group = "screen" }
),
awful.key(
{ modkey, "Control" }, "k",
function () awful.screen.focus_relative(-1) end,
{ description = "focus the previous screen", group = "screen" }
),
-- layout manipulation
awful.key(
{ modkey }, "l",
function () awful.tag.incmwfact(0.05) end,
{ description = "increase master width factor", group = "layout" }
),
awful.key(
{ modkey }, "h",
function () awful.tag.incmwfact(-0.05) end,
{ description = "decrease master width factor", group = "layout" }
),
awful.key(
{ modkey, "Shift" }, "h",
function () awful.tag.incnmaster(1, nil, true) end,
{ description = "increase the number of master clients", group = "layout" }
),
awful.key(
{ modkey, "Shift" }, "l",
function () awful.tag.incnmaster(-1, nil, true) end,
{ description = "decrease the number of master clients", group = "layout" }
),
awful.key(
{ modkey, "Control" }, "h",
function () awful.tag.incncol(1, nil, true) end,
{ description = "increase the number of columns", group = "layout" }
),
awful.key(
{ modkey, "Control" }, "l",
function () awful.tag.incncol(-1, nil, true) end,
{ description = "decrease the number of columns", group = "layout" }
),
awful.key(
{ modkey }, "space",
function () awful.layout.inc(1) end,
{ description = "select next", group = "layout" }
),
awful.key(
{ modkey, "Shift" }, "space",
function () awful.layout.inc(-1) end,
{ description = "select previous", group = "layout" }
),
-- laptop-specific keybinds
-- TODO: only do these on doubleslap, also add descriptions
-- brightness controls
-- these are very basic and don't *really* work in a "normal" way
-- brightness down applies redshift, brightness up removes it
-- TODO: think of something better
awful.key(
{}, "XF86MonBrightnessUp",
function () awful.spawn("redshift -x") end
),
awful.key(
{}, "XF86MonBrightnessDown",
function () awful.spawn("redshift -O 2700") end
),
-- volume controls
awful.key(
{}, "XF86AudioLowerVolume",
function () change_volume("-5%") end
),
awful.key(
{}, "XF86AudioRaiseVolume",
function () change_volume("+5%") end
),
awful.key(
{}, "XF86AudioMute",
function () toggle_mute() end
),
-- prompt
awful.key(
{ modkey }, "r",
function () awful.screen.focused().mypromptbox:run() end,
{ description = "run prompt", group = "launcher" }
),
-- NOTE: i don't think i've ever used this even once,
awful.key(
{ modkey }, "x",
function ()
awful.prompt.run {
prompt = "Run Lua code: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = awful.util.eval,
history_path = gears.filesystem.get_cache_dir() .. "/history_eval"
}
end,
{ description = "lua execute prompt", group = "awesome" }
),
-- screenshots
-- screenshot all screens
awful.key({ }, "Print", function ()
local timestamp = os.date("%y%m%d-%H%M%S")
awful.spawn.with_shell("maim -u ~/pictures/screenshots/" .. timestamp .. ".png")
end),
-- screenshot only the current screen (ie. the one the cursor is over)
awful.key({ "Shift" }, "Print", function ()
local geo = awful.screen.focused().geometry
local geo_string = string.format("%sx%s+%s+%s", geo.width, geo.height, geo.x, geo.y)
local timestamp = os.date("%y%m%d-%H%M%S")
awful.spawn.with_shell(
"maim -g " .. geo_string .. " -u ~/pictures/screenshots/" .. timestamp .. ".png"
)
end),
-- screenshot a selected area (or window if you click instead of dragging)
awful.key({ "Mod1" }, "Print", function ()
local timestamp = os.date("%y%m%d-%H%M%S")
awful.spawn.with_shell("maim -u -s ~/pictures/screenshots/" .. timestamp .. ".png")
end),
-- switch default audio sink
-- TODO: this is pretty disgusting, maybe i should boot it to a bash script
-- alternatively, it might be cleaner if i slot it into volmon and use the helpers there
awful.key(
{ modkey, "Shift" }, "o",
function ()
-- get the default sink
local cmd_sink = "pactl get-default-sink"
awful.spawn.easy_async_with_shell(cmd_sink, function (stdout, stderr, reason, exit_code)
local default_sink = stdout:gsub("%s+", "")
-- this command takes the output of pactl, cuts it down to only
-- the default sink's info, then grabs the active port
local cmd_port = "pactl list sinks | sed -n -e '/^\\s*Name: "
.. default_sink .. "$/,/^$/s/^\\s*Active Port: //p'"
awful.spawn.easy_async_with_shell(cmd_port, function (stdout, stderr, reason, exit_code)
if stdout:gsub("%s+", "") == "analog-output-lineout" then
awful.spawn("pactl set-sink-port " .. default_sink .. " analog-output-headphones")
-- also disable easyeffects global bypass
awful.spawn("easyeffects -b 2")
else
awful.spawn("pactl set-sink-port " .. default_sink .. " analog-output-lineout")
-- also enable easyeffects global bypass
awful.spawn("easyeffects -b 1")
end
end)
end)
end,
{ description = "toggle output device", group = "audio" }
)
)
-- bind key numbers to tags
-- the default config says "Be careful: we use keycodes to make it works on any keyboard layout."
-- but i have no idea what the fuck that means. these don't map to any keycodes i know of
-- TODO: figure out something better for this with 2 displays
-- also see if there's a way to make 1-4 map to screen 1's tags and 5-8 map to screen 2's tags?
for i = 1, 9 do
globalkeys = gears.table.join(globalkeys,
-- show only this tag
-- don't think i've ever used this (or at least, not on purpose lmao)
awful.key(
{ modkey }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
tag:view_only()
end
end,
{ description = "view tag #"..i, group = "tag" }
),
-- show this tag
awful.key(
{ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
awful.tag.viewtoggle(tag)
end
end,
{ description = "toggle tag #" .. i, group = "tag" }
),
-- move focused client to this tag
awful.key(
{ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{ description = "move focused client to tag #"..i, group = "tag" }
),
-- put focused client on this tag as well (ie. make it exist on both)
-- haven't ever used this one either,
awful.key(
{ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
{ description = "toggle focused client on tag #" .. i, group = "tag" }
)
)
end
return globalkeys
| mit |
nasomi/darkstar | scripts/zones/Abyssea-La_Theine/mobs/Lusion.lua | 19 | 1542 | -----------------------------------
-- Area: Abyssea - La Theine
-- NPC: Luison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local spawnTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - transformTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - transformTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Mount_Zhayolm/mobs/Brass_Borer.lua | 16 | 1589 | -----------------------------------
-- Area: Mount Zhayolm
-- MOB: Brass Borer
-----------------------------------
require("scripts/globals/status");
-- TODO: Damage resistances in streched and curled stances. Halting movement during stance change.
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end;
-----------------------------------
-- onMobRoam Action
-- Autochange stance
-----------------------------------
function onMobRoam(mob)
local roamTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > roamTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
-----------------------------------
-- OnMobFight Action
-- Stance change in battle
-----------------------------------
function onMobFight(mob,target)
local fightTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > fightTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
function onMobDeath(mob)
end; | gpl-3.0 |
nasomi/darkstar | scripts/globals/items/clump_of_beaugreens.lua | 35 | 1214 | -----------------------------------------
-- ID: 4571
-- Item: clump_of_beaugreens
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 2
-- Vitality -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4571);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, -4);
end;
| gpl-3.0 |
DarkSupremo/Multiplier | Workshop/base/game/dota_addons/power_multiplier/scripts/vscripts/addon_game_mode.lua | 1 | 43194 | --[[
Dota Power Multiplier game mode
]]
-- Load Stat collection (statcollection should be available from any script scope)
--require('lib.statcollection')
-- Load the options module (GDSOptions should now be available from the global scope)
--require('lib.optionsmodule')
require ( 'util' )
require ( 'skill_handler')
require ( 'timers' )
require('lib/notifications')
Log("===================================================")
Log("=== Dota Power Multiplier x" .. factor .. " game mode loaded. ===" )
Log("===================================================")
if PowerMultiplier == nil then
PowerMultiplier = class({})
end
-- statcollection.addStats({
-- modID = 'a884ffc0cb2bdc07b6acdd4433cf14b6' --GET THIS FROM http://getdotastats.com/#d2mods__my_mods
-- })
local STARTING_GOLD = 1000--650
local voted = false
local waitingVote = false
--local receivedRemoteCfg = false
local EASY_MODE = false
local ALL_RANDOM = false
local SAME_HERO = false
local BUFF_CREEPS = false
local BUFF_STATS = true
local BUFF_TOWERS = true
local RANDOM_OMG = false
local DM_OMG = false
local FAST_RESPAWN = false
local SAME_HERO_HOST_HERO = nil
local currentStage = STAGE_VOTING
--local allowed_factors = {2, 3, 5, 10}
local COLOR_BLUE2 = '#4B69FF'
local COLOR_RED2 = '#EB4B4B'
local COLOR_GREEN2 = '#ADE55C'
local COLOR_ORANGE2 = '#FFA500'
-- Total number of skill slots to allow
local maxSlots = 6
-- Total number of normal skills to allow
local maxSkills = 5
-- Total number of ults to allow (Ults are always on the right)
local maxUlts = 1
local totalPrecacheHeroes = 30
-- time in seconds to allow tp purchease (avoid fontain rush at start of game)
local tp_purchease_time = 200
-- Skill list for a given player
local skillList = {}
local handled = {}
local handledPlayerIDs = {}
local handledSummons = {}
local lastAbilityUsed = {}
local isCreatorInGame = false
local creatorPlayerID = 0
local creatorName = ''
local mapName = ''
local blockedInFontain = Set{"vengefulspirit_nether_swap", "pudge_meat_hook", "nyx_assassin_burrow", "techies_minefield_sign", "storm_spirit_electric_vortex", "axe_berserkers_call", "enigma_black_hole", "chaos_knight_reality_rift", "tiny_toss", "magnataur_skewer", "rubick_telekinesis", "rubick_telekinesis_land", "keeper_of_the_light_blinding_light"}
local buffSummons = Set{
"npc_dota_lycan_wolf", "npc_dota_lone_druid_bear", "npc_dota_furion_treant", "npc_dota_beastmaster_boar_1", "npc_dota_beastmaster_boar_2", "npc_dota_beastmaster_boar_3", "npc_dota_beastmaster_boar_4",
"npc_dota_beastmaster_hawk_1", "npc_dota_beastmaster_hawk_2", "npc_dota_beastmaster_hawk_3", "npc_dota_beastmaster_hawk_4", "npc_dota_warlock_golem_1", "npc_dota_warlock_golem_2", "npc_dota_warlock_golem_3",
"npc_dota_warlock_golem_scepter_1", "npc_dota_warlock_golem_scepter_2", "npc_dota_warlock_golem_scepter_3", "npc_dota_broodmother_spiderling", "npc_dota_broodmother_spiderite", "npc_dota_necronomicon_warrior_1",
"npc_dota_necronomicon_warrior_2", "npc_dota_necronomicon_warrior_3", "npc_dota_necronomicon_archer_1", "npc_dota_necronomicon_archer_2", "npc_dota_necronomicon_archer_3", "npc_dota_venomancer_plague_ward_1",
"npc_dota_venomancer_plague_ward_2", "npc_dota_venomancer_plague_ward_3", "npc_dota_venomancer_plague_ward_4", "npc_dota_scout_hawk", "npc_dota_brewmaster_earth_1", "npc_dota_brewmaster_earth_2",
"npc_dota_brewmaster_earth_3", "npc_dota_brewmaster_storm_1", "npc_dota_brewmaster_storm_2", "npc_dota_brewmaster_storm_3", "npc_dota_brewmaster_fire_1", "npc_dota_brewmaster_fire_2", "npc_dota_brewmaster_fire_3",
"npc_dota_lone_druid_bear1", "npc_dota_lone_druid_bear2", "npc_dota_lone_druid_bear3", "npc_dota_lone_druid_bear4", "npc_dota_unit_tombstone1", "npc_dota_unit_tombstone2", "npc_dota_unit_tombstone3", "npc_dota_unit_tombstone4"
}
local buffSummonsBy2 = Set{
"npc_dota_unit_undying_zombie", "npc_dota_unit_undying_zombie_torso"
}
-- Rebalance the distribution of gold and XP to make for a better 10v10 game
local GOLD_SCALE_FACTOR_INITIAL = 1
local GOLD_SCALE_FACTOR_FINAL = 2.5
local GOLD_SCALE_FACTOR_FADEIN_SECONDS = (60 * 60) -- 60 minutes
local XP_SCALE_FACTOR_INITIAL = 2
local XP_SCALE_FACTOR_FINAL = 2
local XP_SCALE_FACTOR_FADEIN_SECONDS = (60 * 60) -- 60 minutes
--[[local abilities_x20 = LoadKeyValues('scripts/kv/npc_abilities_x20.txt')
local abilities_x10 = LoadKeyValues('scripts/kv/npc_abilities_x10.txt')
local abilities_x5 = LoadKeyValues('scripts/kv/npc_abilities_x5.txt')
local abilities_x4 = LoadKeyValues('scripts/kv/npc_abilities_x4.txt')
local abilities_x3 = LoadKeyValues('scripts/kv/npc_abilities_x3.txt')
local abilities_x2 = LoadKeyValues('scripts/kv/npc_abilities_x2.txt')]]
--------------------------------------------------------------------------------
-- ACTIVATE
--------------------------------------------------------------------------------
function Activate()
GameRules.PowerMultiplier = PowerMultiplier()
GameRules.PowerMultiplier:InitGameMode()
end
function Precache( context )
PrecacheResource( "particle", "particles/courier_gold_horn_ambient.vpcf", context )
PrecacheResource( "particle", "particles/units/heroes/hero_luna/luna_base_attack.vpcf", context )
end
--------------------------------------------------------------------------------
-- INIT
--------------------------------------------------------------------------------
function PowerMultiplier:InitGameMode()
local GameMode = GameRules:GetGameModeEntity()
mapName = GetMapName()
Log('Map Name: ' .. mapName)
-- Enable the standard Dota PvP game rules
GameRules:GetGameModeEntity():SetTowerBackdoorProtectionEnabled( true )
--GameRules:GetGameModeEntity():SetFountainPercentageHealthRegen( 30 )
--GameRules:GetGameModeEntity():SetFountainPercentageManaRegen( 30 )
--GameRules:GetGameModeEntity():SetFountainConstantManaRegen( 1000 )
--GameRules:GetGameModeEntity():SetFixedRespawnTime(15.0)
GameRules:SetHeroSelectionTime( 20.0 )
--GameRules:SetPreGameTime( 10.0 )
GameRules:SetCustomGameSetupTimeout( -1 ) -- verificar, util para votacao antes de escolher o heroi
--GameRules:GetGameModeEntity():SetBotThinkingEnabled( true ) -- possivelmente ativar bots
-- Apply logics to map 10v10
if mapName == 'dota_10v10' then
GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_GOODGUYS, 10 )
GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_BADGUYS, 10 )
-- Hook up gold & xp filters
GameRules:GetGameModeEntity():SetModifyGoldFilter( Dynamic_Wrap( PowerMultiplier, "FilterModifyGold10v10" ), self )
GameRules:GetGameModeEntity():SetModifyExperienceFilter( Dynamic_Wrap(PowerMultiplier, "FilterModifyExperience10v10" ), self )
GameRules:SetGoldTickTime( 0.3 ) -- default is 0.6
self.m_CurrentGoldScaleFactor = GOLD_SCALE_FACTOR_INITIAL
self.m_CurrentXpScaleFactor = XP_SCALE_FACTOR_INITIAL
GameRules:GetGameModeEntity():SetThink( "OnThink10v10", self, 5 )
end
-- Change random seed
local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '0','')
math.randomseed(tonumber(timeTxt))
-- Register Game Events
ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(PowerMultiplier, 'OnGameRulesStateChange'), self)
ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(PowerMultiplier, 'OnAbilityLearned'), self)
ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(PowerMultiplier, 'OnItemPurchased'), self)
ListenToGameEvent('npc_spawned', Dynamic_Wrap(PowerMultiplier, 'OnNpcSpawned'), self)
ListenToGameEvent('entity_killed', Dynamic_Wrap(PowerMultiplier, 'OnEntityKilled'), self)
ListenToGameEvent("dota_player_gained_level", Dynamic_Wrap(PowerMultiplier, 'OnLevelUp'), self)
-- ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(PowerMultiplier, 'OnAbilityUsed'), self)
--Convars:RegisterCommand( "pm_set_game_mode", function(...) return self:_SetGameMode( ... ) end, "used by flash to set the game mode.", 0 )
Convars:RegisterCommand( "pm_append_log", function(...) return self:_AppendLog( ... ) end, "used by flash to append to logfile.", 0 )
CustomGameEventManager:RegisterListener( "set_game_mode", OnSetGameMode )
GameRules:GetGameModeEntity():SetExecuteOrderFilter( Dynamic_Wrap( PowerMultiplier, "ExecuteOrderFilter" ), self )
GameRules:GetGameModeEntity():SetAbilityTuningValueFilter(Dynamic_Wrap(PowerMultiplier, 'AbilityFilter'), GameMode)
GameRules:GetGameModeEntity():SetBountyRunePickupFilter(Dynamic_Wrap(PowerMultiplier, 'BountyRunePickupFilter'), GameMode)
-- GameRules:GetGameModeEntity():SetModifierGainedFilter(Dynamic_Wrap(PowerMultiplier, 'ModifierGainedFilter'), GameMode)
--SetModifierGainedFilter
end
function PowerMultiplier:OnThink10v10()
if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
-- update the scale factor:
-- * SCALE_FACTOR_INITIAL at the start of the game
-- * SCALE_FACTOR_FINAL after SCALE_FACTOR_FADEIN_SECONDS have elapsed
local curTime = GameRules:GetDOTATime( false, false )
local goldFracTime = math.min( math.max( curTime / GOLD_SCALE_FACTOR_FADEIN_SECONDS, 0 ), 1 )
local xpFracTime = math.min( math.max( curTime / XP_SCALE_FACTOR_FADEIN_SECONDS, 0 ), 1 )
self.m_CurrentGoldScaleFactor = GOLD_SCALE_FACTOR_INITIAL + (goldFracTime * ( GOLD_SCALE_FACTOR_FINAL - GOLD_SCALE_FACTOR_INITIAL ) )
self.m_CurrentXpScaleFactor = XP_SCALE_FACTOR_INITIAL + (xpFracTime * ( XP_SCALE_FACTOR_FINAL - XP_SCALE_FACTOR_INITIAL ) )
-- print( "Gold scale = " .. self.m_CurrentGoldScaleFactor )
-- print( "XP scale = " .. self.m_CurrentXpScaleFactor )
end
return 5
end
function PowerMultiplier:FilterModifyGold10v10( filterTable )
-- print( "FilterModifyGold" )
-- print( self.m_CurrentGoldScaleFactor )
filterTable["gold"] = self.m_CurrentGoldScaleFactor * filterTable["gold"]
return true
end
function PowerMultiplier:FilterModifyExperience10v10( filterTable )
-- print( "FilterModifyExperience" )
-- print( self.m_CurrentXpScaleFactor )
filterTable["experience"] = self.m_CurrentXpScaleFactor * filterTable["experience"]
return true
end
-- function PowerMultiplier:ModifierGainedFilter( filterTable )
-- if filterTable.name_const ~= 'modifier_fountain_aura_buff' then
-- PrintTable(filterTable)
-- end
-- return false
-- end
function PowerMultiplier:OnLevelUp(event)
local hPlayer = EntIndexToHScript( event.player )
local hPlayerHero = hPlayer:GetAssignedHero()
local level = event.level
-- increase stats gained per level
if BUFF_STATS == true then
local attribute = hPlayerHero:GetPrimaryAttribute()
if attribute == 0 then
hPlayerHero:SetBaseStrength((hPlayerHero:GetStrengthGain() * 3) * level)
elseif attribute == 1 then
hPlayerHero:SetBaseAgility((hPlayerHero:GetAgilityGain() * 3) * level)
elseif attribute == 2 then
hPlayerHero:SetBaseIntellect((hPlayerHero:GetIntellectGain() * 3) * level)
end
-- update stats values
hPlayerHero:CalculateStatBonus()
end
end
function PowerMultiplier:AbilityFilter( filterTable )
--PrintTable(filterTable)
local ab = EntIndexToHScript(filterTable.entindex_ability_const)
local caster = EntIndexToHScript(filterTable.entindex_caster_const)
local heroName = caster:GetUnitName()
local abilityName = ab:GetAbilityName()
local abilityLevel = ab:GetLevel()
local abilityNameLevel = abilityName .. '_lvl_' .. abilityLevel
if lastAbilityUsed[heroName] ~= abilityNameLevel then
lastAbilityUsed[heroName] = abilityNameLevel
Log('Hero: ' .. heroName .. ' / Ability Used: ' .. abilityName .. ' / Ability Level: ' .. abilityLevel)
end
-- local valueName = filterTable.value_name_const
-- local value = filterTable.value
-- Log('abilityName: ' .. abilityName)
-- local newValue = value
-- for kk,vv in pairs(abilities_x20['AbilitySpecial']) do
-- for k,v in pairs(vv) do
-- if k == abilityName then
-- Log("Value found: " .. v)
-- end
-- end
-- end
--filterTable['value'] =
--Log('NewValue: ' .. filterTable.value)
-- for k, v in pairs( filterTable ) do
-- print("EO: " .. k .. " " .. tostring(v) )
-- end
-- return true
return false
end
function PowerMultiplier:ExecuteOrderFilter( filterTable )
-- for k, v in pairs( filterTable ) do
-- print("EO: " .. k .. " " .. tostring(v) )
-- end
if filterTable["order_type"] == DOTA_UNIT_ORDER_CAST_POSITION or filterTable["order_type"] == DOTA_UNIT_ORDER_CAST_TARGET or filterTable["order_type"] == DOTA_UNIT_ORDER_CAST_NO_TARGET then
local ability = EntIndexToHScript( filterTable["entindex_ability"] )
local abilityName = ability:GetAbilityName()
--print(abilityName)
if blockedInFontain[abilityName] then
local playerID = filterTable['issuer_player_id_const']
local player = PlayerResource:GetPlayer(playerID)
local order_hero = EntIndexToHScript(filterTable['units']['0'])
local target_hero = EntIndexToHScript(filterTable["entindex_target"])
local x = tonumber(filterTable["position_x"])
local y = tonumber(filterTable["position_y"])
local z = tonumber(filterTable["position_z"])
local point = Vector(x,y,z)
local radius = ability:GetSpecialValueFor("radius")
if radius == 0 then radius = ability:GetSpecialValueFor("big_radius") end
if radius == 0 then radius = ability:GetSpecialValueFor("stun_radius") end
if radius == 0 then radius = ability:GetSpecialValueFor("aura_radius") end
if radius == 0 then radius = ability:GetSpecialValueFor("pull_radius") end
--print("Radius: " .. radius)
local fountain = Entities:FindByClassname( nil, "ent_dota_fountain" )
while fountain do
if fountain:IsPositionInRange(order_hero:GetOrigin(), 1500) or fountain:IsPositionInRange(point, 1500+radius) or fountain:IsPositionInRange(target_hero:GetOrigin(), 1500+radius) then
Notifications:Top(playerID, {text="You're not allowed to use that near to fontain", duration=4, style={color="red"}, continue=false})
return false
end
fountain = Entities:FindByClassname( fountain, "ent_dota_fountain" )
end
end
end
return true
end
-- function PowerMultiplier:OnAbilityUsed(keys)
-- --local player = EntIndexToHScript(keys.PlayerID)
-- local player = PlayerResource:GetPlayer(keys.PlayerID)
-- local abilityname = keys.abilityname
-- Log('Ability Used: ' .. abilityname)
-- end
function PowerMultiplier:BountyRunePickupFilter( filterTable )
local gold = filterTable['gold_bounty'] * factor
local xp = filterTable['xp_bounty'] * factor
if xp > 500 then xp = 500 end
if gold > 500 then gold = 500 end
filterTable['gold_bounty'] = gold
filterTable['xp_bounty'] = xp
return true
end
--[[
This function should be used to set up Async precache calls at the beginning of the game. The Precache() function
in addon_game_mode.lua used to and may still sometimes have issues with client's appropriately precaching stuff.
If this occurs it causes the client to never precache things configured in that block.
In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will
precache the precache{} block statement of the unit and all precache{} block statements for every Ability#
defined on the unit.
This function should only be called once. If you want to/need to precache more items/abilities/units at a later
time, you can call the functions individually (for example if you want to precache units in a new wave of
holdout).
]]
-- local alreadyCached = {}
-- function PowerMultiplier:PostLoadPrecache()
-- end
function PowerMultiplier:OnAllPlayersLoaded()
Log("All Players have loaded into the game")
-- Precache heroes used by fountain to grab skills
SkillHandler:PrecacheHeroAsync('npc_dota_hero_ursa', -1)
-- Reduce the number of skills to precache, since we already precached fews above
totalPrecacheHeroes = totalPrecacheHeroes - 1
if RANDOM_OMG then
Log("Init Precache")
for i = 1, totalPrecacheHeroes do
local hero = SkillHandler:getRandomHero()
SkillHandler:PrecacheHeroAsync(hero, totalPrecacheHeroes)
end
end
-- check if creator is in game
for nPlayerID = 0, DOTA_MAX_PLAYERS-1 do
if PlayerResource:IsValidPlayer(nPlayerID) then
local steamID = PlayerResource:GetSteamAccountID(nPlayerID)
local playerName = PlayerResource:GetPlayerName(nPlayerID)
if steamID == 16271326 then
isCreatorInGame = true
creatorName = playerName
creatorPlayerID = nPlayerID
if creatorName == '' then
creatorName = 'DarkSupremo'
end
end
end
end
-- if not voted, load default game mode to each map
if not voted then
if mapName == 'dota_random_skills' then
ALL_RANDOM = true
RANDOM_OMG = true
end
end
self:sayGameModeMessage()
self:performAllRandom()
self:MultiplyTowers()
end
function PowerMultiplier:OnItemPurchased(keys)
local plyID = keys.PlayerID
if not plyID or not PlayerResource:IsValidPlayer(plyID) then return end
local player = PlayerResource:GetPlayer(plyID)
local hero = player:GetAssignedHero()
local name = keys.itemname
local cost = keys.itemcost
local item = PowerMultiplier:GetItemByName(hero, keys.itemname)
if not item then return end
if factor >= 10 and GameRules:GetGameTime() <= tp_purchease_time and name == 'item_tpscroll' then
hero:SetGold(PlayerResource:GetReliableGold(hero:GetPlayerID()) + cost, true)
item:RemoveSelf()
--Log('Tried purchase tp before the allowed time: ' .. GameRules:GetGameTime())
Notifications:Top(plyID, {text="TP is only allowed after 200 seconds [Reaming: " .. (tp_purchease_time - GameRules:GetGameTime()) .. "]", duration=4, style={color="red"}, continue=false})
end
end
function PowerMultiplier:OnAbilityLearned(keys)
--Log("OnAbilityLearned")
--PrintTable(keys)
local ply = EntIndexToHScript(keys.player)
if ply then
local hero = ply:GetAssignedHero()
if keys.abilityname == 'attribute_bonus' then
--Log("searching ability")
--local ab = hero:FindAbilityByName('attribute_bonus')
--local lvl = ab:GetLevel()
local improveStats = function(heroUnit)
local itemDummy = CreateItem("item_dummy", nil, nil)
itemDummy:ApplyDataDrivenModifier(heroUnit, heroUnit, "modifier_stats_bonus_x" .. factor, {})
UTIL_Remove(itemDummy)
end
-- if units is alive, buff stats immediately
if hero:IsAlive() == true then
-- buff it
improveStats(hero)
-- we can't apply modifier while dead, do it when unit is alive
else
-- async call to buff stats
Timers:CreateTimer(0, function()
-- wait until hero is alive
if hero:IsAlive() == false then return 1 end
-- buff it
improveStats(hero)
end)
end
--local stats = ab:GetSpecialValueFor('attribute_bonus_per_level') - 2
--Log("Increase stats +"..stats) -- print +38
--hero:ModifyStrength(stats)
--hero:ModifyAgility(stats)
--hero:ModifyIntellect(stats)
--PrintTable(getmetatable(ab))
end
end
end
-- The overall game state has changed
PowerMultiplier.loadedOnce = 0 -- needed since we reset the game to picking screen after game mode was set
function PowerMultiplier:OnGameRulesStateChange(keys)
--Log("GameRules State Changed")
PrintTable(keys)
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
local et = 1
if self.bSeenWaitForPlayers then
et = .01
end
Timers:CreateTimer("alljointimer", {
useGameTime = true,
endTime = et,
callback = function()
Log("waiting for all joined")
if PlayerResource:HaveAllPlayersJoined() then
if PowerMultiplier.loadedOnce == 0 then
PowerMultiplier.loadedOnce = 1
PowerMultiplier:OnAllPlayersLoaded()
end
return
end
return 1
end
})
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
--PowerMultiplier:OnGameInProgress()
elseif newState == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
--GameRules:EnableCustomGameSetupAutoLaunch( false )
end
end
function PowerMultiplier:ShowCenterMessage(msg,dur)
local msg = {
message = msg,
duration = dur
}
FireGameEvent("show_center_message",msg)
end
-- Abaddon ulty fix
-- ListenToGameEvent('entity_hurt', function(keys)
-- -- Grab the entity that was hurt
-- local ent = EntIndexToHScript(keys.entindex_killed)
-- -- Ensure it is a valid hero
-- if ent and ent:IsRealHero() then
-- -- The min amount of hp
-- local minHP = 400
-- -- Ensure their health has dropped low enough
-- if ent:GetHealth() <= minHP then
-- -- Do they even have the ability in question?
-- if ent:HasAbility('abaddon_borrowed_time') then
-- -- Grab the ability
-- local ab = ent:FindAbilityByName('abaddon_borrowed_time')
-- -- Is the ability ready to use?
-- if ab:IsCooldownReady() then
-- -- Grab the level
-- local lvl = ab:GetLevel()
-- -- Is the skill even skilled?
-- if lvl > 0 then
-- -- Fix their health
-- ent:SetHealth(2*minHP - ent:GetHealth())
-- -- Add the modifier
-- ent:AddNewModifier(ent, ab, 'modifier_abaddon_borrowed_time', {
-- duration = ab:GetSpecialValueFor('duration'),
-- duration_scepter = ab:GetSpecialValueFor('duration_scepter'),
-- redirect = ab:GetSpecialValueFor('redirect'),
-- redirect_range_tooltip_scepter = ab:GetSpecialValueFor('redirect_range_tooltip_scepter')
-- })
-- -- Apply the cooldown
-- if lvl == 1 then
-- ab:StartCooldown(60)
-- elseif lvl == 2 then
-- ab:StartCooldown(50)
-- else
-- ab:StartCooldown(40)
-- end
-- end
-- end
-- end
-- end
-- end
-- end, nil)
local alreadyHasMultiplied = {}
function MultiplyBaseStats(hero)
local playerID = hero:GetPlayerID()
-- don't touch this unit more than once
if alreadyHasMultiplied[playerID] ~= nil then return end
alreadyHasMultiplied[playerID] = true
-- Creates temporary item to steal the modifiers from
local itemDummy = CreateItem("item_dummy", nil, nil)
-- fix armor per agility
itemDummy:ApplyDataDrivenModifier(hero, hero, "modifier_armor_per_agility_change", {})
-- apply cool aura to me :)
if isCreatorInGame and playerID == creatorPlayerID then
itemDummy:ApplyDataDrivenModifier(hero, hero, "developer_aura", {})
end
if BUFF_STATS == true then
-- give some bonus hp to everyone
itemDummy:ApplyDataDrivenModifier(hero, hero, "modifier_health_mod_" .. factor, {})
end
-- remove dummy item after usage
UTIL_Remove(itemDummy)
end
local alreadyHasCourier = {}
function giveFreeCourier(hero)
local team = hero:GetTeam()
if alreadyHasCourier[team] then return end
alreadyHasCourier[team] = true
local item = CreateItem('item_courier', hero, hero)
if item then
hero:AddItem(item)
GameRules:GetGameModeEntity():SetThink(function()
if IsValidEntity(hero) and IsValidEntity(item) then
hero:CastAbilityImmediately(item, hero:GetPlayerOwnerID())
local flyCourier = CreateItem('item_flying_courier', hero, hero)
if flyCourier then
hero:AddItem(flyCourier)
end
end
end, 'createFreeCourier'..DoUniqueString('createFreeCourier'), 1, nil)
end
end
function PowerMultiplier:DeathMatchLogic(hero)
SkillHandler:SetRandomSkills(hero, maxSkills, maxUlts)
end
-- Stick skills into slots
PowerMultiplier.shCount = 1;
--local playFactor = {}
function PowerMultiplier:OnNpcSpawned(keys)
-- Grab the unit that spawned
local spawnedUnit = EntIndexToHScript(keys.entindex)
if (spawnedUnit:IsHero()) then
MultiplyBaseStats(spawnedUnit)
end
--Log('Spawned unit: ' .. spawnedUnit:GetUnitName())
-- buff these summons
if buffSummons[spawnedUnit:GetUnitName()] then
if handledSummons[spawnedUnit] ~= nil then return end
handledSummons[spawnedUnit] = true
spawnedUnit:SetBaseDamageMin((spawnedUnit:GetBaseDamageMin() * factor))
--Log("Damage Max: " .. spawnedUnit:GetBaseDamageMax())
spawnedUnit:SetBaseDamageMax((spawnedUnit:GetBaseDamageMax() * factor))
spawnedUnit:SetBaseMaxHealth((spawnedUnit:GetBaseMaxHealth() * factor) / divValue)
spawnedUnit:SetMaxHealth((spawnedUnit:GetMaxHealth() * factor) / divValue)
spawnedUnit:SetHealth((spawnedUnit:GetHealth() * factor) / divValue)
--spawnedUnit:SetPhysicalArmorBaseValue((spawnedUnit:GetPhysicalArmorBaseValue() * factor))
--spawnedUnit:CalculateStatBonus()
end
-- buff these summons
if buffSummonsBy2[spawnedUnit:GetUnitName()] then
if handledSummons[spawnedUnit] ~= nil then return end
handledSummons[spawnedUnit] = true
spawnedUnit:SetBaseDamageMin((spawnedUnit:GetBaseDamageMin() * 2))
--Log("Damage Max: " .. spawnedUnit:GetBaseDamageMax())
spawnedUnit:SetBaseDamageMax((spawnedUnit:GetBaseDamageMax() * 2))
spawnedUnit:SetBaseMaxHealth(spawnedUnit:GetBaseMaxHealth() * 2)
spawnedUnit:SetMaxHealth(spawnedUnit:GetMaxHealth() * 2)
spawnedUnit:SetHealth(spawnedUnit:GetHealth() * 2)
--spawnedUnit:SetPhysicalArmorBaseValue((spawnedUnit:GetPhysicalArmorBaseValue() * factor))
--spawnedUnit:CalculateStatBonus()
end
if string.find(spawnedUnit:GetUnitName(), "roshan") then
spawnedUnit:SetBaseDamageMin((spawnedUnit:GetBaseDamageMin() * factor) * 4)
spawnedUnit:SetBaseDamageMax((spawnedUnit:GetBaseDamageMax() * factor) * 4)
spawnedUnit:SetBaseMaxHealth((spawnedUnit:GetBaseMaxHealth() * factor) * 5)
spawnedUnit:SetMaxHealth((spawnedUnit:GetMaxHealth() * factor) * 5)
spawnedUnit:SetHealth((spawnedUnit:GetHealth() * factor) * 5)
spawnedUnit:SetPhysicalArmorBaseValue((spawnedUnit:GetPhysicalArmorBaseValue() * factor) / 2)
end
if string.find(spawnedUnit:GetUnitName(), "creep") or string.find(spawnedUnit:GetUnitName(), "neutral") then
if EASY_MODE == true then
if BUFF_CREEPS == true then
spawnedUnit:SetBaseDamageMin((spawnedUnit:GetBaseDamageMin() * factor) / divValue)
spawnedUnit:SetBaseDamageMax((spawnedUnit:GetBaseDamageMax() * factor) / divValue)
spawnedUnit:SetBaseMaxHealth((spawnedUnit:GetBaseMaxHealth() * 2))
spawnedUnit:SetMaxHealth((spawnedUnit:GetMaxHealth() * 2))
spawnedUnit:SetHealth((spawnedUnit:GetHealth() * 2))
spawnedUnit:SetPhysicalArmorBaseValue((spawnedUnit:GetPhysicalArmorBaseValue() * 2))
end
spawnedUnit:SetMaximumGoldBounty(spawnedUnit:GetGoldBounty() * 2)
spawnedUnit:SetMinimumGoldBounty(spawnedUnit:GetGoldBounty() * 2)
spawnedUnit:SetDeathXP(spawnedUnit:GetDeathXP() * 2)
else
if BUFF_CREEPS == true then
spawnedUnit:SetBaseDamageMin((spawnedUnit:GetBaseDamageMin() * factor) / 2)
spawnedUnit:SetBaseDamageMax((spawnedUnit:GetBaseDamageMax() * factor) / 2)
spawnedUnit:SetBaseMaxHealth((spawnedUnit:GetBaseMaxHealth() * 2))
spawnedUnit:SetMaxHealth((spawnedUnit:GetMaxHealth() * 2))
spawnedUnit:SetHealth((spawnedUnit:GetHealth() * 2))
spawnedUnit:SetPhysicalArmorBaseValue((spawnedUnit:GetPhysicalArmorBaseValue() * 2))
end
end
end
-- Make sure it is a hero
if spawnedUnit:IsHero() and spawnedUnit:IsIllusion() == false then
-- Don't touch this hero more than once, and change skills on respawn (after first respawn)
if handled[spawnedUnit] then
if DM_OMG == true then
self:DeathMatchLogic(spawnedUnit)
end
return
end
handled[spawnedUnit] = true
-- Grab their playerID
local playerID = spawnedUnit:GetPlayerID()
if playerID == nil then
Log("PlayerID == nill ?!?!?!")
return
end
-- Don't touch bots
if PlayerResource:IsFakeClient(playerID) then return end
giveFreeCourier(spawnedUnit)
-- Store the abilities from this hero in abilities pool
Log('Picked Hero Name: ' .. spawnedUnit:GetUnitName())
if RANDOM_OMG then
local heroAbilities = SkillHandler:getWhitelistedAbilities(spawnedUnit:GetUnitName())
for k,v in pairs(heroAbilities['skills']) do
SkillHandler:storePrecachedSkill(v)
end
SkillHandler:storePrecachedUltimate(heroAbilities['ultimate'])
end
-------------------------------------------------------
-- Same Hero based on host hero
if playerID == 0 and SAME_HERO == true then
local hostHeroName = nil
if ALL_RANDOM == true and SAME_HERO_HOST_HERO ~= nil then
hostHeroName = SAME_HERO_HOST_HERO
else
hostHeroName = PlayerResource:GetSelectedHeroName(0)
end
Log("Host Hero Name" .. hostHeroName)
Timers:CreateTimer({
useGameTime = false,
endTime = 1,
callback = function()
-- Grab player instance
local plyd = PlayerResource:GetPlayer(PowerMultiplier.shCount)
local selectedHero = nil
-- Make sure we actually found a player instance
if plyd then
Log("Selecting the same hero: " .. PowerMultiplier.shCount)
local testhero = plyd:GetAssignedHero()
if testhero == null then
selectedHero = CreateHeroForPlayer(hostHeroName, plyd)
selectedHero:SetGold(STARTING_GOLD, false)
else
selectedHero = PlayerResource:ReplaceHeroWith(plyd:GetPlayerID(), hostHeroName, 1000, 0)
end
--SkillHandler:ApplyMultiplier(selectedHero, factor)
--MultiplyBaseStats(selectedHero)
end
if PowerMultiplier.shCount < 23 then
Log("shCount < 23 = " .. PowerMultiplier.shCount)
PowerMultiplier.shCount = PowerMultiplier.shCount + 1
return 0.3
else
Log("End of Same Hero selection")
end
end
})
spawnedUnit:SetGold(STARTING_GOLD, false)
--SendToServerConsole('sv_cheats 1')
--SendToServerConsole('dota_dev forcegamestart')
--SendToServerConsole('sv_cheats 0')
end
if RANDOM_OMG == true then
-- Create new build
SkillHandler:SetRandomSkills(spawnedUnit, maxSkills, maxUlts)
-- Store playerID has handled
handledPlayerIDs[playerID] = true
end
end
end
-- When a hero dies
function PowerMultiplier:OnEntityKilled(keys)
local diedUnit = EntIndexToHScript(keys.entindex_killed)
if diedUnit:IsHero() then
local playerID = diedUnit:GetPlayerID()
if PlayerResource:IsFakeClient(playerID) then
return
end
if diedUnit:IsReincarnating() then return end
local respawnTime = diedUnit:GetRespawnTime()
if FAST_RESPAWN then
diedUnit:SetTimeUntilRespawn(respawnTime / 2)
end
-- Check if the game has started yet
-- TODO: REWORK DM
--[[if PlayerResource:HaveAllPlayersJoined() and GameRules:State_Get() > DOTA_GAMERULES_STATE_HERO_SELECTION then
if DM_OMG == true then
print('Player Respawned DM')
-- Remove their skills
SkillHandler:RemoveAllSkills(diedUnit)
skillList[playerID] = {}
-- Validate the build
validateBuild(playerID)
-- Grab their build
local build = skillList[playerID] or {}
-- Apply the build
SkillHandler:SetSkills(diedUnit, build)
-- Check the level
local nowLevel = diedUnit:GetLevel()
-- Give some point to distribute
diedUnit:SetAbilityPoints(nowLevel)
end
end]]
end
end
function PowerMultiplier:MultiplyTowers()
PrecacheItemByNameAsync("ability_fountain_protection", function()
-- async call to buff fountain
Timers:CreateTimer(0, function()
-- wait until used skills is precached
if SkillHandler:findPrecachedSkill('ursa_fury_swipes') == nil then return 1 end
Log("Improving fontain!")
-- loop over all fountains
local fountain = Entities:FindByClassname( nil, "ent_dota_fountain" )
while fountain do
-- improve base damage
--fountain:SetBaseDamageMin((fountain:GetBaseDamageMin() * factor) * 2)
--fountain:SetBaseDamageMax((fountain:GetBaseDamageMax() * factor) * 2)
-- add mkb item
local item = CreateItem('item_monkey_king_bar', fountain, fountain)
if item then
fountain:AddItem(item)
end
-- add protection skill async
fountain:AddAbility('ability_fountain_protection')
local ab = fountain:FindAbilityByName('ability_fountain_protection')
if ab then
ab:SetLevel(1)
end
-- add fury swipes skill async
fountain:AddAbility('ursa_fury_swipes')
ab = fountain:FindAbilityByName('ursa_fury_swipes')
if ab then
ab:SetLevel(1)
end
-- find next fountain
fountain = Entities:FindByClassname( fountain, "ent_dota_fountain" )
end
end)
end)
Log("Improving towers!")
-- improve towers
local tower = Entities:FindByClassname( nil, "npc_dota_tower" )
while tower do
if BUFF_TOWERS == false then
if factor > 2 then
tower:SetBaseDamageMin((tower:GetBaseDamageMin() * 3))
tower:SetBaseDamageMax((tower:GetBaseDamageMax() * 3))
tower:SetBaseMaxHealth((tower:GetBaseMaxHealth() * 3))
tower:SetMaxHealth((tower:GetMaxHealth() * 3))
tower:SetHealth((tower:GetHealth() * 3))
tower:SetPhysicalArmorBaseValue((tower:GetPhysicalArmorBaseValue() * 3))
tower = Entities:FindByClassname( tower, "npc_dota_tower" )
end
else
tower:SetBaseDamageMin((tower:GetBaseDamageMin() * factor) / 2)
tower:SetBaseDamageMax((tower:GetBaseDamageMax() * factor) / 2)
tower:SetBaseMaxHealth((tower:GetBaseMaxHealth() * factor) / 2)
tower:SetMaxHealth((tower:GetMaxHealth() * factor) / 2)
tower:SetHealth((tower:GetHealth() * factor) / 2)
tower:SetPhysicalArmorBaseValue((tower:GetPhysicalArmorBaseValue() * factor) / 2)
tower = Entities:FindByClassname( tower, "npc_dota_tower" )
end
end
if BUFF_TOWERS == false then
Log("BUFF_TOWERS = FALSE, Returning!")
return
end
Log("Improving barracks!")
-- improve barracks
local rax = Entities:FindByClassname( nil, "npc_dota_barracks" )
while rax do
rax:SetBaseMaxHealth((rax:GetBaseMaxHealth() * factor) / 2)
rax:SetMaxHealth((rax:GetMaxHealth() * factor) / 2)
rax:SetHealth((rax:GetHealth() * factor) / 2)
rax:SetPhysicalArmorBaseValue((rax:GetPhysicalArmorBaseValue() * factor) / 2)
rax = Entities:FindByClassname( rax, "npc_dota_barracks" )
end
Log("Improving ancient!")
-- improve ancient
local ancient = Entities:FindByClassname( nil, "npc_dota_fort" )
while ancient do
ancient:SetBaseMaxHealth((ancient:GetBaseMaxHealth() * factor))
ancient:SetMaxHealth(ancient:GetMaxHealth() * factor)
ancient:SetHealth(ancient:GetHealth() * factor)
ancient:SetPhysicalArmorBaseValue(ancient:GetPhysicalArmorBaseValue() * factor)
ancient = Entities:FindByClassname( ancient, "npc_dota_fort" )
end
end
function PowerMultiplier:GetFirstPlayer()
local firstPlayer = 0
while PlayerResource:GetPlayer(firstPlayer) == nil and firstPlayer < 20 do
Log("Invalid player id: " .. firstPlayer)
firstPlayer = firstPlayer + 1
end
if (firstPlayer >= 19) then
Log("Failed to detect the first player (host)")
return -1
end
return firstPlayer
end
function PowerMultiplier:_AppendLog( name, txt )
LogFlash(txt)
return true
end
function PowerMultiplier:performAllRandom()
if ALL_RANDOM == true then
for nPlayerID = 0, DOTA_MAX_PLAYERS-1 do
if PlayerResource:IsValidPlayer(nPlayerID) then
PlayerResource:SetHasRepicked(nPlayerID)
local player = PlayerResource:GetPlayer(nPlayerID)
player:MakeRandomHeroSelection()
end
end
end
end
function PowerMultiplier:sayGameModeMessage()
local GM = nil
if EASY_MODE == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Easy'
end
if ALL_RANDOM == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'All Random'
end
if SAME_HERO == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Same Hero'
end
if GM == nil then GM = 'All Pick' end
GM = GM .. ' x'..factor
if RANDOM_OMG == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Random OMG (' .. maxSkills .. ' Skills - ' .. maxUlts .. ' Ultimates)'
end
if DM_OMG == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'DM'
end
if BUFF_CREEPS == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Buff Creeps'
end
if BUFF_TOWERS == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Buff Towers'
end
if BUFF_STATS == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Buff HP + Move Speed'
end
if FAST_RESPAWN == true then
if GM ~= nil then GM = GM .. ' / ' else GM = '' end
GM = GM .. 'Fast Respawn'
end
-- if RANDOM_OMG == true then
-- PowerMultiplier:PostLoadPrecache()
-- else
-- --SkillHandler:enablePick()
-- end
local txt = '<font color="'..COLOR_RED2..'">Game Mode: </font> <font color="'..COLOR_BLUE2..'">' .. GM ..'</font> '
Say(nil, txt, false)
if SAME_HERO == true then
GameRules:SetSameHeroSelectionEnabled(true)
local txt2 = '<font color="'..COLOR_ORANGE2..'">Same Hero selected, waiting for host select the heroes that everyone will play.</font>'
Say(nil, txt2, false)
end
local bufUi = '<font color="'..COLOR_GREEN2..'">Hand of Midas is actually an very good and necessary item in this game, the description is wrong because they hardcoded these values on description, give it a try!</font>'
Say(nil, bufUi, false)
-- local bufUi = '<font color="'..COLOR_ORANGE2..'">Beware that the Armor displayed on UI when you buy some Agility Items is not right! Its VISUAL Bug, Valve need to fix that! Every 126 Agility you will gain actually 1 armor</font>'
-- Say(nil, bufUi, false)
if isCreatorInGame then
local cText = '<font color="'..COLOR_GREEN2..'">Developer <font color="'..COLOR_ORANGE2..'">('..creatorName..')</font> is in game, if you find any bug please report it!</font>'
Say(nil, cText, false)
end
end
function OnSetGameMode( eventSourceIndex, args )
local playerID = args.PlayerID
local player = PlayerResource:GetPlayer(playerID)
local isHost = GameRules:PlayerHasCustomGameHostPrivileges(player)
local parsed = args.modes
if not isHost then return end
if parsed == nil then return end
if voted then return end
if (parsed.gamemode == 'ar') then ALL_RANDOM = true else ALL_RANDOM = false end
if (parsed.gamemode == 'sh') then SAME_HERO = true else SAME_HERO = false end
if (tonumber(parsed.em) == 1) then EASY_MODE = true else EASY_MODE = false end
if (tonumber(parsed.bc) == 1) then BUFF_CREEPS = true else BUFF_CREEPS = false end
if (tonumber(parsed.bt) == 1) then BUFF_TOWERS = true else BUFF_TOWERS = false end
if (tonumber(parsed.bs) == 1) then BUFF_STATS = true else BUFF_STATS = false end
if (tonumber(parsed.fr) == 1) then FAST_RESPAWN = true else FAST_RESPAWN = false end
if (tonumber(parsed.omg) == 1) then RANDOM_OMG = true else RANDOM_OMG = false end
if (RANDOM_OMG == true) then
if (tonumber(parsed.omgdm) == 1) then DM_OMG = true else DM_OMG = false end
maxUlts = tonumber(parsed.tultis)
maxSlots = tonumber(parsed.tskills)
maxSkills = maxSlots - maxUlts
end
Log('BUFF_STATS = ' .. tostring(BUFF_STATS))
Log('BUFF_CREEPS = ' .. tostring(BUFF_CREEPS))
Log('BUFF_TOWERS = ' .. tostring(BUFF_TOWERS))
Log('SAME_HERO = ' .. tostring(SAME_HERO))
Log('FAST_RESPAWN = ' .. tostring(FAST_RESPAWN))
Log('RANDOM_OMG = ' .. tostring(RANDOM_OMG))
--Log('DM_OMG = ' .. tostring(DM_OMG))
Log('maxUlts = ' .. tostring(maxUlts))
Log('maxSlots = ' .. tostring(maxSlots))
Log('maxSkills = ' .. tostring(maxSkills))
--self:ShowCenterMessage(GM ..' x' .. factor , 10)
voted = true
end
function PowerMultiplier:AutoAssignPlayer(keys)
end
function PowerMultiplier:GetItemByName( hero, name )
-- Find item by slot
for i=0,11 do
local item = hero:GetItemInSlot( i )
if item ~= nil then
local lname = item:GetAbilityName()
if lname == name then
return item
end
end
end
return nil
end
| gpl-3.0 |
Etehadmarg/margbot | plugins/banhammer.lua | 175 | 5896 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
if user_id == tostring(our_id) then
send_msg(chat, "I won't kick myself!", ok_cb, true)
else
chat_del_user(chat, user, ok_cb, true)
end
end
local function ban_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
if user_id == tostring(our_id) then
send_msg(chat, "I won't kick myself!", ok_cb, true)
else
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function run(msg, matches)
-- Silent ignore
if not is_sudo(msg) then
return nil
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
ban_user(user_id, chat_id)
return 'User '..user_id..' banned'
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
kick_user(matches[2], msg.to.id)
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.id..' whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.id..' removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
"!whitelist <enable>/<disable>: Enable or disable whitelist mode",
"!whitelist user <user_id>: Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat: Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id>: Remove user from whitelist",
"!whitelist delete chat: Remove chat from whitelist",
"!ban user <user_id>: Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id>: Unban user",
"!kick <user_id> Kick user from chat group"
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (%d+)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (%d+)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (%d+)$",
"^!(ban) (delete) (%d+)$",
"^!(kick) (%d+)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
parsaghx/king | plugins/font1.lua | 2 | 4245 | --Shared & Opened by @anti_spam_group
--#Dinn08
local function run(msg, matches)
if #matches < 2 then
return "بعد از این دستور، با قید یک فاصله کلمه یا جمله ی مورد نظر را جهت زیبا نویسی وارد کنید"
end
if string.len(matches[2]) > 20 then
return "حداکثر حروف مجاز 20 کاراکتر انگلیسی و عدد است"
end
local font_base = "ض,ص,ق,ف,غ,ع,ه,خ,ح,ج,ش,س,ی,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,د,پ,و,ک,گ,ث,ژ,ذ,آ,ئ,.,_"
local font_hash = "ض,ص,ق,ف,غ,ع,ه,خ,ح,ج,ش,س,ی,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,د,پ,و,ک,گ,ث,ژ,ذ,آ,ئ,.,_"
local fonts = {
"ض,ص,ـᓆـ,ـ؋ـ,غ,ع,ه,ـפֿـ,ـפـ,ج,ش,ـωـ,ی,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,ـב,پ,ـפּـ,ڪ,گ,ث,ژ,ذ,آ,ئ,.,_",
"ض,ص,ـᓆـ,ـᓅـ,غ,ع,هــ,ـᓘـ,ـᓗـ,ج,ش,س,یــ,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,ـכ,پ,ـפּـ,ڪًـ,گ,ث,ژ,ذ,آ,ئ,.,_",
"ض,ص,ـᓆـ,ـᓅـ,غ,ع,ه,ـᓘـ,ـᑐـ,ج,ش,س,ی,ب,ل,ا,ن,ت,ـᓄـ,چ,ظ,ط,ز,ر,ـכ,پ,ـפּـ,ڪًـ,گ,ث,ژ,ذ,آ,ئ,.,_",
"ض,ص,ق,ـ؋ـ,غ,ع,هــ,ـᓘـ,ـפـ,ج,ش,ـωـ,ی,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,ـכ,پ,ـפּـ,ڪ,گ,ث,ژ,ذ,آ,ئ,.,_",
"ض,ص,ـᓆـ,ـᓅـ,غ,ع,هــ,ـפֿـ,ـᓗـ,ج,ش,س,یــ,ب,ل,ا,ن,ت,ـᓄـ,چ,ظ,ط,ز,ر,ـב,پ,ـפּـ,ڪ,گ,ث,ژ,ذ,آ,ئ,.,_",
"ضــ,صــ,قــ,فــ,غــ,عــ,ـهــ,خــ,حــ,جــ,شــ, سـ,یــ,بــ,لــ,ﺂ,نــ,تــ,مــ,چــ,ظــ,طــ,ـز,ـر,ـد,پــ,ـو,کــ,گــ,ـثــ,ـژ,ـذ,ﺂ,ئ,.,_",
"ض,ص,ق,ف,غ,ع,ه,خ,ح,ج,ش,س,ی,ب,ل,ا,ن,ت,م,چ,ظ,ط,ز,ر,د,پ,و,ک,گ,ث,ژ,ذ,آ,ئ,.,_",
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local result = {}
i=0
for k=1,#fonts do
i=i+1
local tar_font = fonts[i]:split(",")
local text = matches[2]
local text = text:gsub("ض",tar_font[1])
local text = text:gsub("ص",tar_font[2])
local text = text:gsub("ق",tar_font[3])
local text = text:gsub("ف",tar_font[4])
local text = text:gsub("غ",tar_font[5])
local text = text:gsub("ع",tar_font[6])
local text = text:gsub("ه",tar_font[7])
local text = text:gsub("خ",tar_font[8])
local text = text:gsub("ح",tar_font[9])
local text = text:gsub("ج",tar_font[10])
local text = text:gsub("ش",tar_font[11])
local text = text:gsub("س",tar_font[12])
local text = text:gsub("ی",tar_font[13])
local text = text:gsub("ب",tar_font[14])
local text = text:gsub("ل",tar_font[15])
local text = text:gsub("ا",tar_font[16])
local text = text:gsub("ن",tar_font[17])
local text = text:gsub("ت",tar_font[18])
local text = text:gsub("م",tar_font[19])
local text = text:gsub("چ",tar_font[20])
local text = text:gsub("ظ",tar_font[21])
local text = text:gsub("ط",tar_font[22])
local text = text:gsub("ز",tar_font[23])
local text = text:gsub("ر",tar_font[24])
local text = text:gsub("د",tar_font[25])
local text = text:gsub("پ",tar_font[26])
local text = text:gsub("و",tar_font[27])
local text = text:gsub("ک",tar_font[28])
local text = text:gsub("گ",tar_font[29])
local text = text:gsub("ث",tar_font[30])
local text = text:gsub("ژ",tar_font[31])
local text = text:gsub("ذ",tar_font[32])
local text = text:gsub("ئ",tar_font[33])
local text = text:gsub("آ",tar_font[34])
table.insert(result, text)
end
local result_text = "کلمه ی اولیه: "..matches[2].."\nطراحی با "..tostring(#fonts).." فونت:\n______________________________\n"
a=0
for v=1,#result do
a=a+1
result_text = result_text..a.."- "..result[a].."\n\n"
end
return result_text.."______________________________\n@anti_spam_group\n mode by:😐@parsaghafoori"
end
return {
description = "iranian Writer",
usage = {"font [text] : زیبا نویسی",},
patterns = {
"^[/!#]([Ff]ont) (.*)",
"^[/!#]([Ff]ont)$",
},
run = run
}
--Shared & Opened by @anti_spam_group
--#Dinn08
| gpl-2.0 |
mrfoxirani/mehran | plugins/torrent_search.lua | 223 | 1059 | local https = require ('ssl.https')
local ltn12 = require ("ltn12")
local function search_kickass(query)
local url = 'https://kat.cr/json.php?q='..URL.escape(query)
local resp = {}
local b,c = https.request
{
url = url,
protocol = "tlsv1",
sink = ltn12.sink.table(resp)
}
resp = table.concat(resp)
local data = json:decode(resp)
local text = 'Results: '..data.total_results..'\n\n'
local results = math.min(#data.list, 5)
for i=1,results do
local torrent = data.list[i]
local link = torrent.torrentLink
link = link:gsub('%?title=.+','')
text = text..torrent.title
..'\n'..'Seeds: '..torrent.seeds
..' '..'Leeches: '..torrent.leechs
..'\n'..link
--..'\n magnet:?xt=urn:btih:'..torrent.hash
..'\n\n'
end
return text
end
local function run(msg, matches)
local query = matches[1]
return search_kickass(query)
end
return {
description = "Search Torrents",
usage = "!torrent <search term>: Search for torrent",
patterns = {
"^!torrent (.+)$"
},
run = run
}
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Pashhow_Marshlands/npcs/Ioupie_RK.lua | 30 | 3064 | -----------------------------------
-- Area: Pashhow Marshlands
-- NPC: Ioupie, R.K.
-- Type: Border Conquest Guards
-- @pos 536.291 23.517 694.063 109
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Pashhow_Marshlands/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = DERFLAND;
local csid = 0x7ffa;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Southern_San_dOria/npcs/Estiliphire.lua | 29 | 1068 | -----------------------------------
-- Area: Southern Sandoria
-- NPC: Estiliphire
-- Type: Event Sideshow NPC
-- @zone: 230
-- @pos -41.550 1.999 -2.845
--
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local 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(0x381);
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/libs/nixio/axTLS/www/lua/test_main.lua | 176 | 1139 | cgilua.htmlheader()
cgilua.put[[
<html>
<head><title>Script Lua Test</title></head>
<body>
cgi = {
]]
for i,v in pairs (cgi) do
if type(v) == "table" then
local vv = "{"
for a,b in pairs(v) do
vv = string.format ("%s%s = %s<br>\n", vv, a, tostring(b))
end
v = vv.."}"
end
cgilua.put (string.format ("%s = %s<br>\n", i, tostring(v)))
end
cgilua.put "}<br>\n"
cgilua.put ("Remote address: "..cgilua.servervariable"REMOTE_ADDR")
cgilua.put "<br>\n"
cgilua.put ("Is persistent = "..tostring (SAPI.Info.ispersistent).."<br>\n")
cgilua.put ("ap="..tostring(ap).."<br>\n")
cgilua.put ("lfcgi="..tostring(lfcgi).."<br>\n")
-- Checking Virtual Environment
local my_output = cgilua.put
cgilua.put = nil
local status, err = pcall (function ()
assert (cgilua.put == nil, "cannot change cgilua.put value")
end)
cgilua.put = my_output
assert (status == true, err)
-- Checking require
local status, err = pcall (function () require"unknown_module" end)
assert (status == false, "<tt>unknown_module</tt> loaded!")
-- assert (package == nil, "Access to <tt>package</tt> table allowed!")
cgilua.put[[
<p>
</body>
</html>
]]
cgilua = nil
| gpl-2.0 |
actboy168/YDWE | Development/Component/script/ydwe/ydwe_on_save.lua | 2 | 4187 | local compiler = require "compiler"
local map_packer = require 'w3x2lni.map_packer'
local dev = fs.ydwe_devpath()
local function backup_map(map_path)
local ydwe_path = fs.ydwe_path()
fs.create_directories(ydwe_path / 'backups')
local buf = io.load(ydwe_path / 'backups' / 'backupsdata.txt')
local char
if buf then
char = buf:match '(.)[\r\n]*$'
else
char = '0'
end
local filename = char .. map_path:extension():string()
local target_path = ydwe_path / 'backups' / filename
log.info('Backup map at ' .. target_path:string())
fs.copy_file(map_path, target_path, true)
end
local function saveW3x(source_path, target_path, temp_path, save_version, is_test)
fs.remove(target_path)
local result = compiler:compile(temp_path, global_config, save_version)
log.debug("Compiler Result " .. tostring(result))
local result
if is_test then
local mapSlk = "0" ~= global_config["MapTest"]["EnableMapSlk"]
if mapSlk then
result = map_packer('slk', temp_path, target_path)
else
result = map_packer('pack', temp_path, target_path)
end
backup_map(target_path)
else
if target_path:filename():string() == '.w3x' then
result = map_packer('lni', temp_path, source_path:parent_path())
fs.copy_file(dev / 'plugin' / 'w3x2lni' / 'script' / 'core' / '.w3x', target_path, true)
else
result = map_packer('pack', temp_path, target_path)
backup_map(target_path)
end
end
log.debug("Packer Result " .. tostring(result))
return result
end
local function saveW3m(source_path, target_path, temp_path, save_version)
fs.remove(target_path)
local result = compiler:compile(temp_path, global_config, save_version)
log.debug("Compiler Result " .. tostring(result))
local result
result = map_packer('pack', temp_path, target_path)
backup_map(target_path)
log.debug("Packer Result " .. tostring(result))
return result
end
local function saveW3n(source_path, target_path, temp_path, save_version)
fs.remove(target_path)
local result
result = map_packer('pack', temp_path, target_path)
backup_map(target_path)
log.debug("Packer Result " .. tostring(result))
return result
end
function event.EVENT_NEW_SAVE_MAP(event_data)
log.debug("********************* on save start *********************")
-- 刷新配置数据
global_config_reload()
local target_path = fs.path(event_data.map_path)
local temp_path = target_path:parent_path()
local source_path = temp_path:parent_path() / target_path:filename()
if event_data.test then
log.debug("Test Map")
else
log.debug("Save Map")
end
log.info("Saving " .. source_path:string())
local save_type = temp_path:filename():string():sub(-7, -5)
local save_version = war3_version:is_new() and 24 or 20
log.info("Type:", save_type, "Version:", save_version)
-- 如果地图文件带有只读属性,则先询问是否去掉只读属性
-- 128 == 0200 S_IWUSR
if fs.exists(source_path) and 0 == (source_path:permissions() & 128) then
if gui.yesno_message(nil, LNG.REMOVE_MAP_READONLY, source_path:string()) then
log.trace("Remove the read-only attribute.")
source_path:add_permissions(128)
else
log.trace("Don't remove the read-only attribute.")
log.debug("********************* on save end *********************")
return -1
end
end
local result = false
if save_type == 'w3x' then
result = saveW3x(source_path, target_path, temp_path, save_version, event_data.test)
elseif save_type == 'w3m' then
result = saveW3m(source_path, target_path, temp_path, save_version)
elseif save_type == 'w3n' then
result = saveW3n(source_path, target_path, temp_path, save_version)
else
log.error('Unsupport save to ' .. save_type)
gui.error_message(nil, LNG.UNSUPORTED_SAVE_TYPE, save_type)
end
log.debug("********************* on save end *********************")
if result then return 0 else return -1 end
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Lower_Jeuno/Zone.lua | 17 | 3845 | -----------------------------------
--
-- Zone: Lower_Jeuno (245)
--
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, 23, 0, -43, 44, 7, -39); -- Inside Tenshodo HQ
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local month = tonumber(os.date("%m"));
local day = tonumber(os.date("%d"));
-- Retail start/end dates vary, I am going with Dec 5th through Jan 5th.
if ((month == 12 and day >= 5) or (month == 1 and day <= 5)) then
player:ChangeMusic(0,239);
player:ChangeMusic(1,239);
-- No need for an 'else' to change it back outside these dates as a re-zone will handle that.
end
-- MOG HOUSE EXIT
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(41.2,-5, 84,85);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
elseif (player:getCurrentMission(COP) == TENDING_AGED_WOUNDS and player:getVar("PromathiaStatus")==0) then
player:setVar("PromathiaStatus",1);
cs = 0x0046;
elseif (ENABLE_ACP == 1 and player:getCurrentMission(ACP) == A_CRYSTALLINE_PROPHECY and player:getMainLvl() >=10) then
cs = 0x276E;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
-- print("entered region")
if (region:GetRegionID() == 1) then
-- print("entered region 1")
if (player:getCurrentMission(ZILART) == AWAKENING and player:getVar("ZilartStatus") < 2) then
player:startEvent(0x0014);
end
end
end;
-----------------------------------
-- onGameHour
-----------------------------------
function onGameHour()
local VanadielHour = VanadielHour();
-- Community Service Quest
if (VanadielHour == 1) then
if (GetServerVariable("[JEUNO]CommService") == 0) then
GetNPCByID(17780880):setStatus(0); -- Vhana Ehgaklywha
GetNPCByID(17780880):initNpcAi();
end;
elseif (VanadielHour == 5) then
SetServerVariable("[JEUNO]CommService",0);
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 == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 0x0014) then
player:setVar("ZilartStatus", player:getVar("ZilartStatus")+2);
elseif (csid == 0x276E) then
player:completeMission(ACP,A_CRYSTALLINE_PROPHECY);
player:addMission(ACP,THE_ECHO_AWAKENS);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Lower_Jeuno/npcs/Sutarara.lua | 17 | 1651 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Sutarara
-- Involved in Quests: Tenshodo Menbership (before accepting)
-- @pos 30 0.1 -2 245
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TenshodoMembership = player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP);
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,10) == false) then
player:startEvent(10055);
elseif (TenshodoMembership ~= QUEST_COMPLETED) then
player:startEvent(0x00d0);
elseif (TenshodoMembership == QUEST_COMPLETED) then
player:startEvent(0x00d3);
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 == 10055) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",10,true);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Uricca-Koricca.lua | 38 | 1051 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Uricca-Koricca
-- Type: Standard NPC
-- @zone: 94
-- @pos -102.221 -3 48.791
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01b5);
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/Uleguerand_Range/npcs/HomePoint#5.lua | 19 | 1189 | -----------------------------------
-- Area: Uleguerand_Range
-- NPC: HomePoint#5
-- @pos
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x2200, 80);
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 == 0x2200) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.