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 |
|---|---|---|---|---|---|
MalRD/darkstar | scripts/globals/items/plate_of_sublime_sushi.lua | 11 | 1690 | -----------------------------------------
-- ID: 6468
-- Item: plate_of_sublime_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +40
-- MP +20
-- STR +6
-- DEX +7
-- MND -3
-- CHR +6
-- Accuracy +10% (cap 100)
-- Ranged Accuracy +10% (cap 100)
-- Resist Sleep +1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,6468)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 40)
target:addMod(dsp.mod.MP, 20)
target:addMod(dsp.mod.STR, 6)
target:addMod(dsp.mod.DEX, 7)
target:addMod(dsp.mod.MND, -3)
target:addMod(dsp.mod.CHR, 6)
target:addMod(dsp.mod.FOOD_ACCP, 10)
target:addMod(dsp.mod.FOOD_ACC_CAP, 100)
target:addMod(dsp.mod.FOOD_RACCP, 10)
target:addMod(dsp.mod.FOOD_RACC_CAP, 100)
target:addMod(dsp.mod.SLEEPRES, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 40)
target:delMod(dsp.mod.MP, 20)
target:delMod(dsp.mod.STR, 6)
target:delMod(dsp.mod.DEX, 7)
target:delMod(dsp.mod.MND, -3)
target:delMod(dsp.mod.CHR, 6)
target:delMod(dsp.mod.FOOD_ACCP, 10)
target:delMod(dsp.mod.FOOD_ACC_CAP, 100)
target:delMod(dsp.mod.FOOD_RACCP, 10)
target:delMod(dsp.mod.FOOD_RACC_CAP, 100)
target:delMod(dsp.mod.SLEEPRES, 1)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c31077447.lua | 3 | 1349 | --びっくり箱
function c31077447.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCondition(c31077447.condition)
e1:SetTarget(c31077447.target)
e1:SetOperation(c31077447.activate)
c:RegisterEffect(e1)
end
function c31077447.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttacker():IsControler(1-tp) and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>1
end
function c31077447.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tc=Duel.GetAttacker()
if chkc then return chkc==tc end
if chk==0 then return tc:IsOnField() and tc:IsCanBeEffectTarget(e) end
Duel.SetTargetCard(tc)
end
function c31077447.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not Duel.NegateAttack() then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,nil,tp,0,LOCATION_MZONE,1,1,tc)
local sc=g:GetFirst()
if sc and Duel.SendtoGrave(sc,REASON_EFFECT)~=0 and sc:IsLocation(LOCATION_GRAVE) then
Duel.BreakEffect()
local val=math.max(0,sc:GetAttack(),sc:GetDefence())
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-val)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c99668578.lua | 9 | 1186 | --星因士 プロキオン
function c99668578.initial_effect(c)
--handes
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(99668578,0))
e1:SetCategory(CATEGORY_HANDES+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,99668578)
e1:SetTarget(c99668578.target)
e1:SetOperation(c99668578.operation)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
end
function c99668578.filter(c)
return c:IsSetCard(0x9c) and c:IsType(TYPE_MONSTER)
end
function c99668578.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1)
and Duel.IsExistingMatchingCard(c99668578.filter,tp,LOCATION_HAND,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c99668578.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.DiscardHand(tp,c99668578.filter,1,1,REASON_EFFECT)~=0 then
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/mobskills/high-tension_discharger.lua | 11 | 1440 | ---------------------------------------------------
-- High-Tension_Discharger
-- Description: Discharges a powerful current that deals Lightning damage to players in a fan-shaped area.
-- Additional effect: Stun
-- Type: Magical
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
-- skillList 54 = Omega
-- skillList 727 = Proto-Omega
-- skillList 728 = Ultima
-- skillList 729 = Proto-Ultima
local skillList = mob:getMobMod(dsp.mobMod.SKILL_LIST)
local mobhp = mob:getHPP()
local phase = mob:getLocalVar("battlePhase")
if ((skillList == 729 and phase >= 1 and phase <= 2) or (skillList == 728 and mobhp < 70 and mobhp >= 40)) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.STUN
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 3, 2)
local dmgmod = 2
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.THUNDER,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.LIGHTNING,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.LIGHTNING)
return dmg
end
| gpl-3.0 |
NENO7/GENERAL | plugins/wlc.lua | 4 | 2721 | --[[ كتابه المطور :- @KNSLTHM@KNSLTHM
@KNSLTHM
@KNSLTHM
@NENO_CH
@NENO_CH
@NENO_CH
--]]
do
local function run(msg, matches, callback, extra)
local data = load_data(_config.moderation.data)
local rules = data[tostring(msg.to.id)]['rules']
local about = data[tostring(msg.to.id)]['description']
local hash = 'group:'..msg.to.id
local group_welcome = redis:hget(hash,'welcome')
if matches[1] == 'حذف الترحيب' and not matches[2] and is_momod(msg) then
redis:hdel(hash,'welcome')
return 'تم حذف الترحيب بنجاح✅'
end
local url , res = http.request('http://api.gpmod.ir/time/')
if res ~= 200 then return "No connection" end
local jdat = json:decode(url)
if is_momod(msg) and matches[1] == 'ضع ترحيب' then
redis:hset(hash,'welcome',matches[2])
return 'تم حفظ الترحيب💡'
end
if matches[1] == 'chat_add_user' and msg.service then
group_welcome = string.gsub(group_welcome, '$userlink', "telegram.me/"..(msg.action.user.username or '').."")
group_welcome = string.gsub(group_welcome, '$gpname', msg.to.title)
group_welcome = string.gsub(group_welcome, '$name', ""..(msg.action.user.print_name or '').."")
group_welcome = string.gsub(group_welcome, '$username', "@"..(msg.action.user.username or '').."")
group_welcome = string.gsub(group_welcome, '$entime', ""..(jdat.ENtime).."")
group_welcome = string.gsub(group_welcome, '$endate', ""..(jdat.ENdate).."")
group_welcome = string.gsub(group_welcome, '$rules', ""..(rules or '').."")
group_welcome = string.gsub(group_welcome, '$about', ""..(about or '').."")
elseif matches[1] == 'chat_add_user_link' and msg.service then
group_welcome = string.gsub(group_welcome, '$userlink', "telegram.me/"..(msg.from.username or '').."")
group_welcome = string.gsub(group_welcome, '$gpname', msg.to.title)
group_welcome = string.gsub(group_welcome, '$name', ""..(msg.from.print_name or '').."")
group_welcome = string.gsub(group_welcome, '$username', "@"..(msg.from.username or '').."")
group_welcome = string.gsub(group_welcome, '$entime', ""..(jdat.ENtime).."")
group_welcome = string.gsub(group_welcome, '$endate', ""..(jdat.ENdate).."")
group_welcome = string.gsub(group_welcome, '$rules', ""..(rules or '').."")
group_welcome = string.gsub(group_welcome, '$about', ""..(about or '').."")
end
return group_welcome
end
return {
patterns = {
"^[!/#](ضع ترحيب) +(.*)$",
"^[!/#](حذف الترحيب)$",
"^(ضع ترحيب) +(.*)$",
"^(حذف الترحيب)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
},
run = run
}
end
--[[ كتابه المطور :- @KNSLTHM@KNSLTHM
@KNSLTHM
@KNSLTHM
@NENO_CH
@NENO_CH
@NENO_CH
--]]
| gpl-2.0 |
Mkalo/forgottenserver | data/actions/scripts/other/doors.lua | 30 | 2024 | function onUse(player, item, fromPosition, target, toPosition, isHotkey)
local itemId = item:getId()
if isInArray(questDoors, itemId) then
if player:getStorageValue(item.actionid) ~= -1 then
item:transform(itemId + 1)
player:teleportTo(toPosition, true)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "The door seems to be sealed against unwanted intruders.")
end
return true
elseif isInArray(levelDoors, itemId) then
if item.actionid > 0 and player:getLevel() >= item.actionid - 1000 then
item:transform(itemId + 1)
player:teleportTo(toPosition, true)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "Only the worthy may pass.")
end
return true
elseif isInArray(keys, itemId) then
if target.actionid > 0 then
if item.actionid == target.actionid and doors[target.itemid] then
target:transform(doors[target.itemid])
return true
end
player:sendTextMessage(MESSAGE_STATUS_SMALL, "The key does not match.")
return true
end
return false
end
if isInArray(horizontalOpenDoors, itemId) or isInArray(verticalOpenDoors, itemId) then
local doorCreature = Tile(toPosition):getTopCreature()
if doorCreature ~= nil then
toPosition.x = toPosition.x + 1
local query = Tile(toPosition):queryAdd(doorCreature, bit.bor(FLAG_IGNOREBLOCKCREATURE, FLAG_PATHFINDING))
if query ~= RETURNVALUE_NOERROR then
toPosition.x = toPosition.x - 1
toPosition.y = toPosition.y + 1
query = Tile(toPosition):queryAdd(doorCreature, bit.bor(FLAG_IGNOREBLOCKCREATURE, FLAG_PATHFINDING))
end
if query ~= RETURNVALUE_NOERROR then
player:sendTextMessage(MESSAGE_STATUS_SMALL, query)
return true
end
doorCreature:teleportTo(toPosition, true)
end
if not isInArray(openSpecialDoors, itemId) then
item:transform(itemId - 1)
end
return true
end
if doors[itemId] then
if item.actionid == 0 then
item:transform(doors[itemId])
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is locked.")
end
return true
end
return false
end
| gpl-2.0 |
jadarve/lluvia | lluvia/nodes/lluvia/imgproc/ImageDownsampleX_r8ui.lua | 1 | 2338 | local builder = ll.class(ll.ComputeNodeBuilder)
builder.name = 'lluvia/imgproc/ImageDownsampleX_r8ui'
builder.doc = [[
Downsamples a gray level image along the X axis.
Let W and H denote the width and height of the input in_gray image, respectively.
The shape of the out_gray image is:
* out_gray.W = floor(W / 2)
* out_gray.H = H
That is, the output width is always an even number.
The value of a pixel out_gray(x, y) is computed as:
out_gray(x, y) = 0.25*in_gray(2*x - 1, y) + 0.5*in_gray(2*x, y) + 0.25*in_gray(2*x + 1, y)
Inputs
------
in_gray : ImageView.
r8ui image.
Outputs
-------
out_gray : ImageView
r8ui image. The downsampled image.
]]
function builder.newDescriptor()
local desc = ll.ComputeNodeDescriptor.new()
desc:init(builder.name, ll.ComputeDimension.D2)
local in_gray = ll.PortDescriptor.new(0, 'in_gray', ll.PortDirection.In, ll.PortType.ImageView)
in_gray:checkImageChannelCountIs(ll.ChannelCount.C1)
in_gray:checkImageChannelTypeIs(ll.ChannelType.Uint8)
desc:addPort(in_gray)
desc:addPort(ll.PortDescriptor.new(1, 'out_gray', ll.PortDirection.Out, ll.PortType.ImageView))
return desc
end
function builder.onNodeInit(node)
local in_gray = node:getPort('in_gray')
-- out_gray descriptors
local imgDesc = ll.ImageDescriptor.new(in_gray.imageDescriptor)
imgDesc.width = in_gray.width // 2
local imgViewDesc = ll.ImageViewDescriptor.new()
imgViewDesc.filterMode = ll.ImageFilterMode.Nearest
imgViewDesc.normalizedCoordinates = false
imgViewDesc.isSampled = false
imgViewDesc:setAddressMode(ll.ImageAddressMode.Repeat)
-- ll::Memory where out_gray will be allocated
local memory = in_gray.memory
local out_gray = memory:createImageView(imgDesc, imgViewDesc)
-- need to change image layout before binding
out_gray:changeImageLayout(ll.ImageLayout.General)
node:bind('out_gray', out_gray)
ll.logd(builder.name, 'in_gray ', string.format('[%d, %d, %d]', in_gray.width, in_gray.height, in_gray.channelCount)
, 'out_gray', string.format('[%d, %d, %d]', out_gray.width, out_gray.height, out_gray.channelCount))
node:configureGridShape(ll.vec3ui.new(out_gray.width, out_gray.height, 1))
end
-- register builder in the system
ll.registerNodeBuilder(builder)
| apache-2.0 |
MalRD/darkstar | scripts/globals/items/colored_egg.lua | 11 | 1033 | -----------------------------------------
-- ID: 4487
-- Item: colored_egg
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 20
-- Magic 20
-- Attack 3
-- Ranged Attack 2
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4487)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 20)
target:addMod(dsp.mod.MP, 20)
target:addMod(dsp.mod.ATT, 3)
target:addMod(dsp.mod.RATT, 2)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 20)
target:delMod(dsp.mod.MP, 20)
target:delMod(dsp.mod.ATT, 3)
target:delMod(dsp.mod.RATT, 2)
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Northern_San_dOria/npcs/Kasaroro.lua | 9 | 3394 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Kasaroro
-- Type: Consulate Representative
-- Involved in Mission: 2-3 Windurst
-- !pos -72 -3 34 231
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(ID.text.FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
pNation = player:getNation();
if (pNation == dsp.nation.WINDURST) then
currentMission = player:getCurrentMission(pNation);
MissionStatus = player:getCharVar("MissionStatus");
if (currentMission == dsp.mission.id.windurst.THE_THREE_KINGDOMS) then
if (MissionStatus == 2) then
player:startEvent(546);
elseif (MissionStatus == 6) then
player:showText(npc,ID.text.KASARORO_DIALOG + 7);
elseif (MissionStatus == 7) then
player:startEvent(547);
elseif (MissionStatus == 11) then
player:showText(npc,ID.text.KASARORO_DIALOG + 20);
end
elseif (currentMission == dsp.mission.id.windurst.THE_THREE_KINGDOMS_SANDORIA) then
if (MissionStatus == 3) then
player:showText(npc,ID.text.KASARORO_DIALOG);
elseif (MissionStatus == 4) then
player:startEvent(549);
elseif (MissionStatus == 5) then
player:startEvent(550); -- done with Sandy first path, now go to bastok
end
elseif (currentMission == dsp.mission.id.windurst.THE_THREE_KINGDOMS_SANDORIA2) then
if (MissionStatus == 8) then
player:showText(npc,ID.text.KASARORO_DIALOG);
elseif (MissionStatus == 10) then
player:startEvent(551);
end
elseif (player:hasCompletedMission(WINDURST,dsp.mission.id.windurst.THE_THREE_KINGDOMS)) then
player:startEvent(604);
else
player:startEvent(548);
end
else
player:startEvent(548);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 546) then
player:addMission(WINDURST,dsp.mission.id.windurst.THE_THREE_KINGDOMS_SANDORIA);
player:delKeyItem(dsp.ki.LETTER_TO_THE_CONSULS_WINDURST);
player:setCharVar("MissionStatus",3);
elseif (csid == 550) then
player:addMission(WINDURST,dsp.mission.id.windurst.THE_THREE_KINGDOMS);
player:setCharVar("MissionStatus",6);
elseif (csid == 547) then
player:addMission(WINDURST,dsp.mission.id.windurst.THE_THREE_KINGDOMS_SANDORIA2);
player:setCharVar("MissionStatus",8);
elseif (csid == 551) then
player:addMission(WINDURST,dsp.mission.id.windurst.THE_THREE_KINGDOMS);
player:delKeyItem(dsp.ki.KINDRED_CREST);
player:addKeyItem(dsp.ki.KINDRED_REPORT);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.KINDRED_REPORT);
player:setCharVar("MissionStatus",11);
end
end; | gpl-3.0 |
tarulas/luadch | luasocket/src/socket.lua | 93 | 4451 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
local _M = socket
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function _M.connect4(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet")
end
function _M.connect6(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet6")
end
function _M.bind(host, port, backlog)
if host == "*" then host = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(host);
if not addrinfo then return nil, err end
local sock, res
err = "no info on address"
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp()
else
sock, err = socket.tcp6()
end
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
res, err = sock:bind(alt.addr, port)
if not res then
sock:close()
else
res, err = sock:listen(backlog)
if not res then
sock:close()
else
return sock
end
end
end
return nil, err
end
_M.try = _M.newtry()
function _M.choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
local sourcet, sinkt = {}, {}
_M.sourcet = sourcet
_M.sinkt = sinkt
_M.BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
_M.sink = _M.choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
_M.source = _M.choose(sourcet)
return _M
| gpl-3.0 |
Lsty/ygopro-scripts | c35073065.lua | 3 | 2146 | --イリュージョン・スナッチ
function c35073065.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(35073065,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c35073065.spcon)
e1:SetTarget(c35073065.sptg)
e1:SetOperation(c35073065.spop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_MSET)
c:RegisterEffect(e2)
end
function c35073065.spcon(e,tp,eg,ep,ev,re,r,rp)
local ec=eg:GetFirst()
return ec:IsControler(tp) and bit.band(ec:GetSummonType(),SUMMON_TYPE_ADVANCE)==SUMMON_TYPE_ADVANCE
end
function c35073065.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetTargetCard(eg)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c35073065.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=eg:GetFirst()
if c:IsRelateToEffect(e) and Duel.SpecialSummonStep(c,0,tp,tp,false,false,POS_FACEUP) then
if ec:IsRelateToEffect(e) and ec:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_RACE)
if ec:IsHasEffect(EFFECT_ADD_RACE) and not ec:IsHasEffect(EFFECT_CHANGE_RACE) then
e1:SetValue(ec:GetOriginalRace())
else
e1:SetValue(ec:GetRace())
end
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CHANGE_ATTRIBUTE)
if ec:IsHasEffect(EFFECT_ADD_ATTRIBUTE) and not ec:IsHasEffect(EFFECT_CHANGE_ATTRIBUTE) then
e2:SetValue(ec:GetOriginalAttribute())
else
e2:SetValue(ec:GetAttribute())
end
e2:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CHANGE_LEVEL)
e3:SetValue(ec:GetLevel())
e3:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e3)
end
Duel.SpecialSummonComplete()
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Attohwa_Chasm/IDs.lua | 12 | 2001 | -----------------------------------
-- Area: Attohwa_Chasm
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.ATTOHWA_CHASM] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
KEYITEM_LOST = 6392, -- Lost key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
MINING_IS_POSSIBLE_HERE = 7208, -- Mining is possible here if you have <item>.
GASPONIA_POISON = 7328, -- The poison of the Gasponia has begun to spread through your body.
OCCASIONAL_LUMPS = 7343, -- Occasionally lumps arise in the ground here, then settle down again. It seems that there is something beneath the earth.
HOMEPOINT_SET = 8230, -- Home point set!
},
mob =
{
AMBUSHER_ANTLION_PH =
{
[16806171] = 16806249, -- -433.309 -4.3 113.841
},
CITIPATI_PH =
{
[16806155] = 16806162, -- -328.973 -12.876 67.481
[16806158] = 16806162, -- -398.931 -4.536 79.640
[16806161] = 16806162, -- -381.284 -9.233 40.054
},
LIOUMERE = 16806031,
TIAMAT = 16806227,
FEELER_ANTLION = 16806242,
},
npc =
{
MIASMA_OFFSET = 16806304,
GASPONIA_OFFSET = 16806327,
EXCAVATION =
{
16806369,
16806370,
16806371,
16806372,
16806373,
16806374,
},
},
}
return zones[dsp.zone.ATTOHWA_CHASM] | gpl-3.0 |
Lsty/ygopro-scripts | c74605254.lua | 3 | 3602 | --DD魔導賢者ガリレイ
function c74605254.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(74605254,1))
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_PZONE)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e2:SetTargetRange(1,0)
e2:SetCondition(aux.nfbdncon)
e2:SetTarget(c74605254.splimit)
c:RegisterEffect(e2)
--scale change
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_PZONE)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetCountLimit(1)
e3:SetCondition(c74605254.sccon)
e3:SetTarget(c74605254.sctg)
e3:SetOperation(c74605254.scop)
c:RegisterEffect(e3)
--tohand
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(74605254,0))
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_QUICK_O)
e4:SetCode(EVENT_FREE_CHAIN)
e4:SetRange(LOCATION_HAND)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCountLimit(1,74605254)
e4:SetCost(c74605254.thcost)
e4:SetTarget(c74605254.thtg)
e4:SetOperation(c74605254.thop)
c:RegisterEffect(e4)
end
function c74605254.splimit(e,c,sump,sumtype,sumpos,targetp)
return not c:IsSetCard(0xaf) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c74605254.sccon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c74605254.filter(c,lv)
return c:IsFaceup() and not c:IsSetCard(0xaf) and c:IsLevelBelow(lv) and c:IsDestructable()
end
function c74605254.sctg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local scl=math.min(10,e:GetHandler():GetLeftScale()+2)
local g=Duel.GetMatchingGroup(c74605254.filter,tp,LOCATION_MZONE,0,nil,scl)
if e:GetHandler():GetLeftScale()<10 then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
end
function c74605254.scop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) or c:GetLeftScale()>=10 then return end
local scl=2
if c:GetLeftScale()==9 then scl=1 end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LSCALE)
e1:SetValue(scl)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_RSCALE)
c:RegisterEffect(e2)
local g=Duel.GetMatchingGroup(c74605254.filter,tp,LOCATION_MZONE,0,nil,c:GetLeftScale())
if g:GetCount()>0 then
Duel.BreakEffect()
Duel.Destroy(g,REASON_EFFECT)
end
end
function c74605254.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsDiscardable() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD)
end
function c74605254.thfilter(c)
return c:IsFaceup() and (c:IsSetCard(0xae) or c:IsSetCard(0xaf)) and c:IsAbleToHand()
end
function c74605254.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(tp) and c74605254.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c74605254.thfilter,tp,LOCATION_ONFIELD,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,c74605254.thfilter,tp,LOCATION_ONFIELD,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c74605254.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/South_Gustaberg/IDs.lua | 2 | 3073 | -----------------------------------
-- Area: South_Gustaberg
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.SOUTH_GUSTABERG] =
{
text =
{
NOTHING_HAPPENS = 141, -- Nothing happens...
ITEM_CANNOT_BE_OBTAINED = 6404, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6410, -- Obtained: <item>.
GIL_OBTAINED = 6411, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6413, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6424, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7071, -- Tallying conquest results...
FISHING_MESSAGE_OFFSET = 7230, -- You can't fish here.
DIG_THROW_AWAY = 7243, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7245, -- You dig and you dig, but find nothing.
MONSTER_TRACKS = 7400, -- You see monster tracks on the ground.
MONSTER_TRACKS_FRESH = 7401, -- You see fresh monster tracks on the ground.
FIRE_GOOD = 7404, -- The fire seems to be good enough for cooking.
FIRE_PUT = 7405, -- You put <item> in the fire.
FIRE_TAKE = 7406, -- You take <item> out of the fire.
FIRE_LONGER = 7407, -- It may take a little while more to cook the <item>.
MEAT_ALREADY_PUT = 7408, -- The <item> is already in the fire.
PLAYER_OBTAINS_ITEM = 7525, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 7526, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 7527, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 7528, -- You already possess that temporary item.
NO_COMBINATION = 7533, -- You were unable to enter a combination.
REGIME_REGISTERED = 9893, -- New training regime registered!
},
mob =
{
CARNERO_PH =
{
[17215638] = 17215626, -- 277.891 -39.854 -413.354
[17215611] = 17215626, -- 186.081 -39.990 -367.942
[17215612] = 17215626, -- 164.245 -39.900 -347.878
[17215624] = 17215626, -- 160.304 -39.990 -460.400
[17215625] = 17215626, -- 201.021 -39.904 -500.721
[17215646] = 17215626, -- 275.135 -39.977 -477.840
[17215645] = 17215626, -- 274.561 -39.972 -476.762
[17215648] = 17215626, -- 213.010 -59.983 -442.766
[17215649] = 17215626, -- 211.745 -59.938 -441.313
},
LEAPING_LIZZY_PH =
{
[17215867] = 17215868, -- -275.441 20.451 -347.294
[17215887] = 17215888, -- -322.871 30.052 -401.184
},
BUBBLY_BERNIE = 17215494,
},
npc =
{
CASKET_BASE = 17216173,
},
}
return zones[dsp.zone.SOUTH_GUSTABERG] | gpl-3.0 |
Lsty/ygopro-scripts | c66200210.lua | 3 | 3397 | --幻獣機ハムストラット
function c66200210.initial_effect(c)
--level
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(c66200210.lvval)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetCondition(c66200210.indcon)
e2:SetValue(1)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
c:RegisterEffect(e3)
--token
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(66200210,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_FLIP)
e4:SetTarget(c66200210.sptg)
e4:SetOperation(c66200210.spop)
c:RegisterEffect(e4)
--spsummon
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(66200210,1))
e5:SetCategory(CATEGORY_SPECIAL_SUMMON)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_MZONE)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET)
e5:SetCountLimit(1,66200210)
e5:SetCost(c66200210.spcost2)
e5:SetTarget(c66200210.sptg2)
e5:SetOperation(c66200210.spop2)
c:RegisterEffect(e5)
end
function c66200210.lvval(e,c)
local tp=c:GetControler()
local lv=0
for i=0,4 do
local tc=Duel.GetFieldCard(tp,LOCATION_MZONE,i)
if tc and tc:IsCode(31533705) then lv=lv+tc:GetLevel() end
end
return lv
end
function c66200210.indcon(e)
return Duel.IsExistingMatchingCard(Card.IsType,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil,TYPE_TOKEN)
end
function c66200210.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0)
end
function c66200210.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=1 then return end
if Duel.IsPlayerCanSpecialSummonMonster(tp,31533705,0x101b,0x4011,0,0,3,RACE_MACHINE,ATTRIBUTE_WIND) then
local token1=Duel.CreateToken(tp,66200211)
Duel.SpecialSummonStep(token1,0,tp,tp,false,false,POS_FACEUP)
local token2=Duel.CreateToken(tp,66200211)
Duel.SpecialSummonStep(token2,0,tp,tp,false,false,POS_FACEUP)
Duel.SpecialSummonComplete()
end
end
function c66200210.spcost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsType,1,nil,TYPE_TOKEN) end
local g=Duel.SelectReleaseGroup(tp,Card.IsType,1,1,nil,TYPE_TOKEN)
Duel.Release(g,REASON_COST)
end
function c66200210.filter(c,e,tp)
return c:IsSetCard(0x101b) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c66200210.sptg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c66200210.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingTarget(c66200210.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c66200210.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c66200210.spop2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Sacrificial_Chamber/npcs/Armoury_Crate.lua | 9 | 7551 | -----------------------------------
-- Area: Sacrificial Chamber
-- NPC: Armoury Crate
-------------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/bcnm")
-------------------------------------
local loot =
{
-- BCNM Jungle Boogymen
[129] =
{
{
{itemid = 13153, droprate = 250}, -- Dark Torque
{itemid = 13156, droprate = 250}, -- Elemental Torque
{itemid = 13157, droprate = 250}, -- Healing Torque
{itemid = 13161, droprate = 250}, -- Wind Torque
},
{
{itemid = 751, droprate = 500}, -- Platinum Beastcoin
{itemid = 4874, droprate = 48}, -- Scroll Of Absorb-STR
{itemid = 4751, droprate = 143}, -- Scroll Of Erase
{itemid = 4714, droprate = 119}, -- Scroll Of Phalanx
{itemid = 4896, droprate = 48}, -- Fire Spirit Pact
{itemid = 1255, droprate = 48}, -- Chunk Of Fire Ore
{itemid = 1256, droprate = 48}, -- Chunk Of Ice Ore
{itemid = 1257, droprate = 48}, -- Chunk Of Wind Ore
{itemid = 1258, droprate = 48}, -- Chunk Of Earth Ore
{itemid = 1259, droprate = 48}, -- Chunk Of Lightning Ore
{itemid = 1260, droprate = 48}, -- Chunk Of Water Ore
{itemid = 1261, droprate = 48}, -- Chunk Of Light Ore
{itemid = 1262, droprate = 48}, -- Chunk Of Dark Ore
},
{
{itemid = 751, droprate = 833}, -- Platinum Beastcoin
{itemid = 1256, droprate = 167}, -- Chunk Of Ice Ore
},
{
{itemid = 13155, droprate = 250}, -- Enfeebling Torque
{itemid = 13148, droprate = 250}, -- Evasion Torque
{itemid = 13151, droprate = 250}, -- Guarding Torque
{itemid = 13158, droprate = 250}, -- Summoning Torque
},
{
{itemid = 654, droprate = 154}, -- Darksteel Ingot
{itemid = 797, droprate = 154}, -- Painite
{itemid = 745, droprate = 154}, -- Gold Ingot
{itemid = 791, droprate = 77}, -- Aquamarine
{itemid = 4175, droprate = 77}, -- Vile Elixir +1
{itemid = 653, droprate = 153}, -- Mythril Ingot
{itemid = 801, droprate = 30}, -- Chrysoberyl
{itemid = 802, droprate = 30}, -- Moonstone
{itemid = 803, droprate = 30}, -- Sunstone
{itemid = 805, droprate = 30}, -- Zircon
{itemid = 791, droprate = 30}, -- Aquamarine
{itemid = 702, droprate = 30}, -- Ebony Log
{itemid = 700, droprate = 30}, -- Mahogany Log
{itemid = 942, droprate = 30}, -- Philosophers Stone
},
{
{itemid = 654, droprate = 77}, -- Darksteel Ingot
{itemid = 802, droprate = 134}, -- Moonstone
{itemid = 652, droprate = 154}, -- Steel Ingot
{itemid = 801, droprate = 50}, -- Chrysoberyl
{itemid = 4173, droprate = 154}, -- Hi-reraiser
{itemid = 784, droprate = 121}, -- Jadeite
{itemid = 837, droprate = 10}, -- Spool Of Malboro Fiber
{itemid = 1110, droprate = 10}, -- Vial Of Black Beetle Blood
{itemid = 769, droprate = 30}, -- Red Rock
{itemid = 770, droprate = 30}, -- Blue Rock
{itemid = 771, droprate = 30}, -- Yellow Rock
{itemid = 772, droprate = 30}, -- Green Rock
{itemid = 773, droprate = 30}, -- Translucent Rock
{itemid = 774, droprate = 30}, -- Purple Rock
{itemid = 775, droprate = 30}, -- Black Rock
{itemid = 776, droprate = 30}, -- White Rock
{itemid = 810, droprate = 50}, -- Fluorite
},
},
-- BCNM Amphibian Assault
[130] =
{
{
{itemid = 13155, droprate = 250}, -- Enfeebling Torque
{itemid = 13152, droprate = 250}, -- Divine Torque
{itemid = 13150, droprate = 250}, -- Shield Torque
{itemid = 13160, droprate = 250}, -- String Torque
},
{
{itemid = 13156, droprate = 250}, -- Elemental Torque
{itemid = 13148, droprate = 250}, -- Evasion Torque
{itemid = 13151, droprate = 250}, -- Guarding Torque
{itemid = 13154, droprate = 250}, -- Enhancing Torque
},
{
{itemid = 1260, droprate = 125}, -- Chunk Of Water Ore
{itemid = 1257, droprate = 125}, -- Chunk Of Wind Ore
{itemid = 1256, droprate = 125}, -- Chunk Of Ice Ore
{itemid = 1259, droprate = 125}, -- Chunk Of Lightning Ore
{itemid = 1261, droprate = 125}, -- Chunk Of Light Ore
{itemid = 1255, droprate = 125}, -- Chunk Of Fire Ore
{itemid = 1262, droprate = 125}, -- Chunk Of Dark Ore
{itemid = 1258, droprate = 125}, -- Chunk Of Earth Ore
},
{
{itemid = 0, droprate = 750}, -- nothing
{itemid = 13158, droprate = 250}, -- Summoning Torque
},
{
{itemid = 0, droprate = 200}, -- nothing
{itemid = 751, droprate = 800}, -- Platinum Beastcoin
},
{
{itemid = 0, droprate = 375}, -- nothing
{itemid = 4896, droprate = 125}, -- Fire Spirit Pact
{itemid = 4874, droprate = 125}, -- Scroll Of Absorb-str
{itemid = 4751, droprate = 125}, -- Scroll Of Erase
{itemid = 4714, droprate = 125}, -- Scroll Of Phalanx
{itemid = 4621, droprate = 125}, -- Scroll Of Raise Ii
},
{
{itemid = 0, droprate = 888}, -- nothing
{itemid = 4175, droprate = 56}, -- Vile Elixir +1
{itemid = 4173, droprate = 56}, -- Hi-reraiser
},
{
{itemid = 810, droprate = 10}, -- Fluorite
{itemid = 797, droprate = 50}, -- Painite
{itemid = 803, droprate = 10}, -- Sunstone
{itemid = 784, droprate = 150}, -- Jadeite
{itemid = 791, droprate = 50}, -- Aquamarine
{itemid = 802, droprate = 150}, -- Moonstone
{itemid = 771, droprate = 50}, -- Yellow Rock
{itemid = 769, droprate = 50}, -- Red Rock
{itemid = 776, droprate = 100}, -- White Rock
{itemid = 772, droprate = 50}, -- Green Rock
{itemid = 773, droprate = 100}, -- Translucent Rock
{itemid = 801, droprate = 150}, -- Chrysoberyl
{itemid = 775, droprate = 50}, -- Black Rock
{itemid = 774, droprate = 50}, -- Purple Rock
},
{
{itemid = 751, droprate = 500}, -- Platinum Beastcoin
{itemid = 887, droprate = 222}, -- Coral Fragment
{itemid = 837, droprate = 10}, -- Spool Of Malboro Fiber
{itemid = 652, droprate = 111}, -- Steel Ingot
{itemid = 702, droprate = 56}, -- Ebony Log
},
},
}
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local battlefield = player:getBattlefield()
if battlefield then
dsp.battlefield.HandleLootRolls(battlefield, loot[battlefield:getID()], nil, npc)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
Frenzie/koreader | plugins/exporter.koplugin/target/markdown.lua | 4 | 4730 | local UIManager = require("ui/uimanager")
local md = require("template/md")
local _ = require("gettext")
local T = require("ffi/util").template
-- markdown exporter
local MarkdownExporter = require("base"):new {
name = "markdown",
extension = "md",
mimetype = "text/markdown",
init_callback = function(self, settings)
local changed = false
if not settings.formatting_options or settings.highlight_formatting == nil then
settings.formatting_options = settings.formatting_options or {
lighten = "italic",
underscore = "underline_markdownit",
strikeout = "strikethrough",
invert = "bold",
}
settings.highlight_formatting = settings.highlight_formatting or true
changed = true
end
return changed, settings
end,
}
local formatter_buttons = {
{ _("None"), "none" },
{ _("Bold"), "bold" },
{ _("Bold italic"), "bold_italic" },
{ _("Italic"), "italic" },
{ _("Strikethrough"), "strikethrough" },
{ _("Underline (Markdownit style, with ++)"), "underline_markdownit" },
{ _("Underline (with <u></u> tags)"), "underline_u_tag" },
}
function MarkdownExporter:editFormatStyle(drawer_style, label, touchmenu_instance)
local radio_buttons = {}
for _idx, v in ipairs(formatter_buttons) do
table.insert(radio_buttons, {
{
text = v[1],
checked = self.settings.formatting_options[drawer_style] == v[2],
provider = v[2],
},
})
end
UIManager:show(require("ui/widget/radiobuttonwidget"):new {
title_text = T(_("Formatting style for %1"), label),
width_factor = 0.8,
radio_buttons = radio_buttons,
callback = function(radio)
self.settings.formatting_options[drawer_style] = radio.provider
touchmenu_instance:updateItems()
end,
})
end
function MarkdownExporter:onInit()
local changed = false
if self.settings.formatting_options == nil then
self.settings.formatting_options = {
lighten = "italic",
underscore = "underline_markdownit",
strikeout = "strikethrough",
invert = "bold",
}
changed = true
end
if self.settings.highlight_formatting == nil then
self.settings.highlight_formatting = true
changed = true
end
if changed then
self:saveSettings()
end
end
local highlight_style = {
{ _("Lighten"), "lighten" },
{ _("Underline"), "underscore" },
{ _("Strikeout"), "strikeout" },
{ _("Invert"), "invert" },
}
function MarkdownExporter:getMenuTable()
local menu = {
text = _("Markdown"),
checked_func = function() return self:isEnabled() end,
sub_item_table = {
{
text = _("Export to Markdown"),
checked_func = function() return self:isEnabled() end,
callback = function() self:toggleEnabled() end,
},
{
text = _("Format highlights based on style"),
checked_func = function() return self.settings.highlight_formatting end,
callback = function() self.settings.highlight_formatting = not self.settings.highlight_formatting end,
},
}
}
for _idx, entry in ipairs(highlight_style) do
table.insert(menu.sub_item_table, {
text_func = function()
return entry[1] .. ": " .. md.formatters[self.settings.formatting_options[entry[2]]].label
end,
enabled_func = function()
return self.settings.highlight_formatting
end,
keep_menu_open = true,
callback = function(touchmenu_instance)
self:editFormatStyle(entry[2], entry[1], touchmenu_instance)
end,
})
end
return menu
end
function MarkdownExporter:export(t)
local path = self:getFilePath(t)
local file = io.open(path, "w")
if not file then return false end
for idx, book in ipairs(t) do
file:write(md.prepareBookContent(book, self.settings.formatting_options, self.settings.highlight_formatting))
if idx < #t then
file:write("\n")
end
end
file:write("\n\n_Generated at: " .. self:getTimeStamp() .. "_")
file:close()
return true
end
function MarkdownExporter:share(t)
local content = md.prepareBookContent(t, self.settings.formatting_options, self.settings.highlight_formatting) .. "\n\n_Generated at: " .. self:getTimeStamp() .. "_"
self:shareText(content)
end
return MarkdownExporter
| agpl-3.0 |
Lsty/ygopro-scripts | c27655513.lua | 3 | 1204 | --スクリーチ
function c27655513.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(27655513,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c27655513.condition)
e1:SetTarget(c27655513.target)
e1:SetOperation(c27655513.operation)
c:RegisterEffect(e1)
end
function c27655513.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_BATTLE)
end
function c27655513.filter(c)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToGrave()
end
function c27655513.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,2,tp,LOCATION_DECK)
end
function c27655513.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c27655513.filter,tp,LOCATION_DECK,0,nil)
if g:GetCount()>1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local sg=g:Select(tp,2,2,nil)
Duel.SendtoGrave(sg,REASON_EFFECT)
elseif Duel.IsPlayerCanDiscardDeck(tp,2) then
local cg=Duel.GetFieldGroup(tp,LOCATION_DECK,0)
Duel.ConfirmCards(1-tp,cg)
Duel.ConfirmCards(tp,cg)
Duel.ShuffleDeck(tp)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c78637313.lua | 5 | 1612 | --闇からの呼び声
function c78637313.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--adjust
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetCode(EVENT_ADJUST)
e2:SetRange(LOCATION_SZONE)
e2:SetOperation(c78637313.adjustop)
c:RegisterEffect(e2)
--
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EFFECT_CANNOT_SSET)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetTargetRange(0,1)
e3:SetTarget(c78637313.target)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_SZONE)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetCode(EFFECT_CANNOT_ACTIVATE)
e4:SetTargetRange(0,1)
e4:SetValue(c78637313.aclimit)
c:RegisterEffect(e4)
end
function c78637313.filter(c)
return bit.band(c:GetSummonType(),SUMMON_TYPE_SPECIAL)~=0 and c:GetReasonEffect()
and c:GetReasonEffect():GetHandler():IsCode(83764718)
end
function c78637313.adjustop(e,tp,eg,ep,ev,re,r,rp)
local phase=Duel.GetCurrentPhase()
if (phase==PHASE_DAMAGE and not Duel.IsDamageCalculated()) or phase==PHASE_DAMAGE_CAL then return end
local g=Duel.GetMatchingGroup(c78637313.filter,0,LOCATION_MZONE,LOCATION_MZONE,nil)
if Duel.SendtoGrave(g,REASON_EFFECT)>0 then
Duel.Readjust()
end
end
function c78637313.target(e,c)
return c:IsCode(83764718)
end
function c78637313.aclimit(e,re,tp)
return re:GetHandler():IsCode(83764718)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c80889750.lua | 3 | 3365 | --デストーイ・サーベル・タイガー
function c80889750.initial_effect(c)
--fusion material
c:EnableReviveLimit()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(c80889750.fscon)
e1:SetOperation(c80889750.fsop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c80889750.spcon)
e2:SetTarget(c80889750.sptg)
e2:SetOperation(c80889750.spop)
c:RegisterEffect(e2)
--atk
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(LOCATION_MZONE,0)
e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xad))
e3:SetValue(400)
c:RegisterEffect(e3)
--indes
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e4:SetCode(EVENT_SPSUMMON_SUCCESS)
e4:SetCondition(c80889750.indcon)
e4:SetOperation(c80889750.indop)
c:RegisterEffect(e4)
end
function c80889750.mfilter1(c,mg)
return c:IsSetCard(0xad) and c:IsType(TYPE_FUSION) and mg:IsExists(c80889750.mfilter2,1,c)
end
function c80889750.mfilter2(c)
return c:IsSetCard(0xa9) or c:IsSetCard(0xc3)
end
function c80889750.fscon(e,mg,gc)
if mg==nil then return true end
if gc then return false end
return mg:IsExists(c80889750.mfilter1,1,nil,mg)
end
function c80889750.fsop(e,tp,eg,ep,ev,re,r,rp,gc)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g1=eg:FilterSelect(tp,c80889750.mfilter1,1,1,nil,eg)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g2=eg:FilterSelect(tp,c80889750.mfilter2,1,63,g1:GetFirst())
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
end
function c80889750.spcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
function c80889750.spfilter(c,e,tp)
return c:IsSetCard(0xad) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80889750.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c80889750.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c80889750.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c80889750.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c80889750.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function c80889750.indcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return bit.band(c:GetSummonType(),SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION and c:GetMaterialCount()>=3
end
function c80889750.indop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
c:RegisterEffect(e2)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c25769732.lua | 3 | 1647 | --機械改造工場
function c25769732.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c25769732.target)
e1:SetOperation(c25769732.operation)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(300)
c:RegisterEffect(e2)
--def up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_DEFENCE)
e3:SetValue(300)
c:RegisterEffect(e3)
--equip limit
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_EQUIP_LIMIT)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e4:SetValue(c25769732.eqlimit)
c:RegisterEffect(e4)
end
function c25769732.eqlimit(e,c)
return c:IsRace(RACE_MACHINE)
end
function c25769732.filter(c)
return c:IsFaceup() and c:IsRace(RACE_MACHINE)
end
function c25769732.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c25769732.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c25769732.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c25769732.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c25769732.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c38430673.lua | 3 | 1077 | --グランドクロス
function c38430673.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c38430673.condition)
e1:SetTarget(c38430673.target)
e1:SetOperation(c38430673.activate)
c:RegisterEffect(e1)
end
function c38430673.filter(c)
return c:IsFaceup() and c:IsCode(30241314)
end
function c38430673.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c38430673.filter,tp,LOCATION_ONFIELD,0,1,nil)
end
function c38430673.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,300)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c38430673.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Damage(1-tp,300,REASON_EFFECT)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
ThingMesh/openwrt-luci | applications/luci-statistics/luasrc/statistics/rrdtool/definitions/ping.lua | 78 | 1192 | --[[
Luci statistics - ping plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: ping.lua 6810 2011-01-29 03:33:48Z jow $
]]--
module("luci.statistics.rrdtool.definitions.ping", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
-- Ping roundtrip time
{ title = "%H: ICMP Round Trip Time", vlabel = "ms",
number_format = "%5.1lf ms", data = {
sources = { ping = { "ping" } },
options = { ping__ping = { noarea = true, title = "%di" } }
} },
-- Ping droprate
{ title = "%H: ICMP Drop Rate", vlabel = "%",
number_format = "%5.2lf %%", data = {
types = { "ping_droprate" },
options = { ping_droprate = { title = "%di" } }
} },
-- Ping standard deviation
{ title = "%H: ICMP Standard Deviation", vlabel = "ms",
number_format = "%5.2lf ms", data = {
types = { "ping_stddev" },
options = { ping_stddev = { title = "%di" } }
} },
}
end
| apache-2.0 |
Mijyuoon/starfall | lua/entities/starfall_screen/shared.lua | 1 | 1169 | ENT.Type = "anim"
ENT.Base = "base_wire_entity"
ENT.PrintName = "Starfall"
ENT.Author = "Colonel Thirty Two"
ENT.Contact = "initrd.gz@gmail.com"
ENT.Purpose = ""
ENT.Instructions = ""
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.SFAcceptNetMsg = true
function ENT:hudModelCheck()
return self:GetModel() == "models/bull/dynamicbutton.mdl"
end
function ENT:resetCpuTime()
if self.instance then
self.instance:resetCpuTime()
end
end
function ENT:runScriptHook(hook, ...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local instance = SF.instance
SF.instance = nil
local ok, rt = self.instance:runScriptHook(hook, ...)
SF.instance = instance
if not ok then self:Error(rt)
else return rt end
end
end
function ENT:runScriptHookForResult(hook,...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local instance = SF.instance
SF.instance = nil
local ok, rt = self.instance:runScriptHookForResult(hook, ...)
SF.instance = instance
if not ok then self:Error(rt)
else return rt end
end
end | bsd-3-clause |
Lsty/ygopro-scripts | c70456282.lua | 5 | 2233 | --A BF-霧雨のクナイ
function c70456282.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c70456282.spcon)
e1:SetOperation(c70456282.spop)
c:RegisterEffect(e1)
--lv change
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetTarget(c70456282.lvtg)
e2:SetOperation(c70456282.lvop)
c:RegisterEffect(e2)
end
function c70456282.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>-1
and Duel.CheckReleaseGroup(c:GetControler(),Card.IsSetCard,1,nil,0x33)
end
function c70456282.spop(e,tp,eg,ep,ev,re,r,rp,c)
local g=Duel.SelectReleaseGroup(tp,Card.IsSetCard,1,1,nil,0x33)
Duel.Release(g,REASON_COST)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_ADD_TYPE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(TYPE_TUNER)
e1:SetReset(RESET_EVENT+0xfe0000)
c:RegisterEffect(e1)
end
function c70456282.filter(c)
return c:IsFaceup() and c:IsType(TYPE_SYNCHRO) and c:GetLevel()>0
end
function c70456282.lvtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c70456282.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c70456282.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c70456282.filter,tp,LOCATION_MZONE,0,1,1,nil)
local t={}
local i=1
local p=1
local lv=g:GetFirst():GetLevel()
for i=1,8 do
if lv~=i then t[p]=i p=p+1 end
end
t[p]=nil
Duel.Hint(HINT_SELECTMSG,tp,567)
e:SetLabel(Duel.AnnounceNumber(tp,table.unpack(t)))
end
function c70456282.lvop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Port_Bastok/npcs/Nokkhi_Jinjahl.lua | 12 | 5133 | -----------------------------------
-- Area: Port Bastok
-- NPC: Nokkhi Jinjahl
-- Type: Travelling Merchant NPC / NPC Quiver Maker / Bastok 1st Place
-- !pos 111 8 -47 236
-----------------------------------
local ID = require("scripts/zones/Port_Bastok/IDs");
-----------------------------------
function onTrade(player,npc,trade)
local ammoList =
{
{21307, 6199}, -- arrow, achiyalabopa
{21306, 6200}, -- arrow, adlivun
{19195, 5819}, -- arrow, antlion
{18154, 4221}, -- arrow, beetle
{21309, 6137}, -- arrow, chapuli
{18159, 4224}, -- arrow, demon
{21302, 6269}, -- arrow, eminent
{19800, 5912}, -- arrow, gargouille
{18156, 4222}, -- arrow, horn
{17320, 4225}, -- arrow, iron
{17325, 5332}, -- arrow, kabura
{21308, 6138}, -- arrow, mantid
{21303, 6280}, -- arrow, ra'kaznar
{21304, 6202}, -- arrow, raaz
{19182, 5871}, -- arrow, ruszor
{18155, 4223}, -- arrow, scorpion
{17321, 4226}, -- arrow, silver
{18158, 5333}, -- arrow, sleep
{17330, 4219}, -- arrow, stone
{21305, 6201}, -- arrow, tulfaire
{21314, 6278}, -- bolt, abrasion
{21321, 6203}, -- bolt, achiyalabopa
{18148, 5335}, -- bolt, acid
{19801, 5913}, -- bolt, adaman
{21320, 6204}, -- bolt, adlivun
{21318, 6206}, -- bolt, bismuth
{18150, 5334}, -- bolt, blind
{18151, 5339}, -- bolt, bloody
{21322, 6140}, -- bolt, damascus
{19183, 5872}, -- bolt, dark adaman
{19196, 5820}, -- bolt, darkling
{17338, 4229}, -- bolt, darksteel
{21316, 6270}, -- bolt, eminent
{19197, 5821}, -- bolt, fusion
{21313, 6310}, -- bolt, gashing
{18153, 5336}, -- bolt, holy
{21324, 6139}, -- bolt, midrium
{17337, 4228}, -- bolt, mythril
{21323, 6141}, -- bolt, oxidant
{21317, 6281}, -- bolt, ra'kaznar
{21315, 6279}, -- bolt, righteous
{18149, 5337}, -- bolt, sleep
{21319, 6205}, -- bolt, titanium
{18152, 5338}, -- bolt, venom
{19803, 5915}, -- bullet, adaman
{21336, 6208}, -- bullet, adlivun
{21337, 6207}, -- bullet, achiyalabopa
{17340, 5363}, -- bullet
{21333, 6210}, -- bullet, bismuth
{17343, 5359}, -- bullet, bronze
{21338, 6143}, -- bullet, damascus
{19184, 5873}, -- bullet, dark adaman
{21330, 6311}, -- bullet, decimating
{21328, 6437}, -- bullet, divine
{19198, 5822}, -- bullet, dweomer
{21331, 6271}, -- bullet, eminent
{17312, 5353}, -- bullet, iron
{19802, 5914}, -- bullet, orichalcum
{19199, 5823}, -- bullet, oberon's
{21332, 6282}, -- bullet, ra'kaznar
{17341, 5340}, -- bullet, silver
{18723, 5416}, -- bullet, steel
{18160, 5341}, -- bullet, spartan
{21335, 6209}, -- bullet, titanium
{2176, 5402}, -- card, fire
{2177, 5403}, -- card, ice
{2178, 5404}, -- card, wind
{2179, 5405}, -- card, earth
{2180, 5406}, -- card, thunder
{2181, 5407}, -- card, water
{2182, 5408}, -- card, light
{2183, 5409}, -- card, dark
};
local carnationsNeeded = 0;
local giveToPlayer = {};
-- check for invalid items
for i = 0,8,1 do
local itemId = trade:getItemId(i);
if (itemId > 0 and itemId ~= 948) then
local validSlot = false;
for k, v in pairs(ammoList) do
if (v[1] == itemId) then
local itemQty = trade:getSlotQty(i);
if (itemQty % 99 ~= 0) then
player:messageSpecial(ID.text.NOKKHI_BAD_COUNT);
return;
end;
local stacks = itemQty / 99;
carnationsNeeded = carnationsNeeded + stacks;
giveToPlayer[#giveToPlayer+1] = {v[2], stacks};
validSlot = true;
break;
end
end
if (not validSlot) then
player:messageSpecial(ID.text.NOKKHI_BAD_ITEM);
return;
end
end
end
-- check for correct number of carnations
if (carnationsNeeded == 0 or trade:getItemQty(948) ~= carnationsNeeded) then
player:messageSpecial(ID.text.NOKKHI_BAD_COUNT);
return;
end
-- check for enough inventory space
if (player:getFreeSlotsCount() < carnationsNeeded) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, giveToPlayer[1][1]);
return;
end
-- make the trade
player:messageSpecial(ID.text.NOKKHI_GOOD_TRADE);
for k, v in pairs(giveToPlayer) do
player:addItem(v[1], v[2]);
player:messageSpecial(ID.text.ITEM_OBTAINED,v[1]);
end
player:tradeComplete();
end;
function onTrigger(player,npc)
player:startEvent(285,npc:getID());
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c68073522.lua | 5 | 1217 | --魂吸収
function c68073522.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--LP up
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(68073522,0))
e2:SetCategory(CATEGORY_RECOVER)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_REMOVE)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c68073522.condition)
e2:SetTarget(c68073522.target)
e2:SetOperation(c68073522.operation)
c:RegisterEffect(e2)
end
function c68073522.filter(c)
return not c:IsType(TYPE_TOKEN)
end
function c68073522.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c68073522.filter,1,nil)
end
function c68073522.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsRelateToEffect(e) end
local ct=eg:FilterCount(c68073522.filter,nil)
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(ct*500)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,0,0,tp,ct*500)
end
function c68073522.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
end
| gpl-2.0 |
gallenmu/MoonGen | libmoon/lua/lib/argparse.lua | 4 | 29810 | -- The MIT License (MIT)
-- Copyright (c) 2013 - 2015 Peter Melnichenko
-- 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.
local function deep_update(t1, t2)
for k, v in pairs(t2) do
if type(v) == "table" then
v = deep_update({}, v)
end
t1[k] = v
end
return t1
end
-- A property is a tuple {name, callback}.
-- properties.args is number of properties that can be set as arguments
-- when calling an object.
local function class(prototype, properties, parent)
-- Class is the metatable of its instances.
local cl = {}
cl.__index = cl
if parent then
cl.__prototype = deep_update(deep_update({}, parent.__prototype), prototype)
else
cl.__prototype = prototype
end
if properties then
local names = {}
-- Create setter methods and fill set of property names.
for _, property in ipairs(properties) do
local name, callback = property[1], property[2]
cl[name] = function(self, value)
if not callback(self, value) then
self["_" .. name] = value
end
return self
end
names[name] = true
end
function cl.__call(self, ...)
-- When calling an object, if the first argument is a table,
-- interpret keys as property names, else delegate arguments
-- to corresponding setters in order.
if type((...)) == "table" then
for name, value in pairs((...)) do
if names[name] then
self[name](self, value)
end
end
else
local nargs = select("#", ...)
for i, property in ipairs(properties) do
if i > nargs or i > properties.args then
break
end
local arg = select(i, ...)
if arg ~= nil then
self[property[1]](self, arg)
end
end
end
return self
end
end
-- If indexing class fails, fallback to its parent.
local class_metatable = {}
class_metatable.__index = parent
function class_metatable.__call(self, ...)
-- Calling a class returns its instance.
-- Arguments are delegated to the instance.
local object = deep_update({}, self.__prototype)
setmetatable(object, self)
return object(...)
end
return setmetatable(cl, class_metatable)
end
local function typecheck(name, types, value)
for _, type_ in ipairs(types) do
if type(value) == type_ then
return true
end
end
error(("bad property '%s' (%s expected, got %s)"):format(name, table.concat(types, " or "), type(value)))
end
local function typechecked(name, ...)
local types = {...}
return {name, function(_, value) typecheck(name, types, value) end}
end
local multiname = {"name", function(self, value)
typecheck("name", {"string"}, value)
for alias in value:gmatch("%S+") do
self._name = self._name or alias
table.insert(self._aliases, alias)
end
-- Do not set _name as with other properties.
return true
end}
local function parse_boundaries(str)
if tonumber(str) then
return tonumber(str), tonumber(str)
end
if str == "*" then
return 0, math.huge
end
if str == "+" then
return 1, math.huge
end
if str == "?" then
return 0, 1
end
if str:match "^%d+%-%d+$" then
local min, max = str:match "^(%d+)%-(%d+)$"
return tonumber(min), tonumber(max)
end
if str:match "^%d+%+$" then
local min = str:match "^(%d+)%+$"
return tonumber(min), math.huge
end
end
local function boundaries(name)
return {name, function(self, value)
typecheck(name, {"number", "string"}, value)
local min, max = parse_boundaries(value)
if not min then
error(("bad property '%s'"):format(name))
end
self["_min" .. name], self["_max" .. name] = min, max
end}
end
local actions = {}
local option_action = {"action", function(_, value)
typecheck("action", {"function", "string"}, value)
if type(value) == "string" and not actions[value] then
error(("unknown action '%s'"):format(value))
end
end}
local option_init = {"init", function(self)
self._has_init = true
end}
local option_default = {"default", function(self, value)
if type(value) ~= "string" then
self._init = value
self._has_init = true
return true
end
end}
local add_help = {"add_help", function(self, value)
typecheck("add_help", {"boolean", "string", "table"}, value)
if self._has_help then
table.remove(self._options)
self._has_help = false
end
if value then
local help = self:flag()
:description "Show this help message and exit."
:action(function()
print(self:get_help())
os.exit(0)
end)
if value ~= true then
help = help(value)
end
if not help._name then
help "-h" "--help"
end
self._has_help = true
end
end}
local Parser = class({
_arguments = {},
_options = {},
_commands = {},
_mutexes = {},
_require_command = true,
_handle_options = true
}, {
args = 3,
typechecked("name", "string"),
typechecked("description", "string"),
typechecked("epilog", "string"),
typechecked("usage", "string"),
typechecked("help", "string"),
typechecked("require_command", "boolean"),
typechecked("handle_options", "boolean"),
typechecked("action", "function"),
typechecked("command_target", "string"),
add_help
})
local Command = class({
_aliases = {}
}, {
args = 3,
multiname,
typechecked("description", "string"),
typechecked("epilog", "string"),
typechecked("target", "string"),
typechecked("usage", "string"),
typechecked("help", "string"),
typechecked("require_command", "boolean"),
typechecked("handle_options", "boolean"),
typechecked("action", "function"),
typechecked("command_target", "string"),
add_help
}, Parser)
local Argument = class({
_minargs = 1,
_maxargs = 1,
_mincount = 1,
_maxcount = 1,
_defmode = "unused",
_show_default = true
}, {
args = 5,
typechecked("name", "string"),
typechecked("description", "string"),
option_default,
typechecked("convert", "function", "table"),
boundaries("args"),
typechecked("target", "string"),
typechecked("defmode", "string"),
typechecked("show_default", "boolean"),
typechecked("argname", "string", "table"),
{"combine", function(self, val) typecheck("combine", {"boolean", "nil"}, val) self._combine = val == nil or val return true end},
option_action,
option_init
})
local Option = class({
_aliases = {},
_mincount = 0,
_overwrite = true
}, {
args = 6,
multiname,
typechecked("description", "string"),
option_default,
typechecked("convert", "function", "table"),
boundaries("args"),
boundaries("count"),
typechecked("target", "string"),
typechecked("defmode", "string"),
typechecked("show_default", "boolean"),
typechecked("overwrite", "boolean"),
typechecked("argname", "string", "table"),
option_action,
option_init
}, Argument)
function Argument:_get_argument_list()
local buf = {}
local i = 1
while i <= math.min(self._minargs, 3) do
local argname = self:_get_argname(i)
if self._default and self._defmode:find "a" then
argname = "[" .. argname .. "]"
end
table.insert(buf, argname)
i = i+1
end
while i <= math.min(self._maxargs, 3) do
table.insert(buf, "[" .. self:_get_argname(i) .. "]")
i = i+1
if self._maxargs == math.huge then
break
end
end
if i < self._maxargs and not self._combine then
table.insert(buf, "...")
end
return buf
end
function Argument:_get_usage()
local usage = table.concat(self:_get_argument_list(), " ")
if self._default and self._defmode:find "u" then
if self._maxargs > 1 or (self._minargs == 1 and not self._defmode:find "a") then
usage = "[" .. usage .. "]"
end
end
return usage
end
function actions.store_true(result, target)
result[target] = true
end
function actions.store_false(result, target)
result[target] = false
end
function actions.store(result, target, argument)
result[target] = argument
end
function actions.count(result, target, _, overwrite)
if not overwrite then
result[target] = result[target] + 1
end
end
function actions.append(result, target, argument, overwrite)
result[target] = result[target] or {}
table.insert(result[target], argument)
if overwrite then
table.remove(result[target], 1)
end
end
function actions.concat(result, target, arguments, overwrite)
if overwrite then
error("'concat' action can't handle too many invocations")
end
result[target] = result[target] or {}
for _, argument in ipairs(arguments) do
table.insert(result[target], argument)
end
end
function Argument:_get_action()
local action, init
if self._maxcount == 1 then
if self._maxargs == 0 then
action, init = "store_true", nil
else
action, init = "store", nil
end
else
if self._maxargs == 0 then
action, init = "count", 0
else
action, init = "append", {}
end
end
if self._action then
action = self._action
end
if self._has_init then
init = self._init
end
if type(action) == "string" then
action = actions[action]
end
return action, init
end
-- Returns placeholder for `narg`-th argument.
function Argument:_get_argname(narg)
local argname = self._argname or self:_get_default_argname()
if type(argname) == "table" then
return argname[narg]
else
return argname
end
end
function Argument:_get_default_argname()
return "<" .. self._name .. ">"
end
function Option:_get_default_argname()
return "<" .. self:_get_default_target() .. ">"
end
-- Returns label to be shown in the help message.
function Argument:_get_label()
return self._name
end
function Option:_get_label()
local variants = {}
local argument_list = self:_get_argument_list()
table.insert(argument_list, 1, nil)
for _, alias in ipairs(self._aliases) do
argument_list[1] = alias
table.insert(variants, table.concat(argument_list, " "))
end
return table.concat(variants, ", ")
end
function Command:_get_label()
return table.concat(self._aliases, ", ")
end
function Argument:_get_description()
if self._default and self._show_default then
if self._description then
return ("%s (default: %s)"):format(self._description, self._default)
else
return ("default: %s"):format(self._default)
end
else
return self._description or ""
end
end
function Command:_get_description()
return self._description or ""
end
function Option:_get_usage()
local usage = self:_get_argument_list()
table.insert(usage, 1, self._name)
usage = table.concat(usage, " ")
if self._mincount == 0 or self._default then
usage = "[" .. usage .. "]"
end
return usage
end
function Argument:_get_default_target()
return self._name
end
function Option:_get_default_target()
local res
for _, alias in ipairs(self._aliases) do
if alias:sub(1, 1) == alias:sub(2, 2) then
res = alias:sub(3)
break
end
end
res = res or self._name:sub(2)
return (res:gsub("-", "_"))
end
function Option:_is_vararg()
return self._maxargs ~= self._minargs
end
function Parser:_get_fullname()
local parent = self._parent
local buf = {self._name}
while parent do
table.insert(buf, 1, parent._name)
parent = parent._parent
end
return table.concat(buf, " ")
end
function Parser:_update_charset(charset)
charset = charset or {}
for _, command in ipairs(self._commands) do
command:_update_charset(charset)
end
for _, option in ipairs(self._options) do
for _, alias in ipairs(option._aliases) do
charset[alias:sub(1, 1)] = true
end
end
return charset
end
function Parser:argument(...)
local argument = Argument(...)
table.insert(self._arguments, argument)
return argument
end
function Parser:option(...)
local option = Option(...)
if self._has_help then
table.insert(self._options, #self._options, option)
else
table.insert(self._options, option)
end
return option
end
function Parser:flag(...)
return self:option():args(0)(...)
end
function Parser:command(...)
local command = Command():add_help(true)(...)
command._parent = self
table.insert(self._commands, command)
return command
end
function Parser:mutex(...)
local options = {...}
for i, option in ipairs(options) do
assert(getmetatable(option) == Option, ("bad argument #%d to 'mutex' (Option expected)"):format(i))
end
table.insert(self._mutexes, options)
return self
end
local max_usage_width = 120
local usage_welcome = "Usage: "
function Parser:get_usage()
if self._usage then
return self._usage
end
local lines = {usage_welcome .. self:_get_fullname()}
local function add(s)
if #lines[#lines]+1+#s <= max_usage_width then
lines[#lines] = lines[#lines] .. " " .. s
else
lines[#lines+1] = (" "):rep(#usage_welcome) .. s
end
end
-- This can definitely be refactored into something cleaner
local mutex_options = {}
local vararg_mutexes = {}
-- First, put mutexes which do not contain vararg options and remember those which do
for _, mutex in ipairs(self._mutexes) do
local buf = {}
local is_vararg = false
for _, option in ipairs(mutex) do
if option:_is_vararg() then
is_vararg = true
end
table.insert(buf, option:_get_usage())
mutex_options[option] = true
end
local repr = "(" .. table.concat(buf, " | ") .. ")"
if is_vararg then
table.insert(vararg_mutexes, repr)
else
add(repr)
end
end
-- Second, put regular options
for _, option in ipairs(self._options) do
if not mutex_options[option] and not option:_is_vararg() then
add(option:_get_usage())
end
end
-- Put positional arguments
for _, argument in ipairs(self._arguments) do
add(argument:_get_usage())
end
-- Put mutexes containing vararg options
for _, mutex_repr in ipairs(vararg_mutexes) do
add(mutex_repr)
end
for _, option in ipairs(self._options) do
if not mutex_options[option] and option:_is_vararg() then
add(option:_get_usage())
end
end
if #self._commands > 0 then
if self._require_command then
add("<command>")
else
add("[<command>]")
end
add("...")
end
return table.concat(lines, "\n")
end
local margin_len = 3
local margin_len2 = 40
local margin = (" "):rep(margin_len)
local margin2 = (" "):rep(margin_len2)
local function make_two_columns(s1, s2)
if s2 == "" then
return margin .. s1
end
s2 = s2:gsub("\n", "\n" .. margin2)
if #s1 < (margin_len2-margin_len) then
return margin .. s1 .. (" "):rep(margin_len2-margin_len-#s1) .. s2
else
return margin .. s1 .. "\n" .. margin2 .. s2
end
end
function Parser:get_help()
if self._help then
return self._help
end
local blocks = {self:get_usage()}
if self._description then
table.insert(blocks, self._description)
end
local labels = {"Arguments:", "Options:", "Commands:"}
for i, elements in ipairs{self._arguments, self._options, self._commands} do
if #elements > 0 then
local buf = {labels[i]}
for _, element in ipairs(elements) do
table.insert(buf, make_two_columns(element:_get_label(), element:_get_description()))
end
table.insert(blocks, table.concat(buf, "\n"))
end
end
if self._epilog then
table.insert(blocks, self._epilog)
end
return table.concat(blocks, "\n\n")
end
local function get_tip(context, wrong_name)
local context_pool = {}
local possible_name
local possible_names = {}
for name in pairs(context) do
if type(name) == "string" then
for i = 1, #name do
possible_name = name:sub(1, i - 1) .. name:sub(i + 1)
if not context_pool[possible_name] then
context_pool[possible_name] = {}
end
table.insert(context_pool[possible_name], name)
end
end
end
for i = 1, #wrong_name + 1 do
possible_name = wrong_name:sub(1, i - 1) .. wrong_name:sub(i + 1)
if context[possible_name] then
possible_names[possible_name] = true
elseif context_pool[possible_name] then
for _, name in ipairs(context_pool[possible_name]) do
possible_names[name] = true
end
end
end
local first = next(possible_names)
if first then
if next(possible_names, first) then
local possible_names_arr = {}
for name in pairs(possible_names) do
table.insert(possible_names_arr, "'" .. name .. "'")
end
table.sort(possible_names_arr)
return "\nDid you mean one of these: " .. table.concat(possible_names_arr, " ") .. "?"
else
return "\nDid you mean '" .. first .. "'?"
end
else
return ""
end
end
local ElementState = class({
invocations = 0
})
function ElementState:__call(state, element)
self.state = state
self.result = state.result
self.element = element
self.target = element._target or element:_get_default_target()
self.action, self.result[self.target] = element:_get_action()
return self
end
function ElementState:error(fmt, ...)
self.state:error(fmt, ...)
end
function ElementState:convert(argument)
local converter = self.element._convert
if converter then
local ok, err
if type(converter) == "function" then
ok, err = converter(argument)
else
ok = converter[argument]
end
if ok == nil then
self:error(err and "%s" or "malformed argument '%s'", err or argument)
end
argument = ok
end
return argument
end
function ElementState:default(mode)
return self.element._defmode:find(mode) and self.element._default
end
local function bound(noun, min, max, is_max)
local res = ""
if min ~= max then
res = "at " .. (is_max and "most" or "least") .. " "
end
local number = is_max and max or min
return res .. tostring(number) .. " " .. noun .. (number == 1 and "" or "s")
end
function ElementState:invoke(alias)
self.open = true
self.name = ("%s '%s'"):format(alias and "option" or "argument", alias or self.element._name)
self.overwrite = false
if self.invocations >= self.element._maxcount then
if self.element._overwrite then
self.overwrite = true
else
self:error("%s must be used %s", self.name, bound("time", self.element._mincount, self.element._maxcount, true))
end
else
self.invocations = self.invocations + 1
end
self.args = {}
if self.element._maxargs <= 0 then
self:close()
end
return self.open
end
function ElementState:pass(argument)
argument = self:convert(argument)
table.insert(self.args, argument)
if #self.args >= self.element._maxargs then
self:close()
end
return self.open
end
function ElementState:complete_invocation()
while #self.args < self.element._minargs do
self:pass(self.element._default)
end
end
function ElementState:close()
if self.open then
self.open = false
if #self.args < self.element._minargs then
if self:default("a") then
self:complete_invocation()
else
if #self.args == 0 then
if getmetatable(self.element) == Argument then
self:error("missing %s", self.name)
elseif self.element._maxargs == 1 then
self:error("%s requires an argument", self.name)
end
end
self:error("%s requires %s", self.name, bound("argument", self.element._minargs, self.element._maxargs))
end
end
local args = self.args
if self.element._maxargs <= 1 then
args = args[1]
end
if self.element._maxargs == 1 and self.element._minargs == 0 and self.element._mincount ~= self.element._maxcount then
args = self.args
end
if self.element._combine then
args = table.concat(args, " ")
end
self.action(self.result, self.target, args, self.overwrite)
end
end
local ParseState = class({
result = {},
options = {},
arguments = {},
argument_i = 1,
element_to_mutexes = {},
mutex_to_used_option = {},
command_actions = {}
})
function ParseState:__call(parser, error_handler)
self.parser = parser
self.error_handler = error_handler
self.charset = parser:_update_charset()
self:switch(parser)
return self
end
function ParseState:error(fmt, ...)
self.error_handler(self.parser, fmt:format(...))
end
function ParseState:switch(parser)
self.parser = parser
if parser._action then
table.insert(self.command_actions, {action = parser._action, name = parser._name})
end
for _, option in ipairs(parser._options) do
option = ElementState(self, option)
table.insert(self.options, option)
for _, alias in ipairs(option.element._aliases) do
self.options[alias] = option
end
end
for _, mutex in ipairs(parser._mutexes) do
for _, option in ipairs(mutex) do
if not self.element_to_mutexes[option] then
self.element_to_mutexes[option] = {}
end
table.insert(self.element_to_mutexes[option], mutex)
end
end
for _, argument in ipairs(parser._arguments) do
argument = ElementState(self, argument)
table.insert(self.arguments, argument)
argument:invoke()
end
self.handle_options = parser._handle_options
self.argument = self.arguments[self.argument_i]
self.commands = parser._commands
for _, command in ipairs(self.commands) do
for _, alias in ipairs(command._aliases) do
self.commands[alias] = command
end
end
end
function ParseState:get_option(name)
local option = self.options[name]
if not option then
self:error("unknown option '%s'%s", name, get_tip(self.options, name))
else
return option
end
end
function ParseState:get_command(name)
local command = self.commands[name]
if not command then
if #self.commands > 0 then
self:error("unknown command '%s'%s", name, get_tip(self.commands, name))
else
self:error("too many arguments")
end
else
return command
end
end
function ParseState:invoke(option, name)
self:close()
if self.element_to_mutexes[option.element] then
for _, mutex in ipairs(self.element_to_mutexes[option.element]) do
local used_option = self.mutex_to_used_option[mutex]
if used_option and used_option ~= option then
self:error("option '%s' can not be used together with %s", name, used_option.name)
else
self.mutex_to_used_option[mutex] = option
end
end
end
if option:invoke(name) then
self.option = option
end
end
function ParseState:pass(arg)
if self.option then
if not self.option:pass(arg) then
self.option = nil
end
elseif self.argument then
if not self.argument:pass(arg) then
self.argument_i = self.argument_i + 1
self.argument = self.arguments[self.argument_i]
end
else
local command = self:get_command(arg)
self.result[command._target or command._name] = true
if self.parser._command_target then
self.result[self.parser._command_target] = command._name
end
self:switch(command)
end
end
function ParseState:close()
if self.option then
self.option:close()
self.option = nil
end
end
function ParseState:finalize()
self:close()
for i = self.argument_i, #self.arguments do
local argument = self.arguments[i]
if #argument.args == 0 and argument:default("u") then
argument:complete_invocation()
else
argument:close()
end
end
if self.parser._require_command and #self.commands > 0 then
self:error("a command is required")
end
for _, option in ipairs(self.options) do
local name = option.name or ("option '%s'"):format(option.element._name)
if option.invocations == 0 then
if option:default("u") then
option:invoke(name)
option:complete_invocation()
option:close()
end
end
local mincount = option.element._mincount
if option.invocations < mincount then
if option:default("a") then
while option.invocations < mincount do
option:invoke(name)
option:close()
end
elseif option.invocations == 0 then
self:error("missing %s", name)
else
self:error("%s must be used %s", name, bound("time", mincount, option.element._maxcount))
end
end
end
for i = #self.command_actions, 1, -1 do
self.command_actions[i].action(self.result, self.command_actions[i].name)
end
end
function ParseState:parse(args)
for _, arg in ipairs(args) do
local plain = true
if self.handle_options then
local first = arg:sub(1, 1)
if self.charset[first] then
if #arg > 1 then
plain = false
if arg:sub(2, 2) == first then
if #arg == 2 then
self:close()
self.handle_options = false
else
local equals = arg:find "="
if equals then
local name = arg:sub(1, equals - 1)
local option = self:get_option(name)
if option.element._maxargs <= 0 then
self:error("option '%s' does not take arguments", name)
end
self:invoke(option, name)
self:pass(arg:sub(equals + 1))
else
local option = self:get_option(arg)
self:invoke(option, arg)
end
end
else
for i = 2, #arg do
local name = first .. arg:sub(i, i)
local option = self:get_option(name)
self:invoke(option, name)
if i ~= #arg and option.element._maxargs > 0 then
self:pass(arg:sub(i + 1))
break
end
end
end
end
end
end
if plain then
self:pass(arg)
end
end
self:finalize()
return self.result
end
function Parser:error(msg)
io.stderr:write(("%s\n\nError: %s\n"):format(self:get_usage(), msg))
os.exit(1)
end
-- Compatibility with strict.lua and other checkers:
local default_cmdline = rawget(_G, "arg") or {}
function Parser:_parse(args, error_handler)
return ParseState(self, error_handler):parse(args or self.default_args or default_cmdline)
end
local function normalizeArgs(...)
local args = ...
if args and type(args) ~= "table" then
args = {...}
-- undo libmoon pre-parsing of numbers
for i, v in ipairs(args) do
args[i] = tostring(v)
end
end
return args
end
function Parser:args(...)
self.default_args = normalizeArgs(...)
end
function Parser:parse(...)
return self:_parse(normalizeArgs(...), self.error)
end
local function xpcall_error_handler(err)
return tostring(err) .. "\noriginal " .. debug.traceback("", 2):sub(2)
end
function Parser:pparse(...)
local parse_error
local args = normalizeArgs(...)
local ok, result = xpcall(function()
return self:_parse(args, function(_, err)
parse_error = err
error(err, 0)
end)
end, xpcall_error_handler)
if ok then
return true, result
elseif not parse_error then
error(result, 0)
else
return false, parse_error
end
end
return function(...)
return Parser(default_cmdline[0]):add_help(true)(...)
end
| mit |
Lsty/ygopro-scripts | c30888983.lua | 9 | 1410 | --方舟の選別
function c30888983.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_SUMMON)
e1:SetCondition(c30888983.condition)
e1:SetCost(c30888983.cost)
e1:SetTarget(c30888983.target)
e1:SetOperation(c30888983.activate)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_FLIP_SUMMON)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_SPSUMMON)
c:RegisterEffect(e3)
end
function c30888983.cfilter(c,rc)
return c:IsFaceup() and c:IsRace(rc)
end
function c30888983.filter(c)
return Duel.IsExistingMatchingCard(c30888983.cfilter,0,LOCATION_MZONE,LOCATION_MZONE,1,nil,c:GetRace())
end
function c30888983.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentChain()==0 and eg:IsExists(c30888983.filter,1,nil)
end
function c30888983.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c30888983.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=eg:Filter(c30888983.filter,nil)
Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c30888983.activate(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c30888983.filter,nil)
Duel.NegateSummon(g)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c23639291.lua | 3 | 1473 | --アグレッシブ・クラウディアン
function c23639291.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c23639291.condition)
e1:SetTarget(c23639291.target)
e1:SetOperation(c23639291.operation)
c:RegisterEffect(e1)
end
function c23639291.condition(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
return eg:GetCount()==1 and tc:IsControler(tp) and tc:GetPreviousControler()==tp and tc:IsReason(REASON_DESTROY)
and tc:GetReasonEffect() and tc:GetReasonEffect():GetHandler()==tc
end
function c23639291.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc==eg:GetFirst() end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and eg:GetFirst():IsCanBeSpecialSummoned(e,0,tp,false,false) and eg:GetFirst():IsCanBeEffectTarget(e) end
Duel.SetTargetCard(eg:GetFirst())
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,eg:GetFirst(),1,0,0)
end
function c23639291.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_ATTACK) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_CHANGE_POS_E)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
Duel.SpecialSummonComplete()
tc:AddCounter(0x19,1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c90640901.lua | 3 | 1844 | --リバース・バスター
function c90640901.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e1:SetValue(c90640901.vala)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
c:RegisterEffect(e2)
--actlimit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_ATTACK_ANNOUNCE)
e3:SetOperation(c90640901.atkop)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(90640901,0))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLE_START)
e4:SetCondition(c90640901.descon)
e4:SetTarget(c90640901.destg)
e4:SetOperation(c90640901.desop)
c:RegisterEffect(e4)
end
function c90640901.vala(e,c)
return not c:IsFacedown()
end
function c90640901.atkop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetTargetRange(0,1)
e1:SetValue(c90640901.aclimit)
e1:SetReset(RESET_PHASE+PHASE_DAMAGE)
Duel.RegisterEffect(e1,tp)
end
function c90640901.aclimit(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c90640901.descon(e,tp,eg,ep,ev,re,r,rp)
local d=Duel.GetAttackTarget()
return e:GetHandler()==Duel.GetAttacker() and d and d:IsFacedown() and d:IsDefencePos()
end
function c90640901.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,Duel.GetAttackTarget(),1,0,0)
end
function c90640901.desop(e,tp,eg,ep,ev,re,r,rp)
local d=Duel.GetAttackTarget()
if d:IsRelateToBattle() then
Duel.Destroy(d,REASON_EFFECT)
end
end
| gpl-2.0 |
Mkalo/forgottenserver | data/creaturescripts/scripts/droploot.lua | 19 | 1207 | function onDeath(player, corpse, killer, mostDamage, unjustified, mostDamage_unjustified)
if getPlayerFlagValue(player, PlayerFlag_NotGenerateLoot) or player:getVocation():getId() == VOCATION_NONE then
return true
end
local amulet = player:getSlotItem(CONST_SLOT_NECKLACE)
if amulet and amulet.itemid == ITEM_AMULETOFLOSS and not isInArray({SKULL_RED, SKULL_BLACK}, player:getSkull()) then
local isPlayer = false
if killer then
if killer:isPlayer() then
isPlayer = true
else
local master = killer:getMaster()
if master and master:isPlayer() then
isPlayer = true
end
end
end
if not isPlayer or not player:hasBlessing(6) then
player:removeItem(ITEM_AMULETOFLOSS, 1, -1, false)
end
else
for i = CONST_SLOT_HEAD, CONST_SLOT_AMMO do
local item = player:getSlotItem(i)
if item then
if isInArray({SKULL_RED, SKULL_BLACK}, player:getSkull()) or math.random(item:isContainer() and 100 or 1000) <= player:getLossPercent() then
if not item:moveTo(corpse) then
item:remove()
end
end
end
end
end
if not player:getSlotItem(CONST_SLOT_BACKPACK) then
player:addItem(ITEM_BAG, 1, false, CONST_SLOT_BACKPACK)
end
return true
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Nyzul_Isle/mobs/Naja_Salaheem.lua | 9 | 2870 | -----------------------------------
-- Area: Nyzul Isle (Path of Darkness)
-- Mob: Naja Salaheem
-----------------------------------
local ID = require("scripts/zones/Nyzul_Isle/IDs")
require("scripts/globals/allyassist");
require("scripts/globals/instance");
-----------------------------------
-- Path to Stage 2 Position
local stage2Position =
{
499, 0, -531,
500, 0, -509,
}
-- Path to Stage 3 Position
local stage3Position =
{
490, 0, -500,
473, 0, -499,
473, 0, -486,
459, 0, -486,
460, 0, -446,
}
function onMobSpawn(mob)
mob:addListener("WEAPONSKILL_STATE_ENTER", "WS_START_MSG", function(mob, skillID)
if (skillID == 165) then
mob:showText(mob,ID.text.CHA_CHING);
elseif (skillID == 168) then
mob:showText(mob,ID.text.TWELVE_GOLD_COINS);
elseif (skillID == 169) then
mob:showText(mob,ID.text.NINETY_NINE_SILVER_COINS);
end
end);
end;
function onMobEngaged(mob, target)
-- localVar because we don't want it to repeat she engages a new target.
if (mob:getLocalVar("started") == 0) then
mob:showText(mob,ID.text.ALRRRIGHTY);
mob:setLocalVar("started", 1);
end
end;
function onMobFight(mob,target)
if (mob:getHPP() <= 50 and mob:getLocalVar("lowHPmsg") == 0) then
mob:showText(mob,ID.text.OW);
mob:setLocalVar("lowHPmsg", 1)
elseif (mob:getHPP() > 50 and mob:getLocalVar("lowHPmsg") == 1) then
mob:setLocalVar("lowHPmsg", 0)
end
end;
function onMobDisengaged(mob, target)
local ready = mob:getLocalVar("ready");
if (ready == 1) then
dsp.ally.startAssist(mob, dsp.ally.ASSIST_RANDOM);
end
end;
function onMobRoam(mob)
-- Advance to Stage 2 area
if (mob:getLocalVar("Stage") == 2) then
mob:showText(mob,ID.text.OH_ARE_WE_DONE);
mob:pathThrough(stage2Position, PATHFLAG_SCRIPT);
mob:setMobMod(dsp.mobMod.NO_MOVE, 1);
-- Advance to Stage 3 area
elseif (mob:getLocalVar("Stage") == 3) then
mob:showText(mob,ID.text.NOW_WERE_TALKIN);
mob:pathThrough(stage3Position, PATHFLAG_SCRIPT);
mob:setMobMod(dsp.mobMod.NO_MOVE, 1);
end
-- Ally Assist Check
local ready = mob:getLocalVar("ready");
-- Only start the path once
if (mob:isFollowingPath()) then
mob:setLocalVar("Stage",0);
-- Path must finish before Ally Asisst (no wallhacking!)
elseif (ready == 1) then
mob:setMobMod(dsp.mobMod.NO_MOVE, 0);
dsp.ally.startAssist(mob, dsp.ally.ASSIST_RANDOM);
end
end;
function onCriticalHit(mob)
mob:showText(mob,ID.text.OW);
end;
function onMobDeath(mob, player, isKiller)
-- Loss if Naja dies. Since player will be nil here, it'll only show once.
mob:showText(mob,ID.text.ABQUHBAH);
local instance = mob:getInstance();
instance:fail();
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c33248692.lua | 7 | 1128 | --オプションハンター
function c33248692.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_RECOVER)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetRange(LOCATION_SZONE)
e1:SetCondition(c33248692.condition)
e1:SetTarget(c33248692.target)
e1:SetOperation(c33248692.operation)
c:RegisterEffect(e1)
end
function c33248692.filter(c,tp)
return c:GetPreviousControler()==tp and c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE)
end
function c33248692.condition(e,tp,eg,ep,ev,re,r,rp,chk)
return eg:IsExists(c33248692.filter,1,nil,tp)
end
function c33248692.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local rec=eg:Filter(c33248692.filter,nil,tp):GetFirst():GetBaseAttack()
if rec<0 then rec=0 end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(rec)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,rec)
end
function c33248692.operation(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c76775123.lua | 9 | 1189 | --パトロール・ロボ
function c76775123.initial_effect(c)
--confirm
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(76775123,0))
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c76775123.condition)
e1:SetTarget(c76775123.target)
e1:SetOperation(c76775123.operation)
c:RegisterEffect(e1)
end
function c76775123.condition(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer()
end
function c76775123.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and chkc:IsFacedown() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFacedown,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEDOWN)
Duel.SelectTarget(tp,Card.IsFacedown,tp,0,LOCATION_ONFIELD,1,1,nil)
end
function c76775123.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsFacedown() then
Duel.ConfirmCards(tp,tc)
end
end
| gpl-2.0 |
sairon/packages | net/luci-app-squid/files/squid-cbi.lua | 95 | 1822 | --[[
LuCI Squid module
Copyright (C) 2015, OpenWrt.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
Author: Marko Ratkaj <marko.ratkaj@sartura.hr>
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
require "ubus"
m = Map("squid", translate("Squid"))
m.on_after_commit = function() luci.sys.call("/etc/init.d/squid restart") end
s = m:section(TypedSection, "squid")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
http_port = s:taboption("general", Value, "http_port", translate("Port"))
http_port.datatype = "portrange"
http_port.placeholder = "0-65535"
visible_hostname = s:taboption("general", Value, "visible_hostname", translate("Visible Hostname"))
visible_hostname.datatype="string"
visible_hostname.placeholder = "OpenWrt"
coredump_dir = s:taboption("general", Value, "coredump_dir", translate("Coredump files directory"))
coredump_dir.datatype="string"
coredump_dir.placeholder = "/tmp/squid"
s:tab("advanced", translate("Advanced Settings"))
squid_config_file = s:taboption("advanced", TextValue, "_data", "")
squid_config_file.wrap = "off"
squid_config_file.rows = 25
squid_config_file.rmempty = false
function squid_config_file.cfgvalue()
local uci = require "luci.model.uci".cursor_state()
local file = uci:get("squid", "squid", "config_file")
if file then
return fs.readfile(file) or ""
else
return ""
end
end
function squid_config_file.write(self, section, value)
if value then
local uci = require "luci.model.uci".cursor_state()
local file = uci:get("squid", "squid", "config_file")
fs.writefile(file, value:gsub("\r\n", "\n"))
end
end
return m
| gpl-2.0 |
MahmoudDolah/Firmware-Entry-Points-In-Memory | openwrt/openwrt-generic-x86/usr/lib/lua/luci/model/cbi/admin_network/proto_pppoa.lua | 18 | 3897 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local encaps, atmdev, vci, vpi, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
encaps = section:taboption("general", ListValue, "encaps", translate("PPPoA Encapsulation"))
encaps:value("vc", "VC-Mux")
encaps:value("llc", "LLC")
atmdev = section:taboption("general", Value, "atmdev", translate("ATM device number"))
atmdev.default = "0"
atmdev.datatype = "uinteger"
vci = section:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vci.default = "35"
vci.datatype = "uinteger"
vpi = section:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
vpi.default = "8"
vpi.datatype = "uinteger"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_failure.write = keepalive_interval.write
keepalive_failure.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
rastin45/magic78 | plugins/exchange.lua | 352 | 2076 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local function comma_value(n) -- credit http://richard.warburton.it
local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$')
return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
end
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(value, from, to)
local api = "https://currency-exchange.p.mashape.com/exchange?"
local par1 = "from="..from
local par2 = "&q="..value
local par3 = "&to="..to
local url = api..par1..par2..par3
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "text/plain"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
local curr = comma_value(value).." "..from.." = "..to.." "..comma_value(body)
return curr
end
local function run(msg, matches)
if tonumber(matches[1]) and not matches[2] then
local from = "USD"
local to = "IDR"
local value = matches[1]
return request(value, from, to)
elseif matches[2] and matches[3] then
local from = string.upper(matches[2]) or "USD"
local to = string.upper(matches[3]) or "IDR"
local value = matches[1] or "1"
return request(value, from, to, value)
end
end
return {
description = "Currency Exchange",
usage = {
"!exchange [value] : Exchange value from USD to IDR (default).",
"!exchange [value] [from] [to] : Get Currency Exchange by specifying the value of source (from) and destination (to).",
},
patterns = {
"^!exchange (%d+) (%a+) (%a+)$",
"^!exchange (%d+)",
},
run = run
}
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Western_Altepa_Desert/IDs.lua | 8 | 4455 | -----------------------------------
-- Area: Western_Altepa_Desert
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.WESTERN_ALTEPA_DESERT] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6386, -- You cannot obtain the <item>. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6397, -- You obtain <number> <item>!
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
DIG_THROW_AWAY = 7221, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7223, -- You dig and you dig, but find nothing.
THE_DOOR_IS_LOCKED = 7328, -- The door is locked.
DOES_NOT_RESPOND = 7329, -- It does not respond.
CANNOT_REMOVE_FRAG = 7345, -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7346, -- You have already obtained this monument's <keyitem>. Try searching for another.
ALREADY_HAVE_ALL_FRAGS = 7347, -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine!
FOUND_ALL_FRAGS = 7348, -- You have obtained <keyitem>! You now have all 8 fragments of light!
ZILART_MONUMENT = 7349, -- It is an ancient Zilart monument.
SENSE_OMINOUS_PRESENCE = 7390, -- You sense an ominous presence...
SOMETHING_IS_BURIED_HERE = 7408, -- It looks like something is buried here. If you had <item> you could dig it up.
PLAYER_OBTAINS_ITEM = 7621, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 7622, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 7623, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 7624, -- You already possess that temporary item.
NO_COMBINATION = 7629, -- You were unable to enter a combination.
REGIME_REGISTERED = 9807, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 11796, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
CACTUAR_CANTAUTOR_PH =
{
[17289559] = 17289560, -- -458.944 0.018 -557.266
[17289578] = 17289560, -- -478.142 -0.457 -596.091
},
CELPHIE_PH =
{
[17289473] = 17289453, -- 78.226 -0.497 69.745
[17289450] = 17289453, -- 57.256 0.116 13.972
[17289451] = 17289453, -- 70.263 0.130 -23.484
[17289452] = 17289453, -- 50.014 0.256 7.088
[17289407] = 17289453, -- 10.439 -0.280 -80.476
[17289406] = 17289453, -- 35.924 0.087 -98.228
[17289474] = 17289453, -- 118.575 -0.299 127.016
[17289277] = 17289453, -- 99.000 -0.030 116.000
},
CALCHAS_PH =
{
[17289545] = 17289547,
[17289546] = 17289547,
},
KING_VINEGARROON = 17289575,
SABOTENDER_ENAMORADO = 17289653,
EASTERN_SPHINX = 17289654,
WESTERN_SPHINX = 17289655,
MAHARAJA = 17289656,
},
npc =
{
CASKET_BASE = 17289721,
ALTEPA_GATE = 17289745,
PEDDLESTOX = 17289770,
BEASTMEN_TREASURE =
{
17289773, -- qm3
17289774, -- qm4
17289775, -- qm5
17289776, -- qm6
17289777, -- qm7
17289778, -- qm8
17289779, -- qm9
17289780, -- qm10
},
},
}
return zones[dsp.zone.WESTERN_ALTEPA_DESERT]
| gpl-3.0 |
Lsty/ygopro-scripts | c27340877.lua | 5 | 1180 | --DNA定期健診
function c27340877.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c27340877.target)
e1:SetOperation(c27340877.activate)
c:RegisterEffect(e1)
end
function c27340877.filter(c)
return c:IsFacedown() and c:GetRace()~=0
end
function c27340877.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c27340877.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c27340877.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEDOWN)
Duel.SelectTarget(tp,c27340877.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Hint(HINT_SELECTMSG,1-tp,562)
local rc=Duel.AnnounceAttribute(1-tp,2,0xffffff)
e:SetLabel(rc)
end
function c27340877.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFacedown() then
Duel.ConfirmCards(1-tp,tc)
if tc:IsAttribute(e:GetLabel()) then
Duel.Draw(1-tp,2,REASON_EFFECT)
else
Duel.Draw(tp,2,REASON_EFFECT)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c33866130.lua | 7 | 1283 | --ナチュル・クリフ
function c33866130.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(33866130,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c33866130.spcon)
e1:SetTarget(c33866130.sptg)
e1:SetOperation(c33866130.spop)
c:RegisterEffect(e1)
end
function c33866130.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c33866130.filter(c,e,tp)
return c:IsSetCard(0x2a) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c33866130.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c33866130.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c33866130.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c33866130.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_ATTACK)
end
| gpl-2.0 |
ThingMesh/openwrt-luci | applications/luci-firewall/luasrc/tools/firewall.lua | 59 | 6016 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.tools.firewall", package.seeall)
local ut = require "luci.util"
local ip = require "luci.ip"
local nx = require "nixio"
local translate, translatef = luci.i18n.translate, luci.i18n.translatef
local function tr(...)
return tostring(translate(...))
end
function fmt_neg(x)
if type(x) == "string" then
local v, neg = x:gsub("^ *! *", "")
if neg > 0 then
return v, "%s " % tr("not")
else
return x, ""
end
end
return x, ""
end
function fmt_mac(x)
if x and #x > 0 then
local m, n
local l = { tr("MAC"), " " }
for m in ut.imatch(x) do
m, n = fmt_neg(m)
l[#l+1] = "<var>%s%s</var>" %{ n, m }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("MACs")
end
return table.concat(l, "")
end
end
end
function fmt_port(x, d)
if x and #x > 0 then
local p, n
local l = { tr("port"), " " }
for p in ut.imatch(x) do
p, n = fmt_neg(p)
local a, b = p:match("(%d+)%D+(%d+)")
if a and b then
l[1] = tr("ports")
l[#l+1] = "<var>%s%d-%d</var>" %{ n, a, b }
else
l[#l+1] = "<var>%s%d</var>" %{ n, p }
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("ports")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_ip(x, d)
if x and #x > 0 then
local l = { tr("IP"), " " }
local v, a, n
for v in ut.imatch(x) do
v, n = fmt_neg(v)
a, m = v:match("(%S+)/(%d+%.%S+)")
a = a or v
a = a:match(":") and ip.IPv6(a, m) or ip.IPv4(a, m)
if a and (a:is6() and a:prefix() < 128 or a:prefix() < 32) then
l[1] = tr("IP range")
l[#l+1] = "<var title='%s - %s'>%s%s</var>" %{
a:minhost():string(),
a:maxhost():string(),
n, a:string()
}
else
l[#l+1] = "<var>%s%s</var>" %{
n,
a and a:string() or v
}
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("IPs")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_zone(x, d)
if x == "*" then
return "<var>%s</var>" % tr("any zone")
elseif x and #x > 0 then
return "<var>%s</var>" % x
elseif d then
return "<var>%s</var>" % d
end
end
function fmt_icmp_type(x)
if x and #x > 0 then
local t, v, n
local l = { tr("type"), " " }
for v in ut.imatch(x) do
v, n = fmt_neg(v)
l[#l+1] = "<var>%s%s</var>" %{ n, v }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("types")
end
return table.concat(l, "")
end
end
end
function fmt_proto(x, icmp_types)
if x and #x > 0 then
local v, n
local l = { }
local t = fmt_icmp_type(icmp_types)
for v in ut.imatch(x) do
v, n = fmt_neg(v)
if v == "tcpudp" then
l[#l+1] = "TCP"
l[#l+1] = ", "
l[#l+1] = "UDP"
l[#l+1] = ", "
elseif v ~= "all" then
local p = nx.getproto(v)
if p then
-- ICMP
if (p.proto == 1 or p.proto == 58) and t then
l[#l+1] = translatef(
"%s%s with %s",
n, p.aliases[1] or p.name, t
)
else
l[#l+1] = "%s%s" %{
n,
p.aliases[1] or p.name
}
end
l[#l+1] = ", "
end
end
end
if #l > 0 then
l[#l] = nil
return table.concat(l, "")
end
end
end
function fmt_limit(limit, burst)
burst = tonumber(burst)
if limit and #limit > 0 then
local l, u = limit:match("(%d+)/(%w+)")
l = tonumber(l or limit)
u = u or "second"
if l then
if u:match("^s") then
u = tr("second")
elseif u:match("^m") then
u = tr("minute")
elseif u:match("^h") then
u = tr("hour")
elseif u:match("^d") then
u = tr("day")
end
if burst and burst > 0 then
return translatef("<var>%d</var> pkts. per <var>%s</var>, \
burst <var>%d</var> pkts.", l, u, burst)
else
return translatef("<var>%d</var> pkts. per <var>%s</var>", l, u)
end
end
end
end
function fmt_target(x, dest)
if dest and #dest > 0 then
if x == "ACCEPT" then
return tr("Accept forward")
elseif x == "REJECT" then
return tr("Refuse forward")
elseif x == "NOTRACK" then
return tr("Do not track forward")
else --if x == "DROP" then
return tr("Discard forward")
end
else
if x == "ACCEPT" then
return tr("Accept input")
elseif x == "REJECT" then
return tr("Refuse input")
elseif x == "NOTRACK" then
return tr("Do not track input")
else --if x == "DROP" then
return tr("Discard input")
end
end
end
function opt_enabled(s, t, ...)
if t == luci.cbi.Button then
local o = s:option(t, "__enabled")
function o.render(self, section)
if self.map:get(section, "enabled") ~= "0" then
self.title = tr("Rule is enabled")
self.inputtitle = tr("Disable")
self.inputstyle = "reset"
else
self.title = tr("Rule is disabled")
self.inputtitle = tr("Enable")
self.inputstyle = "apply"
end
t.render(self, section)
end
function o.write(self, section, value)
if self.map:get(section, "enabled") ~= "0" then
self.map:set(section, "enabled", "0")
else
self.map:del(section, "enabled")
end
end
return o
else
local o = s:option(t, "enabled", ...)
o.default = "1"
return o
end
end
function opt_name(s, t, ...)
local o = s:option(t, "name", ...)
function o.cfgvalue(self, section)
return self.map:get(section, "name") or
self.map:get(section, "_name") or "-"
end
function o.write(self, section, value)
if value ~= "-" then
self.map:set(section, "name", value)
self.map:del(section, "_name")
else
self:remove(section)
end
end
function o.remove(self, section)
self.map:del(section, "name")
self.map:del(section, "_name")
end
return o
end
| apache-2.0 |
MalRD/darkstar | scripts/globals/items/ulbukan_lobster.lua | 11 | 1144 | -----------------------------------------
-- ID: 5960
-- Item: Ulbukan Lobster
-- Food Effect: 5 Min, Mithra only
-----------------------------------------
-- Dexterity -3
-- Vitality 1
-- Defense +9%
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.MITHRA) then
result = dsp.msg.basic.CANNOT_EAT
end
if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then
result = 0
end
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,5960)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, -3)
target:addMod(dsp.mod.VIT, 1)
target:addMod(dsp.mod.DEFP, 9)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, -3)
target:delMod(dsp.mod.VIT, 1)
target:delMod(dsp.mod.DEFP, 9)
end
| gpl-3.0 |
Frenzie/koreader | frontend/apps/reader/modules/readerfooter.lua | 3 | 110858 | local BD = require("ui/bidi")
local Blitbuffer = require("ffi/blitbuffer")
local BottomContainer = require("ui/widget/container/bottomcontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local Device = require("device")
local Event = require("ui/event")
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local LeftContainer = require("ui/widget/container/leftcontainer")
local LineWidget = require("ui/widget/linewidget")
local MultiInputDialog = require("ui/widget/multiinputdialog")
local ProgressWidget = require("ui/widget/progresswidget")
local RightContainer = require("ui/widget/container/rightcontainer")
local Size = require("ui/size")
local TextWidget = require("ui/widget/textwidget")
local UIManager = require("ui/uimanager")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local logger = require("logger")
local util = require("util")
local T = require("ffi/util").template
local _ = require("gettext")
local C_ = _.pgettext
local Screen = Device.screen
local MAX_BATTERY_HIDE_THRESHOLD = 1000
local MODE = {
off = 0,
page_progress = 1,
pages_left_book = 2,
time = 3,
pages_left = 4,
battery = 5,
percentage = 6,
book_time_to_read = 7,
chapter_time_to_read = 8,
frontlight = 9,
mem_usage = 10,
wifi_status = 11,
book_title = 12,
book_chapter = 13,
bookmark_count = 14,
chapter_progress = 15,
frontlight_warmth = 16,
custom_text = 17,
}
local symbol_prefix = {
letters = {
time = nil,
pages_left_book = "->",
pages_left = "=>",
-- @translators This is the footer letter prefix for battery % remaining.
battery = C_("FooterLetterPrefix", "B:"),
-- @translators This is the footer letter prefix for the number of bookmarks (bookmark count).
bookmark_count = C_("FooterLetterPrefix", "BM:"),
-- @translators This is the footer letter prefix for percentage read.
percentage = C_("FooterLetterPrefix", "R:"),
-- @translators This is the footer letter prefix for book time to read.
book_time_to_read = C_("FooterLetterPrefix", "TB:"),
-- @translators This is the footer letter prefix for chapter time to read.
chapter_time_to_read = C_("FooterLetterPrefix", "TC:"),
-- @translators This is the footer letter prefix for frontlight level.
frontlight = C_("FooterLetterPrefix", "L:"),
-- @translators This is the footer letter prefix for frontlight warmth (redshift).
frontlight_warmth = C_("FooterLetterPrefix", "R:"),
-- @translators This is the footer letter prefix for memory usage.
mem_usage = C_("FooterLetterPrefix", "M:"),
-- @translators This is the footer letter prefix for Wi-Fi status.
wifi_status = C_("FooterLetterPrefix", "W:"),
-- no prefix for custom text
custom_text = "",
},
icons = {
time = "⌚",
pages_left_book = BD.mirroredUILayout() and "↢" or "↣",
pages_left = BD.mirroredUILayout() and "⇐" or "⇒",
battery = "",
bookmark_count = "☆",
percentage = BD.mirroredUILayout() and "⤟" or "⤠",
book_time_to_read = "⏳",
chapter_time_to_read = BD.mirroredUILayout() and "⥖" or "⤻",
frontlight = "☼",
frontlight_warmth = "💡",
mem_usage = "",
wifi_status = "",
wifi_status_off = "",
custom_text = "",
},
compact_items = {
time = nil,
pages_left_book = BD.mirroredUILayout() and "‹" or "›",
pages_left = BD.mirroredUILayout() and "‹" or "›",
battery = "",
-- @translators This is the footer compact item prefix for the number of bookmarks (bookmark count).
bookmark_count = C_("FooterCompactItemsPrefix", "BM"),
percentage = nil,
book_time_to_read = nil,
chapter_time_to_read = BD.mirroredUILayout() and "«" or "»",
frontlight = "✺",
frontlight_warmth = "⊛",
-- @translators This is the footer compact item prefix for memory usage.
mem_usage = C_("FooterCompactItemsPrefix", "M"),
wifi_status = "",
wifi_status_off = "",
custom_text = "",
}
}
if BD.mirroredUILayout() then
-- We need to RTL-wrap these letters and symbols for proper layout
for k, v in pairs(symbol_prefix.letters) do
local colon = v:find(":")
local wrapped
if colon then
local pre = v:sub(1, colon-1)
local post = v:sub(colon)
wrapped = BD.wrap(pre) .. BD.wrap(post)
else
wrapped = BD.wrap(v)
end
symbol_prefix.letters[k] = wrapped
end
for k, v in pairs(symbol_prefix.icons) do
symbol_prefix.icons[k] = BD.wrap(v)
end
end
local PROGRESS_BAR_STYLE_THICK_DEFAULT_HEIGHT = 7
local PROGRESS_BAR_STYLE_THIN_DEFAULT_HEIGHT = 3
-- android: guidelines for rounded corner margins
local material_pixels = Screen:scaleByDPI(16)
-- functions that generates footer text for each mode
local footerTextGeneratorMap = {
empty = function() return "" end,
frontlight = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].frontlight
local powerd = Device:getPowerDevice()
if powerd:isFrontlightOn() then
if Device:isCervantes() or Device:isKobo() then
return (prefix .. " %d%%"):format(powerd:frontlightIntensity())
else
return (prefix .. " %d"):format(powerd:frontlightIntensity())
end
else
if footer.settings.all_at_once and footer.settings.hide_empty_generators then
return ""
else
return T(_("%1 Off"), prefix)
end
end
end,
frontlight_warmth = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].frontlight_warmth
local powerd = Device:getPowerDevice()
if powerd:isFrontlightOn() then
local warmth = powerd:frontlightWarmth()
if warmth then
return (prefix .. " %d%%"):format(warmth)
end
else
if footer.settings.all_at_once and footer.settings.hide_empty_generators then
return ""
else
return T(_("%1 Off"), prefix)
end
end
end,
battery = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].battery
local powerd = Device:getPowerDevice()
local batt_lvl = 0
local is_charging = false
if Device:hasBattery() then
local main_batt_lvl = powerd:getCapacity()
if Device:hasAuxBattery() and powerd:isAuxBatteryConnected() then
local aux_batt_lvl = powerd:getAuxCapacity()
is_charging = powerd:isAuxCharging()
-- Sum both batteries for the actual text
batt_lvl = main_batt_lvl + aux_batt_lvl
-- But average 'em to compute the icon...
if symbol_type == "icons" or symbol_type == "compact_items" then
prefix = powerd:getBatterySymbol(powerd:isAuxCharged(), is_charging, batt_lvl / 2)
end
else
is_charging = powerd:isCharging()
batt_lvl = main_batt_lvl
if symbol_type == "icons" or symbol_type == "compact_items" then
prefix = powerd:getBatterySymbol(powerd:isCharged(), is_charging, main_batt_lvl)
end
end
end
if footer.settings.all_at_once and batt_lvl > footer.settings.battery_hide_threshold then
return ""
end
-- If we're using icons, use the fancy variable icon from powerd:getBatterySymbol
if symbol_type == "icons" or symbol_type == "compact_items" then
if symbol_type == "compact_items" then
return BD.wrap(prefix)
else
return BD.wrap(prefix) .. batt_lvl .. "%"
end
else
return BD.wrap(prefix) .. " " .. (is_charging and "+" or "") .. batt_lvl .. "%"
end
end,
bookmark_count = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].bookmark_count
local bookmark_count = footer.ui.bookmark:getNumberOfBookmarks()
if footer.settings.all_at_once and footer.settings.hide_empty_generators and bookmark_count == 0 then
return ""
end
return prefix .. " " .. tostring(bookmark_count)
end,
time = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].time
local clock = util.secondsToHour(os.time(), G_reader_settings:isTrue("twelve_hour_clock"))
if not prefix then
return clock
else
return prefix .. " " .. clock
end
end,
page_progress = function(footer)
if footer.pageno then
if footer.ui.pagemap and footer.ui.pagemap:wantsPageLabels() then
-- (Page labels might not be numbers)
return ("%s / %s"):format(footer.ui.pagemap:getCurrentPageLabel(true),
footer.ui.pagemap:getLastPageLabel(true))
end
if footer.ui.document:hasHiddenFlows() then
-- i.e., if we are hiding non-linear fragments and there's anything to hide,
local flow = footer.ui.document:getPageFlow(footer.pageno)
local page = footer.ui.document:getPageNumberInFlow(footer.pageno)
local pages = footer.ui.document:getTotalPagesInFlow(flow)
if flow == 0 then
return ("%d // %d"):format(page, pages)
else
return ("[%d / %d]%d"):format(page, pages, flow)
end
else
return ("%d / %d"):format(footer.pageno, footer.pages)
end
elseif footer.position then
return ("%d / %d"):format(footer.position, footer.doc_height)
end
end,
pages_left_book = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].pages_left_book
if footer.pageno then
if footer.ui.pagemap and footer.ui.pagemap:wantsPageLabels() then
-- (Page labels might not be numbers)
return ("%s %s / %s"):format(prefix,
footer.ui.pagemap:getCurrentPageLabel(true),
footer.ui.pagemap:getLastPageLabel(true))
end
if footer.ui.document:hasHiddenFlows() then
-- i.e., if we are hiding non-linear fragments and there's anything to hide,
local flow = footer.ui.document:getPageFlow(footer.pageno)
local page = footer.ui.document:getPageNumberInFlow(footer.pageno)
local pages = footer.ui.document:getTotalPagesInFlow(flow)
local remaining = pages - page
if footer.settings.pages_left_includes_current_page then
remaining = remaining + 1
end
if flow == 0 then
return ("%s %d // %d"):format(prefix, remaining, pages)
else
return ("%s [%d / %d]%d"):format(prefix, remaining, pages, flow)
end
else
local remaining = footer.pages - footer.pageno
if footer.settings.pages_left_includes_current_page then
remaining = remaining + 1
end
return ("%s %d / %d"):format(prefix, remaining, footer.pages)
end
elseif footer.position then
return ("%s %d / %d"):format(prefix, footer.doc_height - footer.position, footer.doc_height)
end
end,
pages_left = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].pages_left
local left = footer.ui.toc:getChapterPagesLeft(footer.pageno) or footer.ui.document:getTotalPagesLeft(footer.pageno)
if footer.settings.pages_left_includes_current_page then
left = left + 1
end
return prefix .. " " .. left
end,
chapter_progress = function(footer)
local current = footer.ui.toc:getChapterPagesDone(footer.pageno)
-- We want a page number, not a page read count
if current then
current = current + 1
else
current = footer.pageno
end
local total = footer.ui.toc:getChapterPageCount(footer.pageno) or footer.pages
return current .. " ⁄⁄ " .. total
end,
percentage = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].percentage
local digits = footer.settings.progress_pct_format
local string_percentage = "%." .. digits .. "f%%"
if footer.ui.document:hasHiddenFlows() then
local flow = footer.ui.document:getPageFlow(footer.pageno)
if flow ~= 0 then
string_percentage = "[" .. string_percentage .. "]"
end
end
if prefix then
string_percentage = prefix .. " " .. string_percentage
end
return string_percentage:format(footer.progress_bar.percentage * 100)
end,
book_time_to_read = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].book_time_to_read
local left = footer.ui.document:getTotalPagesLeft(footer.pageno)
return footer:getDataFromStatistics(prefix and (prefix .. " ") or "", left)
end,
chapter_time_to_read = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].chapter_time_to_read
local left = footer.ui.toc:getChapterPagesLeft(footer.pageno) or footer.ui.document:getTotalPagesLeft(footer.pageno)
return footer:getDataFromStatistics(
prefix .. " ", left)
end,
mem_usage = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].mem_usage
local statm = io.open("/proc/self/statm", "r")
if statm then
local dummy, rss = statm:read("*number", "*number")
statm:close()
-- we got the nb of 4Kb-pages used, that we convert to MiB
rss = math.floor(rss * (4096 / 1024 / 1024))
return (prefix .. " %d"):format(rss)
end
return ""
end,
wifi_status = function(footer)
-- NOTE: This one deviates a bit from the mold because, in icons mode, we simply use two different icons and no text.
local symbol_type = footer.settings.item_prefix
local NetworkMgr = require("ui/network/manager")
if symbol_type == "icons" or symbol_type == "compact_items" then
if NetworkMgr:isWifiOn() then
return symbol_prefix.icons.wifi_status
else
if footer.settings.all_at_once and footer.settings.hide_empty_generators then
return ""
else
return symbol_prefix.icons.wifi_status_off
end
end
else
local prefix = symbol_prefix[symbol_type].wifi_status
if NetworkMgr:isWifiOn() then
return T(_("%1 On"), prefix)
else
if footer.settings.all_at_once and footer.settings.hide_empty_generators then
return ""
else
return T(_("%1 Off"), prefix)
end
end
end
end,
book_title = function(footer)
local doc_info = footer.ui.document:getProps()
if doc_info and doc_info.title then
local title = doc_info.title:gsub(" ", "\xC2\xA0") -- replace space with no-break-space
local title_widget = TextWidget:new{
text = title,
max_width = footer._saved_screen_width * footer.settings.book_title_max_width_pct * (1/100),
face = Font:getFace(footer.text_font_face, footer.settings.text_font_size),
bold = footer.settings.text_font_bold,
}
local fitted_title_text, add_ellipsis = title_widget:getFittedText()
title_widget:free()
if add_ellipsis then
fitted_title_text = fitted_title_text .. "…"
end
return BD.auto(fitted_title_text)
else
return ""
end
end,
book_chapter = function(footer)
local chapter_title = footer.ui.toc:getTocTitleByPage(footer.pageno)
if chapter_title and chapter_title ~= "" then
chapter_title = chapter_title:gsub(" ", "\xC2\xA0") -- replace space with no-break-space
local chapter_widget = TextWidget:new{
text = chapter_title,
max_width = footer._saved_screen_width * footer.settings.book_chapter_max_width_pct * (1/100),
face = Font:getFace(footer.text_font_face, footer.settings.text_font_size),
bold = footer.settings.text_font_bold,
}
local fitted_chapter_text, add_ellipsis = chapter_widget:getFittedText()
chapter_widget:free()
if add_ellipsis then
fitted_chapter_text = fitted_chapter_text .. "…"
end
return BD.auto(fitted_chapter_text)
else
return ""
end
end,
custom_text = function(footer)
local symbol_type = footer.settings.item_prefix
local prefix = symbol_prefix[symbol_type].custom_text
-- if custom_text contains only spaces, request to merge it with the text before and after,
-- in other words, don't add a separator then.
local merge = footer.custom_text:gsub(" ", ""):len() == 0
return (prefix .. footer.custom_text:rep(footer.custom_text_repetitions)), merge
end,
}
local ReaderFooter = WidgetContainer:extend{
mode = MODE.page_progress,
pageno = nil,
pages = nil,
progress_percentage = 0.0,
footer_text = nil,
text_font_face = "ffont",
height = Screen:scaleBySize(G_defaults:readSetting("DMINIBAR_CONTAINER_HEIGHT")),
horizontal_margin = Size.span.horizontal_default,
bottom_padding = Size.padding.tiny,
settings = nil, -- table
-- added to expose them to unit tests
textGeneratorMap = footerTextGeneratorMap,
}
-- NOTE: This is used in a migration script by ui/data/onetime_migration,
-- which is why it's public.
ReaderFooter.default_settings = {
disable_progress_bar = false, -- enable progress bar by default
disabled = false,
all_at_once = false,
reclaim_height = false,
toc_markers = true,
page_progress = true,
pages_left_book = false,
time = true,
pages_left = true,
battery = Device:hasBattery(),
battery_hide_threshold = Device:hasAuxBattery() and 200 or 100,
percentage = true,
book_time_to_read = true,
chapter_time_to_read = true,
frontlight = false,
mem_usage = false,
wifi_status = false,
book_title = false,
book_chapter = false,
bookmark_count = false,
chapter_progress = false,
item_prefix = "icons",
toc_markers_width = 2, -- unscaled_size_check: ignore
text_font_size = 14, -- unscaled_size_check: ignore
text_font_bold = false,
container_height = G_defaults:readSetting("DMINIBAR_CONTAINER_HEIGHT"),
container_bottom_padding = 1, -- unscaled_size_check: ignore
progress_margin_width = Screen:scaleBySize(Device:isAndroid() and material_pixels or 10), -- default margin (like self.horizontal_margin)
progress_bar_min_width_pct = 20,
book_title_max_width_pct = 30,
book_chapter_max_width_pct = 30,
skim_widget_on_hold = false,
progress_style_thin = false,
progress_bar_position = "alongside",
bottom_horizontal_separator = false,
align = "center",
auto_refresh_time = false,
progress_style_thin_height = PROGRESS_BAR_STYLE_THIN_DEFAULT_HEIGHT,
progress_style_thick_height = PROGRESS_BAR_STYLE_THICK_DEFAULT_HEIGHT,
hide_empty_generators = false,
lock_tap = false,
items_separator = "bar",
progress_pct_format = "0",
progress_margin = false,
pages_left_includes_current_page = false,
}
function ReaderFooter:init()
self.settings = G_reader_settings:readSetting("footer", self.default_settings)
-- Remove items not supported by the current device
if not Device:hasFastWifiStatusQuery() then
MODE.wifi_status = nil
end
if not Device:hasFrontlight() then
MODE.frontlight = nil
end
if not Device:hasBattery() then
MODE.battery = nil
end
-- self.mode_index will be an array of MODE names, with an additional element
-- with key 0 for "off", which feels a bit strange but seems to work...
-- (The same is true for self.settings.order which is saved in settings.)
self.mode_index = {}
self.mode_nb = 0
local handled_modes = {}
if self.settings.order then
-- Start filling self.mode_index from what's been ordered by the user and saved
for i=0, #self.settings.order do
local name = self.settings.order[i]
-- (if name has been removed from our supported MODEs: ignore it)
if MODE[name] then -- this mode still exists
self.mode_index[self.mode_nb] = name
self.mode_nb = self.mode_nb + 1
handled_modes[name] = true
end
end
-- go on completing it with remaining new modes in MODE
end
-- If no previous self.settings.order, fill mode_index with what's in MODE
-- in the original indices order
local orig_indexes = {}
local orig_indexes_to_name = {}
for name, orig_index in pairs(MODE) do
if not handled_modes[name] then
table.insert(orig_indexes, orig_index)
orig_indexes_to_name[orig_index] = name
end
end
table.sort(orig_indexes)
for i = 1, #orig_indexes do
self.mode_index[self.mode_nb] = orig_indexes_to_name[orig_indexes[i]]
self.mode_nb = self.mode_nb + 1
end
-- require("logger").dbg(self.mode_nb, self.mode_index)
-- Container settings
self.height = Screen:scaleBySize(self.settings.container_height)
self.bottom_padding = Screen:scaleBySize(self.settings.container_bottom_padding)
self.mode_list = {}
for i = 0, #self.mode_index do
self.mode_list[self.mode_index[i]] = i
end
if self.settings.disabled then
-- footer feature is completely disabled, stop initialization now
self:disableFooter()
return
end
self.pageno = self.view.state.page
self.has_no_mode = true
self.reclaim_height = self.settings.reclaim_height
for _, m in ipairs(self.mode_index) do
if self.settings[m] then
self.has_no_mode = false
break
end
end
self.footer_text = TextWidget:new{
text = '',
face = Font:getFace(self.text_font_face, self.settings.text_font_size),
bold = self.settings.text_font_bold,
}
-- all width related values will be initialized in self:resetLayout()
self.text_width = 0
self.footer_text.height = 0
self.progress_bar = ProgressWidget:new{
width = nil,
height = nil,
percentage = self.progress_percentage,
tick_width = Screen:scaleBySize(self.settings.toc_markers_width),
ticks = nil, -- ticks will be populated in self:updateFooterText
last = nil, -- last will be initialized in self:updateFooterText
}
if self.settings.progress_style_thin then
self.progress_bar:updateStyle(false, nil)
end
self.text_container = RightContainer:new{
dimen = Geom:new{ w = 0, h = self.height },
self.footer_text,
}
self:updateFooterContainer()
self.mode = G_reader_settings:readSetting("reader_footer_mode") or self.mode
if self.has_no_mode and self.settings.disable_progress_bar then
self.mode = self.mode_list.off
self.view.footer_visible = false
self:resetLayout()
self.footer_text.height = 0
end
if self.settings.all_at_once then
self.view.footer_visible = (self.mode ~= self.mode_list.off)
self:updateFooterTextGenerator()
if self.settings.progress_bar_position ~= "alongside" and self.has_no_mode then
self.footer_text.height = 0
end
else
self:applyFooterMode()
end
self.visibility_change = nil
self.custom_text = G_reader_settings:readSetting("reader_footer_custom_text", "KOReader")
self.custom_text_repetitions =
tonumber(G_reader_settings:readSetting("reader_footer_custom_text_repetitions", "1"))
end
function ReaderFooter:set_custom_text(touchmenu_instance)
local text_dialog
text_dialog = MultiInputDialog:new{
title = "Enter a custom text",
fields = {
{
text = self.custom_text or "",
description = _("Custom string:"),
input_type = "string",
},
{
text = self.custom_text_repetitions,
description =_("Number of repetitions:"),
input_type = "number",
},
},
buttons = {
{
{
text = _("Cancel"),
id = "close",
callback = function()
UIManager:close(text_dialog)
end,
},
{
text = _("Set"),
callback = function()
local inputs = text_dialog:getFields()
local new_text, new_repetitions = inputs[1], inputs[2]
if new_text == "" then
new_text = " "
end
if self.custom_text ~= new_text then
self.custom_text = new_text
G_reader_settings:saveSetting("reader_footer_custom_text",
self.custom_text)
end
new_repetitions = tonumber(new_repetitions) or 1
if new_repetitions < 1 then
new_repetitions = 1
end
if new_repetitions and self.custom_text_repetitions ~= new_repetitions then
self.custom_text_repetitions = new_repetitions
G_reader_settings:saveSetting("reader_footer_custom_text_repetitions",
self.custom_text_repetitions)
end
UIManager:close(text_dialog)
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
},
},
},
}
UIManager:show(text_dialog)
text_dialog:onShowKeyboard()
end
-- Help text string, or function, to be shown, or executed, on a long press on menu item
local option_help_text = {}
option_help_text[MODE.pages_left_book] = _("Can be configured to include or exclude the current page.")
option_help_text[MODE.percentage] = _("Progress percentage can be shown with zero, one or two decimal places.")
option_help_text[MODE.mem_usage] = _("Show memory usage in MiB.")
option_help_text[MODE.custom_text] = ReaderFooter.set_custom_text
function ReaderFooter:updateFooterContainer()
local margin_span = HorizontalSpan:new{ width = self.horizontal_margin }
self.vertical_frame = VerticalGroup:new{}
if self.settings.bottom_horizontal_separator then
self.separator_line = LineWidget:new{
dimen = Geom:new{
w = 0,
h = Size.line.medium,
}
}
local vertical_span = VerticalSpan:new{width = Size.span.vertical_default}
table.insert(self.vertical_frame, self.separator_line)
table.insert(self.vertical_frame, vertical_span)
end
if self.settings.progress_bar_position ~= "alongside" and not self.settings.disable_progress_bar then
self.horizontal_group = HorizontalGroup:new{
margin_span,
self.text_container,
margin_span,
}
else
self.horizontal_group = HorizontalGroup:new{
margin_span,
self.progress_bar,
self.text_container,
margin_span,
}
end
if self.settings.align == "left" then
self.footer_container = LeftContainer:new{
dimen = Geom:new{ w = 0, h = self.height },
self.horizontal_group
}
elseif self.settings.align == "right" then
self.footer_container = RightContainer:new{
dimen = Geom:new{ w = 0, h = self.height },
self.horizontal_group
}
else
self.footer_container = CenterContainer:new{
dimen = Geom:new{ w = 0, h = self.height },
self.horizontal_group
}
end
local vertical_span = VerticalSpan:new{width = Size.span.vertical_default}
if self.settings.progress_bar_position == "above" and not self.settings.disable_progress_bar then
table.insert(self.vertical_frame, self.progress_bar)
table.insert(self.vertical_frame, vertical_span)
table.insert(self.vertical_frame, self.footer_container)
elseif self.settings.progress_bar_position == "below" and not self.settings.disable_progress_bar then
table.insert(self.vertical_frame, self.footer_container)
table.insert(self.vertical_frame, vertical_span)
table.insert(self.vertical_frame, self.progress_bar)
else
table.insert(self.vertical_frame, self.footer_container)
end
self.footer_content = FrameContainer:new{
self.vertical_frame,
background = Blitbuffer.COLOR_WHITE,
bordersize = 0,
padding = 0,
padding_bottom = self.bottom_padding,
}
self.footer_positioner = BottomContainer:new{
dimen = Geom:new{},
self.footer_content,
}
self[1] = self.footer_positioner
end
function ReaderFooter:unscheduleFooterAutoRefresh()
if not self.autoRefreshFooter then return end -- not yet set up
-- Slightly different wording than in rescheduleFooterAutoRefreshIfNeeded because it might not actually be scheduled at all
logger.dbg("ReaderFooter: unschedule autoRefreshFooter")
UIManager:unschedule(self.autoRefreshFooter)
end
function ReaderFooter:rescheduleFooterAutoRefreshIfNeeded()
if not self.autoRefreshFooter then
-- Create this function the first time we're called
self.autoRefreshFooter = function()
-- Only actually repaint the footer if nothing's being shown over ReaderUI (#6616)
-- (We want to avoid the footer to be painted over a widget covering it - we would
-- be fine refreshing it if the widget is not covering it, but this is hard to
-- guess from here.)
if UIManager:getTopWidget() == "ReaderUI" then
self:onUpdateFooter(self.view.footer_visible)
else
logger.dbg("Skipping ReaderFooter repaint, because ReaderUI is not the top-level widget")
-- NOTE: We *do* keep its content up-to-date, though
self:onUpdateFooter()
end
self:rescheduleFooterAutoRefreshIfNeeded() -- schedule (or not) next refresh
end
end
local unscheduled = UIManager:unschedule(self.autoRefreshFooter) -- unschedule if already scheduled
-- Only schedule an update if the footer has items that may change
-- As self.view.footer_visible may be temporarily toggled off by other modules,
-- we can't trust it for not scheduling auto refresh
local schedule = false
if self.settings.auto_refresh_time then
if self.settings.all_at_once then
if self.settings.time or self.settings.battery or self.settings.wifi_status or self.settings.mem_usage then
schedule = true
end
else
if self.mode == self.mode_list.time or self.mode == self.mode_list.battery
or self.mode == self.mode_list.wifi_status or self.mode == self.mode_list.mem_usage then
schedule = true
end
end
end
if schedule then
UIManager:scheduleIn(61 - tonumber(os.date("%S")), self.autoRefreshFooter)
if not unscheduled then
logger.dbg("ReaderFooter: scheduled autoRefreshFooter")
else
logger.dbg("ReaderFooter: rescheduled autoRefreshFooter")
end
elseif unscheduled then
logger.dbg("ReaderFooter: unscheduled autoRefreshFooter")
end
end
function ReaderFooter:setupTouchZones()
if not Device:isTouchDevice() then return end
local DTAP_ZONE_MINIBAR = G_defaults:readSetting("DTAP_ZONE_MINIBAR")
local footer_screen_zone = {
ratio_x = DTAP_ZONE_MINIBAR.x, ratio_y = DTAP_ZONE_MINIBAR.y,
ratio_w = DTAP_ZONE_MINIBAR.w, ratio_h = DTAP_ZONE_MINIBAR.h,
}
self.ui:registerTouchZones({
{
id = "readerfooter_tap",
ges = "tap",
screen_zone = footer_screen_zone,
handler = function(ges) return self:onTapFooter(ges) end,
overrides = {
"readerconfigmenu_ext_tap",
"readerconfigmenu_tap",
"tap_forward",
"tap_backward",
},
-- (Low priority: tap on existing highlights
-- or links have priority)
},
{
id = "readerfooter_hold",
ges = "hold",
screen_zone = footer_screen_zone,
handler = function(ges) return self:onHoldFooter(ges) end,
overrides = {
"readerhighlight_hold",
},
-- (High priority: it's a fallthrough if we held outside the footer)
},
})
end
-- call this method whenever the screen size changes
function ReaderFooter:resetLayout(force_reset)
local new_screen_width = Screen:getWidth()
local new_screen_height = Screen:getHeight()
if new_screen_width == self._saved_screen_width
and new_screen_height == self._saved_screen_height and not force_reset then return end
if self.settings.disable_progress_bar then
self.progress_bar.width = 0
elseif self.settings.progress_bar_position ~= "alongside" then
self.progress_bar.width = math.floor(new_screen_width - 2 * self.settings.progress_margin_width)
else
self.progress_bar.width = math.floor(
new_screen_width - 2 * self.settings.progress_margin_width - self.text_width)
end
if self.separator_line then
self.separator_line.dimen.w = new_screen_width - 2 * self.horizontal_margin
end
if self.settings.disable_progress_bar then
self.progress_bar.height = 0
else
local bar_height
if self.settings.progress_style_thin then
bar_height = self.settings.progress_style_thin_height
else
bar_height = self.settings.progress_style_thick_height
end
self.progress_bar:setHeight(bar_height)
end
self.horizontal_group:resetLayout()
self.footer_positioner.dimen.w = new_screen_width
self.footer_positioner.dimen.h = new_screen_height
self.footer_container.dimen.w = new_screen_width
self.dimen = self.footer_positioner:getSize()
self._saved_screen_width = new_screen_width
self._saved_screen_height = new_screen_height
end
function ReaderFooter:getHeight()
if self.footer_content then
-- NOTE: self.footer_content is self.vertical_frame + self.bottom_padding,
-- self.vertical_frame includes self.text_container (which includes self.footer_text)
return self.footer_content:getSize().h
else
return 0
end
end
function ReaderFooter:disableFooter()
self.onReaderReady = function() end
self.resetLayout = function() end
self.updateFooterPage = function() end
self.updateFooterPos = function() end
self.mode = self.mode_list.off
self.view.footer_visible = false
end
function ReaderFooter:updateFooterTextGenerator()
local footerTextGenerators = {}
for i, m in pairs(self.mode_index) do
if self.settings[m] then
table.insert(footerTextGenerators,
footerTextGeneratorMap[m])
if not self.settings.all_at_once then
-- if not show all at once, then one is enough
self.mode = i
break
end
end
end
if #footerTextGenerators == 0 then
-- all modes are disabled
self.genFooterText = footerTextGeneratorMap.empty
elseif #footerTextGenerators == 1 then
-- there is only one mode enabled, simplify the generator
-- function to that one
self.genFooterText = footerTextGenerators[1]
else
self.genFooterText = self.genAllFooterText
end
-- Even if there's no or a single mode enabled, all_at_once requires this to be set
self.footerTextGenerators = footerTextGenerators
-- notify caller that UI needs update
return true
end
function ReaderFooter:progressPercentage(digits)
local symbol_type = self.settings.item_prefix
local prefix = symbol_prefix[symbol_type].percentage
local string_percentage
if not prefix then
string_percentage = "%." .. digits .. "f%%"
else
string_percentage = prefix .. " %." .. digits .. "f%%"
end
return string_percentage:format(self.progress_bar.percentage * 100)
end
function ReaderFooter:textOptionTitles(option)
local symbol = self.settings.item_prefix
local option_titles = {
all_at_once = _("Show all at once"),
reclaim_height = _("Reclaim bar height from bottom margin"),
bookmark_count = T(_("Bookmark count (%1)"), symbol_prefix[symbol].bookmark_count),
page_progress = T(_("Current page (%1)"), "/"),
pages_left_book = T(_("Pages left in book (%1)"), symbol_prefix[symbol].pages_left_book),
time = symbol_prefix[symbol].time
and T(_("Current time (%1)"), symbol_prefix[symbol].time) or _("Current time"),
chapter_progress = T(_("Current page in chapter (%1)"), " ⁄⁄ "),
pages_left = T(_("Pages left in chapter (%1)"), symbol_prefix[symbol].pages_left),
battery = T(_("Battery status (%1)"), symbol_prefix[symbol].battery),
percentage = symbol_prefix[symbol].percentage
and T(_("Progress percentage (%1)"), symbol_prefix[symbol].percentage) or _("Progress percentage"),
book_time_to_read = symbol_prefix[symbol].book_time_to_read
and T(_("Book time to read (%1)"),symbol_prefix[symbol].book_time_to_read) or _("Book time to read"),
chapter_time_to_read = T(_("Chapter time to read (%1)"), symbol_prefix[symbol].chapter_time_to_read),
frontlight = T(_("Frontlight level (%1)"), symbol_prefix[symbol].frontlight),
frontlight_warmth = T(_("Frontlight warmth (%1)"), symbol_prefix[symbol].frontlight_warmth),
mem_usage = T(_("KOReader memory usage (%1)"), symbol_prefix[symbol].mem_usage),
wifi_status = T(_("Wi-Fi status (%1)"), symbol_prefix[symbol].wifi_status),
book_title = _("Book title"),
book_chapter = _("Current chapter"),
custom_text = T(_("Custom text: \'%1\'%2"), self.custom_text,
self.custom_text_repetitions > 1 and
string.format(" × %d", self.custom_text_repetitions) or ""),
}
return option_titles[option]
end
function ReaderFooter:addToMainMenu(menu_items)
local sub_items = {}
menu_items.status_bar = {
text = _("Status bar"),
sub_item_table = sub_items,
}
-- menu item to fake footer tapping when touch area is disabled
local settings_submenu_num = 1
local DTAP_ZONE_MINIBAR = G_defaults:readSetting("DTAP_ZONE_MINIBAR")
if DTAP_ZONE_MINIBAR.h == 0 or DTAP_ZONE_MINIBAR.w == 0 then
table.insert(sub_items, {
text = _("Toggle mode"),
enabled_func = function()
return not self.view.flipping_visible
end,
callback = function() self:onTapFooter(true) end,
})
settings_submenu_num = 2
end
local getMinibarOption = function(option, callback)
return {
text_func = function()
return self:textOptionTitles(option)
end,
help_text = type(option_help_text[MODE[option]]) == "string"
and option_help_text[MODE[option]],
help_text_func = type(option_help_text[MODE[option]]) == "function" and
function(touchmenu_instance)
option_help_text[MODE[option]](self, touchmenu_instance)
end,
checked_func = function()
return self.settings[option] == true
end,
callback = function()
self.settings[option] = not self.settings[option]
-- We only need to send a SetPageBottomMargin event when we truly affect the margin
local should_signal = false
-- only case that we don't need a UI update is enable/disable
-- non-current mode when all_at_once is disabled.
local should_update = false
local first_enabled_mode_num
local prev_has_no_mode = self.has_no_mode
local prev_reclaim_height = self.reclaim_height
self.has_no_mode = true
for mode_num, m in pairs(self.mode_index) do
if self.settings[m] then
first_enabled_mode_num = mode_num
self.has_no_mode = false
break
end
end
self.reclaim_height = self.settings.reclaim_height
-- refresh margins position
if self.has_no_mode then
self.footer_text.height = 0
should_signal = true
self.genFooterText = footerTextGeneratorMap.empty
self.mode = self.mode_list.off
elseif prev_has_no_mode then
if self.settings.all_at_once then
self.mode = self.mode_list.page_progress
self:applyFooterMode()
G_reader_settings:saveSetting("reader_footer_mode", self.mode)
else
G_reader_settings:saveSetting("reader_footer_mode", first_enabled_mode_num)
end
should_signal = true
elseif self.reclaim_height ~= prev_reclaim_height then
should_signal = true
should_update = true
end
if callback then
should_update = callback(self)
elseif self.settings.all_at_once then
should_update = self:updateFooterTextGenerator()
elseif (self.mode_list[option] == self.mode and self.settings[option] == false)
or (prev_has_no_mode ~= self.has_no_mode) then
-- current mode got disabled, redraw footer with other
-- enabled modes. if all modes are disabled, then only show
-- progress bar
if not self.has_no_mode then
self.mode = first_enabled_mode_num
else
-- If we've just disabled our last mode, first_enabled_mode_num is nil
-- If the progress bar is enabled,
-- fake an innocuous mode so that we switch to showing the progress bar alone, instead of nothing,
-- This is exactly what the "Show progress bar" toggle does.
self.mode = self.settings.disable_progress_bar and self.mode_list.off or self.mode_list.page_progress
end
should_update = true
self:applyFooterMode()
G_reader_settings:saveSetting("reader_footer_mode", self.mode)
end
if should_update or should_signal then
self:refreshFooter(should_update, should_signal)
end
-- The absence or presence of some items may change whether auto-refresh should be ensured
self:rescheduleFooterAutoRefreshIfNeeded()
end,
}
end
table.insert(sub_items, {
text = _("Settings"),
sub_item_table = {
{
text = _("Sort items"),
separator = true,
callback = function()
local item_table = {}
for i=1, #self.mode_index do
table.insert(item_table, {text = self:textOptionTitles(self.mode_index[i]), label = self.mode_index[i]})
end
local SortWidget = require("ui/widget/sortwidget")
local sort_item
sort_item = SortWidget:new{
title = _("Sort footer items"),
item_table = item_table,
callback = function()
for i=1, #sort_item.item_table do
self.mode_index[i] = sort_item.item_table[i].label
end
self.settings.order = self.mode_index
self:updateFooterTextGenerator()
self:onUpdateFooter()
UIManager:setDirty(nil, "ui")
end
}
UIManager:show(sort_item)
end,
},
getMinibarOption("all_at_once", self.updateFooterTextGenerator),
{
text = _("Hide empty items"),
help_text = _([[This will hide values like 0 or off.]]),
enabled_func = function()
return self.settings.all_at_once == true
end,
checked_func = function()
return self.settings.hide_empty_generators == true
end,
callback = function()
self.settings.hide_empty_generators = not self.settings.hide_empty_generators
self:refreshFooter(true, true)
end,
},
getMinibarOption("reclaim_height"),
{
text = _("Auto refresh"),
checked_func = function()
return self.settings.auto_refresh_time == true
end,
callback = function()
self.settings.auto_refresh_time = not self.settings.auto_refresh_time
self:rescheduleFooterAutoRefreshIfNeeded()
end
},
{
text = _("Show footer separator"),
checked_func = function()
return self.settings.bottom_horizontal_separator == true
end,
callback = function()
self.settings.bottom_horizontal_separator = not self.settings.bottom_horizontal_separator
self:refreshFooter(true, true)
end,
},
{
text = _("Lock status bar"),
checked_func = function()
return self.settings.lock_tap == true
end,
callback = function()
self.settings.lock_tap = not self.settings.lock_tap
end,
},
{
text = _("Hold footer to skim"),
checked_func = function()
return self.settings.skim_widget_on_hold == true
end,
callback = function()
self.settings.skim_widget_on_hold = not self.settings.skim_widget_on_hold
end,
},
{
text_func = function()
local font_weight = ""
if self.settings.text_font_bold == true then
font_weight = ", " .. _("bold")
end
return T(_("Font: %1%2"), self.settings.text_font_size, font_weight)
end,
sub_item_table = {
{
text_func = function()
return T(_("Font size: %1"), self.settings.text_font_size)
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local font_size = self.settings.text_font_size
local items_font = SpinWidget:new{
value = font_size,
value_min = 8,
value_max = 36,
default_value = 14,
ok_text = _("Set size"),
title_text = _("Footer font size"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.text_font_size = spin.value
self.footer_text:free()
self.footer_text = TextWidget:new{
text = self.footer_text.text,
face = Font:getFace(self.text_font_face, self.settings.text_font_size),
bold = self.settings.text_font_bold,
}
self.text_container[1] = self.footer_text
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
}
UIManager:show(items_font)
end,
keep_menu_open = true,
},
{
text = _("Use bold font"),
checked_func = function()
return self.settings.text_font_bold == true
end,
callback = function(touchmenu_instance)
self.settings.text_font_bold = not self.settings.text_font_bold
self.footer_text:free()
self.footer_text = TextWidget:new{
text = self.footer_text.text,
face = Font:getFace(self.text_font_face, self.settings.text_font_size),
bold = self.settings.text_font_bold,
}
self.text_container[1] = self.footer_text
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
keep_menu_open = true,
},
}
},
{
text_func = function()
return T(_("Container height: %1"), self.settings.container_height)
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local container_height = self.settings.container_height
local items_font = SpinWidget:new{
value = container_height,
value_min = 7,
value_max = 98,
default_value = G_defaults:readSetting("DMINIBAR_CONTAINER_HEIGHT"),
ok_text = _("Set height"),
title_text = _("Container height"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.container_height = spin.value
self.height = Screen:scaleBySize(self.settings.container_height)
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
}
UIManager:show(items_font)
end,
keep_menu_open = true,
},
{
text_func = function()
return T(_("Container bottom margin: %1"), self.settings.container_bottom_padding)
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local container_bottom_padding = self.settings.container_bottom_padding
local items_font = SpinWidget:new{
value = container_bottom_padding,
value_min = 0,
value_max = 49,
default_value = 1,
ok_text = _("Set margin"),
title_text = _("Container bottom margin"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.container_bottom_padding = spin.value
self.bottom_padding = Screen:scaleBySize(self.settings.container_bottom_padding)
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
}
UIManager:show(items_font)
end,
keep_menu_open = true,
},
{
text = _("Maximum width of items"),
sub_item_table = {
{
text_func = function()
return T(_("Book title: %1 %"), self.settings.book_title_max_width_pct)
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local items = SpinWidget:new{
value = self.settings.book_title_max_width_pct,
value_min = 10,
value_step = 5,
value_hold_step = 20,
value_max = 100,
unit = "%",
title_text = _("Maximum width"),
info_text = _("Maximum book title width in percentage of screen width"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.book_title_max_width_pct = spin.value
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end
}
UIManager:show(items)
end,
keep_menu_open = true,
},
{
text_func = function()
return T(_("Current chapter: %1 %"), self.settings.book_chapter_max_width_pct)
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local items = SpinWidget:new{
value = self.settings.book_chapter_max_width_pct,
value_min = 10,
value_step = 5,
value_hold_step = 20,
value_max = 100,
unit = "%",
title_text = _("Maximum width"),
info_text = _("Maximum chapter width in percentage of screen width"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.book_chapter_max_width_pct = spin.value
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end
}
UIManager:show(items)
end,
keep_menu_open = true,
}
},
},
{
text_func = function()
local align_text
if self.settings.align == "left" then
align_text = _("Left")
elseif self.settings.align == "right" then
align_text = _("Right")
else
align_text = _("Center")
end
return T(_("Alignment: %1"), align_text)
end,
separator = true,
enabled_func = function()
return self.settings.disable_progress_bar or self.settings.progress_bar_position ~= "alongside"
end,
sub_item_table = {
{
text = _("Center"),
checked_func = function()
return self.settings.align == "center"
end,
callback = function()
self.settings.align = "center"
self:refreshFooter(true)
end,
},
{
text = _("Left"),
checked_func = function()
return self.settings.align == "left"
end,
callback = function()
self.settings.align = "left"
self:refreshFooter(true)
end,
},
{
text = _("Right"),
checked_func = function()
return self.settings.align == "right"
end,
callback = function()
self.settings.align = "right"
self:refreshFooter(true)
end,
},
}
},
{
text_func = function()
local prefix_text = ""
if self.settings.item_prefix == "icons" then
prefix_text = _("Icons")
elseif self.settings.item_prefix == "compact_items" then
prefix_text = _("Compact items")
elseif self.settings.item_prefix == "letters" then
prefix_text = _("Letters")
end
return T(_("Prefix: %1"), prefix_text)
end,
sub_item_table = {
{
text_func = function()
local sym_tbl = {}
for _, letter in pairs(symbol_prefix.icons) do
table.insert(sym_tbl, letter)
end
return T(_("Icons (%1)"), table.concat(sym_tbl, " "))
end,
checked_func = function()
return self.settings.item_prefix == "icons"
end,
callback = function()
self.settings.item_prefix = "icons"
self:refreshFooter(true)
end,
},
{
text_func = function()
local sym_tbl = {}
for _, letter in pairs(symbol_prefix.compact_items) do
table.insert(sym_tbl, letter)
end
return T(_("Compact Items (%1)"), table.concat(sym_tbl, " "))
end,
checked_func = function()
return self.settings.item_prefix == "compact_items"
end,
callback = function()
self.settings.item_prefix = "compact_items"
self:refreshFooter(true)
end,
},
{
text_func = function()
local sym_tbl = {}
for _, letter in pairs(symbol_prefix.letters) do
table.insert(sym_tbl, letter)
end
return T(_("Letters (%1)"), table.concat(sym_tbl, " "))
end,
checked_func = function()
return self.settings.item_prefix == "letters"
end,
callback = function()
self.settings.item_prefix = "letters"
self:refreshFooter(true)
end,
},
},
},
{
text_func = function()
local separator = self:get_separator_symbol()
separator = separator ~= "" and separator or "none"
return T(_("Item separator: %1"), separator)
end,
sub_item_table = {
{
text = _("Vertical line (|)"),
checked_func = function()
return self.settings.items_separator == "bar"
end,
callback = function()
self.settings.items_separator = "bar"
self:refreshFooter(true)
end,
},
{
text = _("Bullet (•)"),
checked_func = function()
return self.settings.items_separator == "bullet"
end,
callback = function()
self.settings.items_separator = "bullet"
self:refreshFooter(true)
end,
},
{
text = _("Dot (·)"),
checked_func = function()
return self.settings.items_separator == "dot"
end,
callback = function()
self.settings.items_separator = "dot"
self:refreshFooter(true)
end,
},
{
text = _("No separator"),
checked_func = function()
return self.settings.items_separator == "none"
end,
callback = function()
self.settings.items_separator = "none"
self:refreshFooter(true)
end,
},
},
},
{
text_func = function()
return T(_("Progress percentage format: %1"),
self:progressPercentage(tonumber(self.settings.progress_pct_format)))
end,
sub_item_table = {
{
text_func = function()
return T(_("No decimal point (%1)"), self:progressPercentage(0))
end,
checked_func = function()
return self.settings.progress_pct_format == "0"
end,
callback = function()
self.settings.progress_pct_format = "0"
self:refreshFooter(true)
end,
},
{
text_func = function()
return T(_("1 digit after decimal point (%1)"), self:progressPercentage(1))
end,
checked_func = function()
return self.settings.progress_pct_format == "1"
end,
callback = function()
self.settings.progress_pct_format = "1"
self:refreshFooter(true)
end,
},
{
text_func = function()
return T(_("2 digits after decimal point (%1)"), self:progressPercentage(2))
end,
checked_func = function()
return self.settings.progress_pct_format == "2"
end,
callback = function()
self.settings.progress_pct_format = "2"
self:refreshFooter(true)
end,
},
},
},
{
text = _("Include current page in pages left"),
help_text = _([[
Normally, the current page is not counted as remaining, so "pages left" (in a book or chapter with n pages) will run from n-1 to 0 on the last page.
With this enabled, the current page is included, so the count goes from n to 1 instead.]]),
enabled_func = function()
return self.settings.pages_left or self.settings.pages_left_book
end,
checked_func = function()
return self.settings.pages_left_includes_current_page == true
end,
callback = function()
self.settings.pages_left_includes_current_page = not self.settings.pages_left_includes_current_page
self:refreshFooter(true)
end,
},
}
})
if Device:hasBattery() then
table.insert(sub_items[settings_submenu_num].sub_item_table, 4, {
text_func = function()
if self.settings.battery_hide_threshold <= (Device:hasAuxBattery() and 200 or 100) then
return T(_("Hide battery status if level higher than: %1 %"), self.settings.battery_hide_threshold)
else
return _("Hide battery status")
end
end,
checked_func = function()
return self.settings.battery_hide_threshold < MAX_BATTERY_HIDE_THRESHOLD
end,
enabled_func = function()
return self.settings.all_at_once == true
end,
separator = true,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local battery_threshold = SpinWidget:new{
value = math.min(self.settings.battery_hide_threshold, Device:hasAuxBattery() and 200 or 100),
value_min = 0,
value_max = Device:hasAuxBattery() and 200 or 100,
default_value = Device:hasAuxBattery() and 200 or 100,
unit = "%",
value_hold_step = 10,
title_text = _("Hide battery threshold"),
callback = function(spin)
self.settings.battery_hide_threshold = spin.value
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
extra_text = _("Disable"),
extra_callback = function()
self.settings.battery_hide_threshold = MAX_BATTERY_HIDE_THRESHOLD
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
ok_always_enabled = true,
}
UIManager:show(battery_threshold)
end,
keep_menu_open = true,
})
end
table.insert(sub_items, {
text = _("Progress bar"),
separator = true,
sub_item_table = {
{
text = _("Show progress bar"),
checked_func = function()
return not self.settings.disable_progress_bar
end,
callback = function()
self.settings.disable_progress_bar = not self.settings.disable_progress_bar
if not self.settings.disable_progress_bar then
self:setTocMarkers()
end
-- If the status bar is currently disabled, switch to an innocuous mode to display it
if not self.view.footer_visible then
self.mode = self.mode_list.page_progress
self:applyFooterMode()
G_reader_settings:saveSetting("reader_footer_mode", self.mode)
end
self:refreshFooter(true, true)
end,
},
{
text_func = function()
local text = _("alongside items")
if self.settings.progress_bar_position == "above" then
text = _("above items")
elseif self.settings.progress_bar_position == "below" then
text = _("below items")
end
return T(_("Position: %1"), text)
end,
enabled_func = function()
return not self.settings.disable_progress_bar
end,
sub_item_table = {
{
text = _("Above items"),
checked_func = function()
return self.settings.progress_bar_position == "above"
end,
callback = function()
self.settings.progress_bar_position = "above"
self:refreshFooter(true, true)
end,
},
{
text = _("Below items"),
checked_func = function()
return self.settings.progress_bar_position == "below"
end,
callback = function()
self.settings.progress_bar_position = "below"
self:refreshFooter(true, true)
end,
},
{
text = _("Alongside items"),
checked_func = function()
return self.settings.progress_bar_position == "alongside"
end,
callback = function()
-- "Same as book" is disabled in this mode, and we enforce the defaults.
if self.settings.progress_margin then
self.settings.progress_margin = false
self.settings.progress_margin_width = self.horizontal_margin
end
-- Text alignment is also disabled
self.settings.align = "center"
self.settings.progress_bar_position = "alongside"
self:refreshFooter(true, true)
end
},
},
},
{
text_func = function()
if self.settings.progress_style_thin then
return _("Style: thin")
else
return _("Style: thick")
end
end,
enabled_func = function()
return not self.settings.disable_progress_bar
end,
sub_item_table = {
{
text = _("Thick"),
checked_func = function()
return not self.settings.progress_style_thin
end,
callback = function()
self.settings.progress_style_thin = nil
local bar_height = self.settings.progress_style_thick_height
self.progress_bar:updateStyle(true, bar_height)
self:setTocMarkers()
self:refreshFooter(true, true)
end,
},
{
text = _("Thin"),
checked_func = function()
return self.settings.progress_style_thin
end,
callback = function()
self.settings.progress_style_thin = true
local bar_height = self.settings.progress_style_thin_height
self.progress_bar:updateStyle(false, bar_height)
self:refreshFooter(true, true)
end,
},
{
text = _("Set size"),
callback = function()
local value, value_min, value_max, default_value
if self.settings.progress_style_thin then
default_value = PROGRESS_BAR_STYLE_THIN_DEFAULT_HEIGHT
value = self.settings.progress_style_thin_height or default_value
value_min = 1
value_max = 12
else
default_value = PROGRESS_BAR_STYLE_THICK_DEFAULT_HEIGHT
value = self.settings.progress_style_thick_height or default_value
value_min = 5
value_max = 28
end
local SpinWidget = require("ui/widget/spinwidget")
local items = SpinWidget:new{
value = value,
value_min = value_min,
value_step = 1,
value_hold_step = 2,
value_max = value_max,
default_value = default_value,
title_text = _("Progress bar size"),
keep_shown_on_apply = true,
callback = function(spin)
if self.settings.progress_style_thin then
self.settings.progress_style_thin_height = spin.value
else
self.settings.progress_style_thick_height = spin.value
end
self:refreshFooter(true, true)
end
}
UIManager:show(items)
end,
separator = true,
keep_menu_open = true,
},
{
text = _("Show chapter markers"),
checked_func = function()
return self.settings.toc_markers == true
end,
enabled_func = function()
return not self.settings.progress_style_thin
end,
callback = function()
self.settings.toc_markers = not self.settings.toc_markers
self:setTocMarkers()
self:refreshFooter(true)
end
},
{
text_func = function()
local markers_width_text = _("thick")
if self.settings.toc_markers_width == 1 then
markers_width_text = _("thin")
elseif self.settings.toc_markers_width == 2 then
markers_width_text = _("medium")
end
return T(_("Chapter marker width (%1)"), markers_width_text)
end,
enabled_func = function()
return not self.settings.progress_style_thin and self.settings.toc_markers
end,
sub_item_table = {
{
text = _("Thin"),
checked_func = function()
return self.settings.toc_markers_width == 1
end,
callback = function()
self.settings.toc_markers_width = 1 -- unscaled_size_check: ignore
self:setTocMarkers()
self:refreshFooter(true)
end,
},
{
text = _("Medium"),
checked_func = function()
return self.settings.toc_markers_width == 2
end,
callback = function()
self.settings.toc_markers_width = 2 -- unscaled_size_check: ignore
self:setTocMarkers()
self:refreshFooter(true)
end,
},
{
text = _("Thick"),
checked_func = function()
return self.settings.toc_markers_width == 3
end,
callback = function()
self.settings.toc_markers_width = 3 -- unscaled_size_check: ignore
self:setTocMarkers()
self:refreshFooter(true)
end
},
},
},
},
},
{
text_func = function()
local text = _("static margins (10)")
local cur_width = self.settings.progress_margin_width
if cur_width == 0 then
text = _("no margins (0)")
elseif cur_width == Screen:scaleBySize(material_pixels) then
text = T(_("static margins (%1)"), material_pixels)
end
if self.settings.progress_margin and not self.ui.document.info.has_pages then
text = T(_("same as book margins (%1)"), self.book_margins_footer_width)
end
return T(_("Margins: %1"), text)
end,
enabled_func = function()
return not self.settings.disable_progress_bar
end,
sub_item_table_func = function()
local common = {
{
text = _("No margins (0)"),
checked_func = function()
return self.settings.progress_margin_width == 0
and not self.settings.progress_margin
end,
callback = function()
self.settings.progress_margin_width = 0
self.settings.progress_margin = false
self:refreshFooter(true)
end,
},
{
text_func = function()
if self.ui.document.info.has_pages then
return _("Same as book margins")
end
return T(_("Same as book margins (%1)"), self.book_margins_footer_width)
end,
checked_func = function()
return self.settings.progress_margin and not self.ui.document.info.has_pages
end,
enabled_func = function()
return not self.ui.document.info.has_pages and self.settings.progress_bar_position ~= "alongside"
end,
callback = function()
self.settings.progress_margin = true
self.settings.progress_margin_width = Screen:scaleBySize(self.book_margins_footer_width)
self:refreshFooter(true)
end
},
}
local function customMargin(px)
return {
text = T(_("Static margins (%1)"), px),
checked_func = function()
return self.settings.progress_margin_width == Screen:scaleBySize(px)
and not self.settings.progress_margin
-- if same as book margins is selected in document with pages (pdf) we enforce static margins
or (self.ui.document.info.has_pages and self.settings.progress_margin)
end,
callback = function()
self.settings.progress_margin_width = Screen:scaleBySize(px)
self.settings.progress_margin = false
self:refreshFooter(true)
end,
}
end
local device_defaults
if Device:isAndroid() then
device_defaults = customMargin(material_pixels)
else
device_defaults = customMargin(10)
end
table.insert(common, 2, device_defaults)
return common
end,
},
{
text_func = function()
return T(_("Minimal width: %1 %"), self.settings.progress_bar_min_width_pct)
end,
enabled_func = function()
return self.settings.progress_bar_position == "alongside" and not self.settings.disable_progress_bar
and self.settings.all_at_once
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local items = SpinWidget:new{
value = self.settings.progress_bar_min_width_pct,
value_min = 5,
value_step = 5,
value_hold_step = 20,
value_max = 50,
unit = "%",
title_text = _("Minimal width"),
text = _("Minimal progress bar width in percentage of screen width"),
keep_shown_on_apply = true,
callback = function(spin)
self.settings.progress_bar_min_width_pct = spin.value
self:refreshFooter(true, true)
if touchmenu_instance then touchmenu_instance:updateItems() end
end
}
UIManager:show(items)
end,
keep_menu_open = true,
}
}
})
table.insert(sub_items, getMinibarOption("page_progress"))
table.insert(sub_items, getMinibarOption("pages_left_book"))
table.insert(sub_items, getMinibarOption("time"))
table.insert(sub_items, getMinibarOption("chapter_progress"))
table.insert(sub_items, getMinibarOption("pages_left"))
if Device:hasBattery() then
table.insert(sub_items, getMinibarOption("battery"))
end
table.insert(sub_items, getMinibarOption("bookmark_count"))
table.insert(sub_items, getMinibarOption("percentage"))
table.insert(sub_items, getMinibarOption("book_time_to_read"))
table.insert(sub_items, getMinibarOption("chapter_time_to_read"))
if Device:hasFrontlight() then
table.insert(sub_items, getMinibarOption("frontlight"))
end
if Device:hasNaturalLight() then
table.insert(sub_items, getMinibarOption("frontlight_warmth"))
end
table.insert(sub_items, getMinibarOption("mem_usage"))
if Device:hasFastWifiStatusQuery() then
table.insert(sub_items, getMinibarOption("wifi_status"))
end
table.insert(sub_items, getMinibarOption("book_title"))
table.insert(sub_items, getMinibarOption("book_chapter"))
table.insert(sub_items, getMinibarOption("custom_text"))
-- Settings menu: keep the same parent page for going up from submenu
for i = 1, #sub_items[settings_submenu_num].sub_item_table do
sub_items[settings_submenu_num].sub_item_table[i].menu_item_id = i
end
-- If using crengine, add Alt status bar items at top
if self.ui.crelistener then
table.insert(sub_items, 1, self.ui.crelistener:getAltStatusBarMenu())
end
end
-- this method will be updated at runtime based on user setting
function ReaderFooter:genFooterText() end
function ReaderFooter:get_separator_symbol()
if self.settings.items_separator == "bar" then
return "|"
elseif self.settings.items_separator == "dot" then
return "·"
elseif self.settings.items_separator == "bullet" then
return "•"
end
return ""
end
function ReaderFooter:genAllFooterText()
local info = {}
local separator = " "
if self.settings.item_prefix == "compact_items" then
separator = " "
end
local separator_symbol = self:get_separator_symbol()
if separator_symbol ~= "" then
separator = string.format(" %s ", self:get_separator_symbol())
end
-- We need to BD.wrap() all items and separators, so we're
-- sure they are laid out in our order (reversed in RTL),
-- without ordering by the RTL Bidi algorithm.
local prev_had_merge
for _, gen in ipairs(self.footerTextGenerators) do
-- Skip empty generators, so they don't generate bogus separators
local text, merge = gen(self)
if text and text ~= "" then
if self.settings.item_prefix == "compact_items" then
-- remove whitespace from footer items if symbol_type is compact_items
-- use a hair-space to avoid issues with RTL display
text = text:gsub("%s", "\xE2\x80\x8A")
end
-- if generator request a merge of this item, add it directly,
-- i.e. no separator before and after the text then.
if merge then
local merge_pos = #info == 0 and 1 or #info
info[merge_pos] = (info[merge_pos] or "") .. text
prev_had_merge = true
elseif prev_had_merge then
info[#info] = info[#info] .. text
prev_had_merge = false
else
table.insert(info, BD.wrap(text))
end
end
end
return table.concat(info, BD.wrap(separator))
end
function ReaderFooter:setTocMarkers(reset)
if self.settings.disable_progress_bar or self.settings.progress_style_thin then return end
if reset then
self.progress_bar.ticks = nil
self.pages = self.ui.document:getPageCount()
end
if self.settings.toc_markers then
self.progress_bar.tick_width = Screen:scaleBySize(self.settings.toc_markers_width)
if self.progress_bar.ticks ~= nil then -- already computed
return
end
if self.ui.document:hasHiddenFlows() and self.pageno then
local flow = self.ui.document:getPageFlow(self.pageno)
self.progress_bar.ticks = {}
if self.ui.toc then
-- filter the ticks to show only those in the current flow
for n, pageno in ipairs(self.ui.toc:getTocTicksFlattened()) do
if self.ui.document:getPageFlow(pageno) == flow then
table.insert(self.progress_bar.ticks, self.ui.document:getPageNumberInFlow(pageno))
end
end
end
self.progress_bar.last = self.ui.document:getTotalPagesInFlow(flow)
else
if self.ui.toc then
self.progress_bar.ticks = self.ui.toc:getTocTicksFlattened()
end
if self.view.view_mode == "page" then
self.progress_bar.last = self.pages or self.ui.document:getPageCount()
else
-- in scroll mode, convert pages to positions
if self.ui.toc then
self.progress_bar.ticks = {}
for n, pageno in ipairs(self.ui.toc:getTocTicksFlattened()) do
local idx = self.ui.toc:getTocIndexByPage(pageno)
local pos = self.ui.document:getPosFromXPointer(self.ui.toc.toc[idx].xpointer)
table.insert(self.progress_bar.ticks, pos)
end
end
self.progress_bar.last = self.doc_height or self.ui.document.info.doc_height
end
end
else
self.progress_bar.ticks = nil
end
-- notify caller that UI needs update
return true
end
-- This is implemented by the Statistics plugin
function ReaderFooter:getAvgTimePerPage() end
function ReaderFooter:getDataFromStatistics(title, pages)
local sec = _("N/A")
local average_time_per_page = self:getAvgTimePerPage()
local user_duration_format = G_reader_settings:readSetting("duration_format", "classic")
if average_time_per_page then
sec = util.secondsToClockDuration(user_duration_format, pages * average_time_per_page, true)
end
return title .. sec
end
function ReaderFooter:onUpdateFooter(force_repaint, force_recompute)
if self.pageno then
self:updateFooterPage(force_repaint, force_recompute)
else
self:updateFooterPos(force_repaint, force_recompute)
end
end
function ReaderFooter:updateFooterPage(force_repaint, force_recompute)
if type(self.pageno) ~= "number" then return end
if self.ui.document:hasHiddenFlows() then
local flow = self.ui.document:getPageFlow(self.pageno)
local page = self.ui.document:getPageNumberInFlow(self.pageno)
local pages = self.ui.document:getTotalPagesInFlow(flow)
self.progress_bar.percentage = page / pages
else
self.progress_bar.percentage = self.pageno / self.pages
end
self:updateFooterText(force_repaint, force_recompute)
end
function ReaderFooter:updateFooterPos(force_repaint, force_recompute)
if type(self.position) ~= "number" then return end
self.progress_bar.percentage = self.position / self.doc_height
self:updateFooterText(force_repaint, force_recompute)
end
-- updateFooterText will start as a noop. After onReaderReady event is
-- received, it will initialized as _updateFooterText below
function ReaderFooter:updateFooterText(force_repaint, force_recompute)
end
-- only call this function after document is fully loaded
function ReaderFooter:_updateFooterText(force_repaint, force_recompute)
-- footer is invisible, we need neither a repaint nor a recompute, go away.
if not self.view.footer_visible and not force_repaint and not force_recompute then
return
end
local text = self:genFooterText()
if not text then text = "" end
self.footer_text:setText(text)
if self.settings.disable_progress_bar then
if self.has_no_mode or text == "" then
self.text_width = 0
self.footer_text.height = 0
else
-- No progress bar, we're only constrained to fit inside self.footer_container
self.footer_text:setMaxWidth(math.floor(self._saved_screen_width - 2 * self.horizontal_margin))
self.text_width = self.footer_text:getSize().w
self.footer_text.height = self.footer_text:getSize().h
end
self.progress_bar.height = 0
self.progress_bar.width = 0
elseif self.settings.progress_bar_position ~= "alongside" then
if self.has_no_mode or text == "" then
self.text_width = 0
self.footer_text.height = 0
else
-- With a progress bar above or below us, we want to align ourselves to the bar's margins... iff text is centered.
if self.settings.align == "center" then
self.footer_text:setMaxWidth(math.floor(self._saved_screen_width - 2 * self.settings.progress_margin_width))
else
-- Otherwise, we have to constrain ourselves to the container, or weird shit happens.
self.footer_text:setMaxWidth(math.floor(self._saved_screen_width - 2 * self.horizontal_margin))
end
self.text_width = self.footer_text:getSize().w
self.footer_text.height = self.footer_text:getSize().h
end
self.progress_bar.width = math.floor(self._saved_screen_width - 2 * self.settings.progress_margin_width)
else
if self.has_no_mode or text == "" then
self.text_width = 0
self.footer_text.height = 0
else
-- Alongside a progress bar, it's the bar's width plus whatever's left.
local text_max_available_ratio = (100 - self.settings.progress_bar_min_width_pct) * (1/100)
self.footer_text:setMaxWidth(math.floor(text_max_available_ratio * self._saved_screen_width - 2 * self.settings.progress_margin_width - self.horizontal_margin))
-- Add some spacing between the text and the bar
self.text_width = self.footer_text:getSize().w + self.horizontal_margin
self.footer_text.height = self.footer_text:getSize().h
end
self.progress_bar.width = math.floor(
self._saved_screen_width - 2 * self.settings.progress_margin_width - self.text_width)
end
if self.separator_line then
self.separator_line.dimen.w = self._saved_screen_width - 2 * self.horizontal_margin
end
self.text_container.dimen.w = self.text_width
self.horizontal_group:resetLayout()
-- NOTE: This is essentially preventing us from truly using "fast" for panning,
-- since it'll get coalesced in the "fast" panning update, upgrading it to "ui".
-- NOTE: That's assuming using "fast" for pans was a good idea, which, it turned out, not so much ;).
-- NOTE: We skip repaints on page turns/pos update, as that's redundant (and slow).
if force_repaint then
-- If there was a visibility change, notify ReaderView
if self.visibility_change then
self.ui:handleEvent(Event:new("ReaderFooterVisibilityChange"))
self.visibility_change = nil
end
-- NOTE: Getting the dimensions of the widget is impossible without having drawn it first,
-- so, we'll fudge it if need be...
-- i.e., when it's no longer visible, because there's nothing to draw ;).
local refresh_dim = self.footer_content.dimen
-- No more content...
if not self.view.footer_visible and not refresh_dim then
-- So, instead, rely on self:getHeight to compute self.footer_content's height early...
refresh_dim = self.dimen
refresh_dim.h = self:getHeight()
refresh_dim.y = self._saved_screen_height - refresh_dim.h
end
-- If we're making the footer visible (or it already is), we don't need to repaint ReaderUI behind it
if self.view.footer_visible then
-- Unfortunately, it's not a modal (we never show() it), so it's not in the window stack,
-- instead, it's baked inside ReaderUI, so it gets slightly trickier...
-- NOTE: self.view.footer -> self ;).
-- c.f., ReaderView:paintTo()
UIManager:widgetRepaint(self.view.footer, 0, 0)
-- We've painted it first to ensure self.footer_content.dimen is sane
UIManager:setDirty(nil, function()
return self.view.currently_scrolling and "fast" or "ui", self.footer_content.dimen
end)
else
UIManager:setDirty(self.view.dialog, function()
return self.view.currently_scrolling and "fast" or "ui", refresh_dim
end)
end
end
end
-- Note: no need for :onDocumentRerendered(), ReaderToc will catch "DocumentRerendered"
-- and will then emit a "TocReset" after the new ToC is made.
function ReaderFooter:onTocReset()
self:setTocMarkers(true)
if self.view.view_mode == "page" then
self:updateFooterPage()
else
self:updateFooterPos()
end
end
function ReaderFooter:onPageUpdate(pageno)
local toc_markers_update = false
if self.ui.document:hasHiddenFlows() then
local flow = self.pageno and self.ui.document:getPageFlow(self.pageno)
local new_flow = pageno and self.ui.document:getPageFlow(pageno)
if pageno and new_flow ~= flow then
toc_markers_update = true
end
end
self.pageno = pageno
self.pages = self.ui.document:getPageCount()
if toc_markers_update then
self:setTocMarkers(true)
end
self.ui.doc_settings:saveSetting("doc_pages", self.pages) -- for Book information
self:updateFooterPage()
end
function ReaderFooter:onPosUpdate(pos, pageno)
self.position = pos
self.doc_height = self.ui.document.info.doc_height
if pageno then
self.pageno = pageno
self.pages = self.ui.document:getPageCount()
self.ui.doc_settings:saveSetting("doc_pages", self.pages) -- for Book information
end
self:updateFooterPos()
end
function ReaderFooter:onReaderReady()
self.ui.menu:registerToMainMenu(self)
self:setupTouchZones()
-- if same as book margins is selected in document with pages (pdf) we enforce static margins
if self.ui.document.info.has_pages and self.settings.progress_margin then
self.settings.progress_margin_width = Size.span.horizontal_default
self:updateFooterContainer()
-- set progress bar margins for current book
elseif self.settings.progress_margin then
local margins = self.ui.document:getPageMargins()
self.settings.progress_margin_width = math.floor((margins.left + margins.right)/2)
self:updateFooterContainer()
end
self:resetLayout(self.settings.progress_margin_width) -- set widget dimen
self:setTocMarkers()
self.updateFooterText = self._updateFooterText
self:onUpdateFooter()
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onReadSettings(config)
if not self.ui.document.info.has_pages then
local h_margins = config:readSetting("copt_h_page_margins")
or G_reader_settings:readSetting("copt_h_page_margins")
or G_defaults:readSetting("DCREREADER_CONFIG_H_MARGIN_SIZES_MEDIUM")
self.book_margins_footer_width = math.floor((h_margins[1] + h_margins[2])/2)
end
end
function ReaderFooter:applyFooterMode(mode)
if mode ~= nil then self.mode = mode end
local prev_visible_state = self.view.footer_visible
self.view.footer_visible = (self.mode ~= self.mode_list.off)
-- NOTE: _updateFooterText won't actually run the text generator(s) when hidden ;).
-- We're hidden, disable text generation entirely
if not self.view.footer_visible then
self.genFooterText = footerTextGeneratorMap.empty
else
if self.settings.all_at_once then
-- If all-at-once is enabled, we only have toggle from empty to All.
self.genFooterText = self.genAllFooterText
else
-- Otherwise, switch to the right text generator for the new mode
local mode_name = self.mode_index[self.mode]
if not self.settings[mode_name] or self.has_no_mode then
-- all modes disabled, only show progress bar
mode_name = "empty"
end
self.genFooterText = footerTextGeneratorMap[mode_name]
end
end
-- If we changed visibility state at runtime (as opposed to during init), better make sure the layout has been reset...
if prev_visible_state ~= nil and self.view.footer_visible ~= prev_visible_state then
self:updateFooterContainer()
-- NOTE: _updateFooterText does a resetLayout, but not a forced one!
self:resetLayout(true)
-- Flag _updateFooterText to notify ReaderView to recalculate the visible_area!
self.visibility_change = true
end
end
function ReaderFooter:onEnterFlippingMode()
self.orig_mode = self.mode
self:applyFooterMode(self.mode_list.page_progress)
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onExitFlippingMode()
self:applyFooterMode(self.orig_mode)
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onTapFooter(ges)
local ignore_lock = false
if ges == true then
ignore_lock = true
ges = nil
end
if self.view.flipping_visible and ges then
local pos = ges.pos
local dimen = self.progress_bar.dimen
-- if reader footer is not drawn before the dimen value should be nil
if dimen then
local percentage = (pos.x - dimen.x)/dimen.w
self.ui:handleEvent(Event:new("GotoPercentage", percentage))
end
self:onUpdateFooter(true)
return true
end
if self.has_no_mode or (self.settings.lock_tap and not ignore_lock) then
return
end
if self.settings.all_at_once or self.has_no_mode then
if self.mode >= 1 then
self.mode = self.mode_list.off
else
self.mode = self.mode_list.page_progress
end
else
self.mode = (self.mode + 1) % self.mode_nb
for i, m in ipairs(self.mode_index) do
if self.mode == self.mode_list.off then break end
if self.mode == i then
if self.settings[m] then
break
else
self.mode = (self.mode + 1) % self.mode_nb
end
end
end
end
self:applyFooterMode()
G_reader_settings:saveSetting("reader_footer_mode", self.mode)
self:onUpdateFooter(true)
self:rescheduleFooterAutoRefreshIfNeeded()
return true
end
function ReaderFooter:onHoldFooter(ges)
-- We're higher priority than readerhighlight_hold, so, make sure we fall through properly...
if not self.settings.skim_widget_on_hold then
return
end
if not self.view.footer_visible then
return
end
if not self.footer_content.dimen or not self.footer_content.dimen:contains(ges.pos) then
-- We held outside the footer: meep!
return
end
-- We're good, make sure we stop the event from going to readerhighlight_hold
self.ui:handleEvent(Event:new("ShowSkimtoDialog"))
return true
end
function ReaderFooter:refreshFooter(refresh, signal)
self:updateFooterContainer()
self:resetLayout(true)
-- If we signal, the event we send will trigger a full repaint anyway, so we should be able to skip this one.
-- We *do* need to ensure we at least re-compute the footer layout, though, especially when going from visible to invisible...
self:onUpdateFooter(refresh and not signal, refresh and signal)
if signal then
if self.ui.document.provider == "crengine" then
-- This will ultimately trigger an UpdatePos, hence a ReaderUI repaint.
self.ui:handleEvent(Event:new("SetPageBottomMargin", self.ui.document.configurable.b_page_margin))
else
-- No fancy chain of events outside of CRe, just ask for a ReaderUI repaint ourselves ;).
UIManager:setDirty(self.view.dialog, "partial")
end
end
end
function ReaderFooter:onResume()
-- Don't repaint the footer until OutOfScreenSaver if screensaver_delay is enabled...
local screensaver_delay = G_reader_settings:readSetting("screensaver_delay")
if screensaver_delay and screensaver_delay ~= "disable" then
self._delayed_screensaver = true
return
end
-- Maybe perform a footer repaint on resume if it was visible.
self:maybeUpdateFooter()
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onOutOfScreenSaver()
if not self._delayed_screensaver then
return
end
self._delayed_screensaver = nil
-- Maybe perform a footer repaint on resume if it was visible.
self:maybeUpdateFooter()
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onLeaveStandby()
self:maybeUpdateFooter()
self:rescheduleFooterAutoRefreshIfNeeded()
end
function ReaderFooter:onSuspend()
self:unscheduleFooterAutoRefresh()
end
ReaderFooter.onEnterStandby = ReaderFooter.onSuspend
function ReaderFooter:onCloseDocument()
self:unscheduleFooterAutoRefresh()
end
-- Used by event handlers that can trip without direct UI interaction...
function ReaderFooter:maybeUpdateFooter()
-- ...so we need to avoid stomping over unsuspecting widgets (usually, ScreenSaver).
if UIManager:getTopWidget() == "ReaderUI" then
self:onUpdateFooter(self.view.footer_visible)
else
self:onUpdateFooter()
end
end
function ReaderFooter:onFrontlightStateChanged()
-- Custom variant of maybeUpdateFooter that *also* whitelists the FL widget...
local top_wg = UIManager:getTopWidget()
if top_wg == "ReaderUI" or top_wg == "FrontLightWidget" then
self:onUpdateFooter(self.view.footer_visible)
else
self:onUpdateFooter()
end
end
function ReaderFooter:onNetworkConnected()
if self.settings.wifi_status then
self:maybeUpdateFooter()
end
end
function ReaderFooter:onNetworkDisconnected()
if self.settings.wifi_status then
self:onUpdateFooter(self.view.footer_visible)
end
end
function ReaderFooter:onCharging()
self:maybeUpdateFooter()
end
function ReaderFooter:onNotCharging()
self:maybeUpdateFooter()
end
function ReaderFooter:onSetRotationMode()
self:updateFooterContainer()
self:resetLayout(true)
end
function ReaderFooter:onSetPageHorizMargins(h_margins)
self.book_margins_footer_width = math.floor((h_margins[1] + h_margins[2])/2)
if self.settings.progress_margin then
self.settings.progress_margin_width = Screen:scaleBySize(self.book_margins_footer_width)
self:refreshFooter(true)
end
end
function ReaderFooter:onScreenResize()
self:updateFooterContainer()
self:resetLayout(true)
end
function ReaderFooter:onTimeFormatChanged()
self:refreshFooter(true, true)
end
return ReaderFooter
| agpl-3.0 |
maxrio/luci981213 | modules/luci-base/luasrc/sys.lua | 2 | 15029 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local io = require "io"
local os = require "os"
local table = require "table"
local nixio = require "nixio"
local fs = require "nixio.fs"
local uci = require "luci.model.uci"
local luci = {}
luci.util = require "luci.util"
luci.ip = require "luci.ip"
local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select =
tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select
module "luci.sys"
function call(...)
return os.execute(...) / 256
end
exec = luci.util.exec
function mounts()
local data = {}
local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
local ps = luci.util.execi("df")
if not ps then
return
else
ps()
end
for line in ps do
local row = {}
local j = 1
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
if row[k[1]] then
-- this is a rather ugly workaround to cope with wrapped lines in
-- the df output:
--
-- /dev/scsi/host0/bus0/target0/lun0/part3
-- 114382024 93566472 15005244 86% /mnt/usb
--
if not row[k[2]] then
j = 2
line = ps()
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
end
table.insert(data, row)
end
end
return data
end
-- containing the whole environment is returned otherwise this function returns
-- the corresponding string value for the given name or nil if no such variable
-- exists.
getenv = nixio.getenv
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
function httpget(url, stream, target)
if not target then
local source = stream and io.popen or luci.util.exec
return source("wget -qO- '"..url:gsub("'", "").."'")
else
return os.execute("wget -qO '%s' '%s'" %
{target:gsub("'", ""), url:gsub("'", "")})
end
end
function reboot()
return os.execute("reboot >/dev/null 2>&1")
end
function syslog()
return luci.util.exec("logread")
end
function dmesg()
return luci.util.exec("dmesg")
end
function uniqueid(bytes)
local rand = fs.readfile("/dev/urandom", bytes)
return rand and nixio.bin.hexlify(rand)
end
function uptime()
return nixio.sysinfo().uptime
end
net = {}
-- The following fields are defined for arp entry objects:
-- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" }
function net.arptable(callback)
local arp = (not callback) and {} or nil
local e, r, v
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
local r = { }, v
for v in e:gmatch("%S+") do
r[#r+1] = v
end
if r[1] ~= "IP" then
local x = {
["IP address"] = r[1],
["HW type"] = r[2],
["Flags"] = r[3],
["HW address"] = r[4],
["Mask"] = r[5],
["Device"] = r[6]
}
if callback then
callback(x)
else
arp = arp or { }
arp[#arp+1] = x
end
end
end
end
return arp
end
local function _nethints(what, callback)
local _, k, e, mac, ip, name
local cur = uci.cursor()
local ifn = { }
local hosts = { }
local function _add(i, ...)
local k = select(i, ...)
if k then
if not hosts[k] then hosts[k] = { } end
hosts[k][1] = select(1, ...) or hosts[k][1]
hosts[k][2] = select(2, ...) or hosts[k][2]
hosts[k][3] = select(3, ...) or hosts[k][3]
hosts[k][4] = select(4, ...) or hosts[k][4]
end
end
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+")
if ip and mac then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/etc/ethers") then
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/var/dhcp.leases") then
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, name ~= "*" and name)
end
end
end
cur:foreach("dhcp", "host",
function(s)
for mac in luci.util.imatch(s.mac) do
_add(what, mac:upper(), s.ip, nil, s.name)
end
end)
for _, e in ipairs(nixio.getifaddrs()) do
if e.name ~= "lo" then
ifn[e.name] = ifn[e.name] or { }
if e.family == "packet" and e.addr and #e.addr == 17 then
ifn[e.name][1] = e.addr:upper()
elseif e.family == "inet" then
ifn[e.name][2] = e.addr
elseif e.family == "inet6" then
ifn[e.name][3] = e.addr
end
end
end
for _, e in pairs(ifn) do
if e[what] and (e[2] or e[3]) then
_add(what, e[1], e[2], e[3], e[4])
end
end
for _, e in luci.util.kspairs(hosts) do
callback(e[1], e[2], e[3], e[4])
end
end
-- Each entry contains the values in the following order:
-- [ "mac", "name" ]
function net.mac_hints(callback)
if callback then
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4)
end
end)
else
local rv = { }
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv4_hints(callback)
if callback then
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
callback(v4, name)
end
end)
else
local rv = { }
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
rv[#rv+1] = { v4, name }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv6_hints(callback)
if callback then
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
callback(v6, name)
end
end)
else
local rv = { }
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
rv[#rv+1] = { v6, name }
end
end)
return rv
end
end
function net.conntrack(callback)
local connt = {}
if fs.access("/proc/net/nf_conntrack", "r") then
for line in io.lines("/proc/net/nf_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[6] ~= "TIME_WAIT" then
entry.layer3 = flags[1]
entry.layer4 = flags[3]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
elseif fs.access("/proc/net/ip_conntrack", "r") then
for line in io.lines("/proc/net/ip_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[4] ~= "TIME_WAIT" then
entry.layer3 = "ipv4"
entry.layer4 = flags[1]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
else
return nil
end
return connt
end
function net.devices()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
devs[#devs+1] = v.name
end
end
return devs
end
function net.deviceinfo()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
local d = v.data
d[1] = d.rx_bytes
d[2] = d.rx_packets
d[3] = d.rx_errors
d[4] = d.rx_dropped
d[5] = 0
d[6] = 0
d[7] = 0
d[8] = d.multicast
d[9] = d.tx_bytes
d[10] = d.tx_packets
d[11] = d.tx_errors
d[12] = d.tx_dropped
d[13] = 0
d[14] = d.collisions
d[15] = 0
d[16] = 0
devs[v.name] = d
end
end
return devs
end
-- The following fields are defined for route entry tables:
-- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
-- "flags", "device" }
function net.routes(callback)
local routes = { }
for line in io.lines("/proc/net/route") do
local dev, dst_ip, gateway, flags, refcnt, usecnt, metric,
dst_mask, mtu, win, irtt = line:match(
"([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" ..
"(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)"
)
if dev then
gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 )
dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 )
dst_ip = luci.ip.Hex(
dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4
)
local rt = {
dest = dst_ip,
gateway = gateway,
metric = tonumber(metric),
refcount = tonumber(refcnt),
usecount = tonumber(usecnt),
mtu = tonumber(mtu),
window = tonumber(window),
irtt = tonumber(irtt),
flags = tonumber(flags, 16),
device = dev
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
-- The following fields are defined for route entry tables:
-- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
-- "flags", "device" }
function net.routes6(callback)
if fs.access("/proc/net/ipv6_route", "r") then
local routes = { }
for line in io.lines("/proc/net/ipv6_route") do
local dst_ip, dst_prefix, src_ip, src_prefix, nexthop,
metric, refcnt, usecnt, flags, dev = line:match(
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) +([^%s]+)"
)
if dst_ip and dst_prefix and
src_ip and src_prefix and
nexthop and metric and
refcnt and usecnt and
flags and dev
then
src_ip = luci.ip.Hex(
src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false
)
dst_ip = luci.ip.Hex(
dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false
)
nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false )
local rt = {
source = src_ip,
dest = dst_ip,
nexthop = nexthop,
metric = tonumber(metric, 16),
refcount = tonumber(refcnt, 16),
usecount = tonumber(usecnt, 16),
flags = tonumber(flags, 16),
device = dev,
-- lua number is too small for storing the metric
-- add a metric_raw field with the original content
metric_raw = metric
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
end
function net.pingtest(host)
return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1")
end
process = {}
function process.info(key)
local s = {uid = nixio.getuid(), gid = nixio.getgid()}
return not key and s or s[key]
end
function process.list()
local data = {}
local k
local ps = luci.util.execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
function process.setgroup(gid)
return nixio.setgid(gid)
end
function process.setuser(uid)
return nixio.setuid(uid)
end
process.signal = nixio.kill
user = {}
-- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" }
user.getuser = nixio.getpw
function user.getpasswd(username)
local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username)
local pwh = pwe and (pwe.pwdp or pwe.passwd)
if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then
return nil, pwe
else
return pwh, pwe
end
end
function user.checkpasswd(username, pass)
local pwh, pwe = user.getpasswd(username)
if pwe then
return (pwh == nil or nixio.crypt(pass, pwh) == pwh)
end
return false
end
function user.setpasswd(username, password)
if password then
password = password:gsub("'", [['"'"']])
end
if username then
username = username:gsub("'", [['"'"']])
end
return os.execute(
"(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " ..
"passwd '" .. username .. "' >/dev/null 2>&1"
)
end
wifi = {}
function wifi.getiwinfo(ifname)
local stat, iwinfo = pcall(require, "iwinfo")
if ifname then
local d, n = ifname:match("^(%w+)%.network(%d+)")
local wstate = luci.util.ubus("network.wireless", "status") or { }
d = d or ifname
n = n and tonumber(n) or 1
if type(wstate[d]) == "table" and
type(wstate[d].interfaces) == "table" and
type(wstate[d].interfaces[n]) == "table" and
type(wstate[d].interfaces[n].ifname) == "string"
then
ifname = wstate[d].interfaces[n].ifname
else
ifname = d
end
local t = stat and iwinfo.type(ifname)
local x = t and iwinfo[t] or { }
return setmetatable({}, {
__index = function(t, k)
if k == "ifname" then
return ifname
elseif x[k] then
return x[k](ifname)
end
end
})
end
end
init = {}
init.dir = "/etc/init.d/"
function init.names()
local names = { }
for name in fs.glob(init.dir.."*") do
names[#names+1] = fs.basename(name)
end
return names
end
function init.index(name)
if fs.access(init.dir..name) then
return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null"
%{ init.dir, name })
end
end
local function init_action(action, name)
if fs.access(init.dir..name) then
return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action })
end
end
function init.enabled(name)
return (init_action("enabled", name) == 0)
end
function init.enable(name)
return (init_action("enable", name) == 1)
end
function init.disable(name)
return (init_action("disable", name) == 0)
end
function init.start(name)
return (init_action("start", name) == 0)
end
function init.stop(name)
return (init_action("stop", name) == 0)
end
-- Internal functions
function _parse_mixed_record(cnt, delimiter)
delimiter = delimiter or " "
local data = {}
local flags = {}
for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do
for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do
local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*')
if k then
if x == "" then
table.insert(flags, k)
else
data[k] = v
end
end
end
end
return data, flags
end
| apache-2.0 |
Lsty/ygopro-scripts | c88205593.lua | 9 | 1202 | --エレキングコブラ
function c88205593.initial_effect(c)
--direct attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DIRECT_ATTACK)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(88205593,0))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BATTLE_DAMAGE)
e2:SetCondition(c88205593.condition)
e2:SetTarget(c88205593.target)
e2:SetOperation(c88205593.operation)
c:RegisterEffect(e2)
end
function c88205593.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp and Duel.GetAttackTarget()==nil
end
function c88205593.filter(c)
return c:IsSetCard(0xe) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c88205593.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c88205593.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c88205593.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
cshore-firmware/openwrt-luci | applications/luci-app-wifischedule/luasrc/model/cbi/wifischedule/wifi_schedule.lua | 10 | 7885 | -- Copyright (c) 2016, prpl Foundation
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without
-- fee is hereby granted, provided that the above copyright notice and this permission notice appear
-- in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
-- INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
-- FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-- ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
-- Author: Nils Koenig <openwrt@newk.it>
local fs = require "nixio.fs"
local sys = require "luci.sys"
function time_validator(self, value, desc)
if value ~= nil then
h_str, m_str = string.match(value, "^(%d%d?):(%d%d?)$")
h = tonumber(h_str)
m = tonumber(m_str)
if ( h ~= nil and
h >= 0 and
h <= 23 and
m ~= nil and
m >= 0 and
m <= 59) then
return value
end
end
return nil, translatef("The value %s is invalid", desc)
end
-- -------------------------------------------------------------------------------------------------
-- BEGIN Map
m = Map("wifi_schedule", translate("Wifi Schedule"), translate("Defines a schedule when to turn on and off wifi."))
function m.on_commit(self)
sys.exec("/usr/bin/wifi_schedule.sh cron")
end
-- END Map
-- BEGIN Global Section
global_section = m:section(TypedSection, "global", translate("Global Settings"))
global_section.optional = false
global_section.rmempty = false
global_section.anonymous = true
-- END Section
-- BEGIN Global Enable Checkbox
global_enable = global_section:option(Flag, "enabled", translate("Enable Wifi Schedule"))
global_enable.optional = false
global_enable.rmempty = false
function global_enable.validate(self, value, global_section)
if value == "1" then
if ( fs.access("/sbin/wifi") and
fs.access("/usr/bin/wifi_schedule.sh") )then
return value
else
return nil, translate("Could not find required /usr/bin/wifi_schedule.sh or /sbin/wifi")
end
else
return "0"
end
end
-- END Global Enable Checkbox
-- BEGIN Global Logging Checkbox
global_logging = global_section:option(Flag, "logging", translate("Enable logging"))
global_logging.optional = false
global_logging.rmempty = false
global_logging.default = 0
-- END Global Enable Checkbox
-- BEGIN Global Activate WiFi Button
enable_wifi = global_section:option(Button, "enable_wifi", translate("Activate wifi"))
function enable_wifi.write()
sys.exec("/usr/bin/wifi_schedule.sh start manual")
end
-- END Global Activate Wifi Button
-- BEGIN Global Disable WiFi Gracefully Button
disable_wifi_gracefully = global_section:option(Button, "disable_wifi_gracefully", translate("Disable wifi gracefully"))
function disable_wifi_gracefully.write()
sys.exec("/usr/bin/wifi_schedule.sh stop manual")
end
-- END Global Disable Wifi Gracefully Button
-- BEGIN Disable WiFi Forced Button
disable_wifi_forced = global_section:option(Button, "disable_wifi_forced", translate("Disabled wifi forced"))
function disable_wifi_forced.write()
sys.exec("/usr/bin/wifi_schedule.sh forcestop manual")
end
-- END Global Disable WiFi Forced Button
-- BEGIN Global Unload Modules Checkbox
global_unload_modules = global_section:option(Flag, "unload_modules", translate("Unload Modules (experimental; saves more power)"))
global_unload_modules.optional = false
global_unload_modules.rmempty = false
global_unload_modules.default = 0
-- END Global Unload Modules Checkbox
-- BEGIN Modules
modules = global_section:option(TextValue, "modules", "")
modules:depends("unload_modules", global_unload_modules.enabled);
modules.wrap = "off"
modules.rows = 10
function modules.cfgvalue(self, section)
mod = uci.get("wifi_schedule", section, "modules")
if mod == nil then
mod = ""
end
return mod:gsub(" ", "\r\n")
end
function modules.write(self, section, value)
if value then
value_list = value:gsub("\r\n", " ")
ListValue.write(self, section, value_list)
uci.set("wifi_schedule", section, "modules", value_list)
end
end
-- END Modules
-- BEGIN Determine Modules
determine_modules = global_section:option(Button, "determine_modules", translate("Determine Modules Automatically"))
determine_modules:depends("unload_modules", global_unload_modules.enabled);
function determine_modules.write(self, section)
output = sys.exec("/usr/bin/wifi_schedule.sh getmodules")
modules:write(section, output)
end
-- END Determine Modules
-- BEGIN Section
d = m:section(TypedSection, "entry", translate("Schedule events"))
d.addremove = true
--d.anonymous = true
-- END Section
-- BEGIN Enable Checkbox
c = d:option(Flag, "enabled", translate("Enable"))
c.optional = false
c.rmempty = false
-- END Enable Checkbox
-- BEGIN Day(s) of Week
dow = d:option(MultiValue, "daysofweek", translate("Day(s) of Week"))
dow.optional = false
dow.rmempty = false
dow:value("Monday", translate("Monday"))
dow:value("Tuesday", translate("Tuesday"))
dow:value("Wednesday", translate("Wednesday"))
dow:value("Thursday", translate("Thursday"))
dow:value("Friday", translate("Friday"))
dow:value("Saturday", translate("Saturday"))
dow:value("Sunday", translate("Sunday"))
-- END Day(s) of Weel
-- BEGIN Start Wifi Dropdown
starttime = d:option(Value, "starttime", translate("Start WiFi"))
starttime.optional = false
starttime.rmempty = false
starttime:value("00:00")
starttime:value("01:00")
starttime:value("02:00")
starttime:value("03:00")
starttime:value("04:00")
starttime:value("05:00")
starttime:value("06:00")
starttime:value("07:00")
starttime:value("08:00")
starttime:value("09:00")
starttime:value("10:00")
starttime:value("11:00")
starttime:value("12:00")
starttime:value("13:00")
starttime:value("14:00")
starttime:value("15:00")
starttime:value("16:00")
starttime:value("17:00")
starttime:value("18:00")
starttime:value("19:00")
starttime:value("20:00")
starttime:value("21:00")
starttime:value("22:00")
starttime:value("23:00")
function starttime.validate(self, value, d)
return time_validator(self, value, translate("Start Time"))
end
-- END Start Wifi Dropdown
-- BEGIN Stop Wifi Dropdown
stoptime = d:option(Value, "stoptime", translate("Stop WiFi"))
stoptime.optional = false
stoptime.rmempty = false
stoptime:value("00:00")
stoptime:value("01:00")
stoptime:value("02:00")
stoptime:value("03:00")
stoptime:value("04:00")
stoptime:value("05:00")
stoptime:value("06:00")
stoptime:value("07:00")
stoptime:value("08:00")
stoptime:value("09:00")
stoptime:value("10:00")
stoptime:value("11:00")
stoptime:value("12:00")
stoptime:value("13:00")
stoptime:value("14:00")
stoptime:value("15:00")
stoptime:value("16:00")
stoptime:value("17:00")
stoptime:value("18:00")
stoptime:value("19:00")
stoptime:value("20:00")
stoptime:value("21:00")
stoptime:value("22:00")
stoptime:value("23:00")
function stoptime.validate(self, value, d)
return time_validator(self, value, translate("Stop Time"))
end
-- END Stop Wifi Dropdown
-- BEGIN Force Wifi Stop Checkbox
force_wifi = d:option(Flag, "forcewifidown", translate("Force disabling wifi even if stations associated"))
force_wifi.default = false
force_wifi.rmempty = false
function force_wifi.validate(self, value, d)
if value == "0" then
if fs.access("/usr/bin/iwinfo") then
return value
else
return nil, translate("Could not find required programm /usr/bin/iwinfo")
end
else
return "1"
end
end
-- END Force Wifi Checkbox
return m
| apache-2.0 |
Distrotech/vlc | share/lua/playlist/appletrailers.lua | 88 | 3309 | --[[
Translate trailers.apple.com video webpages URLs to the corresponding
movie URL
$Id$
Copyright © 2007-2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "trailers.apple.com" )
and string.match( vlc.path, "web.inc" )
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function sort(a, b)
if(a == nil) then return false end
if(b == nil) then return false end
local str_a
local str_b
if(string.find(a.name, '%(') == 1) then
str_a = tonumber(string.sub(a.name, 2, string.find(a.name, 'p') - 1))
str_b = tonumber(string.sub(b.name, 2, string.find(b.name, 'p') - 1))
else
str_a = string.sub(a.name, 1, string.find(a.name, '%(') - 2)
str_b = string.sub(b.name, 1, string.find(b.name, '%(') - 2)
if(str_a == str_b) then
str_a = tonumber(string.sub(a.name, string.len(str_a) + 3, string.find(a.name, 'p', string.len(str_a) + 3) - 1))
str_b = tonumber(string.sub(b.name, string.len(str_b) + 3, string.find(b.name, 'p', string.len(str_b) + 3) - 1))
end
end
if(str_a > str_b) then return false else return true end
end
-- Parse function.
function parse()
local playlist = {}
local description = ''
local art_url = ''
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "h3>.-</h3" ) then
description = find( line, "h3>(.-)</h3")
vlc.msg.dbg(description)
end
if string.match( line, 'img src=') then
for img in string.gmatch(line, '<img src="(http://.*%.jpg)" ') do
art_url = img
end
for i,value in pairs(playlist) do
if value.arturl == '' then
playlist[i].arturl = art_url
end
end
end
if string.match( line, 'class="hd".-%.mov') then
for urlline,resolution in string.gmatch(line, 'class="hd".-href="(.-%.mov)".->(%d+.-p)') do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
table.insert( playlist, { path = urlline,
name = description.." "..resolution,
arturl = art_url,
options = {":http-user-agent=QuickTime/7.5", ":play-and-pause", ":demux=avformat"} } )
end
end
end
return playlist
end
| gpl-2.0 |
Lsty/ygopro-scripts | c61254509.lua | 5 | 1433 | --トライポッド・フィッシュ
function c61254509.initial_effect(c)
--lv up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(61254509,0))
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c61254509.condition)
e1:SetTarget(c61254509.target)
e1:SetOperation(c61254509.operation)
c:RegisterEffect(e1)
end
function c61254509.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_GRAVE)
end
function c61254509.filter(c)
return c:IsFaceup() and c:IsRace(RACE_FISH+RACE_SEASERPENT+RACE_AQUA) and c:IsLevelAbove(1)
end
function c61254509.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c61254509.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c61254509.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c61254509.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c61254509.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c29455728.lua | 3 | 1653 | --ツイン・フォトン・リザード
function c29455728.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcFunRep(c,aux.FilterBoolFunction(Card.IsSetCard,0x55),2,true)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(29455728,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c29455728.cost)
e1:SetTarget(c29455728.target)
e1:SetOperation(c29455728.operation)
c:RegisterEffect(e1)
end
function c29455728.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c29455728.mgfilter(c,e,tp,fusc)
return not c:IsControler(tp) or not c:IsLocation(LOCATION_GRAVE)
or bit.band(c:GetReason(),0x40008)~=0x40008 or c:GetReasonCard()~=fusc
or not c:IsCanBeSpecialSummoned(e,0,tp,false,false) or c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c29455728.target(e,tp,eg,ep,ev,re,r,rp,chk)
local g=e:GetHandler():GetMaterial()
if chk==0 then return g:GetCount()>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)+1>=g:GetCount()
and bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
and not g:IsExists(c29455728.mgfilter,1,nil,e,tp,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0)
end
function c29455728.operation(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetHandler():GetMaterial()
if Duel.GetLocationCount(tp,LOCATION_MZONE)>=g:GetCount()
and not g:IsExists(c29455728.mgfilter,1,nil,e,tp,e:GetHandler()) then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
CommandPost/CommandPost-App | Hammerspoon/setup.lua | 4 | 3411 | local modpath, frameworkspath, prettypath, fullpath, configdir, docstringspath, hasinitfile, autoload_extensions = ...
local userruntime = "~/.local/share/hammerspoon/site"
local paths = {
configdir .. "/?.lua",
configdir .. "/?/init.lua",
configdir .. "/Spoons/?.spoon/init.lua",
package.path,
modpath .. "/?.lua",
modpath .. "/?/init.lua",
userruntime .. "/?.lua",
userruntime .. "/?/init.lua",
userruntime .. "/Spoons/?.spoon/init.lua",
}
local cpaths = {
configdir .. "/?.dylib",
configdir .. "/?.so",
package.cpath,
frameworkspath .. "/?.dylib",
userruntime .. "/lib/?.dylib",
userruntime .. "/lib/?.so",
}
package.path = table.concat(paths, ";")
package.cpath = table.concat(cpaths, ";")
print("-- package.path: " .. package.path)
print("-- package.cpath: " .. package.cpath)
local preload = function(m) return function() return require(m) end end
package.preload['hs.application.watcher'] = preload 'hs.libapplicationwatcher'
package.preload['hs.audiodevice.watcher'] = preload 'hs.libaudiodevicewatcher'
package.preload['hs.battery.watcher'] = preload 'hs.libbatterywatcher'
package.preload['hs.bonjour.service'] = preload 'hs.libbonjourservice'
package.preload['hs.caffeinate.watcher'] = preload 'hs.libcaffeinatewatcher'
package.preload['hs.canvas.matrix'] = preload 'hs.canvas_matrix'
package.preload['hs.drawing.color'] = preload 'hs.drawing_color'
package.preload['hs.doc.hsdocs'] = preload 'hs.hsdocs'
package.preload['hs.doc.markdown'] = preload 'hs.libmarkdown'
package.preload['hs.doc.builder'] = preload 'hs.doc_builder'
package.preload['hs.fs.volume'] = preload 'hs.libfsvolume'
package.preload['hs.fs.xattr'] = preload 'hs.libfsxattr'
package.preload['hs.host.locale'] = preload 'hs.host_locale'
package.preload['hs.httpserver.hsminweb'] = preload 'hs.httpserver_hsminweb'
package.preload['hs.location.geocoder'] = preload 'hs.location_geocoder'
package.preload['hs.network.configuration'] = preload 'hs.network_configuration'
package.preload['hs.network.host'] = preload 'hs.network_host'
package.preload['hs.network.ping'] = preload 'hs.network_ping'
package.preload['hs.pasteboard.watcher'] = preload 'hs.libpasteboardwatcher'
package.preload['hs.screen.watcher'] = preload 'hs.libscreenwatcher'
package.preload['hs.socket.udp'] = preload 'hs.libsocketudp'
package.preload['hs.spaces.watcher'] = preload 'hs.libspaces_watcher'
package.preload['hs.uielement.watcher'] = preload 'hs.libuielementwatcher'
package.preload['hs.usb.watcher'] = preload 'hs.libusbwatcher'
package.preload['hs.webview.datastore'] = preload 'hs.libwebviewdatastore'
package.preload['hs.webview.usercontent'] = preload 'hs.libwebviewusercontent'
package.preload['hs.webview.toolbar'] = preload 'hs.webview_toolbar'
package.preload['hs.wifi.watcher'] = preload 'hs.libwifiwatcher'
package.preload['hs.window.filter'] = preload 'hs.window_filter'
package.preload['hs.window.highlight'] = preload 'hs.window_highlight'
package.preload['hs.window.layout'] = preload 'hs.window_layout'
package.preload['hs.window.switcher'] = preload 'hs.window_switcher'
package.preload['hs.window.tiling'] = preload 'hs.window_tiling'
return require'hs._coresetup'.setup(...)
| mit |
patixx/bostg | plugins/ingroup.lua | 9 | 54260 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_ads = 'yes',
lock_abuse = 'yes',
welcome_stat = 'yes',
sticker = 'ok',
antitag = 'no',
lock_chat = 'no',
lock_join = 'no',
welcome = 'chat',
-- silent = 'no',
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_ads = 'yes',
lock_abuse = 'yes',
welcome_stat = 'yes',
sticker = 'ok',
antitag = 'no',
lock_chat = 'no',
lock_join = 'no',
-- silent = 'no',
welcome = 'chat',
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_ads = 'yes',
lock_abuse = 'yes',
welcome_stat = 'yes',
sticker = 'ok',
antitag = 'no',
lock_chat = 'no',
lock_join = 'no',
-- silent = 'no',
welcome = 'chat',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_ads = 'yes',
lock_abuse = 'yes',
welcome_stat = 'yes',
sticker = 'ok',
antitag = 'no',
lock_chat = 'no',
lock_join = 'no',
-- silent = 'no',
welcome = 'chat',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name✏️: "..settings.lock_name.."\nLock group photo🎡: "..settings.lock_photo.."\nLock group member👥: "..settings.lock_member.."\nflood sensitivity🤘: f."..NUM_MSG_MAX.."\nBot protection👾: "..bots_protection.."\nAds protection☠: "..settings.lock_ads.."\nlock chat❎☠: "..settings.lock_chat.."\nLock Tag🆔: "..settings.antitag.."\nSticker Policy👻: "..settings.sticker.."\nWelcome👤➕:"..settings.welcome.."\nantispam: kick\n> Bot Version: 5.5"
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_tag(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_tag_lock = data[tostring(target)]['settings']['antitag']
if group_tag_lock == 'yes' then
return 'tag is already locked'
else
data[tostring(target)]['settings']['antitag'] = 'yes'
save_data(_config.moderation.data, data)
return 'tag has been locked'
end
end
local function unlock_group_tag(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_tag_lock = data[tostring(target)]['settings']['antitag']
if group_tag_lock == 'no' then
return 'tag is already unlocked'
else
data[tostring(target)]['settings']['antitag'] = 'no'
save_data(_config.moderation.data, data)
return 'tag has been unlocked'
end
end
local function lock_group_chat(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_chat_lock = data[tostring(target)]['settings']['lock_chat']
if group_chat_lock == 'yes' then
return 'chat is already locked'
else
data[tostring(target)]['settings']['lock_chat'] = 'yes'
save_data(_config.moderation.data, data)
return 'chat has been locked'
end
end
local function unlock_group_chat(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_chat_lock = data[tostring(target)]['settings']['lock_chat']
if group_chat_lock == 'no' then
return 'chat is already unlocked'
else
data[tostring(target)]['settings']['lock_chat'] = 'no'
save_data(_config.moderation.data, data)
return 'chat has been unlocked'
end
end
local function lock_group_join(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_join_lock = data[tostring(target)]['settings']['lock_join']
if group_join_lock == 'yes' then
return ' joining Link is already locked'
else
data[tostring(target)]['settings']['lock_join'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link has been locked'
end
end
local function unlock_group_join(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_join_lock = data[tostring(target)]['settings']['lock_join']
if group_join_lock == 'no' then
return ' joining Link is already unlocked'
else
data[tostring(target)]['settings']['lock_join'] = 'no'
save_data(_config.moderation.data, data)
return ' joining Link has been unlocked'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_ads(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_ads_lock = data[tostring(target)]['settings']['lock_ads']
if group_ads_lock == 'yes' then
return 'Ads protection is already enabled'
else
data[tostring(target)]['settings']['lock_ads'] = 'yes'
save_data(_config.moderation.data, data)
return 'Ads protection has been enabled'
end
end
local function unlock_group_ads(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_ads_lock = data[tostring(target)]['settings']['lock_ads']
if group_ads_lock == 'no' then
return 'Ads protection is already disabled'
else
data[tostring(target)]['settings']['lock_ads'] = 'no'
save_data(_config.moderation.data, data)
return 'Ads protection has been disabled'
end
local function silent(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local silent = data[tostring(target)]['settings']['silent']
if silent == 'yes' then
return 'Group silent is already enabled'
else
data[tostring(target)]['settings']['silent'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group silent has been enabled'
end
end
end
local function unlock_silent(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_silent = data[tostring(target)]['settings']['silent']
if group_silent == 'no' then
return 'Group silent is already disabled'
else
data[tostring(target)]['settings']['silent'] = 'no'
save_data(_config.moderation.data, data)
return 'Group silent has been disabled'
end
local function lock_group_fosh(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_fosh_lock = data[tostring(target)]['settings']['antifosh']
if group_fosh_lock == 'yes' then
return 'fosh is already locked'
else
data[tostring(target)]['settings']['antifosh'] = 'yes'
save_data(_config.moderation.data, data)
return 'fosh has been locked'
end
end
local function unlock_group_fosh(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_fosh_lock = data[tostring(target)]['settings']['antifosh']
if group_fosh_lock == 'no' then
return 'fosh is already unlocked'
else
data[tostring(target)]['settings']['antifosh'] = 'no'
save_data(_config.moderation.data, data)
return 'fosh has been unlocked'
end
end
local function welcome_yes(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local welcome_yes = data[tostring(target)]['settings']['welcome_yes']
if welcome_yes == 'yes' then
return 'Welcome is already enabled'
else
data[tostring(target)]['settings']['welcome_yes'] = 'yes'
save_data(_config.moderation.data, data)
return 'Welcome has been enabled'
end
end
end
local function welcome_no(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local welcome_no = data[tostring(target)]['settings']['welcome_no']
if group_ads_lock == 'no' then
return 'Welcome is already disabled'
else
data[tostring(target)]['settings']['welcome_no'] = 'no'
save_data(_config.moderation.data, data)
return 'Welcome has been disabled'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'silent' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] turned on silent ")
return silent(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] turned off silent ")
return unlock_silent(msg, data, target)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'ads' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked ads ")
return lock_group_ads(msg, data, target)
end
if matches[2] == 'fosh' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh ")
return lock_group_fosh(msg, data, target)
end
if matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'chat' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked chat ")
return lock_group_chat(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
if matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked joining link ")
return lock_group_join(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'ads' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked ads ")
return unlock_group_ads(msg, data, target)
end
if matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag ")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'chat' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked chat ")
return unlock_group_chat(msg, data, target)
end
if matches[2] == 'fosh' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh ")
return unlock_group_fosh(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
if matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked joining link ")
return unlock_group_join(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'info' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/.]([Aa]dd)$",
"^[!/.]([Aa]dd) (realm)$",
"^[!/.]([Rr]em)$",
"^[!/.]([Rr]em) (realm)$",
"^[!/.]([Rr]ules)$",
"^[!/.]([Aa]bout)$",
"^[!/.]([Ss]etname) (.*)$",
"^[!/.]([Ss]etphoto)$",
"^[!/.]([Pp]romote) (.*)$",
"^[!/.]([Pp]romote)",
"^[!/.]([Hh]elp)$",
"^[!/.]([Cc]lean) (.*)$",
"^[!/.]([Kk]ill) (chat)$",
"^[!/.]([Kk]ill) (realm)$",
"^[!/.]([Dd]emote) (.*)$",
"^[!/.]([Dd]emote)",
"^[!/.]([Ss]et) ([^%s]+) (.*)$",
"^[!/.]([Ss]ilent) (.*)$",
"^[!/.]([Ll]ock) (.*)$",
"^[!/.]([Ss]etowner) (%d+)$",
"^[!/.]([Ss]etowner)",
"^[!/.]([Oo]wner)$",
"^[!/.]([Ii]nfo) (.*)$",
"^[!/.]([Ss]etgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/.]([Uu]nlock) (.*)$",
"^[!/.]([Ss]etflood) (%d+)$",
"^[!/.]([Ss]ettings)$",
"^[!/.]([Pp]ublic) (.*)$",
"^[!/.]([Mm]odlist)$",
"^[!/.]([Nn]ewlink)$",
"^[!/.]([Ll]ink)$",
"^[!/.]([Kk]ickinactive)$",
"^[!/.]([Kk]ickinactive) (%d+)$",
"^([Aa]dd)$",
"^([Aa]dd) (realm)$",
"^([Rr]em)$",
"^([Rr]em) (realm)$",
"^([Rr]ules)$",
"^([Aa]bout)$",
"^([Ss]etname) (.*)$",
"^([Ss]etphoto)$",
"^([Pp]romote) (.*)$",
"^([Pp]romote)",
"^([Hh]elp)$",
"^([Cc]lean) (.*)$",
"^([Kk]ill) (chat)$",
"^([Kk]ill) (realm)$",
"^([Dd]emote) (.*)$",
"^([Dd]emote)",
"^([Ss]et) ([^%s]+) (.*)$",
"^([Ss]ilent) (.*)$",
"^([Ll]ock) (.*)$",
"^([Ww]elcome) (.*)$",
"^([Ss]etowner) (%d+)$",
"^([Ss]etowner)",
"^([Oo]wner)$",
"^([Ii]nfo) (.*)$",
"^([Ss]etgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^([Uu]nlock) (.*)$",
"^([Ss]etflood) (%d+)$",
"^([Ss]ettings)$",
"^([Pp]ublic) (.*)$",
"^([Mm]odlist)$",
"^([Nn]ewlink)$",
"^([Ll]ink)$",
"^([Kk]ickinactive)$",
"^([Kk]ickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
-- by hamed980
| gpl-2.0 |
Lsty/ygopro-scripts | c54250060.lua | 3 | 3393 | --召魔装着
function c54250060.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_FZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c54250060.atktg)
e2:SetValue(300)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_DEFENCE)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(54250060,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_FZONE)
e4:SetCountLimit(1)
e4:SetCost(c54250060.spcost)
e4:SetTarget(c54250060.sptg)
e4:SetOperation(c54250060.spop)
c:RegisterEffect(e4)
--to hand
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(54250060,1))
e5:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_FZONE)
e5:SetCountLimit(1)
e5:SetCost(c54250060.thcost)
e5:SetTarget(c54250060.thtg)
e5:SetOperation(c54250060.thop)
c:RegisterEffect(e5)
end
function c54250060.atktg(e,c)
return c:IsRace(RACE_DRAGON+RACE_WARRIOR+RACE_SPELLCASTER)
end
function c54250060.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_DISCARD+REASON_COST,nil)
end
function c54250060.spfilter(c,e,tp)
return c:IsSetCard(0xca) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c54250060.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c54250060.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c54250060.spop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c54250060.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c54250060.cfilter(c)
return c:IsRace(RACE_WARRIOR+RACE_SPELLCASTER) and c:IsAbleToRemoveAsCost()
end
function c54250060.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c54250060.cfilter,tp,LOCATION_GRAVE,0,4,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c54250060.cfilter,tp,LOCATION_GRAVE,0,4,4,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c54250060.thfilter(c)
return c:IsSetCard(0xcb) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c54250060.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c54250060.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c54250060.thop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c54250060.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
CommandPost/CommandPost-App | extensions/fs/test_fs.lua | 6 | 9606 | -- hs.fs tests
require("hs.fs")
require("hs.socket")
testDir = "/private/tmp/hs_fs_test_dir/"
function writeFile(filename, contents)
io.open(filename, "w"):write(contents):close()
end
function setUp()
os.execute("mkdir "..testDir)
return success()
end
function tearDown()
os.execute("rm -r "..testDir)
return success()
end
function testMkdir()
local dirname = testDir.."mkdir_test_directory"
assertTrue(hs.fs.mkdir(dirname))
local status, err = hs.fs.mkdir(dirname)
assertFalse(status)
assertIsEqual("File exists", err)
return success()
end
function testChdir()
local dirname = testDir.."chdir_test_directory"
assertTrue(hs.fs.mkdir(dirname))
assertTrue(hs.fs.chdir(dirname))
assertIsEqual(dirname, hs.fs.currentDir())
local status, err = hs.fs.chdir("some_non_existent_dir")
assertIsNil(status)
assertIsEqual("No such file or directory", err:match("No such file or directory"))
return success()
end
function testRmdir()
local dirname = testDir.."some_unique_directory/"
local dirnameWithContents = testDir.."some_unique_directory_with_contents/"
local filename = "test.txt"
local result, errorMsg
assertTrue(hs.fs.mkdir(dirname))
assertTrue(hs.fs.rmdir(dirname))
assertTrue(hs.fs.mkdir(dirnameWithContents))
writeFile(dirnameWithContents..filename, "some text\n")
result, errorMsg = hs.fs.rmdir(dirnameWithContents)
assertIsNil(result)
assertIsEqual(errorMsg, "Directory not empty")
os.execute("rm "..dirnameWithContents..filename)
assertTrue(hs.fs.rmdir(dirnameWithContents))
result, errorMsg = hs.fs.rmdir("~/some_non_existent_dir")
assertIsNil(result)
assertIsEqual(errorMsg, "No such file or directory")
return success()
end
function testAttributes()
local dirname = testDir.."attributes_test_directory/"
local filename = "test.txt"
local pipename = "pipe"
assertTrue(hs.fs.mkdir(dirname))
writeFile(dirname..filename, "some text\n")
os.execute("mkfifo "..dirname..pipename)
local noFileInfo = hs.fs.attributes("~/non_existent_file")
local dirMode = hs.fs.attributes(dirname, "mode")
local fileInfo = hs.fs.attributes(dirname..filename)
local fifoInfo = hs.fs.attributes(dirname..pipename)
local charDeviceInfo = hs.fs.attributes("/dev/urandom")
local blockDeviceInfo = hs.fs.attributes("/dev/disk0")
assertIsNil(noFileInfo)
assertIsEqual("directory", dirMode)
assertIsEqual("file", fileInfo.mode)
assertIsEqual("named pipe", fifoInfo.mode)
assertIsEqual("char device", charDeviceInfo.mode)
assertIsEqual("block device", blockDeviceInfo.mode)
local status, err = hs.fs.attributes(dirname, "bad_attribute_name")
assertIsNil(status)
assertIsEqual("invalid attribute name 'bad_attribute_name'", err)
if hs.socket then
local sockname, socket = "sock", nil
socket = hs.socket.server(dirname..sockname)
assertIsEqual("socket", hs.fs.attributes(dirname..sockname).mode)
socket:disconnect()
end
return success()
end
function testTags()
local dirname = testDir.."tag_test_directory/"
local filename = "test.txt"
local filename2 = "test2.txt"
local tags = {"really cool tag", "another cool tag"}
local tag = {"some tag"}
assertTrue(hs.fs.mkdir(dirname))
writeFile(dirname..filename, "some text\n")
writeFile(dirname..filename2, "some more text\n")
hs.fs.chdir(dirname)
assertFalse(pcall(hs.fs.tagsGet, "non_existent_file"))
assertFalse(pcall(hs.fs.tagsSet, "non_existent_file", tags))
assertIsNil(hs.fs.tagsGet(filename))
assertIsNil(hs.fs.tagsGet(filename2))
hs.fs.tagsAdd(filename, tags)
hs.fs.tagsAdd(filename2, hs.fs.tagsGet(filename))
assertListsEqual(tags, hs.fs.tagsGet(filename))
assertListsEqual(tags, hs.fs.tagsGet(filename2))
hs.fs.tagsAdd(filename, tag)
assertListsEqual(table.pack(tag[1], table.unpack(tags)), hs.fs.tagsGet(filename))
hs.fs.tagsRemove(filename, tag)
assertListsEqual(tags, hs.fs.tagsGet(filename))
hs.fs.tagsSet(filename, tag)
assertListsEqual(tag, hs.fs.tagsGet(filename))
hs.fs.tagsSet(filename, tags)
assertListsEqual(tags, hs.fs.tagsGet(filename))
hs.fs.tagsSet(filename2, {})
assertIsNil(hs.fs.tagsGet(filename2))
return success()
end
function testLinks()
local dirname = testDir.."link_test_directory/"
local filename = "test.txt"
local symlinkname = "test.symlink"
local hardlinkname = "test.hardlink"
assertTrue(hs.fs.mkdir(dirname))
writeFile(dirname..filename, "some text\n")
assertTrue(hs.fs.link(dirname..filename, dirname..symlinkname, true))
status, err = hs.fs.link(dirname..filename, dirname..symlinkname, true)
assertIsNil(status)
assertTrue(hs.fs.link(dirname..filename, dirname..hardlinkname))
status, err2 = hs.fs.link(dirname..filename, dirname..hardlinkname)
assertIsNil(status)
assertIsEqual("file", hs.fs.attributes(dirname..symlinkname).mode)
assertIsEqual("file", hs.fs.attributes(dirname..hardlinkname).mode)
assertIsEqual("link", hs.fs.symlinkAttributes(dirname..symlinkname).mode)
assertIsEqual("file", hs.fs.symlinkAttributes(dirname..hardlinkname).mode)
return success()
end
function testTouch()
local dirname = hs.fs.temporaryDirectory()
local filename = "test.txt"
local aTime, mTime = 300, 200
local status, err = hs.fs.touch("non_existent_file")
assertIsNil(status)
assertIsEqual("No such file or directory", err)
writeFile(dirname..filename, "some contents\n")
assertTrue(hs.fs.touch(dirname..filename, aTime))
assertIsEqual(aTime, hs.fs.attributes(dirname..filename).access)
assertIsEqual(aTime, hs.fs.attributes(dirname..filename).modification)
assertTrue(hs.fs.touch(dirname..filename, aTime, mTime))
assertIsEqual(aTime, hs.fs.attributes(dirname..filename).access)
assertIsEqual(mTime, hs.fs.attributes(dirname..filename).modification)
return success()
end
function testFileUTI()
local dirname = testDir.."file_uti_test_directory/"
local filename = "test.txt"
assertTrue(hs.fs.mkdir(dirname))
writeFile(dirname..filename, "some text\n")
assertIsEqual("public.plain-text", hs.fs.fileUTI(dirname..filename))
assertIsNil(hs.fs.fileUTI("non_existent_file"))
return success()
end
function testDirWalker()
local dirname = testDir.."dirwalker_test_directory/"
local filenames = {"test1.txt", "test2.txt", "test3.txt"}
assertTrue(hs.fs.mkdir(dirname))
hs.fnutils.each(filenames, function(filename)
writeFile(dirname..filename, "some text\n")
end)
local iterfn, dirobj = hs.fs.dir(dirname)
local dirContents = {}
repeat
local filename = dirobj:next()
table.insert(dirContents, filename)
until filename == nil
dirobj:close()
table.insert(filenames, "."); table.insert(filenames, "..")
assertListsEqual(filenames, dirContents)
iterfn, dirobj = hs.fs.dir(dirname)
dirobj:close()
local status, err = pcall(hs.fs.dir, "some_non_existent_dir")
assertFalse(status)
assertIsEqual("cannot open", err:match("cannot open"))
return success()
end
function testLockDir()
local dirname = testDir.."lockdir_test_directory/"
local lock, lock2, err
assertTrue(hs.fs.mkdir(dirname))
lock, err = hs.fs.lockDir(dirname)
assertIsUserdata(lock)
assertIsNil(err)
assertIsEqual("link", hs.fs.symlinkAttributes(dirname.."lockfile.lfs").mode)
lock2, err = hs.fs.lockDir(dirname)
assertIsEqual("File exists", err)
lock:free()
lock2, err = hs.fs.lockDir(dirname)
assertIsUserdata(lock2)
assertIsNil(err)
assertIsEqual("link", hs.fs.symlinkAttributes(dirname.."lockfile.lfs").mode)
lock2:free()
return success()
end
function testLock()
local dirname = testDir.."lock_test_directory/"
local filename = "test.txt"
local lock, err, lock2, err2
assertTrue(hs.fs.mkdir(dirname))
writeFile(dirname..filename, "1234567890")
f = io.open(dirname..filename, "r")
lock, err = hs.fs.lock(f, "r")
assertTrue(lock)
assertIsNil(err)
lock2, err2 = hs.fs.lock(f, "w")
assertIsNil(lock2)
assertIsEqual("Bad file descriptor", err2)
assertTrue(hs.fs.unlock(f))
f:close()
f = io.open(dirname..filename, "w")
lock, err = hs.fs.lock(f, "w")
assertTrue(lock)
assertIsNil(err)
lock2, err2 = hs.fs.lock(f, "r")
assertIsNil(lock2)
assertIsEqual("Bad file descriptor", err2)
assertTrue(hs.fs.unlock(f))
f:close()
return success()
end
function testVolumesValues()
print(path, newPath)
if (type(path) == "string" and path == "/Volumes/"..ramdiskName and
type(newPath) == "string" and newPath == "/Volumes/"..ramdiskRename) then
return success()
else
return string.format("Waiting for success...")
end
end
function testVolumes()
local volumes = hs.fs.volume.allVolumes()
assertIsEqual(false, volumes["/"].NSURLVolumeIsEjectableKey)
ramdiskName = "ramDisk"
ramdiskRename = "renamedDisk"
local volumeWatcherCallback = function(event, info)
if event == hs.fs.volume.didMount then
path = info.path:match("(/Volumes/"..ramdiskName..")/?$")
if not path then return end
os.execute("diskutil rename "..ramdiskName.." "..ramdiskRename)
end
if event == hs.fs.volume.didRename then
-- NOTE: in this case, `info` is returned as a NSURL object:
newPath = info.path and info.path.filePath:match("(/Volumes/"..ramdiskRename..")/?$")
if not newPath then return end
hs.fs.volume.eject(newPath)
volumeWatcher:stop()
end
end
volumeWatcher = hs.fs.volume.new(volumeWatcherCallback):start()
assertIsString(tostring(volumeWatcher))
os.execute("diskutil erasevolume HFS+ '"..ramdiskName.."' `hdiutil attach -nomount ram://2048`")
return success()
end
| mit |
summitly/luazmq | src/zmq.lua | 1 | 6222 | module( ... , package.seeall)
local luazmq = require("luazmq");
zmq_version = luazmq.zmq_version
zmq_errno = luazmq.zmq_errno
zmq_strerror = luazmq.zmq_strerror
zmq_ctx_new = luazmq.zmq_ctx_new
zmq_ctx_term = luazmq.zmq_ctx_term
zmq_ctx_shutdown = luazmq.zmq_ctx_shutdown
zmq_ctx_set = luazmq.zmq_ctx_set
zmq_ctx_get = luazmq.zmq_ctx_get
zmq_msg_new = luazmq.zmq_msg_new
zmq_msg_init = luazmq.zmq_msg_init
zmq_msg_init_size = luazmq.zmq_msg_init_size
zmq_msg_send = luazmq.zmq_msg_send
zmq_msg_recv = luazmq.zmq_msg_recv
zmq_msg_close = luazmq.zmq_msg_close
zmq_msg_move = luazmq.zmq_msg_move
zmq_msg_copy = luazmq.zmq_msg_copy
zmq_msg_data = luazmq.zmq_msg_data
zmq_msg_size = luazmq.zmq_msg_size
zmq_msg_more = luazmq.zmq_msg_more
zmq_msg_get = luazmq.zmq_msg_get
zmq_msg_set = luazmq.zmq_msg_set
zmq_socket = luazmq.zmq_socket
zmq_close = luazmq.zmq_close
zmq_setsockopt = luazmq.zmq_setsockopt
zmq_getsockopt = luazmq.zmq_getsockopt
zmq_bind = luazmq.zmq_bind
zmq_connect = luazmq.zmq_connect
zmq_disconnect = luazmq.zmq_disconnect
zmq_send = luazmq.zmq_send
zmq_send_const = luazmq.zmq_send_const
zmq_recv = luazmq.zmq_recv
zmq_socket_monitor = luazmq.zmq_socket_monitor
zmq_sendmsg = luazmq.zmq_sendmsg
zmq_recvmsg = luazmq.zmq_recvmsg
--°æ±¾ÐÅÏ¢
ZMQ_VERSION_MAJOR = 4
ZMQ_VERSION_MINOR = 0
ZMQ_VERSION_PATCH = 4
ZMQ_VERSION = ZMQ_VERSION_MAJOR * 10000 + ZMQ_VERSION_MINOR * 100 + ZMQ_VERSION_PATCH
--´íÎó´úÂë
ZMQ_HAUSNUMBERO = 156384712
--ƽ̨´íÎó
ENOTSUP = ZMQ_HAUSNUMBERO + 1
EPROTONOSUPPORT = ZMQ_HAUSNUMBERO + 2
ENOBUFS = ZMQ_HAUSNUMBERO + 3
ENETDOWN = ZMQ_HAUSNUMBERO + 4
EADDRINUSE = ZMQ_HAUSNUMBERO + 5
EADDRNOTAVAIL = ZMQ_HAUSNUMBERO + 6
ECONNREFUSED = ZMQ_HAUSNUMBERO + 7
EINPROGRESS = ZMQ_HAUSNUMBERO + 8
ENOTSOCK = ZMQ_HAUSNUMBERO + 9
EMSGSIZE = ZMQ_HAUSNUMBERO + 10
EAFNOSUPPORT = ZMQ_HAUSNUMBERO + 11
ENETUNREACH = ZMQ_HAUSNUMBERO + 12
ECONNABORTED = ZMQ_HAUSNUMBERO + 13
ECONNRESET = ZMQ_HAUSNUMBERO + 14
ENOTCONN = ZMQ_HAUSNUMBERO + 15
ETIMEDOUT = ZMQ_HAUSNUMBERO + 16
EHOSTUNREACH = ZMQ_HAUSNUMBERO + 17
ENETRESET = ZMQ_HAUSNUMBERO + 18
--0MQ±¾Éí´íÎó
EFSM = ZMQ_HAUSNUMBERO + 51
ENOCOMPATPROTO = ZMQ_HAUSNUMBERO + 52
ETERM = ZMQ_HAUSNUMBERO + 53
EMTHREAD = ZMQ_HAUSNUMBERO + 54
--0MQÔËÐвÎÊý
ZMQ_IO_THREADS = 1
ZMQ_MAX_SOCKETS = 2
ZMQ_IO_THREADS_DFLT = 1
ZMQ_MAX_SOCKETS_DFLT = 1023
--0MQ socket¶¨Òå
--SocketÀàÐÍ
ZMQ_PAIR = 0
ZMQ_PUB = 1
ZMQ_SUB = 2
ZMQ_REQ = 3
ZMQ_REP = 4
ZMQ_DEALER = 5
ZMQ_ROUTER = 6
ZMQ_PULL = 7
ZMQ_PUSH = 8
ZMQ_XPUB = 9
ZMQ_XSUB = 10
ZMQ_STREAM = 11
--SocketÑ¡Ïî
ZMQ_AFFINITY = 4
ZMQ_IDENTITY = 5
ZMQ_SUBSCRIBE = 6
ZMQ_UNSUBSCRIBE = 7
ZMQ_RATE = 8
ZMQ_RECOVERY_IVL = 9
ZMQ_SNDBUF = 11
ZMQ_RCVBUF = 12
ZMQ_RCVMORE = 13
ZMQ_FD = 14
ZMQ_EVENTS = 15
ZMQ_TYPE = 16
ZMQ_LINGER = 17
ZMQ_RECONNECT_IVL = 18
ZMQ_BACKLOG = 19
ZMQ_RECONNECT_IVL_MAX = 21
ZMQ_MAXMSGSIZE = 22
ZMQ_SNDHWM = 23
ZMQ_RCVHWM = 24
ZMQ_MULTICAST_HOPS = 25
ZMQ_RCVTIMEO = 27
ZMQ_SNDTIMEO = 28
ZMQ_LAST_ENDPOINT = 32
ZMQ_ROUTER_MANDATORY = 33
ZMQ_TCP_KEEPALIVE = 34
ZMQ_TCP_KEEPALIVE_CNT = 35
ZMQ_TCP_KEEPALIVE_IDLE = 36
ZMQ_TCP_KEEPALIVE_INTVL = 37
ZMQ_TCP_ACCEPT_FILTER = 38
ZMQ_IMMEDIATE = 39
ZMQ_XPUB_VERBOSE = 40
ZMQ_ROUTER_RAW = 41
ZMQ_IPV6 = 42
ZMQ_MECHANISM = 43
ZMQ_PLAIN_SERVER = 44
ZMQ_PLAIN_USERNAME = 45
ZMQ_PLAIN_PASSWORD = 46
ZMQ_CURVE_SERVER = 47
ZMQ_CURVE_PUBLICKEY = 48
ZMQ_CURVE_SECRETKEY = 49
ZMQ_CURVE_SERVERKEY = 50
ZMQ_PROBE_ROUTER = 51
ZMQ_REQ_CORRELATE = 52
ZMQ_REQ_RELAXED = 53
ZMQ_CONFLATE = 54
ZMQ_ZAP_DOMAIN = 55
--MessageÑ¡Ïî
ZMQ_MORE = 1
--Send/recvÑ¡Ïî
ZMQ_DONTWAIT = 1
SNDMORE = 2
--Security mechanisms
ZMQ_NULL = 0
ZMQ_PLAIN = 1
ZMQ_CURVE = 2
--0MQ socket events and monitoring
--Socket transport events (tcp and ipc only)
ZMQ_EVENT_CONNECTED = 1
ZMQ_EVENT_CONNECT_DELAYED = 2
ZMQ_EVENT_CONNECT_RETRIED = 4
ZMQ_EVENT_LISTENING = 8
ZMQ_EVENT_BIND_FAILED = 16
ZMQ_EVENT_ACCEPTED = 32
ZMQ_EVENT_ACCEPT_FAILED = 64
ZMQ_EVENT_CLOSED = 128
ZMQ_EVENT_CLOSE_FAILED = 256
ZMQ_EVENT_DISCONNECTED = 512
ZMQ_EVENT_MONITOR_STOPPED = 1024
ZMQ_EVENT_ALL = 2047 --1|2|4| ... | 1024
| lgpl-3.0 |
Frenzie/koreader | frontend/depgraph.lua | 8 | 8306 | --[[--
DepGraph module.
Library for constructing dependency graphs.
Example:
local dg = DepGraph:new{}
dg:addNode('a1', {'a2', 'b1'})
dg:addNode('b1', {'a2', 'c1'})
dg:addNode('c1')
-- The return value of dg:serialize() will be:
-- {'a2', 'c1', 'b1', 'a1'}
NOTE: Insertion order is preserved, duplicates are automatically prevented (both as main nodes and as deps).
]]
local DepGraph = {}
function DepGraph:new(new_o)
local o = new_o or {}
o.nodes = {}
setmetatable(o, self)
self.__index = self
return o
end
-- Check if node exists, and is active
function DepGraph:checkNode(id)
for _, n in ipairs(self.nodes) do
if n.key == id and not n.disabled then
return true
end
end
return false
end
-- Returns a (node, node_index) tuple
function DepGraph:getNode(id)
for i, n in ipairs(self.nodes) do
if n.key == id then
return n, i
end
end
return nil, nil
end
-- Like getNode, but only for active nodes:
-- if node is nil but index is set, node is disabled
function DepGraph:getActiveNode(id)
local node, index = self:getNode(id)
if node and node.disabled then
return nil, index
end
return node, index
end
-- Add a node, with an optional list of dependencies
-- If dependencies don't exist as proper nodes yet, they'll be created, in order.
-- If node already exists, the new list of dependencies is *appended* to the existing one, without duplicates.
function DepGraph:addNode(node_key, deps)
-- Find main node if it already exists
local node = self:getNode(node_key)
if node then
-- If it exists, but was disabled, re-enable it
if node.disabled then
node.disabled = nil
end
else
-- If it doesn't exist at all, create it
node = { key = node_key }
table.insert(self.nodes, node)
end
-- No dependencies? We're done!
if not deps then
return
end
-- Create dep nodes if they don't already exist
local node_deps = node.deps or {}
for _, dep_node_key in ipairs(deps) do
local dep_node = self:getNode(dep_node_key)
if dep_node then
-- If it exists, but was disabled, re-enable it
if dep_node.disabled then
dep_node.disabled = nil
end
else
-- Create dep node itself if need be
dep_node = { key = dep_node_key }
table.insert(self.nodes, dep_node)
end
-- Update deps array the long way 'round, and prevent duplicates, in case deps was funky as hell.
local exists = false
for _, k in ipairs(node_deps) do
if k == dep_node_key then
exists = true
break
end
end
if not exists then
table.insert(node_deps, dep_node_key)
end
end
-- Update main node with its updated deps
node.deps = node_deps
end
-- Attempt to remove a node, as well as all traces of it from other nodes' deps
-- If node has deps, it's kept, but marked as disabled, c.f., lenghty comment below.
function DepGraph:removeNode(node_key)
-- We shouldn't remove a node if it has dependencies (as these may have been added via addNodeDep
-- (as opposed to the optional deps list passed to addNode), like what InputContainer does with overrides,
-- overrides originating from completely *different* nodes,
-- meaning those other nodes basically add themselves to another's deps).
-- We don't want to lose the non-native dependency on these other nodes in case we later re-addNode this one
-- with its stock dependency list.
local node, index = self:getNode(node_key)
if node then
if not node.deps or #node.deps == 0 then
-- No dependencies, can be wiped safely
table.remove(self.nodes, index)
else
-- Can't remove it, just flag it as disabled instead
node.disabled = true
end
end
-- On the other hand, we definitely should remove it from the deps of every *other* node.
for _, curr_node in ipairs(self.nodes) do
-- Is not the to be removed node, and has deps
if curr_node.key ~= node_key and curr_node.deps then
-- Walk that node's deps to check if it depends on us
for idx, dep_node_key in ipairs(curr_node.deps) do
-- If it did, wipe ourselves from there
if dep_node_key == node_key then
table.remove(curr_node.deps, idx)
break
end
end
end
end
end
-- Add a single dep_node_key to node_key's deps
function DepGraph:addNodeDep(node_key, dep_node_key)
-- Check the main node
local node = self:getNode(node_key)
if node then
-- If it exists, but was disabled, re-enable it
if node.disabled then
node.disabled = nil
end
else
-- If it doesn't exist at all, create it
node = { key = node_key }
table.insert(self.nodes, node)
end
-- Then check the dep node
local dep_node = self:getNode(dep_node_key)
if dep_node then
-- If it exists, but was disabled, re-enable it
if dep_node.disabled then
dep_node.disabled = nil
end
else
-- Create dep node itself if need be
dep_node = { key = dep_node_key }
table.insert(self.nodes, dep_node)
end
-- If main node currently doesn't have deps, start with an empty array
if not node.deps then
node.deps = {}
end
-- Prevent duplicate deps
local exists = false
for _, k in ipairs(node.deps) do
if k == dep_node_key then
exists = true
break
end
end
if not exists then
table.insert(node.deps, dep_node_key)
end
end
-- Remove a single dep_node_key from node_key's deps
function DepGraph:removeNodeDep(node_key, dep_node_key)
local node = self:getNode(node_key)
if node.deps then
for idx, dep_key in ipairs(node.deps) do
if dep_key == dep_node_key then
table.remove(node.deps, idx)
break
end
end
end
end
-- Return a list (array) of node keys, ordered by insertion order and dependency.
-- Dependencies come first (and are also ordered by insertion order themselves).
function DepGraph:serialize()
local visited = {}
local ordered_nodes = {}
for _, n in ipairs(self.nodes) do
local node_key = n.key
if not visited[node_key] then
local queue = { node_key }
while #queue > 0 do
local pos = #queue
local curr_node_key = queue[pos]
local curr_node = self:getActiveNode(curr_node_key)
local all_deps_visited = true
if curr_node and curr_node.deps then
for _, dep_node_key in ipairs(curr_node.deps) do
if not visited[dep_node_key] then
-- Only insert to queue for later process if node has dependencies
local dep_node = self:getActiveNode(dep_node_key)
-- Only if it was active!
if dep_node then
if dep_node.deps then
table.insert(queue, dep_node_key)
else
table.insert(ordered_nodes, dep_node_key)
end
end
visited[dep_node_key] = true
all_deps_visited = false
break
end
end
end
if all_deps_visited then
visited[curr_node_key] = true
table.remove(queue, pos)
-- Only if it was active!
if curr_node then
table.insert(ordered_nodes, curr_node_key)
end
end
end
end
end
return ordered_nodes
end
return DepGraph
| agpl-3.0 |
Lsty/ygopro-scripts | c47421985.lua | 7 | 1306 | --ハイドロ・ジェネクス
function c47421985.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsCode,68505803),aux.NonTuner(Card.IsAttribute,ATTRIBUTE_WATER),1)
c:EnableReviveLimit()
--recover
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(47421985,0))
e1:SetCategory(CATEGORY_RECOVER)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCondition(c47421985.reccon)
e1:SetTarget(c47421985.rectg)
e1:SetOperation(c47421985.recop)
c:RegisterEffect(e1)
end
function c47421985.reccon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local t=Duel.GetAttackTarget()
if ev==1 then t=Duel.GetAttacker() end
if not c:IsRelateToBattle() or c:IsFacedown() then return false end
e:SetLabel(t:GetAttack())
return t:GetLocation()==LOCATION_GRAVE and t:IsType(TYPE_MONSTER)
end
function c47421985.rectg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(e:GetLabel())
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,e:GetLabel())
end
function c47421985.recop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
| gpl-2.0 |
Aaa1r/DRAGON | plugins/admin.lua | 41 | 9539 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--Function to add log supergroup
local function logadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id
save_data(_config.moderation.data, data)
local text = 'Log_SuperGroup has has been set!'
reply_msg(msg.id,text,ok_cb,false)
return
end
--Function to remove log supergroup
local function logrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = 'Log_SuperGroup has has been removed!'
reply_msg(msg.id,text,ok_cb,false)
return
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairsByKeys(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
-- 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 reload_plugins( )
plugins = {}
return load_plugins()
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if not is_admin1(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "pmblock" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "pmunblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
if not is_sudo(msg) then-- Sudo only
return
end
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
if not is_sudo(msg) then-- Sudo only
return
end
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent a group dialog list with both json and text format to your private messages"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
if matches[1] == "sync_gbans" then
if not is_sudo(msg) then-- Sudo only
return
end
local url = "http://seedteam.org/Teleseed/Global_bans.json"
local SEED_gbans = http.request(url)
local jdat = json:decode(SEED_gbans)
for k,v in pairs(jdat) do
redis:hset('user:'..v, 'print_name', k)
banall_user(v)
print(k, v.." Globally banned")
end
end
if matches[1] == 'reload' then
receiver = get_receiver(msg)
reload_plugins(true)
post_msg(receiver, "Reloaded!", ok_cb, false)
return "Reloaded!"
end
--[[*For Debug*
if matches[1] == "vardumpmsg" and is_admin1(msg) then
local text = serpent.block(msg, {comment=false})
send_large_msg("channel#id"..msg.to.id, text)
end]]
if matches[1] == 'updateid' then
local data = load_data(_config.moderation.data)
local long_id = data[tostring(msg.to.id)]['long_id']
if not long_id then
data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
return "Updated ID"
end
end
if matches[1] == 'addlog' and not matches[2] then
if is_log_group(msg) then
return "Already a Log_SuperGroup"
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logadd(msg)
end
if matches[1] == 'remlog' and not matches[2] then
if not is_log_group(msg) then
return "Not a Log_SuperGroup"
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") removed")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logrem(msg)
end
return
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/](pm) (%d+) (.*)$",
"^[#!/](import) (.*)$",
"^[#!/](pmunblock) (%d+)$",
"^[#!/](pmblock) (%d+)$",
"^[#!/](markread) (on)$",
"^[#!/](markread) (off)$",
"^[#!/](setbotphoto)$",
"^[#!/](contactlist)$",
"^[#!/](dialoglist)$",
"^[#!/](delcontact) (%d+)$",
"^[#/!](reload)$",
"^[#/!](updateid)$",
"^[#/!](addlog)$",
"^[#/!](remlog)$",
"%[(photo)%]",
},
run = run,
pre_process = pre_process
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/test/plugins/admin.lua
---Modified by @Rondoozle for supergroups
| gpl-2.0 |
ASDF482/TeleTak | plugins/badword.lua | 1 | 2477 |
local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
text = text..'🙋 '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'addword' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'badwords' then
return list_variablesbad(msg)
elseif matches[2] == 'clearbadwords' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'remword' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/])(rw) (.*)$",
"^([!/])(addword) (.*)$",
"^([!/])(remword) (.*)$",
"^([!/])(badwords)$",
"^([!/])(clearbadwords)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
Frenzie/koreader | frontend/document/pdfdocument.lua | 4 | 14289 | local CacheItem = require("cacheitem")
local CanvasContext = require("document/canvascontext")
local DocCache = require("document/doccache")
local DocSettings = require("docsettings")
local Document = require("document/document")
local DrawContext = require("ffi/drawcontext")
local logger = require("logger")
local util = require("util")
local ffi = require("ffi")
local C = ffi.C
local pdf = nil
local PdfDocument = Document:extend{
_document = false,
is_pdf = true,
dc_null = DrawContext.new(),
koptinterface = nil,
provider = "mupdf",
provider_name = "MuPDF",
}
function PdfDocument:init()
if not pdf then pdf = require("ffi/mupdf") end
-- mupdf.color has to stay false for kopt to work correctly
-- and be accurate (including its job about showing highlight
-- boxes). We will turn it on and off in PdfDocument:preRenderPage()
-- and :postRenderPage() when mupdf is called without kopt involved.
pdf.color = false
self:updateColorRendering()
self.koptinterface = require("document/koptinterface")
self.koptinterface:setDefaultConfigurable(self.configurable)
local ok
ok, self._document = pcall(pdf.openDocument, self.file)
if not ok then
error(self._document) -- will contain error message
end
self.is_reflowable = self._document:isDocumentReflowable()
self.reflowable_font_size = self:convertKoptToReflowableFontSize()
-- no-op on PDF
self:layoutDocument()
self.is_open = true
self.info.has_pages = true
self.info.configurable = true
if self._document:needsPassword() then
self.is_locked = true
else
self:_readMetadata()
end
end
function PdfDocument:layoutDocument(font_size)
if font_size then
self.reflowable_font_size = font_size
end
self._document:layoutDocument(
CanvasContext:getWidth(),
CanvasContext:getHeight(),
CanvasContext:scaleBySize(self.reflowable_font_size))
end
local default_font_size = 22
-- the koptreader config goes from 0.1 to 3.0, but we want a regular font size
function PdfDocument:convertKoptToReflowableFontSize(font_size)
if font_size then
return font_size * default_font_size
end
local size
if DocSettings:hasSidecarFile(self.file) then
local doc_settings = DocSettings:open(self.file)
size = doc_settings:readSetting("kopt_font_size")
end
if size then
return size * default_font_size
elseif G_reader_settings:readSetting("kopt_font_size") then
return G_reader_settings:readSetting("kopt_font_size") * default_font_size
elseif G_defaults:readSetting("DKOPTREADER_CONFIG_FONT_SIZE") then
return G_defaults:readSetting("DKOPTREADER_CONFIG_FONT_SIZE") * default_font_size
else
return default_font_size
end
end
function PdfDocument:preRenderPage()
pdf.color = self.render_color
end
function PdfDocument:postRenderPage()
pdf.color = false
end
function PdfDocument:unlock(password)
if not self._document:authenticatePassword(password) then
return false
end
self.is_locked = false
self:_readMetadata()
return true
end
function PdfDocument:comparePositions(pos1, pos2)
return self.koptinterface:comparePositions(self, pos1, pos2)
end
function PdfDocument:getPageTextBoxes(pageno)
local page = self._document:openPage(pageno)
local text = page:getPageText()
page:close()
return text
end
function PdfDocument:getPanelFromPage(pageno, pos)
return self.koptinterface:getPanelFromPage(self, pageno, pos)
end
function PdfDocument:getWordFromPosition(spos)
return self.koptinterface:getWordFromPosition(self, spos)
end
function PdfDocument:getTextFromPositions(spos0, spos1)
return self.koptinterface:getTextFromPositions(self, spos0, spos1)
end
function PdfDocument:getPageBoxesFromPositions(pageno, ppos0, ppos1)
return self.koptinterface:getPageBoxesFromPositions(self, pageno, ppos0, ppos1)
end
function PdfDocument:nativeToPageRectTransform(pageno, rect)
return self.koptinterface:nativeToPageRectTransform(self, pageno, rect)
end
function PdfDocument:getSelectedWordContext(word, nb_words, pos)
return self.koptinterface:getSelectedWordContext(word, nb_words, pos)
end
function PdfDocument:getOCRWord(pageno, wbox)
return self.koptinterface:getOCRWord(self, pageno, wbox)
end
function PdfDocument:getOCRText(pageno, tboxes)
return self.koptinterface:getOCRText(self, pageno, tboxes)
end
function PdfDocument:getPageBlock(pageno, x, y)
return self.koptinterface:getPageBlock(self, pageno, x, y)
end
function PdfDocument:getUsedBBox(pageno)
local hash = "pgubbox|"..self.file.."|"..self.reflowable_font_size.."|"..pageno
local cached = DocCache:check(hash)
if cached then
return cached.ubbox
end
local page = self._document:openPage(pageno)
local used = {}
used.x0, used.y0, used.x1, used.y1 = page:getUsedBBox()
local pwidth, pheight = page:getSize(self.dc_null)
-- clamp to page BBox
if used.x0 < 0 then used.x0 = 0 end
if used.x1 > pwidth then used.x1 = pwidth end
if used.y0 < 0 then used.y0 = 0 end
if used.y1 > pheight then used.y1 = pheight end
DocCache:insert(hash, CacheItem:new{
ubbox = used,
size = 256, -- might be closer to 160
})
page:close()
return used
end
function PdfDocument:getPageLinks(pageno)
local hash = "pglinks|"..self.file.."|"..self.reflowable_font_size.."|"..pageno
local cached = DocCache:check(hash)
if cached then
return cached.links
end
local page = self._document:openPage(pageno)
local links = page:getPageLinks()
DocCache:insert(hash, CacheItem:new{
links = links,
size = 64 + (8 * 32 * #links),
})
page:close()
return links
end
-- returns nil if file is not a pdf, true if document is a writable pdf, false else
function PdfDocument:_checkIfWritable()
local suffix = util.getFileNameSuffix(self.file)
if string.lower(suffix) ~= "pdf" then return nil end
if self.is_writable == nil then
local handle = io.open(self.file, 'r+b')
self.is_writable = handle ~= nil
if handle then handle:close() end
end
return self.is_writable
end
local function _quadpointsFromPboxes(pboxes)
-- will also need mupdf_h.lua to be evaluated once
-- but this is guaranteed at this point
local n = #pboxes
local quadpoints = ffi.new("float[?]", 8*n)
for i=1, n do
-- The order must be left bottom, right bottom, left top, right top.
-- https://bugs.ghostscript.com/show_bug.cgi?id=695130
quadpoints[8*i-8] = pboxes[i].x
quadpoints[8*i-7] = pboxes[i].y + pboxes[i].h
quadpoints[8*i-6] = pboxes[i].x + pboxes[i].w
quadpoints[8*i-5] = pboxes[i].y + pboxes[i].h
quadpoints[8*i-4] = pboxes[i].x
quadpoints[8*i-3] = pboxes[i].y
quadpoints[8*i-2] = pboxes[i].x + pboxes[i].w
quadpoints[8*i-1] = pboxes[i].y
end
return quadpoints, n
end
local function _quadpointsToPboxes(quadpoints, n)
-- reverse of previous function
local pboxes = {}
for i=1, n do
table.insert(pboxes, {
x = quadpoints[8*i-4],
y = quadpoints[8*i-3],
w = quadpoints[8*i-6] - quadpoints[8*i-4],
h = quadpoints[8*i-5] - quadpoints[8*i-3],
})
end
return pboxes
end
function PdfDocument:saveHighlight(pageno, item)
local can_write = self:_checkIfWritable()
if can_write ~= true then return can_write end
self.is_edited = true
local quadpoints, n = _quadpointsFromPboxes(item.pboxes)
local page = self._document:openPage(pageno)
local annot_type = C.PDF_ANNOT_HIGHLIGHT
if item.drawer == "lighten" then
annot_type = C.PDF_ANNOT_HIGHLIGHT
elseif item.drawer == "underscore" then
annot_type = C.PDF_ANNOT_UNDERLINE
elseif item.drawer == "strikeout" then
annot_type = C.PDF_ANNOT_STRIKE_OUT
end
page:addMarkupAnnotation(quadpoints, n, annot_type) -- may update/adjust quadpoints
-- Update pboxes with the possibly adjusted coordinates (this will have it updated
-- in self.view.highlight.saved[page])
item.pboxes = _quadpointsToPboxes(quadpoints, n)
page:close()
self:resetTileCacheValidity()
end
function PdfDocument:deleteHighlight(pageno, item)
local can_write = self:_checkIfWritable()
if can_write ~= true then return can_write end
self.is_edited = true
local quadpoints, n = _quadpointsFromPboxes(item.pboxes)
local page = self._document:openPage(pageno)
local annot = page:getMarkupAnnotation(quadpoints, n)
if annot ~= nil then
page:deleteMarkupAnnotation(annot)
self:resetTileCacheValidity()
end
page:close()
end
function PdfDocument:updateHighlightContents(pageno, item, contents)
local can_write = self:_checkIfWritable()
if can_write ~= true then return can_write end
self.is_edited = true
local quadpoints, n = _quadpointsFromPboxes(item.pboxes)
local page = self._document:openPage(pageno)
local annot = page:getMarkupAnnotation(quadpoints, n)
if annot ~= nil then
page:updateMarkupAnnotation(annot, contents)
self:resetTileCacheValidity()
end
page:close()
end
function PdfDocument:writeDocument()
logger.info("writing document to", self.file)
self._document:writeDocument(self.file)
end
function PdfDocument:close()
-- NOTE: We can't just rely on Document:close's return code for that, as we need self._document
-- in :writeDocument, and it would have been destroyed.
local DocumentRegistry = require("document/documentregistry")
if DocumentRegistry:getReferenceCount(self.file) == 1 then
-- We're the final reference to this Document instance.
if self.is_edited then
self:writeDocument()
end
end
Document.close(self)
end
function PdfDocument:getProps()
local props = self._document:getMetadata()
if props.title == "" then
local startPos = util.lastIndexOf(self.file, "%/")
if startPos > 0 then
props.title = string.sub(self.file, startPos + 1, -5) --remove extension .pdf
else
props.title = string.sub(self.file, 0, -5)
end
end
props.authors = props.author
props.series = ""
props.language = ""
props.keywords = props.keywords
props.description = props.subject
return props
end
function PdfDocument:getLinkFromPosition(pageno, pos)
return self.koptinterface:getLinkFromPosition(self, pageno, pos)
end
function PdfDocument:clipPagePNGFile(pos0, pos1, pboxes, drawer, filename)
return self.koptinterface:clipPagePNGFile(self, pos0, pos1, pboxes, drawer, filename)
end
function PdfDocument:clipPagePNGString(pos0, pos1, pboxes, drawer)
return self.koptinterface:clipPagePNGString(self, pos0, pos1, pboxes, drawer)
end
function PdfDocument:getPageBBox(pageno)
return self.koptinterface:getPageBBox(self, pageno)
end
function PdfDocument:getPageDimensions(pageno, zoom, rotation)
return self.koptinterface:getPageDimensions(self, pageno, zoom, rotation)
end
function PdfDocument:getCoverPageImage()
return self.koptinterface:getCoverPageImage(self)
end
function PdfDocument:findText(pattern, origin, reverse, caseInsensitive, page)
return self.koptinterface:findText(self, pattern, origin, reverse, caseInsensitive, page)
end
function PdfDocument:renderPage(pageno, rect, zoom, rotation, gamma, render_mode, hinting)
return self.koptinterface:renderPage(self, pageno, rect, zoom, rotation, gamma, render_mode, hinting)
end
function PdfDocument:hintPage(pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:hintPage(self, pageno, zoom, rotation, gamma, render_mode)
end
function PdfDocument:drawPage(target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:drawPage(self, target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
end
function PdfDocument:register(registry)
--- Document types ---
registry:addProvider("cbt", "application/vnd.comicbook+tar", self, 100)
registry:addProvider("cbz", "application/vnd.comicbook+zip", self, 100)
registry:addProvider("cbz", "application/x-cbz", self, 100) -- Alternative mimetype for OPDS.
registry:addProvider("epub", "application/epub+zip", self, 50)
registry:addProvider("epub3", "application/epub+zip", self, 50)
registry:addProvider("fb2", "application/fb2", self, 80)
registry:addProvider("htm", "text/html", self, 90)
registry:addProvider("html", "text/html", self, 90)
registry:addProvider("pdf", "application/pdf", self, 100)
registry:addProvider("tar", "application/x-tar", self, 10)
registry:addProvider("xhtml", "application/xhtml+xml", self, 90)
registry:addProvider("xml", "application/xml", self, 10)
registry:addProvider("xps", "application/oxps", self, 100)
registry:addProvider("zip", "application/zip", self, 20)
--- Picture types ---
registry:addProvider("gif", "image/gif", self, 90)
-- MS HD Photo == JPEG XR
registry:addProvider("hdp", "image/vnd.ms-photo", self, 90)
registry:addProvider("j2k", "image/jp2", self, 90)
registry:addProvider("jp2", "image/jp2", self, 90)
registry:addProvider("jpeg", "image/jpeg", self, 90)
registry:addProvider("jpg", "image/jpeg", self, 90)
-- JPEG XR
registry:addProvider("jxr", "image/jxr", self, 90)
registry:addProvider("pam", "image/x-portable-arbitrarymap", self, 90)
registry:addProvider("pbm", "image/x‑portable‑bitmap", self, 90)
registry:addProvider("pgm", "image/x‑portable‑bitmap", self, 90)
registry:addProvider("png", "image/png", self, 90)
registry:addProvider("pnm", "image/x‑portable‑bitmap", self, 90)
registry:addProvider("ppm", "image/x‑portable‑bitmap", self, 90)
registry:addProvider("svg", "image/svg+xml", self, 80)
registry:addProvider("tif", "image/tiff", self, 90)
registry:addProvider("tiff", "image/tiff", self, 90)
-- Windows Media Photo == JPEG XR
registry:addProvider("wdp", "image/vnd.ms-photo", self, 90)
end
return PdfDocument
| agpl-3.0 |
Lsty/ygopro-scripts | c95956346.lua | 7 | 1314 | --シャインエンジェル
function c95956346.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(95956346,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c95956346.condition)
e1:SetTarget(c95956346.target)
e1:SetOperation(c95956346.operation)
c:RegisterEffect(e1)
end
function c95956346.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE)
end
function c95956346.filter(c,e,tp)
return c:IsAttackBelow(1500) and c:IsAttribute(ATTRIBUTE_LIGHT)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c95956346.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c95956346.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c95956346.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c95956346.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_ATTACK)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c94484482.lua | 3 | 1970 | --スリップ・サモン
function c94484482.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c94484482.condition)
e1:SetTarget(c94484482.target)
e1:SetOperation(c94484482.activate)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c94484482.condition2)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e3)
end
function c94484482.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c94484482.cfilter(c,tp)
return c:GetSummonPlayer()==1-tp
end
function c94484482.condition2(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c94484482.cfilter,1,nil,tp)
end
function c94484482.spfilter(c,e,tp)
return c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c94484482.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c94484482.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c94484482.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c94484482.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_DEFENCE)~=0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetOperation(c94484482.retop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
function c94484482.retop(e,tp,eg,ep,ev,re,r,rp)
Duel.SendtoHand(e:GetHandler(),nil,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c86997073.lua | 3 | 1311 | --機動要塞フォルテシモ
function c86997073.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(86997073,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetTarget(c86997073.target)
e1:SetOperation(c86997073.operation)
c:RegisterEffect(e1)
end
function c86997073.filter(c,e,sp)
return c:IsSetCard(0x6013) and c:IsCanBeSpecialSummoned(e,0,sp,false,false)
end
function c86997073.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c86997073.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c86997073.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c86997073.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
MahmoudDolah/Firmware-Entry-Points-In-Memory | openwrt/openwrt-generic-x86/usr/lib/lua/luci/tools/firewall.lua | 63 | 5812 | -- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.firewall", package.seeall)
local ut = require "luci.util"
local ip = require "luci.ip"
local nx = require "nixio"
local translate, translatef = luci.i18n.translate, luci.i18n.translatef
local function tr(...)
return tostring(translate(...))
end
function fmt_neg(x)
if type(x) == "string" then
local v, neg = x:gsub("^ *! *", "")
if neg > 0 then
return v, "%s " % tr("not")
else
return x, ""
end
end
return x, ""
end
function fmt_mac(x)
if x and #x > 0 then
local m, n
local l = { tr("MAC"), " " }
for m in ut.imatch(x) do
m, n = fmt_neg(m)
l[#l+1] = "<var>%s%s</var>" %{ n, m }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("MACs")
end
return table.concat(l, "")
end
end
end
function fmt_port(x, d)
if x and #x > 0 then
local p, n
local l = { tr("port"), " " }
for p in ut.imatch(x) do
p, n = fmt_neg(p)
local a, b = p:match("(%d+)%D+(%d+)")
if a and b then
l[1] = tr("ports")
l[#l+1] = "<var>%s%d-%d</var>" %{ n, a, b }
else
l[#l+1] = "<var>%s%d</var>" %{ n, p }
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("ports")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_ip(x, d)
if x and #x > 0 then
local l = { tr("IP"), " " }
local v, a, n
for v in ut.imatch(x) do
v, n = fmt_neg(v)
a, m = v:match("(%S+)/(%d+%.%S+)")
a = a or v
a = a:match(":") and ip.IPv6(a, m) or ip.IPv4(a, m)
if a and (a:is6() and a:prefix() < 128 or a:prefix() < 32) then
l[1] = tr("IP range")
l[#l+1] = "<var title='%s - %s'>%s%s</var>" %{
a:minhost():string(),
a:maxhost():string(),
n, a:string()
}
else
l[#l+1] = "<var>%s%s</var>" %{
n,
a and a:string() or v
}
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("IPs")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_zone(x, d)
if x == "*" then
return "<var>%s</var>" % tr("any zone")
elseif x and #x > 0 then
return "<var>%s</var>" % x
elseif d then
return "<var>%s</var>" % d
end
end
function fmt_icmp_type(x)
if x and #x > 0 then
local t, v, n
local l = { tr("type"), " " }
for v in ut.imatch(x) do
v, n = fmt_neg(v)
l[#l+1] = "<var>%s%s</var>" %{ n, v }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("types")
end
return table.concat(l, "")
end
end
end
function fmt_proto(x, icmp_types)
if x and #x > 0 then
local v, n
local l = { }
local t = fmt_icmp_type(icmp_types)
for v in ut.imatch(x) do
v, n = fmt_neg(v)
if v == "tcpudp" then
l[#l+1] = "TCP"
l[#l+1] = ", "
l[#l+1] = "UDP"
l[#l+1] = ", "
elseif v ~= "all" then
local p = nx.getproto(v)
if p then
-- ICMP
if (p.proto == 1 or p.proto == 58) and t then
l[#l+1] = translatef(
"%s%s with %s",
n, p.aliases[1] or p.name, t
)
else
l[#l+1] = "%s%s" %{
n,
p.aliases[1] or p.name
}
end
l[#l+1] = ", "
end
end
end
if #l > 0 then
l[#l] = nil
return table.concat(l, "")
end
end
end
function fmt_limit(limit, burst)
burst = tonumber(burst)
if limit and #limit > 0 then
local l, u = limit:match("(%d+)/(%w+)")
l = tonumber(l or limit)
u = u or "second"
if l then
if u:match("^s") then
u = tr("second")
elseif u:match("^m") then
u = tr("minute")
elseif u:match("^h") then
u = tr("hour")
elseif u:match("^d") then
u = tr("day")
end
if burst and burst > 0 then
return translatef("<var>%d</var> pkts. per <var>%s</var>, \
burst <var>%d</var> pkts.", l, u, burst)
else
return translatef("<var>%d</var> pkts. per <var>%s</var>", l, u)
end
end
end
end
function fmt_target(x, dest)
if dest and #dest > 0 then
if x == "ACCEPT" then
return tr("Accept forward")
elseif x == "REJECT" then
return tr("Refuse forward")
elseif x == "NOTRACK" then
return tr("Do not track forward")
else --if x == "DROP" then
return tr("Discard forward")
end
else
if x == "ACCEPT" then
return tr("Accept input")
elseif x == "REJECT" then
return tr("Refuse input")
elseif x == "NOTRACK" then
return tr("Do not track input")
else --if x == "DROP" then
return tr("Discard input")
end
end
end
function opt_enabled(s, t, ...)
if t == luci.cbi.Button then
local o = s:option(t, "__enabled")
function o.render(self, section)
if self.map:get(section, "enabled") ~= "0" then
self.title = tr("Rule is enabled")
self.inputtitle = tr("Disable")
self.inputstyle = "reset"
else
self.title = tr("Rule is disabled")
self.inputtitle = tr("Enable")
self.inputstyle = "apply"
end
t.render(self, section)
end
function o.write(self, section, value)
if self.map:get(section, "enabled") ~= "0" then
self.map:set(section, "enabled", "0")
else
self.map:del(section, "enabled")
end
end
return o
else
local o = s:option(t, "enabled", ...)
o.default = "1"
return o
end
end
function opt_name(s, t, ...)
local o = s:option(t, "name", ...)
function o.cfgvalue(self, section)
return self.map:get(section, "name") or
self.map:get(section, "_name") or "-"
end
function o.write(self, section, value)
if value ~= "-" then
self.map:set(section, "name", value)
self.map:del(section, "_name")
else
self:remove(section)
end
end
function o.remove(self, section)
self.map:del(section, "name")
self.map:del(section, "_name")
end
return o
end
| apache-2.0 |
maxrio/luci981213 | applications/luci-app-firewall/luasrc/tools/firewall.lua | 63 | 5812 | -- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.firewall", package.seeall)
local ut = require "luci.util"
local ip = require "luci.ip"
local nx = require "nixio"
local translate, translatef = luci.i18n.translate, luci.i18n.translatef
local function tr(...)
return tostring(translate(...))
end
function fmt_neg(x)
if type(x) == "string" then
local v, neg = x:gsub("^ *! *", "")
if neg > 0 then
return v, "%s " % tr("not")
else
return x, ""
end
end
return x, ""
end
function fmt_mac(x)
if x and #x > 0 then
local m, n
local l = { tr("MAC"), " " }
for m in ut.imatch(x) do
m, n = fmt_neg(m)
l[#l+1] = "<var>%s%s</var>" %{ n, m }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("MACs")
end
return table.concat(l, "")
end
end
end
function fmt_port(x, d)
if x and #x > 0 then
local p, n
local l = { tr("port"), " " }
for p in ut.imatch(x) do
p, n = fmt_neg(p)
local a, b = p:match("(%d+)%D+(%d+)")
if a and b then
l[1] = tr("ports")
l[#l+1] = "<var>%s%d-%d</var>" %{ n, a, b }
else
l[#l+1] = "<var>%s%d</var>" %{ n, p }
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("ports")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_ip(x, d)
if x and #x > 0 then
local l = { tr("IP"), " " }
local v, a, n
for v in ut.imatch(x) do
v, n = fmt_neg(v)
a, m = v:match("(%S+)/(%d+%.%S+)")
a = a or v
a = a:match(":") and ip.IPv6(a, m) or ip.IPv4(a, m)
if a and (a:is6() and a:prefix() < 128 or a:prefix() < 32) then
l[1] = tr("IP range")
l[#l+1] = "<var title='%s - %s'>%s%s</var>" %{
a:minhost():string(),
a:maxhost():string(),
n, a:string()
}
else
l[#l+1] = "<var>%s%s</var>" %{
n,
a and a:string() or v
}
end
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("IPs")
end
return table.concat(l, "")
end
end
return d and "<var>%s</var>" % d
end
function fmt_zone(x, d)
if x == "*" then
return "<var>%s</var>" % tr("any zone")
elseif x and #x > 0 then
return "<var>%s</var>" % x
elseif d then
return "<var>%s</var>" % d
end
end
function fmt_icmp_type(x)
if x and #x > 0 then
local t, v, n
local l = { tr("type"), " " }
for v in ut.imatch(x) do
v, n = fmt_neg(v)
l[#l+1] = "<var>%s%s</var>" %{ n, v }
l[#l+1] = ", "
end
if #l > 1 then
l[#l] = nil
if #l > 3 then
l[1] = tr("types")
end
return table.concat(l, "")
end
end
end
function fmt_proto(x, icmp_types)
if x and #x > 0 then
local v, n
local l = { }
local t = fmt_icmp_type(icmp_types)
for v in ut.imatch(x) do
v, n = fmt_neg(v)
if v == "tcpudp" then
l[#l+1] = "TCP"
l[#l+1] = ", "
l[#l+1] = "UDP"
l[#l+1] = ", "
elseif v ~= "all" then
local p = nx.getproto(v)
if p then
-- ICMP
if (p.proto == 1 or p.proto == 58) and t then
l[#l+1] = translatef(
"%s%s with %s",
n, p.aliases[1] or p.name, t
)
else
l[#l+1] = "%s%s" %{
n,
p.aliases[1] or p.name
}
end
l[#l+1] = ", "
end
end
end
if #l > 0 then
l[#l] = nil
return table.concat(l, "")
end
end
end
function fmt_limit(limit, burst)
burst = tonumber(burst)
if limit and #limit > 0 then
local l, u = limit:match("(%d+)/(%w+)")
l = tonumber(l or limit)
u = u or "second"
if l then
if u:match("^s") then
u = tr("second")
elseif u:match("^m") then
u = tr("minute")
elseif u:match("^h") then
u = tr("hour")
elseif u:match("^d") then
u = tr("day")
end
if burst and burst > 0 then
return translatef("<var>%d</var> pkts. per <var>%s</var>, \
burst <var>%d</var> pkts.", l, u, burst)
else
return translatef("<var>%d</var> pkts. per <var>%s</var>", l, u)
end
end
end
end
function fmt_target(x, dest)
if dest and #dest > 0 then
if x == "ACCEPT" then
return tr("Accept forward")
elseif x == "REJECT" then
return tr("Refuse forward")
elseif x == "NOTRACK" then
return tr("Do not track forward")
else --if x == "DROP" then
return tr("Discard forward")
end
else
if x == "ACCEPT" then
return tr("Accept input")
elseif x == "REJECT" then
return tr("Refuse input")
elseif x == "NOTRACK" then
return tr("Do not track input")
else --if x == "DROP" then
return tr("Discard input")
end
end
end
function opt_enabled(s, t, ...)
if t == luci.cbi.Button then
local o = s:option(t, "__enabled")
function o.render(self, section)
if self.map:get(section, "enabled") ~= "0" then
self.title = tr("Rule is enabled")
self.inputtitle = tr("Disable")
self.inputstyle = "reset"
else
self.title = tr("Rule is disabled")
self.inputtitle = tr("Enable")
self.inputstyle = "apply"
end
t.render(self, section)
end
function o.write(self, section, value)
if self.map:get(section, "enabled") ~= "0" then
self.map:set(section, "enabled", "0")
else
self.map:del(section, "enabled")
end
end
return o
else
local o = s:option(t, "enabled", ...)
o.default = "1"
return o
end
end
function opt_name(s, t, ...)
local o = s:option(t, "name", ...)
function o.cfgvalue(self, section)
return self.map:get(section, "name") or
self.map:get(section, "_name") or "-"
end
function o.write(self, section, value)
if value ~= "-" then
self.map:set(section, "name", value)
self.map:del(section, "_name")
else
self:remove(section)
end
end
function o.remove(self, section)
self.map:del(section, "name")
self.map:del(section, "_name")
end
return o
end
| apache-2.0 |
Distrotech/vlc | share/lua/playlist/break.lua | 113 | 1995 | --[[
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and ( string.match( vlc.path, "^break.com" )
or string.match( vlc.path, "^www.break.com" ) )
end
-- Parse function.
function parse()
filepath = ""
filename = ""
filetitle = ""
arturl = ""
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "sGlobalContentFilePath=" ) then
_,_,filepath= string.find( line, "sGlobalContentFilePath='(.-)'" )
end
if string.match( line, "sGlobalFileName=" ) then
_,_,filename = string.find( line, ".*sGlobalFileName='(.-)'")
end
if string.match( line, "sGlobalContentTitle=" ) then
_,_,filetitle = string.find( line, "sGlobalContentTitle='(.-)'")
end
if string.match( line, "el=\"videothumbnail\" href=\"" ) then
_,_,arturl = string.find( line, "el=\"videothumbnail\" href=\"(.-)\"" )
end
if string.match( line, "videoPath" ) then
_,_,videopath = string.find( line, ".*videoPath', '(.-)'" )
return { { path = videopath..filepath.."/"..filename..".flv"; title = filetitle; arturl = arturl } }
end
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Garlaige_Citadel/npcs/Mashira.lua | 9 | 1703 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: Mashira
-- Involved in Quests: Rubbish day, Making Amens!
-- !pos 141 -6 138 200
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
local ID = require("scripts/zones/Garlaige_Citadel/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.RUBBISH_DAY) == QUEST_ACCEPTED and player:getCharVar("RubbishDayVar") == 0) then
player:startEvent(11,1); -- For the quest "Rubbish day"
elseif (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_AMENS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(dsp.ki.BROKEN_WAND) == true) then
player:startEvent(11,3);
else player:startEvent(11,0); -- Making Amens dialogue
end
else
player:startEvent(11,3); -- Standard dialog and menu
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
RubbishDay = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.RUBBISH_DAY);
MakingAmens = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_AMENS);
if (csid == 11 and option == 1 and RubbishDay == QUEST_ACCEPTED) then
player:delKeyItem(dsp.ki.MAGIC_TRASH);
player:setCharVar("RubbishDayVar",1);
elseif (csid == 11 and option == 0 and MakingAmens == QUEST_ACCEPTED) then
player:addKeyItem(dsp.ki.BROKEN_WAND); --Broken Wand
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.BROKEN_WAND);
player:tradeComplete();
end
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c84243274.lua | 3 | 3957 | --VWXYZ-ドラゴン・カタパルトキャノン
function c84243274.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCode2(c,58859575,91998119,true,true)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c84243274.splimit)
c:RegisterEffect(e1)
--special summon rule
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPSUMMON_PROC)
e2:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e2:SetRange(LOCATION_EXTRA)
e2:SetCondition(c84243274.spcon)
e2:SetOperation(c84243274.spop)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(84243274,0))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetTarget(c84243274.rmtg)
e3:SetOperation(c84243274.rmop)
c:RegisterEffect(e3)
--poschange
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(84243274,1))
e4:SetCategory(CATEGORY_POSITION)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_ATTACK_ANNOUNCE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetTarget(c84243274.postg)
e4:SetOperation(c84243274.posop)
c:RegisterEffect(e4)
end
function c84243274.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA)
end
function c84243274.spfilter(c,code)
return c:IsCode(code) and c:IsAbleToRemoveAsCost()
end
function c84243274.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<-1 then return false end
local g1=Duel.GetMatchingGroup(c84243274.spfilter,tp,LOCATION_ONFIELD,0,nil,58859575)
local g2=Duel.GetMatchingGroup(c84243274.spfilter,tp,LOCATION_ONFIELD,0,nil,91998119)
if g1:GetCount()==0 or g2:GetCount()==0 then return false end
if ft>0 then return true end
local f1=g1:FilterCount(Card.IsLocation,nil,LOCATION_MZONE)
local f2=g2:FilterCount(Card.IsLocation,nil,LOCATION_MZONE)
if ft==-1 then return f1>0 and f2>0
else return f1>0 or f2>0 end
end
function c84243274.spop(e,tp,eg,ep,ev,re,r,rp,c)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local g1=Duel.GetMatchingGroup(c84243274.spfilter,tp,LOCATION_ONFIELD,0,nil,58859575)
local g2=Duel.GetMatchingGroup(c84243274.spfilter,tp,LOCATION_ONFIELD,0,nil,91998119)
g1:Merge(g2)
local g=Group.CreateGroup()
local tc=nil
for i=1,2 do
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
if ft<=0 then
tc=g1:FilterSelect(tp,Card.IsLocation,1,1,nil,LOCATION_MZONE):GetFirst()
else
tc=g1:Select(tp,1,1,nil):GetFirst()
end
g:AddCard(tc)
g1:Remove(Card.IsCode,nil,tc:GetCode())
ft=ft+1
end
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c84243274.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsAbleToRemove() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
end
function c84243274.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c84243274.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
local bc=Duel.GetAttackTarget()
if chk==0 then return bc and bc:IsCanBeEffectTarget(e) end
Duel.SetTargetCard(bc)
Duel.SetOperationInfo(0,CATEGORY_POSITION,bc,1,0,0)
end
function c84243274.posop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.ChangePosition(tc,POS_FACEUP_DEFENCE,POS_FACEDOWN_DEFENCE,POS_FACEUP_ATTACK,POS_FACEUP_ATTACK,true)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c91754175.lua | 2 | 1471 | --犬タウルス
function c91754175.initial_effect(c)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(91754175,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetCountLimit(1)
e1:SetCondition(c91754175.condition)
e1:SetTarget(c91754175.target)
e1:SetOperation(c91754175.operation)
c:RegisterEffect(e1)
end
function c91754175.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttackTarget()~=nil
end
function c91754175.tgfilter(c)
return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToGrave()
end
function c91754175.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c91754175.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil)
local c=e:GetHandler()
local tc=g:GetFirst()
if tc and Duel.SendtoGrave(tc,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_GRAVE)
and c:IsRelateToBattle() and c:IsFaceup() then
local lv=tc:GetLevel()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(lv*100)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c17375316.lua | 9 | 1061 | --押収
function c17375316.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c17375316.cost)
e1:SetTarget(c17375316.target)
e1:SetOperation(c17375316.activate)
c:RegisterEffect(e1)
end
function c17375316.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c17375316.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
Duel.SetTargetPlayer(tp)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,1)
end
function c17375316.activate(e,tp,eg,ep,ev,re,r,rp)
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
local g=Duel.GetFieldGroup(p,0,LOCATION_HAND)
if g:GetCount()>0 then
Duel.ConfirmCards(p,g)
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_DISCARD)
local sg=g:Select(p,1,1,nil)
Duel.SendtoGrave(sg,REASON_EFFECT+REASON_DISCARD)
Duel.ShuffleHand(1-p)
end
end
| gpl-2.0 |
tryroach/vlc | share/lua/sd/frenchtv.lua | 111 | 1356 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { title="French TV" }
end
function main()
node = vlc.sd.add_node( {title="Canal +"} )
node:add_subitem( {title="Le SAV des émissions ",path="http://www.canalplus.fr/index.php?pid=1782",options={"http-forward-cookies"}} )
node:add_subitem( {title="Les Guignols",path="http://www.canalplus.fr/index.php?pid=1784",options={"http-forward-cookies"}} )
node:add_subitem( {title="La Météo de Pauline Lefevre",path="http://www.canalplus.fr/index.php?pid=2834",options={"http-forward-cookies"}} )
end
| gpl-2.0 |
Mike325/.vim | lua/neovim/autocmds.lua | 1 | 2767 | local api = vim.api
local M = {
funcs = {
g = {},
b = {},
},
}
function M.create_autogrp(autogrp)
api.nvim_command('augroup ' .. autogrp .. ' | autocmd! | autogrp end')
end
function M.get_autocmd(autocmd)
vim.validate { autocmd = { autocmd, 'table' } }
if not autocmd.event and not autocmd.group then
vim.notify(
'Missing arguments!! get_autocmd need event or group attribbute',
'ERROR',
{ title = 'Nvim Autocmd' }
)
return false
end
local autocmd_str = { 'autocmd' }
autocmd_str[#autocmd_str + 1] = autocmd.group ~= nil and autocmd.group or nil
autocmd_str[#autocmd_str + 1] = autocmd.event ~= nil and autocmd.event or nil
local ok, _ = pcall(api.nvim_exec, table.concat(autocmd_str, ' '), true)
if not ok then
return nil
end
return true
-- TODO: Work in parse autocmd output
end
function M.has_autocmd(autocmd)
return M.get_autocmd(autocmd) ~= nil
end
function M.set_autocmd(autocmd)
vim.validate { autocmd = { autocmd, 'table' } }
if not autocmd.event then
vim.notify(
'Missing arguments!! set_autocmd need event attribbute',
'ERROR',
{ title = 'Nvim Autocmd' }
)
return false
end
local autocmd_str = { 'autocmd' }
local once = autocmd.once ~= nil and '++once' or nil
local nested = autocmd.nested ~= nil and '++nested' or nil
local cmd = autocmd.cmd ~= nil and autocmd.cmd or nil
local event = autocmd.event ~= nil and autocmd.event or nil
local group = autocmd.group ~= nil and autocmd.group or nil
local clean = autocmd.clean ~= nil and autocmd.clean or nil
local pattern = autocmd.pattern ~= nil and autocmd.pattern or nil
if group ~= nil then
autocmd_str[#autocmd_str + 1] = group
end
if event ~= nil then
if type(event) == 'table' then
event = table.concat(event, ',')
end
autocmd_str[#autocmd_str + 1] = event
end
if pattern ~= nil then
if type(pattern) == 'table' then
pattern = table.concat(pattern, ',')
end
autocmd_str[#autocmd_str + 1] = pattern
end
if once ~= nil then
autocmd_str[#autocmd_str + 1] = once
end
if nested ~= nil then
autocmd_str[#autocmd_str + 1] = nested
end
if cmd == nil then
autocmd_str[1] = 'autocmd!'
else
autocmd_str[#autocmd_str + 1] = cmd
end
if clean ~= nil and group ~= nil then
M.create_autogrp(group)
elseif group ~= nil and not M.has_autocmd { group = group } then
M.create_autogrp(group)
end
api.nvim_command(table.concat(autocmd_str, ' '))
end
return M
| mit |
ThingMesh/openwrt-luci | libs/lucid-http/luasrc/lucid/http/LuciWebPublisher.lua | 52 | 1651 | --[[
LuCId HTTP-Slave
(c) 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ipairs, pcall, type = ipairs, pcall, type
local luci = require "luci.lucid.http.handler.luci"
local srv = require "luci.lucid.http.server"
module "luci.lucid.http.LuciWebPublisher"
--- Prepare a LuCI web publisher and assign it to a given Virtual Host.
-- @param server HTTP daemon object
-- @param config publisher configuration
function factory(server, config)
pcall(function()
require "luci.dispatcher"
require "luci.cbi"
end)
config.domain = config.domain or ""
local vhost = server:get_vhosts()[config.domain]
if not vhost then
vhost = srv.VHost()
server:set_vhost(config.domain, vhost)
end
local prefix
if config.physical and #config.physical > 0 then
prefix = {}
for k in config.physical:gmatch("[^/]+") do
if #k > 0 then
prefix[#prefix+1] = k
end
end
end
local handler = luci.Luci(config.name, prefix)
if config.exec then
for _, r in ipairs(config.exec) do
if r:sub(1,1) == ":" then
handler:restrict({interface = r:sub(2)})
else
handler:restrict({user = r})
end
end
end
local mypath
if type(config.virtual) == "table" then
for _, v in ipairs(config.virtual) do
mypath = mypath or v
vhost:set_handler(v, handler)
end
else
mypath = config.virtual
vhost:set_handler(config.virtual or "", handler)
end
if config.home then
vhost.default = mypath
end
end
| apache-2.0 |
Lsty/ygopro-scripts | c126218.lua | 3 | 1247 | --悪魔のサイコロ
function c126218.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c126218.condition)
e1:SetTarget(c126218.target)
e1:SetOperation(c126218.activate)
c:RegisterEffect(e1)
end
function c126218.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c126218.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
end
function c126218.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
if g:GetCount()>0 then
local d=Duel.TossDice(tp,1)*100
local sc=g:GetFirst()
while sc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
e1:SetValue(-d)
sc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENCE)
sc:RegisterEffect(e2)
sc=g:GetNext()
end
end
end | gpl-2.0 |
Lsty/ygopro-scripts | c81919143.lua | 3 | 1901 | --ブレイン・クラッシャー
function c81919143.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81919143,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c81919143.spcon)
e1:SetTarget(c81919143.sptg)
e1:SetOperation(c81919143.spop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_BATTLE_DESTROYING)
e2:SetOperation(c81919143.regop)
c:RegisterEffect(e2)
end
function c81919143.regop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RegisterFlagEffect(81919143,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c81919143.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(81919143)~=0
end
function c81919143.filter(c,e,tp,rc,tid)
return c:IsReason(REASON_BATTLE) and c:GetReasonCard()==rc and c:GetTurnID()==tid
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c81919143.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c81919143.filter(chkc,e,tp,e:GetHandler(),Duel.GetTurnCount()) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c81919143.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp,e:GetHandler(),Duel.GetTurnCount()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c81919143.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp,e:GetHandler(),Duel.GetTurnCount())
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0)
end
function c81919143.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c73289035.lua | 3 | 3101 | --武神帝-ツクヨミ
function c73289035.initial_effect(c)
c:SetUniqueOnField(1,0,73289035)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_LIGHT),4,2)
c:EnableReviveLimit()
--draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73289035,0))
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c73289035.cost)
e1:SetTarget(c73289035.target)
e1:SetOperation(c73289035.operation)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCondition(c73289035.spcon)
e2:SetTarget(c73289035.sptg)
e2:SetOperation(c73289035.spop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_REMOVE)
c:RegisterEffect(e3)
local e4=e2:Clone()
e4:SetCode(EVENT_TO_DECK)
c:RegisterEffect(e4)
end
function c73289035.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c73289035.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2) and Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>0 end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,0,LOCATION_HAND)
end
function c73289035.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
Duel.Draw(tp,2,REASON_EFFECT)
end
end
function c73289035.spcon(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetHandler():GetOverlayCount()
e:SetLabel(ct)
return rp~=tp and bit.band(r,REASON_EFFECT)~=0 and ct>0
and e:GetHandler():IsPreviousPosition(POS_FACEUP) and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c73289035.spfilter(c,e,tp)
return c:GetLevel()==4 and c:IsSetCard(0x88) and c:IsRace(RACE_BEASTWARRIOR) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c73289035.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c73289035.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c73289035.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
local ct=e:GetLabel()
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ct>ft then ct=ft end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c73289035.spfilter,tp,LOCATION_GRAVE,0,1,ct,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0)
end
function c73289035.spop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<g:GetCount() then return end
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c77585513.lua | 7 | 1338 | --人造人間-サイコ・ショッカー
function c77585513.initial_effect(c)
--cannot trigger
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_TRIGGER)
e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(0xa,0xa)
e1:SetTarget(c77585513.distg)
c:RegisterEffect(e1)
--disable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_SZONE,LOCATION_SZONE)
e2:SetTarget(c77585513.distg)
c:RegisterEffect(e2)
--disable effect
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_CHAIN_SOLVING)
e3:SetRange(LOCATION_MZONE)
e3:SetOperation(c77585513.disop)
c:RegisterEffect(e3)
--disable trap monster
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_DISABLE_TRAPMONSTER)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e4:SetTarget(c77585513.distg)
c:RegisterEffect(e4)
end
function c77585513.distg(e,c)
return c:IsType(TYPE_TRAP)
end
function c77585513.disop(e,tp,eg,ep,ev,re,r,rp)
local tl=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION)
if tl==LOCATION_SZONE and re:IsActiveType(TYPE_TRAP) then
Duel.NegateEffect(ev)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/spells/bluemagic/seedspray.lua | 8 | 1911 | -----------------------------------------
-- Spell: Seedspray
-- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP
-- Spell cost: 61 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 2
-- Stat Bonus: VIT+1
-- Level: 61
-- Casting Time: 4 seconds
-- Recast Time: 35 seconds
-- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation can close Induration or Detonation)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL
params.dmgtype = DMGTYPE_SLASH
params.scattr = SC_GRAVITATION
params.numhits = 3
params.multiplier = 1.925
params.tp150 = 1.25
params.tp300 = 1.25
params.azuretp = 1.25
params.duppercap = 61
params.str_wsc = 0.0
params.dex_wsc = 0.30
params.vit_wsc = 0.0
params.agi_wsc = 0.0
params.int_wsc = 0.20
params.mnd_wsc = 0.0
params.chr_wsc = 0.0
damage = BluePhysicalSpell(caster, target, spell, params)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
local chance = math.random()
if (damage > 0 and chance > 1) then
local typeEffect = dsp.effect.DEFENSE_DOWN
target:delStatusEffect(typeEffect)
target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect))
end
return damage
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/effects/debilitation.lua | 12 | 1133 | -----------------------------------
--
--
--
-----------------------------------
local stats_bits =
{
dsp.mod.STR,
dsp.mod.DEX,
dsp.mod.VIT,
dsp.mod.AGI,
dsp.mod.INT,
dsp.mod.MND,
dsp.mod.CHR,
dsp.mod.HPP,
dsp.mod.MPP
}
function onEffectGain(target,effect)
local power = effect:getPower()
for statbit,mod in ipairs(stats_bits) do
if bit.band(bit.lshift(1, statbit - 1), power) > 0 then
if mod == dsp.mod.HPP or mod == dsp.mod.MPP then
target:addMod(mod, -40)
else
target:addMod(mod, -30)
end
end
end
target:setStatDebilitation(power)
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
local power = effect:getPower()
for statbit,mod in ipairs(stats_bits) do
if bit.band(bit.lshift(1, statbit - 1), power) > 0 then
if mod == dsp.mod.HPP or mod == dsp.mod.MPP then
target:delMod(mod, -40)
else
target:delMod(mod, -30)
end
end
end
target:setStatDebilitation(0)
end
| gpl-3.0 |
adan830/luacheck | spec/check_spec.lua | 3 | 12682 | local check = require "luacheck.check"
describe("check", function()
it("does not find anything wrong in an empty block", function()
assert.same({}, check(""))
end)
it("does not find anything wrong in used locals", function()
assert.same({
{code = "113", name = "print", line = 5, column = 4, end_column = 8}
}, check[[
local a
local b = 5
a = 6
do
print(b, {a})
end
]])
end)
it("detects global set", function()
assert.same({
{code = "111", name = "foo", line = 1, column = 1, end_column = 3, top = true}
}, check[[
foo = {}
]])
end)
it("detects global set in nested functions", function()
assert.same({
{code = "111", name = "foo", line = 2, column = 4, end_column = 6}
}, check[[
local function bar()
foo = {}
end
bar()
]])
end)
it("detects global access in multi-assignments", function()
assert.same({
{code = "111", name = "y", line = 2, column = 4, end_column = 4, top = true},
{code = "532", line = 2, column = 6, end_column = 6},
{code = "113", name = "print", line = 3, column = 1, end_column = 5}
}, check[[
local x
x, y = 1
print(x)
]])
end)
it("detects global access in self swap", function()
assert.same({
{code = "113", name = "a", line = 1, column = 11, end_column = 11},
{code = "113", name = "print", line = 2, column = 1, end_column = 5}
}, check[[
local a = a
print(a)
]])
end)
it("detects global mutation", function()
assert.same({
{code = "112", name = "a", line = 1, column = 1, end_column = 1}
}, check[[
a[1] = 6
]])
end)
it("detects unused locals", function()
assert.same({
{code = "211", name = "a", line = 1, column = 7, end_column = 7},
{code = "113", name = "print", line = 5, column = 4, end_column = 8}
}, check[[
local a = 4
do
local b = 6
print(b)
end
]])
end)
it("detects unused locals from function arguments", function()
assert.same({
{code = "212", name = "foo", line = 1, column = 17, end_column = 19}
}, check[[
return function(foo, ...)
return ...
end
]])
end)
it("detects unused implicit self", function()
assert.same({
{code = "212", name = "self", self = true, line = 2, column = 11, end_column = 11}
}, check[[
local a = {}
function a:b()
end
]])
end)
it("detects unused locals from loops", function()
assert.same({
{code = "213", name = "i", line = 1, column = 5, end_column = 5},
{code = "213", name = "i", line = 2, column = 5, end_column = 5},
{code = "113", name = "pairs", line = 2, column = 10, end_column = 14}
}, check[[
for i=1, 2 do end
for i in pairs{} do end
]])
end)
it("detects unused values", function()
assert.same({
{code = "311", name = "a", line = 3, column = 4, end_column = 4},
{code = "311", name = "a", line = 5, column = 4, end_column = 4},
{code = "113", name = "print", line = 9, column = 1, end_column = 5}
}, check[[
local a
if ... then
a = 2
else
a = 3
end
a = 5
print(a)
]])
end)
it("does not detect unused value when it and a closure using it can live together", function()
assert.same({
{code = "113", name = "escape", line = 3, column = 4, end_column = 9}
}, check[[
local a = 3
if true then
escape(function() return a end)
end
]])
end)
it("does not consider value assigned to upvalue as unused if it is accessed in another closure", function()
assert.same({}, check[[
local a
local function f(x) a = x end
local function g() return a end
return f, g
]])
end)
it("does not consider a variable initialized if it can't get a value due to short rhs", function()
assert.same({}, check[[
local a, b = "foo"
b = "bar"
return a, b
]])
end)
it("considers a variable initialized if short rhs ends with potential multivalue", function()
assert.same({
{code = "311", name = "b", line = 2, column = 13, end_column = 13, secondary = true}
}, check[[
return function(...)
local a, b = ...
b = "bar"
return a, b
end
]])
end)
it("reports unused variable as secondary if it is assigned together with a used one", function()
assert.same({
{code = "211", name = "a", line = 2, column = 10, end_column = 10, secondary = true}
}, check[[
return function(f)
local a, b = f()
return b
end
]])
end)
it("reports unused value as secondary if it is assigned together with a used one", function()
assert.same({
{code = "231", name = "a", line = 2, column = 10, end_column = 10, secondary = true}
}, check[[
return function(f)
local a, b
a, b = f()
return b
end
]])
assert.same({
{code = "231", name = "a", line = 2, column = 10, end_column = 10, secondary = true}
}, check[[
return function(f, t)
local a
a, t[1] = f()
end
]])
end)
it("considers a variable assigned even if it can't get a value due to short rhs (it still gets nil)", function()
assert.same({
{code = "311", name = "a", line = 1, column = 7, end_column = 7},
{code = "311", name = "b", line = 1, column = 10, end_column = 10},
{code = "532", line = 2, column = 6, end_column = 6}
}, check[[
local a, b = "foo", "bar"
a, b = "bar"
return a, b
]])
end)
it("reports vartype == var when the unused value is not the initial", function()
assert.same({
{code = "312", name = "b", line = 1, column = 23, end_column = 23},
{code = "311", name = "a", line = 2, column = 4, end_column = 4}
}, check[[
local function foo(a, b)
a = a or "default"
a = 42
b = 7
return a, b
end
return foo
]])
end)
it("does not detect unused values in loops", function()
assert.same({
{code = "113", name = "print", line = 3, column = 4, end_column = 8},
{code = "113", name = "math", line = 4, column = 8, end_column = 11}
}, check[[
local a = 10
while a > 0 do
print(a)
a = math.floor(a/2)
end
]])
end)
it("handles upvalues before infinite loops", function()
assert.same({
{code = "221", name = "x", line = 1, column = 7, end_column = 7},
{code = "211", name = "f", func = true, line = 2, column = 16, end_column = 16}
}, check[[
local x
local function f() return x end
::loop::
goto loop
]])
end)
it("detects redefinition in the same scope", function()
assert.same({
{code = "211", name = "foo", line = 1, column = 7, end_column = 9},
{code = "411", name = "foo", line = 2, column = 7, end_column = 9, prev_line = 1, prev_column = 7},
{code = "113", name = "print", line = 3, column = 1, end_column = 5}
}, check[[
local foo
local foo = "bar"
print(foo)
]])
end)
it("detects redefinition of function arguments", function()
assert.same({
{code = "212", name = "foo", line = 1, column = 17, end_column = 19},
{code = "212", name = "...", line = 1, column = 22, end_column = 24},
{code = "412", name = "foo", line = 2, column = 10, end_column = 12, prev_line = 1, prev_column = 17}
}, check[[
return function(foo, ...)
local foo = 1
return foo
end
]])
end)
it("marks redefinition of implicit self", function()
assert.same({
{code = "112", name = "t", line = 1, column = 10, end_column = 10},
{code = "212", name = "self", line = 1, column = 11, end_column = 11, self = true},
{code = "212", name = "self", line = 3, column = 14, end_column = 14, self = true},
{code = "432", name = "self", line = 3, column = 14, end_column = 14, self = true, prev_line = 1, prev_column = 11}
}, check[[
function t:f()
local o = {}
function o:g() end
end
]])
assert.same({
{code = "112", name = "t", line = 1, column = 10, end_column = 10},
{code = "212", name = "self", line = 1, column = 14, end_column = 17},
{code = "212", name = "self", line = 3, column = 14, end_column = 14, self = true},
{code = "432", name = "self", line = 3, column = 14, end_column = 14, prev_line = 1, prev_column = 14}
}, check[[
function t.f(self)
local o = {}
function o:g() end
end
]])
assert.same({
{code = "112", name = "t", line = 1, column = 10, end_column = 10},
{code = "212", name = "self", line = 1, column = 11, end_column = 11, self = true},
{code = "212", name = "self", line = 3, column = 17, end_column = 20},
{code = "432", name = "self", line = 3, column = 17, end_column = 20, prev_line = 1, prev_column = 11}
}, check[[
function t:f()
local o = {}
function o.g(self) end
end
]])
end)
it("detects shadowing definitions", function()
assert.same({
{code = "431", name = "a", line = 4, column = 10, end_column = 10, prev_line = 1, prev_column = 7},
{code = "421", name = "a", line = 7, column = 13, end_column = 13, prev_line = 4, prev_column = 10}
}, check[[
local a = 46
return a, function(foo, ...)
local a = 1
do
local a = 6
foo(a, ...)
end
return a
end
]])
end)
it("detects unset variables", function()
assert.same({
{code = "221", name = "a", line = 1, column = 7, end_column = 7}
}, check[[
local a
return a
]])
end)
it("detects unused labels", function()
assert.same({
{code = "521", name = "fail", line = 2, column = 4, end_column = 11}
}, check[[
::fail::
do ::fail:: end
goto fail
]])
end)
it("detects unreachable code", function()
assert.same({
{code = "511", line = 2, column = 1, end_column = 2}
}, check[[
do return end
if ... then return 6 end
return 3
]])
assert.same({
{code = "511", line = 7, column = 1, end_column = 2},
{code = "511", line = 13, column = 1, end_column = 6}
}, check[[
if ... then
return 4
else
return 6
end
if ... then
return 7
else
return 8
end
return 3
]])
end)
it("detects unreachable code with literal conditions", function()
assert.same({
{code = "511", line = 4, column = 1, end_column = 6}
}, check[[
while true do
(...)()
end
return
]])
assert.same({}, check[[
repeat
if ... then
break
end
until false
return
]])
assert.same({
{code = "511", line = 6, column = 1, end_column = 6}
}, check[[
repeat
if nil then
break
end
until false
return
]])
end)
it("detects unreachable expressions", function()
assert.same({
{code = "511", line = 3, column = 7, end_column = 9}
}, check[[
repeat
return
until ...
]])
assert.same({
{code = "511", line = 3, column = 8, end_column = 10}
}, check[[
if true then
(...)()
elseif ... then
(...)()
end
]])
end)
it("detects accessing uninitialized variables", function()
assert.same({
{code = "113", name = "get", line = 6, column = 8, end_column = 10},
{code = "321", name = "a", line = 6, column = 12, end_column = 12}
}, check[[
local a
if ... then
a = 5
else
a = get(a)
end
return a
]])
end)
it("does not detect accessing unitialized variables incorrectly in loops", function()
assert.same({
{code = "113", name = "get", line = 4, column = 8, end_column = 10}
}, check[[
local a
while not a do
a = get()
end
return a
]])
end)
it("detects unbalanced assignments", function()
assert.same({
{code = "532", line = 4, column = 6, end_column = 6},
{code = "531", line = 5, column = 6, end_column = 6}
}, check[[
local a, b = 4; (...)(a)
a, b = (...)(); (...)(a, b)
a, b = 5; (...)(a, b)
a, b = 1, 2, 3; (...)(a, b)
]])
end)
it("detects empty blocks", function()
assert.same({
{code = "541", line = 1, column = 1, end_column = 2},
{code = "542", line = 3, column = 8, end_column = 11},
{code = "542", line = 5, column = 12, end_column = 15},
{code = "542", line = 7, column = 1, end_column = 4}
}, check[[
do end
if ... then
elseif ... then
else
end
while ... do end
repeat until ...
]])
end)
it("handles argparse sample", function()
assert.table(check(io.open("spec/samples/argparse.lua", "rb"):read("*a")))
end)
end)
| mit |
cshore-firmware/openwrt-luci | modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/profile.lua | 68 | 2553 | -- Copyright 2011-2012 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
local uci = require "luci.model.uci".cursor()
local ipkg = require "luci.model.ipkg"
local community = uci:get("freifunk", "community", "name")
if community == nil then
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "profile_error"))
return
else
community = "profile_" .. community
m = Map(community, translate("Community settings"), translate("These are the settings of your local community."))
c = m:section(NamedSection, "profile", "community")
local name = c:option(Value, "name", "Name")
name.rmempty = false
local homepage = c:option(Value, "homepage", translate("Homepage"))
local cc = c:option(Value, "country", translate("Country code"))
function cc.cfgvalue(self, section)
return uci:get(community, "wifi_device", "country")
end
function cc.write(self, sec, value)
if value then
uci:set(community, "wifi_device", "country", value)
uci:save(community)
end
end
local ssid = c:option(Value, "ssid", translate("ESSID"))
ssid.rmempty = false
local prefix = c:option(Value, "mesh_network", translate("Mesh prefix"))
prefix.datatype = "ip4addr"
prefix.rmempty = false
local splash_net = c:option(Value, "splash_network", translate("Network for client DHCP addresses"))
splash_net.datatype = "ip4addr"
splash_net.rmempty = false
local splash_prefix = c:option(Value, "splash_prefix", translate("Client network size"))
splash_prefix.datatype = "range(0,32)"
splash_prefix.rmempty = false
local ipv6 = c:option(Flag, "ipv6", translate("Enable IPv6"))
ipv6.rmempty = true
local ipv6_config = c:option(ListValue, "ipv6_config", translate("IPv6 Config"))
ipv6_config:depends("ipv6", 1)
ipv6_config:value("static")
if ipkg.installed ("auto-ipv6-ib") then
ipv6_config:value("auto-ipv6-random")
ipv6_config:value("auto-ipv6-fromv4")
end
ipv6_config.rmempty = true
local ipv6_prefix = c:option(Value, "ipv6_prefix", translate("IPv6 Prefix"), translate("IPv6 network in CIDR notation."))
ipv6_prefix:depends("ipv6", 1)
ipv6_prefix.datatype = "ip6addr"
ipv6_prefix.rmempty = true
local vap = c:option(Flag, "vap", translate("VAP"), translate("Enable a virtual access point (VAP) by default if possible."))
vap.rmempty = true
local lat = c:option(Value, "latitude", translate("Latitude"))
lat.datatype = "range(-180, 180)"
lat.rmempty = false
local lon = c:option(Value, "longitude", translate("Longitude"))
lon.rmempty = false
return m
end
| apache-2.0 |
Lsty/ygopro-scripts | c40101111.lua | 3 | 2077 | --アルティメットサイキッカー
function c40101111.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcFun2(c,c40101111.ffilter,aux.FilterBoolFunction(Card.IsRace,RACE_PSYCHO),true)
--pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
--cannot be destroyed
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetValue(1)
c:RegisterEffect(e3)
--fusion success
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(40101111,0))
e4:SetCategory(CATEGORY_RECOVER)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLE_DESTROYING)
e4:SetCondition(c40101111.recon)
e4:SetTarget(c40101111.rectg)
e4:SetOperation(c40101111.recop)
c:RegisterEffect(e4)
--spsummon condition
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e5:SetCode(EFFECT_SPSUMMON_CONDITION)
e5:SetValue(c40101111.splimit)
c:RegisterEffect(e5)
end
function c40101111.splimit(e,se,sp,st)
if e:GetHandler():IsLocation(LOCATION_EXTRA) then
return bit.band(st,SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
return true
end
function c40101111.ffilter(c)
return c:IsType(TYPE_SYNCHRO) and c:IsRace(RACE_PSYCHO)
end
function c40101111.recon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
return c:IsRelateToBattle() and bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER)
end
function c40101111.rectg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local rec=e:GetHandler():GetBattleTarget():GetAttack()
if rec<0 then rec=0 end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(rec)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,rec)
end
function c40101111.recop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/items/serving_of_cherry_bavarois.lua | 11 | 1064 | -----------------------------------------
-- ID: 5745
-- Item: serving_of_cherry_bavarois
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- HP 25
-- Intelligence 3
-- MP 10
-- HP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5745)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 25)
target:addMod(dsp.mod.INT, 3)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.HPHEAL, 3)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 25)
target:delMod(dsp.mod.INT, 3)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.HPHEAL, 3)
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/spells/pyrohelix.lua | 12 | 2048 | --------------------------------------
-- Spell: Pyrohelix
-- Deals fire damage that gradually reduces
-- a target's HP. Damage dealt is greatly affected by the weather.
--------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
--------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
-- get helix acc/att merits
local merit = caster:getMerit(dsp.merit.HELIX_MAGIC_ACC_ATT)
-- calculate raw damage
local params = {}
params.dmg = 35
params.multiplier = 1
params.skillType = dsp.skill.ELEMENTAL_MAGIC
params.attribute = dsp.mod.INT
params.hasMultipleTargetReduction = false
local dmg = calculateMagicDamage(caster, target, spell, params)
dmg = dmg + caster:getMod(dsp.mod.HELIX_EFFECT)
-- get resist multiplier (1x if no resist)
local params = {}
params.diff = caster:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT)
params.attribute = dsp.mod.INT
params.skillType = dsp.skill.ELEMENTAL_MAGIC
-- bonus accuracy from merit
params.bonus = merit*3
local resist = applyResistance(caster, target, spell, params)
-- get the resisted damage.
dmg = dmg*resist
-- add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg,params)
-- add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement())
-- helix MAB merits are actually a percentage increase
dmg = dmg * ((100 + merit*2)/100)
local dot = dmg
-- add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg)
-- calculate Damage over time
dot = target:magicDmgTaken(dot)
local duration = getHelixDuration(caster) + caster:getMod(dsp.mod.HELIX_DURATION)
duration = duration * (resist/2)
if (dot > 0) then
target:addStatusEffect(dsp.effect.HELIX,dot,3,duration)
end
return dmg
end | gpl-3.0 |
mickelfeng/ABTestingGateway | diversion/diversion.lua | 22 | 7762 | local runtimeModule = require('abtesting.adapter.runtime')
local redisModule = require('abtesting.utils.redis')
local systemConf = require('abtesting.utils.init')
local handler = require('abtesting.error.handler').handler
local ERRORINFO = require('abtesting.error.errcode').info
local cjson = require('cjson.safe')
local utils = require('abtesting.utils.utils')
local resty_lock = require("resty.lock")
local redisConf = systemConf.redisConf
local prefixConf = systemConf.prefixConf
local divConf = systemConf.divConf
local cacheConf = systemConf.cacheConf
local runtimeInfoLib = prefixConf.runtimeInfoPrefix
local domainname = prefixConf.domainname
local shdict_expire = divConf.shdict_expire or 60
local default_backend = divConf.default_backend
local cache_expire = cacheConf.timeout or 0.001
local rt_cache_lock = cacheConf.runtimeInfoLock
local dolog = utils.dolog
local sysConfig = ngx.shared.sysConfig
local kv_upstream = ngx.shared.kv_upstream
local getRewriteInfo = function()
return 'redirect to upstream http://'..ngx.var.backend
end
local doredirect = function()
local ok = ERRORINFO.SUCCESS
local err = 'redirect to upstream http://'..ngx.var.backend
dolog(ok, err)
end
local isNULL = function(v)
return not v or v == ngx.null
end
local areNULL = function(...)
local t = {...}
if not next(t) then
return true
end
for k, v in pairs(t) do
if isNULL(v) then
return true
end
end
return false
end
local isSwitchOff = function(...)
local t = {...}
if not next(t) then
return true
end
for k, v in pairs(t) do
if v == -1 then
return true
end
end
return false
end
local red
local setKeepalive = function(red)
local ok, err = red:keepalivedb()
if not ok then
local errinfo = ERRORINFO.REDIS_KEEPALIVE_ERROR
local errdesc = err
dolog(errinfo, errdesc)
return
end
end
--====================================================
--获取当前domain的运行时
-- 分流模块名 divModulename
-- 分流策略库名 divDataKey
-- 用户特征提取模块名 userInfoModulename
local k_divModname = runtimeInfoLib .. ':' .. domainname .. 'divModulename'
local k_divData = runtimeInfoLib .. ':' .. domainname .. 'divDataKey'
local k_userinfoModname = runtimeInfoLib .. ':' .. domainname .. 'userInfoModulename'
local divModule, divPolicy, userInfoModname
divModname = sysConfig:get(k_divModname)
divPolicy = sysConfig:get(k_divData)
userInfoModname = sysConfig:get(k_userinfoModname)
--step 1: read from cache
if areNULL(divModname, divPolicy, userInfoModname) then
-- setp 2: acquire the lock
local opts = {["timeout"] = tonumber(cache_expire)}
local lock = resty_lock:new(rt_cache_lock, opts)
local elapsed, err = lock:lock(userInfo)
if not elapsed then
-- lock failed acquired
-- but go on. This action just set a fence for all but this request
end
-- setp 3: read from cache again
divModname = sysConfig:get(k_divModname)
divPolicy = sysConfig:get(k_divData)
userInfoModname = sysConfig:get(k_userinfoModname)
if areNULL(divModname, divPolicy, userInfoModname) then
-- step 4: fetch from redis
if not red then
red = redisModule:new(redisConf)
local ok, err = red:connectdb()
if not ok then
local errinfo = ERRORINFO.REDIS_CONNECT_ERROR
dolog(errinfo, err, getRewriteInfo())
local ok, err = lock:unlock()
return
end
end
local pfunc = function()
local runtimeMod = runtimeModule:new(red.redis, runtimeInfoLib)
local runtimeInfo = runtimeMod:get(domainname)
return runtimeInfo
end
local status, info = xpcall(pfunc, handler)
if not status then
local errinfo = info[1]
local errstack = info[2]
local err, desc = errinfo[1], errinfo[2]
dolog(err, desc, getRewriteInfo(), errstack)
local ok, err = lock:unlock()
return
end
divModname = info[1]
divPolicy = info[2]
userInfoModname = info[3]
if areNULL(divModname, divPolicy, userInfoModname) then
local errinfo = ERRORINFO.RUNTIME_BLANK_ERROR
local errdesc = 'runtimeInfo blank'
sysConfig:set(k_divModname, -1, shdict_expire)
sysConfig:set(k_divData, -1, shdict_expire)
sysConfig:set(k_userinfoModname, -1, shdict_expire)
local ok, err = lock:unlock()
if red then setKeepalive(red) end
dolog(errinfo, errdesc, getRewriteInfo())
return
else
sysConfig:set(k_divModname, divModname, shdict_expire)
sysConfig:set(k_divData, divPolicy, shdict_expire)
sysConfig:set(k_userinfoModname, userInfoModname, shdict_expire)
local ok, err = lock:unlock()
end
end
elseif isSwitchOff(divModname, divPolicy, userInfoModname) then
-- switchoff, so goto default upstream
doredirect()
return
else
-- maybe userful
end
--====================================================
--准备工作:
-- 分流模块 divModule
-- 用户特征提取模块 userInfoModule
--获取用户信息:
-- 用户信息 userInfo
local userInfoMod
local diversionMod
local userInfo
local pfunc = function()
userInfoMod = require(userInfoModname)
diversionMod = require(divModname)
userInfo = userInfoMod:get()
end
local ok, info = xpcall(pfunc, handler)
if not ok then
local errinfo = info[1]
local errstack = info[2]
local err, desc = errinfo[1], errinfo[2]
dolog(err, desc, getRewriteInfo(), errstack)
if red then setKeepalive(red) end
return
end
if not userInfo then
local errinfo = ERRORINFO.USERINFO_BLANK_ERROR
local errdesc = userInfoModulename
dolog(errinfo, errdesc, getRewriteInfo())
if red then setKeepalive(red) end
return
end
------------------分流准备工作结束--------------------
--====================================================
local upstream, err = kv_upstream:get(userInfo)
if not upstream then
if not red then
red = redisModule:new(redisConf)
local ok, err = red:connectdb()
if not ok then
local errinfo = ERRORINFO.REDIS_CONNECT_ERROR
dolog(errinfo, err, getRewriteInfo())
return
end
end
local pfunc = function()
local divModule = diversionMod:new(red.redis, divPolicy)
local upstream = divModule:getUpstream(userInfo)
return upstream
end
local status, backend = xpcall(pfunc, handler)
if not status then
local info = backend
local errinfo = info[1]
local errstack = info[2]
local err, desc = errinfo[1], errinfo[2]
dolog(err, desc, getRewriteInfo(), errstack)
return
end
upstream = backend
end
if upstream then
ngx.var.backend = upstream
else
upstream = default_backend
end
kv_upstream:set(userInfo, upstream, shdict_expire)
doredirect()
--------------------分流结果结束----------------------
--====================================================
--====================================================
---------------------后续处理-------------------------
---如果本次请求使用过redis,设置redis对象的keepalive---
------------------------------------------------------
if red then
setKeepalive(red)
end
| mit |
cshore-firmware/openwrt-luci | applications/luci-app-wol/luasrc/model/cbi/wol.lua | 55 | 2319 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = SimpleForm("wol", translate("Wake on LAN"),
translate("Wake on LAN is a mechanism to remotely boot computers in the local network."))
m.submit = translate("Wake up host")
m.reset = false
local has_ewk = fs.access("/usr/bin/etherwake")
local has_wol = fs.access("/usr/bin/wol")
s = m:section(SimpleSection)
if has_ewk and has_wol then
bin = s:option(ListValue, "binary", translate("WoL program"),
translate("Sometimes only one of the two tools works. If one fails, try the other one"))
bin:value("/usr/bin/etherwake", "Etherwake")
bin:value("/usr/bin/wol", "WoL")
end
if has_ewk then
iface = s:option(ListValue, "iface", translate("Network interface to use"),
translate("Specifies the interface the WoL packet is sent on"))
if has_wol then
iface:depends("binary", "/usr/bin/etherwake")
end
iface:value("", translate("Broadcast on all interfaces"))
for _, e in ipairs(sys.net.devices()) do
if e ~= "lo" then iface:value(e) end
end
end
host = s:option(Value, "mac", translate("Host to wake up"),
translate("Choose the host to wake up or enter a custom MAC address to use"))
sys.net.mac_hints(function(mac, name)
host:value(mac, "%s (%s)" %{ mac, name })
end)
function host.write(self, s, val)
local host = luci.http.formvalue("cbid.wol.1.mac")
if host and #host > 0 and host:match("^[a-fA-F0-9:]+$") then
local cmd
local util = luci.http.formvalue("cbid.wol.1.binary") or (
has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol"
)
if util == "/usr/bin/etherwake" then
local iface = luci.http.formvalue("cbid.wol.1.iface")
cmd = "%s -D%s %q" %{
util, (iface ~= "" and " -i %q" % iface or ""), host
}
else
cmd = "%s -v %q" %{ util, host }
end
local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{
translate("Starting WoL utility:"), cmd
}
local p = io.popen(cmd .. " 2>&1")
if p then
while true do
local l = p:read("*l")
if l then
if #l > 100 then l = l:sub(1, 100) .. "..." end
msg = msg .. l .. "<br />"
else
break
end
end
p:close()
end
msg = msg .. "</code></p>"
m.message = msg
end
end
return m
| apache-2.0 |
Lsty/ygopro-scripts | c73915051.lua | 3 | 2351 | --スケープ・ゴート
function c73915051.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetCost(c73915051.cost)
e1:SetTarget(c73915051.target)
e1:SetOperation(c73915051.activate)
c:RegisterEffect(e1)
end
function c73915051.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_SUMMON)==0
and Duel.GetActivityCount(tp,ACTIVITY_FLIPSUMMON)==0 and Duel.GetActivityCount(tp,ACTIVITY_SPSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(1,0)
e1:SetLabelObject(e)
e1:SetTarget(c73915051.sumlimit)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e2:SetCode(EFFECT_CANNOT_SUMMON)
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetTargetRange(1,0)
Duel.RegisterEffect(e2,tp)
local e3=e2:Clone()
e3:SetCode(EFFECT_CANNOT_FLIP_SUMMON)
Duel.RegisterEffect(e3,tp)
end
function c73915051.sumlimit(e,c,sump,sumtype,sumpos,targetp,se)
return e:GetLabelObject()~=se
end
function c73915051.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>3
and Duel.IsPlayerCanSpecialSummonMonster(tp,73915052,0,0x4011,0,0,1,RACE_BEAST,ATTRIBUTE_EARTH) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,4,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,4,0,0)
end
function c73915051.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>3
and Duel.IsPlayerCanSpecialSummonMonster(tp,73915052,0,0x4011,0,0,1,RACE_BEAST,ATTRIBUTE_EARTH) then
for i=1,4 do
local token=Duel.CreateToken(tp,73915051+i)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP_DEFENCE)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UNRELEASABLE_SUM)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000)
token:RegisterEffect(e1,true)
end
Duel.SpecialSummonComplete()
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c43714890.lua | 9 | 1129 | --人投げトロール
function c43714890.initial_effect(c)
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(43714890,0))
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c43714890.cost)
e1:SetTarget(c43714890.target)
e1:SetOperation(c43714890.operation)
c:RegisterEffect(e1)
end
function c43714890.cfilter(c)
local tp=c:GetType()
return bit.band(tp,TYPE_NORMAL)~=0 and bit.band(tp,TYPE_TOKEN)==0
end
function c43714890.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c43714890.cfilter,1,nil) end
local sg=Duel.SelectReleaseGroup(tp,c43714890.cfilter,1,1,nil)
Duel.Release(sg,REASON_COST)
end
function c43714890.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(800)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,800)
end
function c43714890.operation(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
| gpl-2.0 |
rotmanmi/nn | Min.lua | 27 | 1520 | local Min, parent = torch.class('nn.Min', 'nn.Module')
function Min:__init(dimension)
parent.__init(self)
dimension = dimension or 1
self.dimension = dimension
end
function Min:_lazyInit()
self._output = self._output or self.output.new()
self._indices = self._indices or
(torch.type(self.output) == 'torch.CudaTensor' and torch.CudaTensor() or torch.LongTensor())
end
function Min:updateOutput(input)
self:_lazyInit()
torch.min(self._output, self._indices, input, self.dimension)
if input:dim() > 1 then
self.output = self._output:select(self.dimension, 1)
else
self.output = self._output
end
return self.output
end
function Min:updateGradInput(input, gradOutput)
self:_lazyInit()
local gradOutputView
if input:dim() > 1 then
gradOutputView = nn.utils.addSingletonDimension(gradOutput, self.dimension)
else
gradOutputView = gradOutput
end
self.gradInput:resizeAs(input):zero():scatter(self.dimension, self._indices, gradOutputView)
return self.gradInput
end
function Min:type(type)
-- torch.min expects a LongTensor as indices, whereas cutorch.max expects a CudaTensor.
if type == 'torch.CudaTensor' then
parent.type(self, type)
else
-- self._indices must be a LongTensor. Setting it to nil temporarily avoids
-- unnecessary memory allocations.
local indices
indices, self._indices = self._indices, nil
parent.type(self, type)
self._indices = indices and indices:long() or nil
end
return self
end
| bsd-3-clause |
Lsty/ygopro-scripts | c60080151.lua | 3 | 1851 | --好敵手の記憶
function c60080151.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DAMAGE+CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetCondition(c60080151.condition)
e1:SetTarget(c60080151.target)
e1:SetOperation(c60080151.activate)
c:RegisterEffect(e1)
end
function c60080151.condition(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c60080151.target(e,tp,eg,ep,ev,re,r,rp,chk)
local tg=Duel.GetAttacker()
if chk==0 then return tg:IsOnField() and tg:IsAbleToRemove() end
local dam=tg:GetAttack()
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,tp,dam)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,tg,1,0,0)
end
function c60080151.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetAttacker()
if tc and tc:IsAttackable() and not tc:IsStatus(STATUS_ATTACK_CANCELED) then
local dam=tc:GetAttack()
if Duel.Damage(tp,dam,REASON_EFFECT)>0 and Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)>0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCountLimit(1)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCondition(c60080151.spcon)
e1:SetOperation(c60080151.spop)
e1:SetLabelObject(tc)
e1:SetLabel(Duel.GetTurnCount())
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,2)
Duel.RegisterEffect(e1,tp)
tc:RegisterFlagEffect(60080151,RESET_EVENT+0x1fe0000,0,0)
end
end
end
function c60080151.spcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
return Duel.GetTurnCount()~=e:GetLabel() and Duel.GetTurnPlayer()~=tp
and tc:GetFlagEffect(60080151)~=0 and tc:GetReasonEffect():GetHandler()==e:GetHandler()
end
function c60080151.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.SpecialSummon(e:GetLabelObject(),0,tp,tp,false,false,POS_FACEUP)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c5257687.lua | 3 | 1245 | --X・E・N・O
function c5257687.initial_effect(c)
--flip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(5257687,0))
e1:SetCategory(CATEGORY_CONTROL)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c5257687.target)
e1:SetOperation(c5257687.operation)
c:RegisterEffect(e1)
end
function c5257687.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsControlerCanBeChanged() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL)
local g=Duel.SelectTarget(tp,Card.IsControlerCanBeChanged,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_CONTROL,g,1,0,0)
end
function c5257687.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
if Duel.GetControl(tc,tp,PHASE_END,1) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DIRECT_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
elseif not tc:IsImmuneToEffect(e) and tc:IsAbleToChangeControler() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c13683298.lua | 3 | 1471 | --大狼雷鳴
function c13683298.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c13683298.condition)
e1:SetCost(c13683298.cost)
e1:SetTarget(c13683298.target)
e1:SetOperation(c13683298.operation)
c:RegisterEffect(e1)
end
function c13683298.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_GRAVE)
end
function c13683298.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_BATTLE_PHASE)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c13683298.filter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c13683298.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c13683298.filter,tp,0,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(c13683298.filter,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c13683298.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c13683298.filter,tp,0,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c21488686.lua | 4 | 1034 | --サイコ・ヒーリング
function c21488686.initial_effect(c)
--recover
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCategory(CATEGORY_RECOVER)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c21488686.target)
e1:SetOperation(c21488686.operation)
c:RegisterEffect(e1)
end
function c21488686.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c21488686.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.SetTargetPlayer(tp)
local rec=Duel.GetMatchingGroupCount(c21488686.filter,tp,LOCATION_MZONE,0,nil)*1000
Duel.SetTargetParam(rec)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,rec)
end
function c21488686.filter(c)
return c:IsFaceup() and c:IsRace(RACE_PSYCHO)
end
function c21488686.operation(e,tp,eg,ep,ev,re,r,rp)
local rec=Duel.GetMatchingGroupCount(c21488686.filter,tp,LOCATION_MZONE,0,nil)*1000
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
Duel.Recover(p,rec,REASON_EFFECT)
end
| gpl-2.0 |
Mijyuoon/starfall | lua/starfall/permissions/providers_sv/CPPI.lua | 1 | 1150 | --- Provides permissions for entities based on CPPI if present
local P = setmetatable( {}, { __index = SF.Permissions.Provider } )
local ALLOW = SF.Permissions.Result.ALLOW
local DENY = SF.Permissions.Result.DENY
local NEUTRAL = SF.Permissions.Result.NEUTRAL
local canTool = {
[ "ents.parent" ] = true,
[ "ents.unparent" ] = true,
[ "ents.setSolid" ] = true,
[ "ents.enableGravity" ] = true,
[ "ents.setColor" ] = true,
[ "ents.getWirelink" ] = true
}
local canPhysgun = {
[ "ents.applyForce" ] = true,
[ "ents.setPos" ] = true,
[ "ents.setAngles" ] = true,
[ "ents.setVelocity" ] = true,
[ "ents.setFrozen" ] = true
}
local target_type = {
Entity = true,
Player = true,
Vehicle = true,
NPC = true,
}
function P:check ( principal, target, key )
if not CPPI then return NEUTRAL end
if not target_type[type(target)] then return NEUTRAL end
if canTool[ key ] then
if target:CPPICanTool( principal, "starfall_ent_lib" ) then return ALLOW end
return DENY
elseif canPhysgun[ key ] then
if target:CPPICanPhysgun( principal ) then return ALLOW end
return DENY
end
return NEUTRAL
end
SF.Permissions.registerProvider( P )
| bsd-3-clause |
ThingMesh/openwrt-luci | protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua | 61 | 2076 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, defaultroute, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address"))
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
Lsty/ygopro-scripts | c50781944.lua | 7 | 1126 | --エンシェント・クリムゾン・エイプ
function c50781944.initial_effect(c)
--lp rec
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(50781944,0))
e1:SetCategory(CATEGORY_RECOVER)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCondition(c50781944.reccon)
e1:SetTarget(c50781944.rectg)
e1:SetOperation(c50781944.recop)
c:RegisterEffect(e1)
end
function c50781944.filter(c,tp)
return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_MZONE) and
c:GetPreviousControler()==tp and c:IsType(TYPE_MONSTER)
end
function c50781944.reccon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c50781944.filter,1,nil,tp)
end
function c50781944.rectg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1000)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,1000)
end
function c50781944.recop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Lower_Jeuno/npcs/_6t2.lua | 9 | 4056 | -----------------------------------
-- Area: Lower Jeuno
-- Door: Merchant's House
-- Starts & Finishes Quest: Save My Son
-- Optional Involvement in Quest: Chocobo's Wounds, Path of the Beastmaster
-----------------------------------
local ID = require("scripts/zones/Lower_Jeuno/IDs")
require("scripts/globals/settings")
require("scripts/globals/quests")
require("scripts/globals/status")
require("scripts/globals/titles")
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local ANewDawn = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.A_NEW_DAWN);
local ANewDawnEvent = player:getCharVar("ANewDawn_Event");
local ScatteredIntoShadow = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.SCATTERED_INTO_SHADOW);
local SaveMySon = player:getCharVar("SaveMySon_Event");
local ChocobosWounds = player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.CHOCOBO_S_WOUNDS);
local mLvl = player:getMainLvl();
local mJob = player:getMainJob();
-- A New Dawn (BST AF3)
if (ScatteredIntoShadow == QUEST_COMPLETED and ANewDawn == QUEST_AVAILABLE) then
if (mJob == dsp.job.BST and mLvl >= 50) then
if (ANewDawnEvent == 0) then
player:startEvent(5);
elseif (ANewDawnEvent == 1) then
player:startEvent(4);
end
else
player:startEvent(1);
end
elseif (ANewDawn == QUEST_ACCEPTED) then
if (ANewDawnEvent == 2) then
player:startEvent(2);
elseif (ANewDawnEvent >= 4) then
player:startEvent(3);
end
elseif (ANewDawn == QUEST_COMPLETED and ANewDawnEvent == 6) then
player:startEvent(0);
-- Save My Son
elseif (player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SAVE_MY_SON) == QUEST_AVAILABLE and mLvl >= 30) then
player:startEvent(164);
elseif (player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SAVE_MY_SON) == QUEST_ACCEPTED) then
if (SaveMySon == 0) then
player:startEvent(229);
elseif (SaveMySon == 1) then
player:startEvent(163);
end
elseif (player:needToZone() == false and player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SAVE_MY_SON) == QUEST_COMPLETED and SaveMySon == 2) then
player:startEvent(132);
-- Chocobos Wounds
elseif (ChocobosWounds == QUEST_AVAILABLE) then
player:startEvent(64);
elseif (player:getCharVar("ChocobosWounds_Event") > 3) then
player:startEvent(63);
-- Standard Dialogue?, Probably Wrong
else
player:messageSpecial(ID.text.ITS_LOCKED);
end
return 1;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 164 and option == 0) then
player:addQuest(JEUNO, dsp.quest.id.jeuno.SAVE_MY_SON);
elseif (csid == 163) then
if (player:getFreeSlotsCount(0) >= 1) then
player:addTitle(dsp.title.LIFE_SAVER);
player:addItem(13110);
player:messageSpecial(ID.text.ITEM_OBTAINED, 13110);
player:addGil(GIL_RATE*2100);
player:messageSpecial(ID.text.GIL_OBTAINED, GIL_RATE*2100);
player:setCharVar("SaveMySon_Event",2);
player:needToZone(true);
player:addFame(JEUNO,30);
player:completeQuest(JEUNO,dsp.quest.id.jeuno.SAVE_MY_SON);
else
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13110);
end
elseif (csid == 132) then
player:setCharVar("SaveMySon_Event",0);
elseif (csid == 5) then
player:setCharVar("ANewDawn_Event",1);
if (option == 1) then
player:addQuest(JEUNO, dsp.quest.id.jeuno.A_NEW_DAWN);
player:setCharVar("ANewDawn_Event",2);
end
elseif (csid == 4 and option == 1) then
player:addQuest(JEUNO, dsp.quest.id.jeuno.A_NEW_DAWN);
player:setCharVar("ANewDawn_Event",2);
elseif (csid == 0) then
player:setCharVar("ANewDawn_Event",0);
end
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c90019393.lua | 9 | 1261 | --ジェムナイト・アレキサンド
function c90019393.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(90019393,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c90019393.cost)
e1:SetTarget(c90019393.target)
e1:SetOperation(c90019393.operation)
c:RegisterEffect(e1)
end
function c90019393.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c90019393.filter(c,e,tp)
return c:IsSetCard(0x1047) and c:IsType(TYPE_NORMAL) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c90019393.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c90019393.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_DECK)
end
function c90019393.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c90019393.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
sagarwaghmare69/nn | L1HingeEmbeddingCriterion.lua | 63 | 1160 | local L1HingeEmbeddingCriterion, parent = torch.class('nn.L1HingeEmbeddingCriterion', 'nn.Criterion')
function L1HingeEmbeddingCriterion:__init(margin)
parent.__init(self)
margin = margin or 1
self.margin = margin
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function L1HingeEmbeddingCriterion:updateOutput(input,y)
self.output=input[1]:dist(input[2],1);
if y == -1 then
self.output = math.max(0,self.margin - self.output);
end
return self.output
end
local function mathsign(t)
if t>0 then return 1; end
if t<0 then return -1; end
return 2*torch.random(2)-3;
end
function L1HingeEmbeddingCriterion:updateGradInput(input, y)
self.gradInput[1]:resizeAs(input[1])
self.gradInput[2]:resizeAs(input[2])
self.gradInput[1]:copy(input[1])
self.gradInput[1]:add(-1, input[2])
local dist = self.gradInput[1]:norm(1);
self.gradInput[1]:apply(mathsign) -- L1 gradient
if y == -1 then -- just to avoid a mul by 1
if dist > self.margin then
self.gradInput[1]:zero()
else
self.gradInput[1]:mul(-1)
end
end
self.gradInput[2]:zero():add(-1, self.gradInput[1])
return self.gradInput
end
| bsd-3-clause |
Lsty/ygopro-scripts | c30600344.lua | 3 | 1094 | --エクシーズ・バースト
function c30600344.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c30600344.condition)
e1:SetTarget(c30600344.target)
e1:SetOperation(c30600344.activate)
c:RegisterEffect(e1)
end
function c30600344.cfilter(c)
return c:IsFaceup() and c:IsRankAbove(6)
end
function c30600344.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c30600344.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c30600344.filter(c)
return c:IsFacedown() and c:IsDestructable()
end
function c30600344.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c30600344.filter,tp,0,LOCATION_ONFIELD,1,nil) end
local g=Duel.GetMatchingGroup(c30600344.filter,tp,0,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c30600344.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c30600344.filter,tp,0,LOCATION_ONFIELD,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.