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 |
|---|---|---|---|---|---|
Scavenge/darkstar | scripts/zones/Sealions_Den/Zone.lua | 30 | 2133 | -----------------------------------
--
-- Zone: Sealions_Den (32)
--
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(600.101,130.355,797.612,50);
end
if (player:getCurrentMission(COP) == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==1) then
cs=0x000F;
elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus")==2) then
cs=0x000E;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x000F) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x000E) then
player:setVar("PromathiaStatus",3);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/plate_of_bream_sushi_+1.lua | 12 | 1670 | -----------------------------------------
-- ID: 5177
-- Item: plate_of_bream_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 6
-- Vitality 5
-- Accuracy % 17 (cap 80)
-- Ranged ACC % 17 (cap 80)
-- Sleep Resist 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5177);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 6);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_ACC_CAP, 80);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_FOOD_RACC_CAP, 80);
target:addMod(MOD_SLEEPRES, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 6);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_ACC_CAP, 80);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_FOOD_RACC_CAP, 80);
target:delMod(MOD_SLEEPRES, 2);
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c87798440.lua | 3 | 4285 | --アーマー・ブレイカー
function c87798440.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(87798440,0))
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c87798440.eqtg)
e1:SetOperation(c87798440.eqop)
c:RegisterEffect(e1)
--unequip
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(87798440,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c87798440.uncon)
e2:SetTarget(c87798440.sptg)
e2:SetOperation(c87798440.spop)
c:RegisterEffect(e2)
--destroy sub
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e3:SetCode(EFFECT_DESTROY_SUBSTITUTE)
e3:SetCondition(c87798440.uncon)
e3:SetValue(c87798440.repval)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(87798440,2))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLE_DAMAGE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetRange(LOCATION_SZONE)
e4:SetCondition(c87798440.descon)
e4:SetTarget(c87798440.destg)
e4:SetOperation(c87798440.desop)
c:RegisterEffect(e4)
--eqlimit
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_EQUIP_LIMIT)
e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e5:SetValue(c87798440.eqlimit)
c:RegisterEffect(e5)
end
function c87798440.uncon(e)
return e:GetHandler():IsStatus(STATUS_UNION)
end
function c87798440.repval(e,re,r,rp)
return bit.band(r,REASON_BATTLE)~=0
end
function c87798440.eqlimit(e,c)
return c:IsRace(RACE_WARRIOR)
end
function c87798440.filter(c)
return c:IsFaceup() and c:IsRace(RACE_WARRIOR) and c:GetUnionCount()==0
end
function c87798440.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c87798440.filter(chkc) end
if chk==0 then return e:GetHandler():GetFlagEffect(87798440)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c87798440.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectTarget(tp,c87798440.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0)
e:GetHandler():RegisterFlagEffect(87798440,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c87798440.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if not c:IsRelateToEffect(e) or c:IsFacedown() then return end
if not tc:IsRelateToEffect(e) or not c87798440.filter(tc) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
if not Duel.Equip(tp,c,tc,false) then return end
c:SetStatus(STATUS_UNION,true)
end
function c87798440.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(87798440)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
e:GetHandler():RegisterFlagEffect(87798440,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c87798440.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)
end
end
function c87798440.descon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp and e:GetHandler():GetEquipTarget()==eg:GetFirst() and c87798440.uncon(e)
end
function c87798440.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsDestructable() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c87798440.desop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
zhaozg/lit | deps/http-codec.lua | 2 | 9383 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/http-codec"
version = "3.0.6"
homepage = "https://github.com/luvit/luvit/blob/master/deps/http-codec.lua"
description = "A simple pair of functions for converting between hex and raw strings."
tags = {"codec", "http"}
license = "Apache 2"
author = { name = "Tim Caswell" }
]]
local sub = string.sub
local gsub = string.gsub
local lower = string.lower
local find = string.find
local format = string.format
local concat = table.concat
local match = string.match
local STATUS_CODES = {
[100] = 'Continue',
[101] = 'Switching Protocols',
[102] = 'Processing', -- RFC 2518, obsoleted by RFC 4918
[200] = 'OK',
[201] = 'Created',
[202] = 'Accepted',
[203] = 'Non-Authoritative Information',
[204] = 'No Content',
[205] = 'Reset Content',
[206] = 'Partial Content',
[207] = 'Multi-Status', -- RFC 4918
[300] = 'Multiple Choices',
[301] = 'Moved Permanently',
[302] = 'Moved Temporarily',
[303] = 'See Other',
[304] = 'Not Modified',
[305] = 'Use Proxy',
[307] = 'Temporary Redirect',
[400] = 'Bad Request',
[401] = 'Unauthorized',
[402] = 'Payment Required',
[403] = 'Forbidden',
[404] = 'Not Found',
[405] = 'Method Not Allowed',
[406] = 'Not Acceptable',
[407] = 'Proxy Authentication Required',
[408] = 'Request Time-out',
[409] = 'Conflict',
[410] = 'Gone',
[411] = 'Length Required',
[412] = 'Precondition Failed',
[413] = 'Request Entity Too Large',
[414] = 'Request-URI Too Large',
[415] = 'Unsupported Media Type',
[416] = 'Requested Range Not Satisfiable',
[417] = 'Expectation Failed',
[418] = "I'm a teapot", -- RFC 2324
[422] = 'Unprocessable Entity', -- RFC 4918
[423] = 'Locked', -- RFC 4918
[424] = 'Failed Dependency', -- RFC 4918
[425] = 'Unordered Collection', -- RFC 4918
[426] = 'Upgrade Required', -- RFC 2817
[428] = 'Precondition Required', -- RFC 6585
[429] = 'Too Many Requests', -- RFC 6585
[431] = 'Request Header Fields Too Large', -- RFC 6585
[500] = 'Internal Server Error',
[501] = 'Not Implemented',
[502] = 'Bad Gateway',
[503] = 'Service Unavailable',
[504] = 'Gateway Time-out',
[505] = 'HTTP Version not supported',
[506] = 'Variant Also Negotiates', -- RFC 2295
[507] = 'Insufficient Storage', -- RFC 4918
[509] = 'Bandwidth Limit Exceeded',
[510] = 'Not Extended', -- RFC 2774
[511] = 'Network Authentication Required' -- RFC 6585
}
local function encoder()
local mode
local encodeHead, encodeRaw, encodeChunked
function encodeHead(item)
if not item or item == "" then
return item
elseif not (type(item) == "table") then
error("expected a table but got a " .. type(item) .. " when encoding data")
end
local head, chunkedEncoding
local version = item.version or 1.1
if item.method then
local path = item.path
assert(path and #path > 0, "expected non-empty path")
head = { item.method .. ' ' .. item.path .. ' HTTP/' .. version .. '\r\n' }
else
local reason = item.reason or STATUS_CODES[item.code]
head = { 'HTTP/' .. version .. ' ' .. item.code .. ' ' .. reason .. '\r\n' }
end
for i = 1, #item do
local key, value = unpack(item[i])
local lowerKey = lower(key)
if lowerKey == "transfer-encoding" then
chunkedEncoding = lower(value) == "chunked"
end
value = gsub(tostring(value), "[\r\n]+", " ")
head[#head + 1] = key .. ': ' .. tostring(value) .. '\r\n'
end
head[#head + 1] = '\r\n'
mode = chunkedEncoding and encodeChunked or encodeRaw
return concat(head)
end
function encodeRaw(item)
if type(item) ~= "string" then
mode = encodeHead
return encodeHead(item)
end
return item
end
function encodeChunked(item)
if type(item) ~= "string" then
mode = encodeHead
local extra = encodeHead(item)
if extra then
return "0\r\n\r\n" .. extra
else
return "0\r\n\r\n"
end
end
if #item == 0 then
mode = encodeHead
end
return format("%x", #item) .. "\r\n" .. item .. "\r\n"
end
mode = encodeHead
return function (item)
return mode(item)
end
end
local function decoder()
-- This decoder is somewhat stateful with 5 different parsing states.
local decodeHead, decodeEmpty, decodeRaw, decodeChunked, decodeCounted
local mode -- state variable that points to various decoders
local bytesLeft -- For counted decoder
-- This state is for decoding the status line and headers.
function decodeHead(chunk, index)
if not chunk or index > #chunk then return end
local _, last = find(chunk, "\r?\n\r?\n", index)
-- First make sure we have all the head before continuing
if not last then
if (#chunk - index) <= 8 * 1024 then return end
-- But protect against evil clients by refusing heads over 8K long.
error("entity too large")
end
-- Parse the status/request line
local head = {}
local _, offset
local version
_, offset, version, head.code, head.reason =
find(chunk, "^HTTP/(%d%.%d) (%d+) ([^\r\n]*)\r?\n", index)
if offset then
head.code = tonumber(head.code)
else
_, offset, head.method, head.path, version =
find(chunk, "^(%u+) ([^ ]+) HTTP/(%d%.%d)\r?\n", index)
if not offset then
error("expected HTTP data")
end
end
version = tonumber(version)
head.version = version
head.keepAlive = version > 1.0
-- We need to inspect some headers to know how to parse the body.
local contentLength
local chunkedEncoding
-- Parse the header lines
while true do
local key, value
_, offset, key, value = find(chunk, "^([^:\r\n]+): *([^\r\n]*)\r?\n", offset + 1)
if not offset then break end
local lowerKey = lower(key)
-- Inspect a few headers and remember the values
if lowerKey == "content-length" then
contentLength = tonumber(value)
elseif lowerKey == "transfer-encoding" then
chunkedEncoding = lower(value) == "chunked"
elseif lowerKey == "connection" then
head.keepAlive = lower(value) == "keep-alive"
end
head[#head + 1] = {key, value}
end
if head.keepAlive and (not (chunkedEncoding or (contentLength and contentLength > 0)))
or (head.method == "GET" or head.method == "HEAD") then
mode = decodeEmpty
elseif chunkedEncoding then
mode = decodeChunked
elseif contentLength then
bytesLeft = contentLength
mode = decodeCounted
elseif not head.keepAlive then
mode = decodeRaw
end
return head, last + 1
end
-- This is used for inserting a single empty string into the output string for known empty bodies
function decodeEmpty(chunk, index)
mode = decodeHead
return "", index
end
function decodeRaw(chunk, index)
if #chunk < index then return end
return sub(chunk, index)
end
function decodeChunked(chunk, index)
local header = match(chunk, "^[^\r\n]+\r\n", index)
if not header then
if #chunk - index > 8192 then
error("chunk-size header too large")
end
return
end
-- we ignore chunk extensions
local len = match(header, "^(%x+)")
-- But protect against evil clients by refusing chunk-sizes longer than 16 hex digits.
if not len or #len > 16 then
error("invalid chunk-size")
end
index = index + #header
local offset = index - 1
local length = tonumber(len, 16)
if #chunk < offset + length + 2 then return end
if length == 0 then
mode = decodeHead
end
assert(sub(chunk, index + length, index + length + 1) == "\r\n")
local piece = sub(chunk, index, index + length - 1)
return piece, index + length + 2
end
function decodeCounted(chunk, index)
if bytesLeft == 0 then
mode = decodeEmpty
return mode(chunk, index)
end
local offset = index - 1
local length = #chunk - offset
-- Make sure we have at least one byte to process
if length == 0 then return end
-- If there isn't enough data left, emit what we got so far
if length < bytesLeft then
bytesLeft = bytesLeft - length
return sub(chunk, index)
end
mode = decodeEmpty
return sub(chunk, index, offset + bytesLeft), index + bytesLeft
end
-- Switch between states by changing which decoder mode points to
mode = decodeHead
return function (chunk, index)
return mode(chunk, index)
end
end
return {
encoder = encoder,
decoder = decoder,
}
| apache-2.0 |
Lsty/ygopro-scripts | c16708652.lua | 3 | 1832 | --カラクリ粉
function c16708652.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c16708652.condition)
e1:SetTarget(c16708652.target)
e1:SetOperation(c16708652.activate)
c:RegisterEffect(e1)
end
function c16708652.condition(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return ph==PHASE_BATTLE or (ph==PHASE_DAMAGE and not Duel.IsDamageCalculated())
end
function c16708652.filter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsSetCard(0x11)
end
function c16708652.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c16708652.filter,tp,LOCATION_MZONE,LOCATION_MZONE,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(16708652,0))
local g1=Duel.SelectTarget(tp,c16708652.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(16708652,1))
local g2=Duel.SelectTarget(tp,c16708652.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,g1:GetFirst())
e:SetLabelObject(g1:GetFirst())
end
function c16708652.activate(e,tp,eg,ep,ev,re,r,rp)
local tc1=e:GetLabelObject()
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local tc2=g:GetFirst()
if tc1==tc2 then tc2=g:GetNext() end
if tc1:IsRelateToEffect(e) and tc1:IsPosition(POS_FACEUP_ATTACK) and tc2:IsRelateToEffect(e) then
Duel.ChangePosition(tc1,POS_FACEUP_DEFENCE)
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(tc1:GetAttack())
tc2:RegisterEffect(e1)
end
end
| gpl-2.0 |
colesbury/cudnn.torch | SpatialConvolution.lua | 1 | 9718 | local SpatialConvolution, parent =
torch.class('cudnn.SpatialConvolution', 'nn.SpatialConvolution')
local ffi = require 'ffi'
local errcheck = cudnn.errcheck
function SpatialConvolution:__init(nInputPlane, nOutputPlane,
kW, kH, dW, dH, padW, padH, groups)
parent.__init(self, nInputPlane, nOutputPlane, kW, kH, dW, dH)
self.padW = padW or 0
self.padH = padH or 0
self.groups = groups or 1
assert(nInputPlane % self.groups == 0,
'nInputPlane should be divisible by nGroups')
assert(nOutputPlane % self.groups == 0,
'nOutputPlane should be divisible by nGroups')
self.weight = torch.Tensor(nOutputPlane, nInputPlane/self.groups, kW, kH)
self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane/self.groups, kW, kH)
self:reset()
self.iSize = torch.LongStorage(4):fill(0)
end
-- if you change the configuration of the module manually, call this
function SpatialConvolution:resetWeightDescriptors()
assert(torch.typename(self.weight) == 'torch.CudaTensor',
'Only Cuda supported duh!')
assert(torch.typename(self.bias) == 'torch.CudaTensor',
'Only Cuda supported duh!')
-- for compatibility
self.groups = self.groups or 1
-- create filterDescriptor for weight
self.weightDesc = ffi.new('struct cudnnFilterStruct*[1]')
errcheck('cudnnCreateFilterDescriptor', self.weightDesc)
local desc = torch.IntTensor({self.nOutputPlane/self.groups,
self.nInputPlane/self.groups,
self.kH, self.kW})
errcheck('cudnnSetFilterNdDescriptor', self.weightDesc[0],
'CUDNN_DATA_FLOAT', 4,
desc:data());
local function destroyWDesc(d)
errcheck('cudnnDestroyFilterDescriptor', d[0]);
end
ffi.gc(self.weightDesc, destroyWDesc)
-- create descriptor for bias
local bias_slice = {{}, {1,self.nOutputPlane/self.groups}, {}, {}}
self.biasDesc = cudnn.toDescriptor(self.bias:view(1, self.nOutputPlane,1,1)[bias_slice])
end
function SpatialConvolution:fastest(mode)
if mode == nil then mode = true end
self.fastest_mode = mode
return self
end
function SpatialConvolution:createIODescriptors(input)
local batch = true
if input:dim() == 3 then
input = input:view(1, input:size(1), input:size(2), input:size(3))
batch = false
end
assert(input:dim() == 4 and input:isContiguous());
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
self.iSize = input:size()
-- resize gradInput
if self.gradInput then self.gradInput:resizeAs(input); end
assert(self.nInputPlane == input:size(2), 'input has to contain: '
.. self.nInputPlane
.. ' feature maps, but received input of size: '
.. input:size(1) .. ' x ' .. input:size(2) ..
' x ' .. input:size(3) .. ' x ' .. input:size(4))
-- create input descriptor
local input_slice = {{},{1,self.nInputPlane/self.groups},{},{}}
self.iDesc = cudnn.toDescriptor(input[input_slice])
-- create conv descriptor
self.convDesc = ffi.new('struct cudnnConvolutionStruct*[1]')
errcheck('cudnnCreateConvolutionDescriptor', self.convDesc)
local pad = torch.IntTensor({self.padH, self.padW})
local stride = torch.IntTensor({self.dH, self.dW})
local upscale = torch.IntTensor({1,1})
errcheck('cudnnSetConvolutionNdDescriptor', self.convDesc[0],
2, pad:data(),
stride:data(), upscale:data(), 'CUDNN_CROSS_CORRELATION');
local function destroyConvDesc(d)
errcheck('cudnnDestroyConvolutionDescriptor', d[0]);
end
ffi.gc(self.convDesc, destroyConvDesc)
-- create output descriptor and resize output
local oSize = torch.IntTensor(4)
local oSizeD = oSize:data()
errcheck('cudnnGetConvolutionNdForwardOutputDim',
self.convDesc[0], self.iDesc[0],
self.weightDesc[0], 4, oSizeD)
oSize[2] = oSize[2] * self.groups
self.output:resize(oSize:long():storage())
-- create descriptor for output
local output_slice = {{},{1,self.nOutputPlane/self.groups},{},{}}
self.oDesc = cudnn.toDescriptor(self.output[output_slice])
-- create forwardAlgorithm descriptors for
local algType = ffi.new("cudnnConvolutionFwdAlgo_t[?]", 1)
local algSearchMode = 'CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT'
local algWorkspaceLimit = self.nInputPlane * self.kH * self.kW * 4 -- 4 = sizeof int.
if self.fastest_mode then algSearchMode = 'CUDNN_CONVOLUTION_FWD_PREFER_FASTEST' end
errcheck('cudnnGetConvolutionForwardAlgorithm',
cudnn.getHandle(),
self.iDesc[0], self.weightDesc[0],
self.convDesc[0], self.oDesc[0],
algSearchMode, algWorkspaceLimit, algType)
self.algType = algType
local bufSize = torch.LongTensor(1)
errcheck('cudnnGetConvolutionForwardWorkspaceSize',
cudnn.getHandle(),
self.iDesc[0], self.weightDesc[0],
self.convDesc[0], self.oDesc[0],
algType[0], bufSize:data())
self.extraBuffer = self.extraBuffer or input.new(1)
if bufSize[1] ~= 0 then self.extraBuffer:resize(bufSize[1]) end
-- create offsets for groups
self.input_offset = self.nInputPlane/self.groups*input:size(3)*input:size(4)
self.output_offset = self.nOutputPlane/self.groups*oSize[3]*oSize[4]
self.weight_offset =
self.nInputPlane/self.groups*self.nOutputPlane/self.groups*self.kW*self.kH
self.bias_offset = self.nOutputPlane/self.groups
if not batch then
self.gradInput = self.gradInput:view(self.gradInput:size(2),
self.gradInput:size(3),
self.gradInput:size(4))
self.output = self.output:view(self.output:size(2),
self.output:size(3),
self.output:size(4))
end
end
end
local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});
function SpatialConvolution:updateOutput(input)
if not self.weightDesc then self:resetWeightDescriptors() end
self:createIODescriptors(input)
for g=0,self.groups-1 do
errcheck('cudnnConvolutionForward', cudnn.getHandle(),
one:data(),
self.iDesc[0], input:data() + g*self.input_offset,
self.weightDesc[0], self.weight:data() + g*self.weight_offset,
self.convDesc[0], self.algType[0],
self.extraBuffer:data(), self.extraBuffer:nElement(),
zero:data(),
self.oDesc[0], self.output:data() + g*self.output_offset);
errcheck('cudnnAddTensor', cudnn.getHandle(),
'CUDNN_ADD_SAME_C',
one:data(), self.biasDesc[0], self.bias:data() + g*self.bias_offset,
one:data(), self.oDesc[0], self.output:data() + g*self.output_offset);
end
return self.output
end
function SpatialConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
assert((gradOutput:dim() == 3 or gradOutput:dim() == 4)
and gradOutput:isContiguous());
if not self.weightDesc then self:resetWeightDescriptors() end
self:createIODescriptors(input)
for g=0,self.groups-1 do
errcheck('cudnnConvolutionBackwardData', cudnn.getHandle(),
one:data(),
self.weightDesc[0], self.weight:data() + g*self.weight_offset,
self.oDesc[0], gradOutput:data() + g*self.output_offset,
self.convDesc[0],
zero:data(),
self.iDesc[0], self.gradInput:data() + g*self.input_offset);
end
return self.gradInput
end
function SpatialConvolution:accGradParameters(input, gradOutput, scale)
self.scaleT = self.scaleT or torch.FloatTensor(1):fill(1.0)
-- this line forces this member to always be on CPU (needed for cudnn)
self.scaleT = self.scaleT:float()
scale = scale or 1.0
self.scaleT[1] = scale
assert((gradOutput:dim() == 3 or gradOutput:dim() == 4)
and gradOutput:isContiguous());
self:createIODescriptors(input)
if not self.weightDesc then self:resetWeightDescriptors() end
for g=0,self.groups-1 do
-- gradBias
errcheck('cudnnConvolutionBackwardBias', cudnn.getHandle(),
self.scaleT:data(),
self.oDesc[0], gradOutput:data() + g*self.output_offset,
one:data(),
self.biasDesc[0], self.gradBias:data() + g*self.bias_offset);
-- gradWeight
errcheck('cudnnConvolutionBackwardFilter', cudnn.getHandle(),
self.scaleT:data(),
self.iDesc[0], input:data() + g*self.input_offset,
self.oDesc[0], gradOutput:data() + g*self.output_offset,
self.convDesc[0],
one:data(),
self.weightDesc[0], self.gradWeight:data() + g*self.weight_offset);
end
end
--[[
function SpatialConvolution:zeroGradParameters()
-- gradWeight, gradBias to zero
errcheck('cudnnSetTensor', cudnn.getHandle(),
self.weightDesc, self.gradWeight:data(), zero:data());
errcheck('cudnnSetTensor', cudnn.getHandle(),
self.biasDesc, self.gradBias:data(), zero:data());
end
]]--
| bsd-2-clause |
Mike325/.vim | lua/plugins/snippets/lua.lua | 1 | 8393 | local load_module = require('utils.helpers').load_module
local ls = load_module 'luasnip'
if not ls then
return false
end
local s = ls.snippet
local sn = ls.snippet_node
local t = ls.text_node
-- local isn = ls.indent_snippet_node
local i = ls.insert_node
local f = ls.function_node
local c = ls.choice_node
local d = ls.dynamic_node
-- local l = require('luasnip.extras').lambda
local r = require('luasnip.extras').rep
-- local p = require('luasnip.extras').partial
-- local m = require('luasnip.extras').match
-- local n = require('luasnip.extras').nonempty
-- local dl = require('luasnip.extras').dynamic_lambda
local fmt = require('luasnip.extras.fmt').fmt
-- local fmta = require('luasnip.extras.fmt').fmta
-- local types = require 'luasnip.util.types'
-- local events = require 'luasnip.util.events'
-- local conds = require 'luasnip.extras.expand_conditions'
local utils = RELOAD 'plugins.snippets.utils'
local saved_text = utils.saved_text
local get_comment = utils.get_comment
local surround_with_func = utils.surround_with_func
local function else_clause(args, snip, old_state, placeholder)
local nodes = {}
if snip.captures[1] == 'e' then
table.insert(nodes, t { '', 'else', '\t' })
table.insert(nodes, i(1, get_comment 'code'))
else
table.insert(nodes, t { '' })
end
local snip_node = sn(nil, nodes)
snip_node.old_state = old_state
return snip_node
end
local function rec_val()
return sn(nil, {
c(1, {
t { '' },
sn(nil, {
t { ',', '\t' },
i(1, 'arg'),
t { ' = { ' },
r(1),
t { ', ' },
c(2, {
i(1, "'string'"),
i(1, "'table'"),
i(1, "'function'"),
i(1, "'number'"),
i(1, "'boolean'"),
}),
c(3, {
t { '' },
t { ', true' },
}),
t { ' }' },
d(4, rec_val, {}),
}),
}),
})
end
-- TODO: Add pcall snippet and use TS to parse saved function and separete the funcion name and the args
-- stylua: ignore
ls.snippets.lua = {
s(
{ trig = "(l?)fun", regTrig = true },
fmt([[
{}function {}({}) {{
{}
}}
]], {
f(function(_, snip)
-- stylua: ignore
return snip.captures[1] == 'l' and 'local ' or ''
end, {}),
i(1, 'name'),
i(2, 'args'),
d(3, saved_text, {}, {indent = true}),
}
)),
s('for', fmt([[
for {}, {} in ipairs({}) do
{}
end
]], {
i(1, 'k'),
i(2, 'v'),
i(3, 'tbl'),
d(4, saved_text, {}, {indent = true}),
})),
s('forp', fmt([[
for {}, {} in pairs({}) do
{}
end
]], {
i(1, 'k'),
i(2, 'v'),
i(3, 'tbl'),
d(4, saved_text, {}, {indent = true}),
})),
s('fori', fmt([[
for {} = {}, {} do
{}
end
]], {
i(1, 'idx'),
i(2, '0'),
i(3, '10'),
d(4, saved_text, {}, {indent = true}),
})),
s(
{ trig = "if(e?)", regTrig = true },
{
t{"if "}, i(1, 'condition'), t{" then", ""},
d(2, saved_text, {}, {indent = true}),
d(3, else_clause, {}, {}),
t{"", "end"},
}
),
s('w', fmt([[
while {} do
{}
end
]], {
i(1, 'true'),
d(2, saved_text, {}, {text = ':', indent = true}),
})),
s('elif', fmt([[
elif {} {{
{}
}}
]],{
i(1, 'condition'),
d(2, saved_text, {}, {indent = true}),
})),
s("req", fmt([[require "{}"]], {
i(1, 'module'),
})),
s("l", fmt([[local {} = {}]], {
i(1, 'var'),
i(2, '{}'),
})),
s("ign", { t{"-- stylua: ignore"} }),
s("sty", { t{"-- stylua: ignore"} }),
s("map", {
t{"vim.keymap.set("},
t{"'"}, i(1, 'n'), t{"', "},
t{"\t'"}, i(2, 'LHS'), t{"', "},
t{"\t'"}, i(3, 'RHS'), t{"', "},
t{"\t{"}, i(4, 'noremap = true'), t{"}"},
t{")"},
}),
s("val", {
t({"vim.validate {"}),
t{'', "\t"}, i(1, 'arg'), t{" = { "}, r(1), t{", "},
c(2, {
i(1, "'string'"),
i(1, "'table'"),
i(1, "'function'"),
i(1, "'number'"),
i(1, "'boolean'"),
}),
c(3, {
t{""},
t{", true"},
}),
t({" }"}),
d(4, rec_val, {}),
t({'', "}"}),
}),
s("com", {
t{"set_command {", ""},
t{"\tlhs = '"}, i(1, 'Command'), t{"',", ""},
t{"\trhs = '"}, i(2, 'lua P(true)'), t{"',", ""},
t{"\targs = { force = true, "}, i(3, "nargs = '?', "), t{"},", ""},
t{"}"},
}),
s("au", {
t{"set_autocmd {", ""},
t{"\tevent = '"}, i(1, 'FileType'), t{"',", ""},
t{"\tpattern = '"}, i(2, '*'), t{"',", ""},
t{"\tcmd = '"}, i(3, 'lua P(true)'), t{"',", ""},
t{"\tgroup = '"}, i(4, 'NewGroup'), t{"',", ""},
t{"}"},
}),
s('lext', fmt([[vim.list_extend({}, {})]],{
d(1, surround_with_func, {}, {text = 'tbl'}),
i(2, "'node'"),
})),
s('text', fmt([[vim.tbl_extend('{}', {}, {})]],{
c(1, {
t{'force'},
t{'keep'},
t{'error'},
}),
d(2, surround_with_func, {}, {text = 'tbl'}),
i(3, "'node'"),
})),
s('not', fmt([[vim.notify("{}", "{}"{})]],{
d(1, surround_with_func, {}, {text = 'msg'}),
c(2, {
t{'INFO'},
t{'WARN'},
t{'ERROR'},
t{'DEBUG'},
}),
c(3, {
t{''},
sn(nil, { t{', { title = '}, i(1, "'title'"), t{' }'} }),
}),
})),
s('use', fmt([[use {{ '{}' }}]],{
i(1, 'plugin'),
})),
s('desc', fmt([[
describe('{}', funcion()
it('{}', funcion()
{}
end)
end)
]],{
i(1, 'DESCRIPTION'),
i(2, 'DESCRIPTION'),
i(3, '-- test'),
})),
s('it', fmt([[
it('{}', funcion()
{}
end)
]],{
i(1, 'DESCRIPTION'),
i(2, '-- test'),
})),
s(
{ trig = '(n?)eq', regTrig = true },
fmt([[assert.{}({}, {})]],{
f(function(_, snip)
-- stylua: ignore
if snip.captures[1] == 'n' then
-- stylua: ignore
return 'are_not.same('
end
-- stylua: ignore
return 'are.same('
end, {}),
i(1, 'expected'),
i(2, 'result'),
})),
s(
{ trig = '(n?)eq', regTrig = true },
fmt([[assert.{}({}, {})]],{
f(function(_, snip)
-- stylua: ignore
if snip.captures[1] == 'n' then
-- stylua: ignore
return 'are_not.equal('
end
-- stylua: ignore
return 'are.equal('
end, {}),
i(1, 'expected'),
i(2, 'result'),
})),
s('haserr', fmt([[assert.has.error(function() {} end{})]],{
i(1, 'error()'),
c(2, {
t{''},
sn(nil, { t{", '"}, i(1, 'error'), t{"'"} }),
}),
})),
s(
{ trig = 'is(_?)true', regTrig = true },
fmt([[assert.is_true({})]], {
d(1, surround_with_func, {}, {text = 'true'}),
}
)),
s(
{ trig = 'is(_?)false', regTrig = true },
fmt([[assert.is_false({})]], {
d(1, surround_with_func, {}, {text = 'false'}),
}
)),
s('pr', fmt([[print({})]],{
i(1, 'msg'),
})),
s('istruthy', fmt([[assert.is_truthy({})]],{ d(1, surround_with_func, {}, {text = 'true'}), })),
s('isfalsy', fmt([[assert.is_falsy({})]],{ d(1, surround_with_func, {}, {text = 'false'}), })),
s('truthy', fmt([[assert.is_truthy({})]],{ d(1, surround_with_func, {}, {text = 'true'}), })),
s('falsy', fmt([[assert.is_falsy({})]],{ d(1, surround_with_func, {}, {text = 'false'}), })),
}
| mit |
Lsty/ygopro-scripts | c53408006.lua | 3 | 1672 | --ジェム・マーチャント
function c53408006.initial_effect(c)
--atk,def up
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetDescription(aux.Stringid(53408006,0))
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetRange(LOCATION_HAND)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(c53408006.condition)
e1:SetCost(c53408006.cost)
e1:SetOperation(c53408006.operation)
c:RegisterEffect(e1)
end
function c53408006.filter(c)
return c:IsAttribute(ATTRIBUTE_EARTH) and c:IsType(TYPE_NORMAL)
end
function c53408006.condition(e,tp,eg,ep,ev,re,r,rp)
local phase=Duel.GetCurrentPhase()
if phase~=PHASE_DAMAGE or Duel.IsDamageCalculated() then return false end
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
return (a:GetControler()==tp and c53408006.filter(a) and a:IsRelateToBattle())
or (d and d:GetControler()==tp and d:IsFaceup() and c53408006.filter(d) and d:IsRelateToBattle())
end
function c53408006.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c53408006.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local a=Duel.GetAttacker()
if Duel.GetTurnPlayer()~=tp then a=Duel.GetAttackTarget() end
if not a:IsRelateToBattle() then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e1:SetValue(1000)
a:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENCE)
a:RegisterEffect(e2)
end
| gpl-2.0 |
mikhail-angelov/vlc | share/lua/playlist/france2.lua | 113 | 2115 | --[[
$Id$
Copyright © 2008 the VideoLAN team
Authors: Antoine Cellerier <dionoea 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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "jt.france2.fr/player/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "class=\"editiondate\"" ) then
_,_,editiondate = string.find( line, "<h1>(.-)</h1>" )
end
if string.match( line, "mms.*%.wmv" ) then
_,_,video = string.find( line, "mms(.-%.wmv)" )
video = "mmsh"..video
table.insert( p, { path = video; name = editiondate } )
end
if string.match( line, "class=\"subjecttimer\"" ) then
oldtime = time
_,_,time = string.find( line, "href=\"(.-)\"" )
if oldtime then
table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } )
end
name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) )
end
end
if oldtime then
table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } )
end
return p
end
| gpl-2.0 |
Lsty/ygopro-scripts | c31786629.lua | 3 | 1154 | --サンダー・ドラゴン
function c31786629.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(31786629,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCost(c31786629.cost)
e1:SetTarget(c31786629.target)
e1:SetOperation(c31786629.operation)
c:RegisterEffect(e1)
end
function c31786629.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsDiscardable() end
Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD)
end
function c31786629.filter(c)
return c:GetCode()==31786629 and c:IsAbleToHand()
end
function c31786629.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.IsExistingMatchingCard(c31786629.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c31786629.operation(e,tp,eg,ep,ev,re,r,rp,chk)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c31786629.filter,tp,LOCATION_DECK,0,1,2,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c33725002.lua | 3 | 4208 | --Vサラマンダー
function c33725002.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(33725002,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c33725002.sptg)
e1:SetOperation(c33725002.spop)
c:RegisterEffect(e1)
--equip
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(33725002,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCategory(CATEGORY_EQUIP)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c33725002.eqtg)
e2:SetOperation(c33725002.eqop)
c:RegisterEffect(e2)
--destroy
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(33725002,2))
e3:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1)
e3:SetCost(c33725002.descost)
e3:SetTarget(c33725002.destg)
e3:SetOperation(c33725002.desop)
c:RegisterEffect(e3)
end
function c33725002.spfilter(c,e,tp)
return c:IsSetCard(0x7f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c33725002.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c33725002.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c33725002.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c33725002.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c33725002.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 c33725002.eqfilter(c)
return c:IsFaceup() and c:IsCode(66970002)
end
function c33725002.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c33725002.eqfilter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c33725002.eqfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c33725002.eqfilter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c33725002.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) or c:IsFacedown() then return end
local tc=Duel.GetFirstTarget()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsRelateToEffect(e) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
Duel.Equip(tp,c,tc,true)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c33725002.eqlimit)
c:RegisterEffect(e1)
end
function c33725002.eqlimit(e,c)
return c:IsSetCard(0x7f)
end
function c33725002.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetEquipTarget():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():GetEquipTarget():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c33725002.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDestructable,tp,0,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,g:GetCount()*1000)
end
function c33725002.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetEquipTarget()
if ec then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
ec:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
ec:RegisterEffect(e2)
end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_MZONE,nil)
local ct=Duel.Destroy(g,REASON_EFFECT)
if ct>0 then
Duel.Damage(1-tp,ct*1000,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/weaponskills/heavy_shot.lua | 10 | 1373 | -----------------------------------
-- Heavy Shot
-- Marksmanship weapon skill
-- Skill Level: 225
-- Delivers a single-hit attack. Chance of params.critical varies with TP.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: AGI:30%
-- 100%TP 200%TP 300%TP
-- 3.50 3.50 3.50
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 3.5 params.ftp200 = 3.5 params.ftp300 = 3.5
params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.3 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.1 params.crit200 = 0.3 params.crit300 = 0.5
params.canCrit = true
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.agi_wsc = 0.7
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
Frenzie/koreader | plugins/newsdownloader.koplugin/main.lua | 1 | 39830 | local BD = require("ui/bidi")
local DataStorage = require("datastorage")
--local DownloadBackend = require("internaldownloadbackend")
--local DownloadBackend = require("luahttpdownloadbackend")
local DownloadBackend = require("epubdownloadbackend")
local ReadHistory = require("readhistory")
local FFIUtil = require("ffi/util")
local FeedView = require("feed_view")
local InfoMessage = require("ui/widget/infomessage")
local LuaSettings = require("frontend/luasettings")
local UIManager = require("ui/uimanager")
local KeyValuePage = require("ui/widget/keyvaluepage")
local InputDialog = require("ui/widget/inputdialog")
local MultiConfirmBox = require("ui/widget/multiconfirmbox")
local NetworkMgr = require("ui/network/manager")
local Persist = require("persist")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local dateparser = require("lib.dateparser")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local util = require("util")
local _ = require("gettext")
local T = FFIUtil.template
local NewsDownloader = WidgetContainer:extend{
name = "news_downloader",
initialized = false,
feed_config_file = "feed_config.lua",
feed_config_path = nil,
news_config_file = "news_settings.lua",
settings = nil,
download_dir_name = "news",
download_dir = nil,
file_extension = ".epub",
config_key_custom_dl_dir = "custom_dl_dir",
empty_feed = {
[1] = "https://",
limit = 5,
download_full_article = true,
include_images = true,
enable_filter = false,
filter_element = ""
},
kv = nil, -- KeyValuePage
}
local FEED_TYPE_RSS = "rss"
local FEED_TYPE_ATOM = "atom"
--local initialized = false
--local feed_config_file_name = "feed_config.lua"
--local news_downloader_config_file = "news_downloader_settings.lua
-- If a title looks like <title>blabla</title> it'll just be feed.title.
-- If a title looks like <title attr="alb">blabla</title> then we get a table
-- where [1] is the title string and the attributes are also available.
local function getFeedTitle(possible_title)
if type(possible_title) == "string" then
return util.htmlEntitiesToUtf8(possible_title)
elseif possible_title[1] and type(possible_title[1]) == "string" then
return util.htmlEntitiesToUtf8(possible_title[1])
end
end
-- There can be multiple links.
-- For now we just assume the first link is probably the right one.
--- @todo Write unit tests.
-- Some feeds that can be used for unit test.
-- http://fransdejonge.com/feed/ for multiple links.
-- https://github.com/koreader/koreader/commits/master.atom for single link with attributes.
local function getFeedLink(possible_link)
local E = {}
if type(possible_link) == "string" then
return possible_link
elseif (possible_link._attr or E).href then
return possible_link._attr.href
elseif ((possible_link[1] or E)._attr or E).href then
return possible_link[1]._attr.href
end
end
function NewsDownloader:init()
self.ui.menu:registerToMainMenu(self)
end
function NewsDownloader:addToMainMenu(menu_items)
menu_items.news_downloader = {
text = _("News downloader (RSS/Atom)"),
sub_item_table_func = function()
return self:getSubMenuItems()
end,
}
end
function NewsDownloader:getSubMenuItems()
self:lazyInitialization()
local sub_item_table
sub_item_table = {
{
text = _("Go to news folder"),
callback = function()
self:openDownloadsFolder()
end,
},
{
text = _("Sync news feeds"),
keep_menu_open = true,
callback = function(touchmenu_instance)
NetworkMgr:runWhenOnline(function() self:loadConfigAndProcessFeedsWithUI(touchmenu_instance) end)
end,
},
{
text = _("Edit news feeds"),
keep_menu_open = true,
callback = function()
local Trapper = require("ui/trapper")
Trapper:wrap(function()
self:viewFeedList()
end)
end,
},
{
text = _("Settings"),
sub_item_table = {
{
text = _("Set download folder"),
keep_menu_open = true,
callback = function() self:setCustomDownloadDirectory() end,
},
{
text = _("Never download images"),
keep_menu_open = true,
checked_func = function()
return self.settings:isTrue("never_download_images")
end,
callback = function()
self.settings:toggle("never_download_images")
self.settings:flush()
end,
},
{
text = _("Delete all downloaded items"),
keep_menu_open = true,
callback = function()
local Trapper = require("ui/trapper")
Trapper:wrap(function()
local should_delete = Trapper:confirm(
_("Are you sure you want to delete all downloaded items?"),
_("Cancel"),
_("Delete")
)
if should_delete then
self:removeNewsButKeepFeedConfig()
Trapper:reset()
else
Trapper:reset()
end
end)
end,
},
},
},
{
text = _("About"),
keep_menu_open = true,
callback = function()
UIManager:show(InfoMessage:new{
text = T(_("News downloader retrieves RSS and Atom news entries and stores them to:\n%1\n\nEach entry is a separate EPUB file that can be browsed by KOReader.\nFeeds can be configured with download limits and other customization through the Edit Feeds menu item."),
BD.dirpath(self.download_dir))
})
end,
},
}
return sub_item_table
end
-- lazyInitialization sets up variables that point to the
-- Downloads folder and the feeds configuration file.
function NewsDownloader:lazyInitialization()
if not self.initialized then
logger.dbg("NewsDownloader: obtaining news folder")
self.settings = LuaSettings:open(("%s/%s"):format(DataStorage:getSettingsDir(), self.news_config_file))
-- Check to see if a custom download directory has been set.
if self.settings:has(self.config_key_custom_dl_dir) then
self.download_dir = self.settings:readSetting(self.config_key_custom_dl_dir)
else
self.download_dir =
("%s/%s/"):format(
DataStorage:getFullDataDir(),
self.download_dir_name)
end
logger.dbg("NewsDownloader: Custom directory set to:", self.download_dir)
-- If the directory doesn't exist we will create it.
if not lfs.attributes(self.download_dir, "mode") then
logger.dbg("NewsDownloader: Creating initial directory")
lfs.mkdir(self.download_dir)
end
-- Now set the path to the feed configuration file.
self.feed_config_path = self.download_dir .. self.feed_config_file
-- If the configuration file doesn't exist create it.
if not lfs.attributes(self.feed_config_path, "mode") then
logger.dbg("NewsDownloader: Creating initial feed config.")
FFIUtil.copyFile(FFIUtil.joinPath(self.path, self.feed_config_file),
self.feed_config_path)
end
self.initialized = true
end
end
function NewsDownloader:loadConfigAndProcessFeeds(touchmenu_instance)
local UI = require("ui/trapper")
logger.dbg("force repaint due to upcoming blocking calls")
local ok, feed_config = pcall(dofile, self.feed_config_path)
if not ok or not feed_config then
UI:info(T(_("Invalid configuration file. Detailed error message:\n%1"), feed_config))
return
end
-- If the file contains no table elements, then the user hasn't set any feeds.
if #feed_config <= 0 then
logger.err("NewsDownloader: empty feed list.", self.feed_config_path)
local should_edit_feed_list = UI:confirm(
T(_("Feed list is empty. If you want to download news, you'll have to add a feed first.")),
_("Close"),
_("Edit feed list")
)
if should_edit_feed_list then
-- Show the user a blank feed view so they can
-- add a feed to their list.
local feed_item_vc = FeedView:getItem(
1,
self.empty_feed,
function(id, edit_key, value)
self:editFeedAttribute(id, edit_key, value)
end
)
self:viewFeedItem(
feed_item_vc
)
end
return
end
local never_download_images = self.settings:isTrue("never_download_images")
local unsupported_feeds_urls = {}
local total_feed_entries = #feed_config
local feed_message
for idx, feed in ipairs(feed_config) do
local url = feed[1]
local limit = feed.limit
local download_full_article = feed.download_full_article == nil or feed.download_full_article
local include_images = not never_download_images and feed.include_images
local enable_filter = feed.enable_filter or feed.enable_filter == nil
local filter_element = feed.filter_element or feed.filter_element == nil
-- Check if the two required attributes are set.
if url and limit then
feed_message = T(_("Processing %1/%2:\n%3"), idx, total_feed_entries, BD.url(url))
UI:info(feed_message)
-- Process the feed source.
self:processFeedSource(
url,
tonumber(limit),
unsupported_feeds_urls,
download_full_article,
include_images,
feed_message,
enable_filter,
filter_element)
else
logger.warn("NewsDownloader: invalid feed config entry.", feed)
end
end
if #unsupported_feeds_urls <= 0 then
-- When no errors are present, we get a happy message.
feed_message = _("Downloading news finished.")
else
-- When some errors are present, we get a sour message that includes
-- information about the source of the error.
local unsupported_urls = ""
for key, value in pairs(unsupported_feeds_urls) do
-- Create the error message.
unsupported_urls = unsupported_urls .. " " .. value[1] .. " " .. value[2]
-- Not sure what this does.
if key ~= #unsupported_feeds_urls then
unsupported_urls = BD.url(unsupported_urls) .. ", "
end
end
-- Tell the user there were problems.
feed_message = _("Downloading news finished with errors.")
-- Display a dialogue that requires the user to acknowledge
-- that errors occured.
UI:confirm(
T(_([[
Could not process some feeds.
Unsupported format in: %1. Please
review your feed configuration file.]])
, unsupported_urls),
_("Continue"),
""
)
end
-- Clear the info widgets before displaying the next ui widget.
UI:clear()
-- Check to see if this method was called from the menu. If it was,
-- we will have gotten a touchmenu_instance. This will context gives the user
-- two options about what to do next, which are handled by this block.
if touchmenu_instance then
-- Ask the user if they want to go to their downloads folder
-- or if they'd rather remain at the menu.
feed_message = feed_message .. _("Go to download folder?")
local should_go_to_downloads = UI:confirm(
feed_message,
_("Close"),
_("Go to downloads")
)
if should_go_to_downloads then
-- Go to downloads folder.
UI:clear()
self:openDownloadsFolder()
touchmenu_instance:closeMenu()
NetworkMgr:afterWifiAction()
return
else
-- Return to the menu.
NetworkMgr:afterWifiAction()
return
end
end
return
end
function NewsDownloader:loadConfigAndProcessFeedsWithUI(touchmenu_instance)
local Trapper = require("ui/trapper")
Trapper:wrap(function()
self:loadConfigAndProcessFeeds(touchmenu_instance)
end)
end
function NewsDownloader:processFeedSource(url, limit, unsupported_feeds_urls, download_full_article, include_images, message, enable_filter, filter_element)
local ok, response = pcall(function()
return DownloadBackend:getResponseAsString(url)
end)
local feeds
-- Check to see if a response is available to deserialize.
if ok then
feeds = self:deserializeXMLString(response)
end
-- If the response is not available (for a reason that we don't know),
-- add the URL to the unsupported feeds list.
if not ok or not feeds then
local error_message
if not ok then
error_message = _("(Reason: Failed to download content)")
else
error_message = _("(Reason: Error during feed deserialization)")
end
table.insert(
unsupported_feeds_urls,
{
url,
error_message
}
)
return
end
-- Check to see if the feed uses RSS.
local is_rss = feeds.rss
and feeds.rss.channel
and feeds.rss.channel.title
and feeds.rss.channel.item
and feeds.rss.channel.item[1]
and feeds.rss.channel.item[1].title
and feeds.rss.channel.item[1].link
-- Check to see if the feed uses Atom.
local is_atom = feeds.feed
and feeds.feed.title
and feeds.feed.entry[1]
and feeds.feed.entry[1].title
and feeds.feed.entry[1].link
-- Process the feeds accordingly.
if is_atom then
ok = pcall(function()
return self:processFeed(
FEED_TYPE_ATOM,
feeds,
limit,
download_full_article,
include_images,
message,
enable_filter,
filter_element
)
end)
elseif is_rss then
ok = pcall(function()
return self:processFeed(
FEED_TYPE_RSS,
feeds,
limit,
download_full_article,
include_images,
message,
enable_filter,
filter_element
)
end)
end
-- If the feed can't be processed, or it is neither
-- Atom or RSS, then add it to the unsupported feeds list
-- and return an error message.
if not ok or (not is_rss and not is_atom) then
local error_message
if not ok then
error_message = _("(Reason: Failed to download content)")
elseif not is_rss then
error_message = _("(Reason: Couldn't process RSS)")
elseif not is_atom then
error_message = _("(Reason: Couldn't process Atom)")
end
table.insert(
unsupported_feeds_urls,
{
url,
error_message
}
)
end
end
function NewsDownloader:deserializeXMLString(xml_str)
-- uses LuaXML https://github.com/manoelcampos/LuaXML
-- The MIT License (MIT)
-- Copyright (c) 2016 Manoel Campos da Silva Filho
-- see: koreader/plugins/newsdownloader.koplugin/lib/LICENSE_LuaXML
local treehdl = require("lib/handler")
local libxml = require("lib/xml")
-- Instantiate the object that parses the XML file as a Lua table.
local xmlhandler = treehdl.simpleTreeHandler()
-- Remove UTF-8 byte order mark, as it will cause LuaXML to fail
xml_str = xml_str:gsub("^\xef\xbb\xbf", "", 1)
-- Instantiate the object that parses the XML to a Lua table.
local ok = pcall(function()
libxml.xmlParser(xmlhandler):parse(xml_str)
end)
if not ok then return end
return xmlhandler.root
end
function NewsDownloader:processFeed(feed_type, feeds, limit, download_full_article, include_images, message, enable_filter, filter_element)
local feed_title
local feed_item
local total_items
-- Setup the above vars based on feed type.
if feed_type == FEED_TYPE_RSS then
feed_title = util.htmlEntitiesToUtf8(feeds.rss.channel.title)
feed_item = feeds.rss.channel.item
total_items = (limit == 0)
and #feeds.rss.channel.item
or limit
else
feed_title = getFeedTitle(feeds.feed.title)
feed_item = feeds.feed.entry
total_items = (limit == 0)
and #feeds.feed.entry
or limit
end
-- Get the path to the output directory.
local feed_output_dir = ("%s%s/"):format(
self.download_dir,
util.getSafeFilename(util.htmlEntitiesToUtf8(feed_title)))
-- Create the output directory if it doesn't exist.
if not lfs.attributes(feed_output_dir, "mode") then
lfs.mkdir(feed_output_dir)
end
-- Download the feed
for index, feed in pairs(feed_item) do
-- If limit has been met, stop downloading feed.
if limit ~= 0 and index - 1 == limit then
break
end
-- Create a message to display during processing.
local article_message = T(
_("%1\n\nFetching article %2/%3:"),
message,
index,
total_items
)
-- Get the feed description.
local feed_description
if feed_type == FEED_TYPE_RSS then
feed_description = feed.description
else
feed_description = feed.summary
end
-- Download the article.
if download_full_article then
self:downloadFeed(
feed,
feed_output_dir,
include_images,
article_message,
enable_filter,
filter_element
)
else
self:createFromDescription(
feed,
feed_description,
feed_output_dir,
include_images,
article_message
)
end
end
end
local function parseDate(dateTime)
-- Uses lua-feedparser https://github.com/slact/lua-feedparser
-- feedparser is available under the (new) BSD license.
-- see: koreader/plugins/newsdownloader.koplugin/lib/LICENCE_lua-feedparser
local date = dateparser.parse(dateTime)
return os.date("%y-%m-%d_%H-%M_", date)
end
-- This appears to be used by Atom feeds in processFeed.
local function getTitleWithDate(feed)
local title = util.getSafeFilename(getFeedTitle(feed.title))
if feed.updated then
title = parseDate(feed.updated) .. title
elseif feed.pubDate then
title = parseDate(feed.pubDate) .. title
elseif feed.published then
title = parseDate(feed.published) .. title
end
return title
end
function NewsDownloader:downloadFeed(feed, feed_output_dir, include_images, message, enable_filter, filter_element)
local title_with_date = getTitleWithDate(feed)
local news_file_path = ("%s%s%s"):format(feed_output_dir,
title_with_date,
self.file_extension)
local file_mode = lfs.attributes(news_file_path, "mode")
if file_mode == "file" then
logger.dbg("NewsDownloader:", news_file_path, "already exists. Skipping")
else
logger.dbg("NewsDownloader: News file will be stored to :", news_file_path)
local article_message = T(_("%1\n%2"), message, title_with_date)
local link = getFeedLink(feed.link)
local html = DownloadBackend:loadPage(link)
DownloadBackend:createEpub(news_file_path, html, link, include_images, article_message, enable_filter, filter_element)
end
end
function NewsDownloader:createFromDescription(feed, content, feed_output_dir, include_images, message)
local title_with_date = getTitleWithDate(feed)
local news_file_path = ("%s%s%s"):format(feed_output_dir,
title_with_date,
self.file_extension)
local file_mode = lfs.attributes(news_file_path, "mode")
if file_mode == "file" then
logger.dbg("NewsDownloader:", news_file_path, "already exists. Skipping")
else
logger.dbg("NewsDownloader: News file will be stored to :", news_file_path)
local article_message = T(_("%1\n%2"), message, title_with_date)
local footer = _("This is just a description of the feed. To download the full article instead, go to the News Downloader settings and change 'download_full_article' to 'true'.")
local html = string.format([[<!DOCTYPE html>
<html>
<head><meta charset='UTF-8'><title>%s</title></head>
<body><header><h2>%s</h2></header><article>%s</article>
<br><footer><small>%s</small></footer>
</body>
</html>]], feed.title, feed.title, content, footer)
local link = getFeedLink(feed.link)
DownloadBackend:createEpub(news_file_path, html, link, include_images, article_message)
end
end
function NewsDownloader:removeNewsButKeepFeedConfig()
logger.dbg("NewsDownloader: Removing news from :", self.download_dir)
for entry in lfs.dir(self.download_dir) do
if entry ~= "." and entry ~= ".." and entry ~= self.feed_config_file then
local entry_path = self.download_dir .. "/" .. entry
local entry_mode = lfs.attributes(entry_path, "mode")
if entry_mode == "file" then
os.remove(entry_path)
elseif entry_mode == "directory" then
FFIUtil.purgeDir(entry_path)
end
end
end
UIManager:show(InfoMessage:new{
text = _("All downloaded news feed items deleted.")
})
end
function NewsDownloader:setCustomDownloadDirectory()
require("ui/downloadmgr"):new{
onConfirm = function(path)
logger.dbg("NewsDownloader: set download directory to: ", path)
self.settings:saveSetting(self.config_key_custom_dl_dir, ("%s/"):format(path))
self.settings:flush()
logger.dbg("NewsDownloader: Coping to new download folder previous self.feed_config_file from: ", self.feed_config_path)
FFIUtil.copyFile(self.feed_config_path, ("%s/%s"):format(path, self.feed_config_file))
self.initialized = false
self:lazyInitialization()
end,
}:chooseDir()
end
function NewsDownloader:viewFeedList()
local UI = require("ui/trapper")
UI:info(_("Loading news feed list…"))
-- Protected call to see if feed config path returns a file that can be opened.
local ok, feed_config = pcall(dofile, self.feed_config_path)
if not ok or not feed_config then
local change_feed_config = UI:confirm(
_("Could not open feed list. Feeds configuration file is invalid."),
_("Close"),
_("View file")
)
if change_feed_config then
self:changeFeedConfig()
end
return
end
UI:clear()
-- See if the config file contains any feed items
if #feed_config <= 0 then
logger.err("NewsDownloader: empty feed list.", self.feed_config_path)
-- Why not ask the user if they want to add one?
-- Or, in future, move along to our list UI with an entry for new feeds
--return
end
local view_content = FeedView:getList(
feed_config,
function(feed_item_vc)
self:viewFeedItem(
feed_item_vc
)
end,
function(id, edit_key, value)
self:editFeedAttribute(id, edit_key, value)
end,
function(id)
self:deleteFeed(id)
end
)
-- Add a "Add new feed" button with callback
table.insert(
view_content,
{
_("Add new feed"),
"",
callback = function()
-- Prepare the view with all the callbacks for editing the attributes
local feed_item_vc = FeedView:getItem(
#feed_config + 1,
self.empty_feed,
function(id, edit_key, value)
self:editFeedAttribute(id, edit_key, value)
end
)
self:viewFeedItem(
feed_item_vc
)
end
}
)
-- Show the list of feeds.
if #self.kv ~= 0 then
UIManager:close(self.kv)
end
self.kv = KeyValuePage:new{
title = _("RSS/Atom feeds"),
value_overflow_align = "right",
kv_pairs = view_content,
callback_return = function()
UIManager:close(self.kv)
end
}
UIManager:show(self.kv)
end
function NewsDownloader:viewFeedItem(data)
if #self.kv ~= 0 then
UIManager:close(self.kv)
end
self.kv = KeyValuePage:new{
title = _("Edit Feed"),
value_overflow_align = "left",
kv_pairs = data,
callback_return = function()
self:viewFeedList()
end
}
UIManager:show(self.kv)
end
function NewsDownloader:editFeedAttribute(id, key, value)
local kv = self.kv
-- There are basically two types of values: string (incl. numbers)
-- and booleans. This block chooses what type of value our
-- attribute will need and displays the corresponding dialog.
if key == FeedView.URL
or key == FeedView.LIMIT
or key == FeedView.FILTER_ELEMENT then
local title
local input_type
local description
if key == FeedView.URL then
title = _("Edit feed URL")
input_type = "string"
elseif key == FeedView.LIMIT then
title = _("Edit feed limit")
description = _("Set to 0 for no limit to how many items are downloaded")
input_type = "number"
elseif key == FeedView.FILTER_ELEMENT then
title = _("Edit filter element.")
description = _("Filter based on the given CSS selector. E.g.: name_of_css.element.class")
input_type = "string"
else
return false
end
local input_dialog
input_dialog = InputDialog:new{
title = title,
input = value,
input_type = input_type,
description = description,
buttons = {
{
{
text = _("Cancel"),
id = "close",
callback = function()
UIManager:close(input_dialog)
UIManager:show(kv)
end,
},
{
text = _("Save"),
is_enter_default = true,
callback = function()
UIManager:close(input_dialog)
self:updateFeedConfig(id, key, input_dialog:getInputValue())
end,
},
}
},
}
UIManager:show(input_dialog)
input_dialog:onShowKeyboard()
return true
else
local text
if key == FeedView.DOWNLOAD_FULL_ARTICLE then
text = _("Download full article?")
elseif key == FeedView.INCLUDE_IMAGES then
text = _("Include images?")
elseif key == FeedView.ENABLE_FILTER then
text = _("Enable CSS filter?")
end
local multi_box
multi_box= MultiConfirmBox:new{
text = text,
choice1_text = _("Yes"),
choice1_callback = function()
UIManager:close(multi_box)
self:updateFeedConfig(id, key, true)
end,
choice2_text = _("No"),
choice2_callback = function()
UIManager:close(multi_box)
self:updateFeedConfig(id, key, false)
end,
cancel_callback = function()
UIManager:close(multi_box)
UIManager:show(kv)
end,
}
UIManager:show(multi_box)
end
end
function NewsDownloader:updateFeedConfig(id, key, value)
local UI = require("ui/trapper")
-- Because this method is called at the menu,
-- we might not have an active view. So this conditional
-- statement avoids closing a null reference.
if #self.kv ~= 0 then
UIManager:close(self.kv)
end
-- It's possible that we will get a null value.
-- This block catches that possibility.
if id ~= nil and key ~= nil and value ~= nil then
-- This logger is a bit opaque because T() wasn't playing nice with booleans
logger.dbg("Newsdownloader: attempting to update config:")
else
logger.dbg("Newsdownloader: null value supplied to update. Not updating config")
return
end
local ok, feed_config = pcall(dofile, self.feed_config_path)
if not ok or not feed_config then
UI:info(T(_("Invalid configuration file. Detailed error message:\n%1"), feed_config))
return
end
-- If the file contains no table elements, then the user hasn't set any feeds.
if #feed_config <= 0 then
logger.dbg("NewsDownloader: empty feed list.", self.feed_config_path)
end
-- Check to see if the id is larger than the number of feeds. If it is,
-- then we know this is a new add. Insert the base array.
if id > #feed_config then
table.insert(
feed_config,
self.empty_feed
)
end
local new_config = {}
-- In this loop, we cycle through the feed items. A series of
-- conditionals checks to see if we are at the right id
-- and key (i.e.: the key that triggered this function.
-- If we are at the right spot, we overrite (or create) the value
for idx, feed in ipairs(feed_config) do
-- Check to see if this is the correct feed to update.
if idx == id then
if key == FeedView.URL then
if feed[1] then
-- If the value exists, then it's been set. So all we do
-- is overwrite the value.
feed[1] = value
else
-- If the value doesn't exist, then we need to set it.
-- So we insert it into the table.
table.insert(
feed,
{
value
}
)
end
elseif key == FeedView.LIMIT then
if feed.limit then
feed.limit = value
else
table.insert(
feed,
{
"limit",
value
}
)
end
elseif key == FeedView.DOWNLOAD_FULL_ARTICLE then
if feed.download_full_article ~= nil then
feed.download_full_article = value
else
table.insert(
feed,
{
"download_full_article",
value
}
)
end
elseif key == FeedView.INCLUDE_IMAGES then
if feed.include_images ~= nil then
feed.include_images = value
else
table.insert(
feed,
{
"include_images",
value
}
)
end
elseif key == FeedView.ENABLE_FILTER then
if feed.enable_filter ~= nil then
feed.enable_filter = value
else
table.insert(
feed,
{
"enable_filter",
value
}
)
end
elseif key == FeedView.FILTER_ELEMENT then
if feed.filter_element then
feed.filter_element = value
else
table.insert(
feed,
{
"filter_element",
value
}
)
end
end
end
-- Now we insert the updated (or newly created) feed into the
-- new config feed that we're building in this loop.
table.insert(
new_config,
feed
)
end
-- Save the config
logger.dbg("NewsDownloader: config to save", new_config)
self:saveConfig(new_config)
-- Refresh the view
local feed_item_vc = FeedView:getItem(
id,
new_config[id],
function(cb_id, cb_edit_key, cb_value)
self:editFeedAttribute(cb_id, cb_edit_key, cb_value)
end
)
self:viewFeedItem(
feed_item_vc
)
end
function NewsDownloader:deleteFeed(id)
local UI = require("ui/trapper")
logger.dbg("Newsdownloader: attempting to delete feed")
-- Check to see if we can get the config file.
local ok, feed_config = pcall(dofile, self.feed_config_path)
if not ok or not feed_config then
UI:info(T(_("Invalid configuration file. Detailed error message:\n%1"), feed_config))
return
end
-- In this loop, we cycle through the feed items. A series of
-- conditionals checks to see if we are at the right id
-- and key (i.e.: the key that triggered this function.
-- If we are at the right spot, we overrite (or create) the value
local new_config = {}
for idx, feed in ipairs(feed_config) do
-- Check to see if this is the correct feed to update.
if idx ~= id then
table.insert(
new_config,
feed
)
end
end
-- Save the config
local Trapper = require("ui/trapper")
Trapper:wrap(function()
logger.dbg("NewsDownloader: config to save", new_config)
self:saveConfig(new_config)
end)
-- Refresh the view
self:viewFeedList()
end
function NewsDownloader:saveConfig(config)
local UI = require("ui/trapper")
UI:info(_("Saving news feed list…"))
local persist = Persist:new{
path = self.feed_config_path
}
local ok = persist:save(config)
if not ok then
UI:info(_("Could not save news feed config."))
else
UI:info(_("News feed config updated successfully."))
end
UI:reset()
end
function NewsDownloader:changeFeedConfig()
local feed_config_file = io.open(self.feed_config_path, "rb")
local config = feed_config_file:read("*all")
feed_config_file:close()
local config_editor
logger.info("NewsDownloader: opening configuration file", self.feed_config_path)
config_editor = InputDialog:new{
title = T(_("Config: %1"), BD.filepath(self.feed_config_path)),
input = config,
input_type = "string",
para_direction_rtl = false, -- force LTR
fullscreen = true,
condensed = true,
allow_newline = true,
cursor_at_end = false,
add_nav_bar = true,
reset_callback = function()
return config
end,
save_callback = function(content)
if content and #content > 0 then
local parse_error = util.checkLuaSyntax(content)
if not parse_error then
local syntax_okay, syntax_error = pcall(loadstring(content))
if syntax_okay then
feed_config_file = io.open(self.feed_config_path, "w")
feed_config_file:write(content)
feed_config_file:close()
return true, _("Configuration saved")
else
return false, T(_("Configuration invalid: %1"), syntax_error)
end
else
return false, T(_("Configuration invalid: %1"), parse_error)
end
end
return false, _("Configuration empty")
end,
}
UIManager:show(config_editor)
config_editor:onShowKeyboard()
end
function NewsDownloader:openDownloadsFolder()
local FileManager = require("apps/filemanager/filemanager")
if self.ui.document then
self.ui:onClose()
end
if FileManager.instance then
FileManager.instance:reinit(self.download_dir)
else
FileManager:showFiles(self.download_dir)
end
end
function NewsDownloader:onCloseDocument()
local document_full_path = self.ui.document.file
if document_full_path and self.download_dir and self.download_dir == string.sub(document_full_path, 1, string.len(self.download_dir)) then
logger.dbg("NewsDownloader: document_full_path:", document_full_path)
logger.dbg("NewsDownloader: self.download_dir:", self.download_dir)
logger.dbg("NewsDownloader: removing NewsDownloader file from history.")
ReadHistory:removeItemByPath(document_full_path)
local doc_dir = util.splitFilePathName(document_full_path)
self.ui:setLastDirForFileBrowser(doc_dir)
end
end
--
-- KeyValuePage doesn't like to get a table with sub tables.
-- This function flattens an array, moving all nested tables
-- up the food chain, so to speak
--
function NewsDownloader:flattenArray(base_array, source_array)
for key, value in pairs(source_array) do
if value[2] == nil then
-- If the value is empty, then it's probably supposed to be a line
table.insert(
base_array,
"---"
)
else
if value["callback"] then
table.insert(
base_array,
{
value[1], value[2], callback = value["callback"]
}
)
else
table.insert(
base_array,
{
value[1], value[2]
}
)
end
end
end
return base_array
end
return NewsDownloader
| agpl-3.0 |
ThingMesh/openwrt-luci | applications/luci-statistics/luasrc/statistics/rrdtool/definitions/olsrd.lua | 85 | 3643 | --[[
Luci statistics - olsrd plugin diagram definition
Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.statistics.rrdtool.definitions.olsrd", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
local g = { }
if plugin_instance == "routes" then
g[#g+1] = {
-- diagram data description
title = "%H: Total amount of OLSR routes", vlabel = "n",
number_format = "%5.0lf", data = {
types = { "routes" },
options = {
routes = {
color = "ff0000",
title = "Total number of routes"
}
}
}
}
g[#g+1] = {
title = "%H: Average route ETX", vlabel = "ETX", detail = true,
number_format = "%5.1lf",data = {
instances = { "average" }, -- falls es irgendwann mal welche pro ip gibt, wie bei links, dann werden die hier excludiert
types = { "route_etx" },
options = {
route_etx = {
title = "Average route ETX"
}
}
}
}
g[#g+1] = {
title = "%H: Average route metric", vlabel = "metric", detail = true,
number_format = "%5.1lf", data = {
instances = { "average" }, -- falls es irgendwann mal welche pro ip gibt, wie bei links, dann werden die hier excludiert
types = { "route_metric" },
options = {
route_metric = {
title = "Average route metric"
}
}
}
}
elseif plugin_instance == "links" then
g[#g+1] = {
-- diagram data description
title = "%H: Total amount of OLSR neighbours", vlabel = "n",
number_format = "%5.0lf", data = {
instances = { "" },
types = { "links" },
options = {
links = {
color = "00ff00",
title = "Number of neighbours"
}
}
}
}
local instances = graph.tree:data_instances(plugin, plugin_instance, "signal_quality")
table.sort(instances)
-- define one diagram per host, containing the rx and lq values
local i
for i = 1, #instances, 2 do
local dsn1 = "signal_quality_%s_value" % instances[i]:gsub("[^%w]+", "_")
local dsn2 = "signal_quality_%s_value" % instances[i+1]:gsub("[^%w]+", "_")
local host = instances[i]:match("^[^%-]+%-([^%-]+)%-.+")
g[#g+1] = {
title = "%H: Signal Quality" .. " (" .. (host or "avg") ..")", vlabel = "ETX",
number_format = "%5.2lf", detail = true,
data = {
types = { "signal_quality" },
instances = {
signal_quality = { instances[i], instances[i+1] },
},
options = {
[dsn1] = {
color = "00ff00",
title = "LQ (%s)" % (host or "avg"),
},
[dsn2] = {
color = "0000ff",
title = "NLQ (%s)" % (host or "avg"),
flip = true
}
}
}
}
end
elseif plugin_instance == "topology" then
g[#g+1] = {
title= "%H: Total amount of OLSR links", vlabel = "n",
number_format = "%5.0lf", data = {
instances = { "" },
types = { "links" },
options = {
links = {
color = "0000ff",
title = "Total number of links"
}
}
}
}
g[#g+1] = {
title= "%H: Average signal quality", vlabel = "n",
number_format = "%5.2lf", detail = true,
data = {
instances = { "average" }, -- exclude possible per-ip stuff
types = { "signal_quality" },
options = {
signal_quality = {
color = "0000ff",
title = "Average signal quality"
}
}
}
}
end
return g
end
| apache-2.0 |
MalRD/darkstar | scripts/globals/items/yilanbaligi.lua | 11 | 1131 | -----------------------------------------
-- ID: 5458
-- Item: Yilanbaligi
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-- Evasion 5
-----------------------------------------
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,5458)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.MND, -4)
target:addMod(dsp.mod.EVA, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.MND, -4)
target:delMod(dsp.mod.EVA, 5)
end
| gpl-3.0 |
gallenmu/MoonGen | libmoon/deps/luajit/src/jit/dis_mips.lua | 59 | 13773 | ----------------------------------------------------------------------------
-- LuaJIT MIPS disassembler module.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles all standard MIPS32R1/R2 instructions.
-- Default mode is big-endian, but see: dis_mipsel.lua
------------------------------------------------------------------------------
local type = type
local byte, format = string.byte, string.format
local match, gmatch = string.match, string.gmatch
local concat = table.concat
local bit = require("bit")
local band, bor, tohex = bit.band, bit.bor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Primary and extended opcode maps
------------------------------------------------------------------------------
local map_movci = { shift = 16, mask = 1, [0] = "movfDSC", "movtDSC", }
local map_srl = { shift = 21, mask = 1, [0] = "srlDTA", "rotrDTA", }
local map_srlv = { shift = 6, mask = 1, [0] = "srlvDTS", "rotrvDTS", }
local map_special = {
shift = 0, mask = 63,
[0] = { shift = 0, mask = -1, [0] = "nop", _ = "sllDTA" },
map_movci, map_srl, "sraDTA",
"sllvDTS", false, map_srlv, "sravDTS",
"jrS", "jalrD1S", "movzDST", "movnDST",
"syscallY", "breakY", false, "sync",
"mfhiD", "mthiS", "mfloD", "mtloS",
"dsllvDST", false, "dsrlvDST", "dsravDST",
"multST", "multuST", "divST", "divuST",
"dmultST", "dmultuST", "ddivST", "ddivuST",
"addDST", "addu|moveDST0", "subDST", "subu|neguDS0T",
"andDST", "or|moveDST0", "xorDST", "nor|notDST0",
false, false, "sltDST", "sltuDST",
"daddDST", "dadduDST", "dsubDST", "dsubuDST",
"tgeSTZ", "tgeuSTZ", "tltSTZ", "tltuSTZ",
"teqSTZ", false, "tneSTZ", false,
"dsllDTA", false, "dsrlDTA", "dsraDTA",
"dsll32DTA", false, "dsrl32DTA", "dsra32DTA",
}
local map_special2 = {
shift = 0, mask = 63,
[0] = "maddST", "madduST", "mulDST", false,
"msubST", "msubuST",
[32] = "clzDS", [33] = "cloDS",
[63] = "sdbbpY",
}
local map_bshfl = {
shift = 6, mask = 31,
[2] = "wsbhDT",
[16] = "sebDT",
[24] = "sehDT",
}
local map_dbshfl = {
shift = 6, mask = 31,
[2] = "dsbhDT",
[5] = "dshdDT",
}
local map_special3 = {
shift = 0, mask = 63,
[0] = "extTSAK", [1] = "dextmTSAP", [3] = "dextTSAK",
[4] = "insTSAL", [6] = "dinsuTSEQ", [7] = "dinsTSAL",
[32] = map_bshfl, [36] = map_dbshfl, [59] = "rdhwrTD",
}
local map_regimm = {
shift = 16, mask = 31,
[0] = "bltzSB", "bgezSB", "bltzlSB", "bgezlSB",
false, false, false, false,
"tgeiSI", "tgeiuSI", "tltiSI", "tltiuSI",
"teqiSI", false, "tneiSI", false,
"bltzalSB", "bgezalSB", "bltzallSB", "bgezallSB",
false, false, false, false,
false, false, false, false,
false, false, false, "synciSO",
}
local map_cop0 = {
shift = 25, mask = 1,
[0] = {
shift = 21, mask = 15,
[0] = "mfc0TDW", [4] = "mtc0TDW",
[10] = "rdpgprDT",
[11] = { shift = 5, mask = 1, [0] = "diT0", "eiT0", },
[14] = "wrpgprDT",
}, {
shift = 0, mask = 63,
[1] = "tlbr", [2] = "tlbwi", [6] = "tlbwr", [8] = "tlbp",
[24] = "eret", [31] = "deret",
[32] = "wait",
},
}
local map_cop1s = {
shift = 0, mask = 63,
[0] = "add.sFGH", "sub.sFGH", "mul.sFGH", "div.sFGH",
"sqrt.sFG", "abs.sFG", "mov.sFG", "neg.sFG",
"round.l.sFG", "trunc.l.sFG", "ceil.l.sFG", "floor.l.sFG",
"round.w.sFG", "trunc.w.sFG", "ceil.w.sFG", "floor.w.sFG",
false,
{ shift = 16, mask = 1, [0] = "movf.sFGC", "movt.sFGC" },
"movz.sFGT", "movn.sFGT",
false, "recip.sFG", "rsqrt.sFG", false,
false, false, false, false,
false, false, false, false,
false, "cvt.d.sFG", false, false,
"cvt.w.sFG", "cvt.l.sFG", "cvt.ps.sFGH", false,
false, false, false, false,
false, false, false, false,
"c.f.sVGH", "c.un.sVGH", "c.eq.sVGH", "c.ueq.sVGH",
"c.olt.sVGH", "c.ult.sVGH", "c.ole.sVGH", "c.ule.sVGH",
"c.sf.sVGH", "c.ngle.sVGH", "c.seq.sVGH", "c.ngl.sVGH",
"c.lt.sVGH", "c.nge.sVGH", "c.le.sVGH", "c.ngt.sVGH",
}
local map_cop1d = {
shift = 0, mask = 63,
[0] = "add.dFGH", "sub.dFGH", "mul.dFGH", "div.dFGH",
"sqrt.dFG", "abs.dFG", "mov.dFG", "neg.dFG",
"round.l.dFG", "trunc.l.dFG", "ceil.l.dFG", "floor.l.dFG",
"round.w.dFG", "trunc.w.dFG", "ceil.w.dFG", "floor.w.dFG",
false,
{ shift = 16, mask = 1, [0] = "movf.dFGC", "movt.dFGC" },
"movz.dFGT", "movn.dFGT",
false, "recip.dFG", "rsqrt.dFG", false,
false, false, false, false,
false, false, false, false,
"cvt.s.dFG", false, false, false,
"cvt.w.dFG", "cvt.l.dFG", false, false,
false, false, false, false,
false, false, false, false,
"c.f.dVGH", "c.un.dVGH", "c.eq.dVGH", "c.ueq.dVGH",
"c.olt.dVGH", "c.ult.dVGH", "c.ole.dVGH", "c.ule.dVGH",
"c.df.dVGH", "c.ngle.dVGH", "c.deq.dVGH", "c.ngl.dVGH",
"c.lt.dVGH", "c.nge.dVGH", "c.le.dVGH", "c.ngt.dVGH",
}
local map_cop1ps = {
shift = 0, mask = 63,
[0] = "add.psFGH", "sub.psFGH", "mul.psFGH", false,
false, "abs.psFG", "mov.psFG", "neg.psFG",
false, false, false, false,
false, false, false, false,
false,
{ shift = 16, mask = 1, [0] = "movf.psFGC", "movt.psFGC" },
"movz.psFGT", "movn.psFGT",
false, false, false, false,
false, false, false, false,
false, false, false, false,
"cvt.s.puFG", false, false, false,
false, false, false, false,
"cvt.s.plFG", false, false, false,
"pll.psFGH", "plu.psFGH", "pul.psFGH", "puu.psFGH",
"c.f.psVGH", "c.un.psVGH", "c.eq.psVGH", "c.ueq.psVGH",
"c.olt.psVGH", "c.ult.psVGH", "c.ole.psVGH", "c.ule.psVGH",
"c.psf.psVGH", "c.ngle.psVGH", "c.pseq.psVGH", "c.ngl.psVGH",
"c.lt.psVGH", "c.nge.psVGH", "c.le.psVGH", "c.ngt.psVGH",
}
local map_cop1w = {
shift = 0, mask = 63,
[32] = "cvt.s.wFG", [33] = "cvt.d.wFG",
}
local map_cop1l = {
shift = 0, mask = 63,
[32] = "cvt.s.lFG", [33] = "cvt.d.lFG",
}
local map_cop1bc = {
shift = 16, mask = 3,
[0] = "bc1fCB", "bc1tCB", "bc1flCB", "bc1tlCB",
}
local map_cop1 = {
shift = 21, mask = 31,
[0] = "mfc1TG", "dmfc1TG", "cfc1TG", "mfhc1TG",
"mtc1TG", "dmtc1TG", "ctc1TG", "mthc1TG",
map_cop1bc, false, false, false,
false, false, false, false,
map_cop1s, map_cop1d, false, false,
map_cop1w, map_cop1l, map_cop1ps,
}
local map_cop1x = {
shift = 0, mask = 63,
[0] = "lwxc1FSX", "ldxc1FSX", false, false,
false, "luxc1FSX", false, false,
"swxc1FSX", "sdxc1FSX", false, false,
false, "suxc1FSX", false, "prefxMSX",
false, false, false, false,
false, false, false, false,
false, false, false, false,
false, false, "alnv.psFGHS", false,
"madd.sFRGH", "madd.dFRGH", false, false,
false, false, "madd.psFRGH", false,
"msub.sFRGH", "msub.dFRGH", false, false,
false, false, "msub.psFRGH", false,
"nmadd.sFRGH", "nmadd.dFRGH", false, false,
false, false, "nmadd.psFRGH", false,
"nmsub.sFRGH", "nmsub.dFRGH", false, false,
false, false, "nmsub.psFRGH", false,
}
local map_pri = {
[0] = map_special, map_regimm, "jJ", "jalJ",
"beq|beqz|bST00B", "bne|bnezST0B", "blezSB", "bgtzSB",
"addiTSI", "addiu|liTS0I", "sltiTSI", "sltiuTSI",
"andiTSU", "ori|liTS0U", "xoriTSU", "luiTU",
map_cop0, map_cop1, false, map_cop1x,
"beql|beqzlST0B", "bnel|bnezlST0B", "blezlSB", "bgtzlSB",
"daddiTSI", "daddiuTSI", false, false,
map_special2, "jalxJ", false, map_special3,
"lbTSO", "lhTSO", "lwlTSO", "lwTSO",
"lbuTSO", "lhuTSO", "lwrTSO", false,
"sbTSO", "shTSO", "swlTSO", "swTSO",
false, false, "swrTSO", "cacheNSO",
"llTSO", "lwc1HSO", "lwc2TSO", "prefNSO",
false, "ldc1HSO", "ldc2TSO", "ldTSO",
"scTSO", "swc1HSO", "swc2TSO", false,
false, "sdc1HSO", "sdc2TSO", "sdTSO",
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "sp", "r30", "ra",
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then extra = "\t->"..sym end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-7s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-7s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
local function get_be(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
return bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3)
end
local function get_le(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
return bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0)
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local op = ctx:get()
local operands = {}
local last = nil
ctx.op = op
ctx.rel = nil
local opat = map_pri[rshift(op, 26)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._
end
local name, pat = match(opat, "^([a-z0-9_.]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.|]*)(.*)")
if altname then pat = pat2 end
for p in gmatch(pat, ".") do
local x = nil
if p == "S" then
x = map_gpr[band(rshift(op, 21), 31)]
elseif p == "T" then
x = map_gpr[band(rshift(op, 16), 31)]
elseif p == "D" then
x = map_gpr[band(rshift(op, 11), 31)]
elseif p == "F" then
x = "f"..band(rshift(op, 6), 31)
elseif p == "G" then
x = "f"..band(rshift(op, 11), 31)
elseif p == "H" then
x = "f"..band(rshift(op, 16), 31)
elseif p == "R" then
x = "f"..band(rshift(op, 21), 31)
elseif p == "A" then
x = band(rshift(op, 6), 31)
elseif p == "E" then
x = band(rshift(op, 6), 31) + 32
elseif p == "M" then
x = band(rshift(op, 11), 31)
elseif p == "N" then
x = band(rshift(op, 16), 31)
elseif p == "C" then
x = band(rshift(op, 18), 7)
if x == 0 then x = nil end
elseif p == "K" then
x = band(rshift(op, 11), 31) + 1
elseif p == "P" then
x = band(rshift(op, 11), 31) + 33
elseif p == "L" then
x = band(rshift(op, 11), 31) - last + 1
elseif p == "Q" then
x = band(rshift(op, 11), 31) - last + 33
elseif p == "I" then
x = arshift(lshift(op, 16), 16)
elseif p == "U" then
x = band(op, 0xffff)
elseif p == "O" then
local disp = arshift(lshift(op, 16), 16)
operands[#operands] = format("%d(%s)", disp, last)
elseif p == "X" then
local index = map_gpr[band(rshift(op, 16), 31)]
operands[#operands] = format("%s(%s)", index, last)
elseif p == "B" then
x = ctx.addr + ctx.pos + arshift(lshift(op, 16), 16)*4 + 4
ctx.rel = x
x = format("0x%08x", x)
elseif p == "J" then
local a = ctx.addr + ctx.pos
x = a - band(a, 0x0fffffff) + band(op, 0x03ffffff)*4
ctx.rel = x
x = format("0x%08x", x)
elseif p == "V" then
x = band(rshift(op, 8), 7)
if x == 0 then x = nil end
elseif p == "W" then
x = band(op, 7)
if x == 0 then x = nil end
elseif p == "Y" then
x = band(rshift(op, 6), 0x000fffff)
if x == 0 then x = nil end
elseif p == "Z" then
x = band(rshift(op, 6), 1023)
if x == 0 then x = nil end
elseif p == "0" then
if last == "r0" or last == 0 then
local n = #operands
operands[n] = nil
last = operands[n-1]
if altname then
local a1, a2 = match(altname, "([^|]*)|(.*)")
if a1 then name, altname = a1, a2
else name = altname end
end
end
elseif p == "1" then
if last == "ra" then
operands[#operands] = nil
end
else
assert(false)
end
if x then operands[#operands+1] = x; last = x end
end
return putop(ctx, name, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
stop = stop - stop % 4
ctx.pos = ofs - ofs % 4
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
ctx.get = get_be
return ctx
end
local function create_el(code, addr, out)
local ctx = create(code, addr, out)
ctx.get = get_le
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
local function disass_el(code, addr, out)
create_el(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 32 then return map_gpr[r] end
return "f"..(r-32)
end
-- Public module functions.
return {
create = create,
create_el = create_el,
disass = disass,
disass_el = disass_el,
regname = regname
}
| mit |
MalRD/darkstar | scripts/globals/weaponskills/starburst.lua | 10 | 1329 | -----------------------------------
-- Starburst
-- Staff weapon skill
-- Skill Level: 100
-- Deals light or darkness elemental damage. Damage varies with TP.
-- Aligned with the Shadow Gorget & Aqua Gorget.
-- Aligned with the Shadow Belt & Aqua Belt.
-- Element: Light/Dark (Random)
-- Modifiers: : STR:40% MND:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 1 params.ftp200 = 2 params.ftp300 = 2.5
params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.DARK params.ele = dsp.magic.ele.LIGHT
params.skill = dsp.skill.STAFF
params.includemab = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.mnd_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Apollyon/mobs/Water_Elemental.lua | 9 | 2117 | -----------------------------------
-- Area: Apollyon SW
-- Mob: Water Elemental
-----------------------------------
require("scripts/globals/limbus");
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1;
local correctelement=false;
switch (elementalday): caseof {
[0] = function (x)
if (mobID==16932913 or mobID==16932921 or mobID==16932929) then
correctelement=true;
end
end ,
[1] = function (x)
if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then
correctelement=true;
end
end ,
[2] = function (x)
if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then
correctelement=true;
end
end ,
[3] = function (x)
if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then
correctelement=true;
end
end ,
[4] = function (x)
if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then
correctelement=true;
end
end ,
[5] = function (x)
if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then
correctelement=true;
end
end ,
[6] = function (x)
if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then
correctelement=true;
end
end ,
[7] = function (x)
if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then
correctelement=true;
end
end ,
};
if (correctelement==true and IselementalDayAreDead() == true) then
GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+313):setStatus(dsp.status.NORMAL);
end
end; | gpl-3.0 |
Lsty/ygopro-scripts | c93751476.lua | 3 | 2659 | --猛炎星-テンレイ
function c93751476.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetOperation(c93751476.regop)
c:RegisterEffect(e1)
--set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(93751476,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetCondition(c93751476.setcon)
e2:SetTarget(c93751476.settg)
e2:SetOperation(c93751476.setop)
c:RegisterEffect(e2)
end
function c93751476.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsReason(REASON_EFFECT) and c:IsReason(REASON_DESTROY) then
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(93751476,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_GRAVE)
e1:SetTarget(c93751476.sptg)
e1:SetOperation(c93751476.spop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
end
function c93751476.spfilter(c,e,tp)
return c:IsSetCard(0x79) and c:GetLevel()==4 and c:GetCode()~=93751476 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c93751476.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c93751476.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c93751476.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,c93751476.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 c93751476.setcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO
and e:GetHandler():GetReasonCard():IsSetCard(0x79)
end
function c93751476.filter(c)
return c:IsSetCard(0x7c) and c:IsType(TYPE_SPELL) and c:IsSSetable()
end
function c93751476.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingMatchingCard(c93751476.filter,tp,LOCATION_DECK,0,1,nil) end
end
function c93751476.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c93751476.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g:GetFirst())
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c48686504.lua | 5 | 1467 | --ローンファイア・ブロッサム
function c48686504.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(48686504,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c48686504.cost)
e1:SetTarget(c48686504.target)
e1:SetOperation(c48686504.operation)
c:RegisterEffect(e1)
end
function c48686504.costfilter(c)
return c:IsFaceup() and c:IsRace(RACE_PLANT)
end
function c48686504.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c48686504.costfilter,1,nil) end
local g=Duel.SelectReleaseGroup(tp,c48686504.costfilter,1,1,nil)
Duel.Release(g,REASON_COST)
end
function c48686504.filter(c,e,tp)
return c:IsRace(RACE_PLANT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c48686504.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c48686504.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_DECK)
end
function c48686504.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,c48686504.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 |
Lsty/ygopro-scripts | c15270885.lua | 3 | 2702 | --トゥーン・ゴブリン突撃部隊
function c15270885.initial_effect(c)
--cannot attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetOperation(c15270885.atklimit)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e4:SetRange(LOCATION_MZONE)
e4:SetCode(EVENT_LEAVE_FIELD)
e4:SetCondition(c15270885.sdescon)
e4:SetOperation(c15270885.sdesop)
c:RegisterEffect(e4)
--direct attack
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_DIRECT_ATTACK)
e5:SetCondition(c15270885.dircon)
c:RegisterEffect(e5)
--to defence
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e6:SetCode(EVENT_PHASE+PHASE_BATTLE)
e6:SetRange(LOCATION_MZONE)
e6:SetCountLimit(1)
e6:SetCondition(c15270885.poscon)
e6:SetOperation(c15270885.posop)
c:RegisterEffect(e6)
end
function c15270885.atklimit(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e:GetHandler():RegisterEffect(e1)
end
function c15270885.sfilter(c)
return c:IsReason(REASON_DESTROY) and c:IsPreviousPosition(POS_FACEUP) and c:GetPreviousCodeOnField()==15259703 and c:IsPreviousLocation(LOCATION_ONFIELD)
end
function c15270885.sdescon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c15270885.sfilter,1,nil)
end
function c15270885.sdesop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
function c15270885.dirfilter1(c)
return c:IsFaceup() and c:IsCode(15259703)
end
function c15270885.dirfilter2(c)
return c:IsFaceup() and c:IsType(TYPE_TOON)
end
function c15270885.dircon(e)
return Duel.IsExistingMatchingCard(c15270885.dirfilter1,e:GetHandlerPlayer(),LOCATION_ONFIELD,0,1,nil)
and not Duel.IsExistingMatchingCard(c15270885.dirfilter2,e:GetHandlerPlayer(),0,LOCATION_MZONE,1,nil)
end
function c15270885.poscon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetAttackedCount()>0
end
function c15270885.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsAttackPos() then
Duel.ChangePosition(c,POS_FACEUP_DEFENCE)
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_CHANGE_POSITION)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_COPY_INHERIT)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,3)
c:RegisterEffect(e1)
end
| gpl-2.0 |
neverlose1/sickmind | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Frenzie/koreader | frontend/util.lua | 4 | 58514 | --[[--
This module contains miscellaneous helper functions for the KOReader frontend.
]]
local BaseUtil = require("ffi/util")
local Utf8Proc = require("ffi/utf8proc")
local lfs = require("libs/libkoreader-lfs")
local _ = require("gettext")
local C_ = _.pgettext
local T = BaseUtil.template
local lshift = bit.lshift
local rshift = bit.rshift
local band = bit.band
local bor = bit.bor
local util = {}
---- Strips all punctuation marks and spaces from a string.
---- @string text the string to be stripped
---- @treturn string stripped text
function util.stripPunctuation(text)
if not text then return end
-- strip ASCII punctuation marks around text
-- and strip any generic punctuation marks (U+2000 - U+206F) in the text
return text:gsub("\226[\128-\131][\128-\191]", ''):gsub("^%p+", ''):gsub("%p+$", '')
end
-- Various whitespace trimming helpers, from http://lua-users.org/wiki/CommonFunctions & http://lua-users.org/wiki/StringTrim
---- Remove leading whitespace from string.
---- @string s the string to be trimmed
---- @treturn string trimmed text
function util.ltrim(s)
return (s:gsub("^%s*", ""))
end
---- Remove trailing whitespace from string.
---- @string s the string to be trimmed
---- @treturn string trimmed text
function util.rtrim(s)
local n = #s
while n > 0 and s:find("^%s", n) do
n = n - 1
end
return s:sub(1, n)
end
---- Remove leading & trailing whitespace from string.
---- @string s the string to be trimmed
---- @treturn string trimmed text
function util.trim(s)
local from = s:match"^%s*()"
return from > #s and "" or s:match(".*%S", from)
end
--[[--
Splits a string by a pattern
Lua doesn't have a string.split() function and most of the time
you don't really need it because string.gmatch() is enough.
However string.gmatch() has one significant disadvantage for me:
You can't split a string while matching both the delimited
strings and the delimiters themselves without tracking positions
and substrings. The gsplit function below takes care of
this problem.
Author: Peter Odding
License: MIT/X11
Source: <a href="http://snippets.luacode.org/snippets/String_splitting_130">http://snippets.luacode.org/snippets/String_splitting_130</a>
]]
----@string str string to split
----@param pattern the pattern to split against
----@bool capture
----@bool capture_empty_entity
function util.gsplit(str, pattern, capture, capture_empty_entity)
pattern = pattern and tostring(pattern) or '%s+'
if (''):find(pattern) then
error('pattern matches empty string!', 2)
end
return coroutine.wrap(function()
local index = 1
repeat
local first, last = str:find(pattern, index)
if first and last then
if index < first or (index == first and capture_empty_entity) then
coroutine.yield(str:sub(index, first - 1))
end
if capture then
coroutine.yield(str:sub(first, last))
end
index = last + 1
else
if index <= #str then
coroutine.yield(str:sub(index))
end
break
end
until index > #str
end)
end
-- Stupid helper for the duration stuff
local function passthrough(n)
return n
end
--[[--
Converts seconds to a clock string.
Source: <a href="https://gist.github.com/jesseadams/791673">https://gist.github.com/jesseadams/791673</a>
]]
---- @int seconds number of seconds
---- @bool withoutSeconds if true 00:00, if false 00:00:00
---- @treturn string clock string in the form of 00:00 or 00:00:00
function util.secondsToClock(seconds, withoutSeconds, withDays)
seconds = tonumber(seconds)
if not seconds then
if withoutSeconds then
return "--:--"
else
return "--:--:--"
end
elseif seconds == 0 or seconds ~= seconds then
if withoutSeconds then
return "00:00"
else
return "00:00:00"
end
else
local round = withoutSeconds and require("optmath").round or passthrough
local days = "0"
local hours
if withDays then
days = string.format("%d", seconds * (1/(24*3600))) -- implicit math.floor for string.format
hours = string.format("%02d", (seconds * (1/3600)) % 24)
else
hours = string.format("%02d", seconds * (1/3600))
end
local mins = string.format("%02d", round(seconds % 3600 * (1/60)))
if withoutSeconds then
if mins == "60" then
-- Can only happen because of rounding, which only happens if withoutSeconds...
mins = string.format("%02d", 0)
hours = string.format("%02d", hours + 1)
end
return (days ~= "0" and (days .. "d") or "") .. hours .. ":" .. mins
else
local secs = string.format("%02d", seconds % 60)
return (days ~= "0" and (days .. "d") or "") .. hours .. ":" .. mins .. ":" .. secs
end
end
end
--- Converts seconds to a period of time string.
---- @int seconds number of seconds
---- @bool withoutSeconds if true 1h30', if false 1h30'10"
---- @bool hmsFormat, if true format 1h30m10s
---- @bool withDays, if true format 1d12h30m10s
---- @treturn string clock string in the form of 1h30'10" or 1h30m10s
function util.secondsToHClock(seconds, withoutSeconds, hmsFormat, withDays, compact)
local SECONDS_SYMBOL = "\""
seconds = tonumber(seconds)
if seconds == 0 then
if withoutSeconds then
if hmsFormat then
return T(_("%1m"), "0")
else
return "0'"
end
else
if hmsFormat then
return T(C_("Time", "%1s"), "0")
else
return "0" .. SECONDS_SYMBOL
end
end
elseif seconds < 60 then
if withoutSeconds and seconds < 30 then
if hmsFormat then
return T(C_("Time", "%1m"), "0")
else
return "0'"
end
elseif withoutSeconds and seconds >= 30 then
if hmsFormat then
return T(C_("Time", "%1m"), "1")
else
return "1'"
end
else
if hmsFormat then
if compact then
return T(C_("Time", "%1s"), string.format("%d", seconds))
else
return T(C_("Time", "%1m%2s"), "0", string.format("%02d", seconds))
end
else
if compact then
return string.format("%d", seconds) .. SECONDS_SYMBOL
else
return "0'" .. string.format("%02d", seconds) .. SECONDS_SYMBOL
end
end
end
else
local time_string = util.secondsToClock(seconds, withoutSeconds, withDays)
if withoutSeconds then
time_string = time_string .. ":"
end
time_string = time_string:gsub(":", C_("Time", "h"), 1)
time_string = time_string:gsub(":", C_("Time", "m"), 1)
time_string = time_string:gsub("^00" .. C_("Time", "h"), "") -- delete leading "00h"
time_string = time_string:gsub("^00" .. C_("Time", "m"), "") -- delete leading "00m"
if time_string:find("^0%d") then
time_string = time_string:gsub("^0", "") -- delete leading "0"
end
if withoutSeconds and time_string == "" then
time_string = "0" .. C_("Time", "m")
end
if hmsFormat then
return withoutSeconds and time_string or (time_string .. C_("Time", "s"))
else
time_string = time_string:gsub(C_("Time", "m"), "'") -- replace m with '
return withoutSeconds and time_string or (time_string .. SECONDS_SYMBOL)
end
end
end
--- Converts seconds to a clock type (classic or modern), based on the given format preference
--- "Classic" format calls secondsToClock, and "Modern" format calls secondsToHClock
---- @string Either "modern" for 1h30'10" or "classic" for 1:30:10
---- @bool withoutSeconds if true 1h30' or 1h30m, if false 1h30'10" or 1h30m10s
---- @bool hmsFormat, modern format only, if true format 1h30m or 1h30m10s
---- @bool withDays, if hours>=24 include days in clock string 1d12h10m10s
---- @bool compact, if set removes all leading zeros (incl. units if necessary)
---- @treturn string clock string in the specific format of 1h30', 1h30'10" resp. 1h30m, 1h30m10s
function util.secondsToClockDuration(format, seconds, withoutSeconds, hmsFormat, withDays, compact)
if format == "modern" then
return util.secondsToHClock(seconds, withoutSeconds, hmsFormat, withDays, compact)
else
-- Assume "classic" to give safe default
return util.secondsToClock(seconds, withoutSeconds, withDays)
end
end
if jit.os == "Windows" then
--- Converts timestamp to an hour string
---- @int seconds number of seconds
---- @bool twelve_hour_clock
---- @treturn string hour string
---- @note: The MS CRT doesn't support either %l & %k, or the - format modifier (as they're not technically C99 or POSIX).
---- They are otherwise supported on Linux, BSD & Bionic, so, just special-case Windows...
---- We *could* arguably feed the os.date output to gsub("^0(%d)(.*)$", "%1%2"), but, while unlikely,
---- it's conceivable that a translator would put something other that the hour at the front of the string ;).
function util.secondsToHour(seconds, twelve_hour_clock)
if twelve_hour_clock then
if os.date("%p", seconds) == "AM" then
-- @translators This is the time in the morning using a 12-hour clock (%I is the hour, %M the minute).
return os.date(_("%I:%M AM"), seconds)
else
-- @translators This is the time in the afternoon using a 12-hour clock (%I is the hour, %M the minute).
return os.date(_("%I:%M PM"), seconds)
end
else
-- @translators This is the time using a 24-hour clock (%H is the hour, %M the minute).
return os.date(_("%H:%M"), seconds)
end
end
else
function util.secondsToHour(seconds, twelve_hour_clock, pad_with_spaces)
if twelve_hour_clock then
if os.date("%p", seconds) == "AM" then
if pad_with_spaces then
-- @translators This is the time in the morning using a 12-hour clock (%_I is the hour, %M the minute).
return os.date(_("%_I:%M AM"), seconds)
else
-- @translators This is the time in the morning using a 12-hour clock (%-I is the hour, %M the minute).
return os.date(_("%-I:%M AM"), seconds)
end
else
if pad_with_spaces then
-- @translators This is the time in the afternoon using a 12-hour clock (%_I is the hour, %M the minute).
return os.date(_("%_I:%M PM"), seconds)
else
-- @translators This is the time in the afternoon using a 12-hour clock (%-I is the hour, %M the minute).
return os.date(_("%-I:%M PM"), seconds)
end
end
else
if pad_with_spaces then
-- @translators This is the time using a 24-hour clock (%_H is the hour, %M the minute).
return os.date(_("%_H:%M"), seconds)
else
-- @translators This is the time using a 24-hour clock (%-H is the hour, %M the minute).
return os.date(_("%-H:%M"), seconds)
end
end
end
end
--- Converts timestamp to a date string
---- @int seconds number of seconds
---- @bool twelve_hour_clock
---- @treturn string date string
function util.secondsToDate(seconds, twelve_hour_clock)
local BD = require("ui/bidi")
-- In order to keep stuff aligned, we'll want to *keep* the padding, but using blanks instead of zeroes.
local time = util.secondsToHour(seconds, twelve_hour_clock, true)
-- @translators This is the date (%Y is the year, %m the month, %d the day)
local day = os.date(_("%Y-%m-%d"), seconds)
return BD.wrap(day) .. " " .. BD.wrap(time)
end
--[[--
Compares values in two different tables.
Source: <https://stackoverflow.com/a/32660766/2470572>
]]
---- @param o1 Lua table
---- @param o2 Lua table
---- @bool ignore_mt
---- @treturn boolean
function util.tableEquals(o1, o2, ignore_mt)
if o1 == o2 then return true end
local o1Type = type(o1)
local o2Type = type(o2)
if o1Type ~= o2Type then return false end
if o1Type ~= 'table' then return false end
if not ignore_mt then
local mt1 = getmetatable(o1)
if mt1 and mt1.__eq then
-- Compare using built in method
return o1 == o2
end
end
local keySet = {}
for key1, value1 in pairs(o1) do
local value2 = o2[key1]
if value2 == nil or util.tableEquals(value1, value2, ignore_mt) == false then
return false
end
keySet[key1] = true
end
for key2, _ in pairs(o2) do
if not keySet[key2] then return false end
end
return true
end
--[[--
Makes a deep copy of a table.
Source: <https://stackoverflow.com/a/16077650/2470572>
]]
---- @param o Lua table
---- @treturn Lua table
function util.tableDeepCopy(o, seen)
seen = seen or {}
if o == nil then return nil end
if seen[o] then return seen[o] end
local no
if type(o) == "table" then
no = {}
seen[o] = no
for k, v in next, o, nil do
no[util.tableDeepCopy(k, seen)] = util.tableDeepCopy(v, seen)
end
setmetatable(no, util.tableDeepCopy(getmetatable(o), seen))
else -- number, string, boolean, etc
no = o
end
return no
end
--- Returns number of keys in a table.
---- @param t Lua table
---- @treturn int number of keys in table t
function util.tableSize(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
--- Append all elements from t2 into t1.
---- @param t1 Lua table
---- @param t2 Lua table
function util.arrayAppend(t1, t2)
for _, v in ipairs(t2) do
table.insert(t1, v)
end
end
--[[--
Remove elements from an array, fast.
Swap & pop, like <http://lua-users.org/lists/lua-l/2013-11/msg00027.html> / <https://stackoverflow.com/a/28942022>, but preserving order.
c.f., <https://stackoverflow.com/a/53038524>
@table t Lua array to filter
@func keep_cb Filtering callback. Takes three arguments: table, index, new index. Returns true to *keep* the item. See link above for potential uses of the third argument.
@usage
local foo = { "a", "b", "c", "b", "d", "e" }
local function drop_b(t, i, j)
-- Discard any item with value "b"
return t[i] ~= "b"
end
util.arrayRemove(foo, drop_b)
]]
function util.arrayRemove(t, keep_cb)
local j, n = 1, #t
for i = 1, n do
if keep_cb(t, i, j) then
-- Move i's kept value to j's position, if it's not already there.
if i ~= j then
t[j] = t[i]
t[i] = nil
end
-- Increment position of where we'll place the next kept value.
j = j + 1
else
t[i] = nil
end
end
return t
end
--- Reverse array elements in-place in table t
---- @param t Lua table
function util.arrayReverse(t)
local i, j = 1, #t
while i < j do
t[i], t[j] = t[j], t[i]
i = i + 1
j = j - 1
end
end
--- Test whether t contains a value equal to v
--- (or such a value that callback returns true),
--- and if so, return the index.
---- @param t Lua table
---- @param v
---- @func callback(v1, v2)
function util.arrayContains(t, v, cb)
cb = cb or function(v1, v2) return v1 == v2 end
for _k, _v in ipairs(t) do
if cb(_v, v) then
return _k
end
end
return false
end
--- Test whether array t contains a reference to array n (at any depth at or below m)
---- @param t Lua table (array only)
---- @param n Lua table (array only)
---- @int m Max nesting level
function util.arrayReferences(t, n, m, l)
if not m then m = 15 end
if not l then l = 0 end
if l > m then
return false
end
if type(t) == "table" then
if t == n then
return true, l
end
for _, v in ipairs(t) do
local matched, depth = util.arrayReferences(v, n, m, l + 1)
if matched then
return matched, depth
end
end
end
return false
end
-- A set of binary search implementations for plain arrays.
-- Should be easy to tweak for arrays of hashes (c.f., UIManager:schedule),
-- or arrays sorted in descending order (c.f., ReadHistory).
-- refs: https://en.wikipedia.org/wiki/Binary_search_algorithm
-- https://rosettacode.org/wiki/Binary_search
--- Perform a binary search for `value` in a *sorted* (ascending) `array`.
---- @param array Lua table (array only, sorted, ascending, every value must match the type of `value` and support comparison operators)
---- @param value
---- @return int index of value in array, or a (nil, insertion index) tuple if value was not found.
function util.bsearch(array, value)
local lo = 1
local hi = #array
while lo <= hi do
-- invariants: value > array[i] for all i < lo
-- value < array[i] for all i > hi
local mid = bit.rshift(lo + hi, 1)
if array[mid] > value then
hi = mid - 1
elseif array[mid] < value then
lo = mid + 1
else
return mid
end
end
return nil, lo
end
--- Perform a leftmost insertion binary search for `value` in a *sorted* (ascending) `array`.
---- @param array Lua table (array only, sorted, ascending, every value must match the type of `value` and support comparison operators)
---- @param value
---- @return int leftmost insertion index of value in array.
function util.bsearch_left(array, value)
local lo = 1
local hi = #array
while lo <= hi do
-- invariants: value > array[i] for all i < lo
-- value <= array[i] for all i > hi
local mid = bit.rshift(lo + hi, 1)
if array[mid] >= value then
hi = mid - 1
else
lo = mid + 1
end
end
return lo
end
--- Perform a rightmost insertion binary search for `value` in a *sorted* (ascending) `array`.
---- @param array Lua table (array only, sorted, ascending, every value must match the type of `value` and support comparison operators)
---- @param value
---- @return int rightmost insertion index of value in array.
function util.bsearch_right(array, value)
local lo = 1
local hi = #array
while lo <= hi do
-- invariants: value >= array[i] for all i < low
-- value < array[i] for all i > high
local mid = bit.rshift(lo + hi, 1)
if array[mid] > value then
hi = mid - 1
else
lo = mid + 1
end
end
return lo
end
-- Merge t2 into t1, overwriting existing elements if they already exist
-- Probably not safe with nested tables (c.f., https://stackoverflow.com/q/1283388)
---- @param t1 Lua table
---- @param t2 Lua table
function util.tableMerge(t1, t2)
for k, v in pairs(t2) do
t1[k] = v
end
end
--[[--
Gets last index of character in string (i.e., strrchr)
Returns the index within this string of the last occurrence of the specified character
or -1 if the character does not occur.
To find . you need to escape it.
]]
---- @string string
---- @string ch
---- @treturn int last occurrence or -1 if not found
function util.lastIndexOf(string, ch)
local i = string:match(".*" .. ch .. "()")
if i == nil then return -1 else return i - 1 end
end
--- Pattern which matches a single well-formed UTF-8 character, including
--- theoretical >4-byte extensions.
-- Taken from <https://www.lua.org/manual/5.4/manual.html#pdf-utf8.charpattern>
util.UTF8_CHAR_PATTERN = '[%z\1-\127\194-\253][\128-\191]*'
--- Reverse the individual greater-than-single-byte characters
-- @string string to reverse
-- Taken from <https://github.com/blitmap/lua-utf8-simple#utf8reverses>
function util.utf8Reverse(text)
text = text:gsub(util.UTF8_CHAR_PATTERN, function (c) return #c > 1 and c:reverse() end)
return text:reverse()
end
--- Splits string into a list of UTF-8 characters.
---- @string text the string to be split.
---- @treturn table list of UTF-8 chars
function util.splitToChars(text)
local tab = {}
if text ~= nil then
local prevcharcode, charcode = 0
-- Supports WTF-8 : https://en.wikipedia.org/wiki/UTF-8#WTF-8
-- a superset of UTF-8, that includes UTF-16 surrogates
-- in UTF-8 bytes (forbidden in well-formed UTF-8).
-- We may get that from bad producers or converters.
-- (luajson, used to decode Wikipedia API json, will not correctly decode
-- this sample: <span lang=\"got\">\ud800\udf45</span> : single Unicode
-- char https://www.compart.com/en/unicode/U+10345 and will give us
-- "\xed\xa0\x80\xed\xbd\x85" as UTF8, instead of the correct "\xf0\x90\x8d\x85")
-- From http://www.unicode.org/faq/utf_bom.html#utf16-1
-- Surrogates are code points from two special ranges of
-- Unicode values, reserved for use as the leading, and
-- trailing values of paired code units in UTF-16. Leading,
-- also called high, surrogates are from D800 to DBFF, and
-- trailing, or low, surrogates are from DC00 to DFFF. They
-- are called surrogates, since they do not represent
-- characters directly, but only as a pair.
local hi_surrogate
local hi_surrogate_uchar
for uchar in text:gmatch(util.UTF8_CHAR_PATTERN) do
charcode = BaseUtil.utf8charcode(uchar)
-- (not sure why we need this prevcharcode check; we could get
-- charcode=nil with invalid UTF-8, but should we then really
-- ignore the following charcode ?)
if prevcharcode then -- utf8
if charcode and charcode >= 0xD800 and charcode <= 0xDBFF then
if hi_surrogate then -- previous unconsumed one, add it even if invalid
table.insert(tab, hi_surrogate_uchar)
end
hi_surrogate = charcode
hi_surrogate_uchar = uchar -- will be added if not followed by low surrogate
elseif hi_surrogate and charcode and charcode >= 0xDC00 and charcode <= 0xDFFF then
-- low surrogate following a high surrogate, good, let's make them a single char
charcode = lshift((hi_surrogate - 0xD800), 10) + (charcode - 0xDC00) + 0x10000
table.insert(tab, util.unicodeCodepointToUtf8(charcode))
hi_surrogate = nil
else
if hi_surrogate then -- previous unconsumed one, add it even if invalid
table.insert(tab, hi_surrogate_uchar)
end
hi_surrogate = nil
table.insert(tab, uchar)
end
end
prevcharcode = charcode
end
end
return tab
end
--- Tests whether c is a CJK character
---- @string c
---- @treturn boolean true if CJK
function util.isCJKChar(c)
-- Smallest CJK codepoint is 0x1100 which requires at least 3 utf8 bytes to
-- encode (U+07FF is the largest codepoint that can be represented in 2
-- bytes with utf8). So if the character is shorter than 3 bytes it's
-- definitely not CJK and no need to decode it.
if #c < 3 then
return false
end
local code = BaseUtil.utf8charcode(c)
-- The weird bracketing is intentional -- we use the lowest possible
-- codepoint as a shortcut so if the codepoint is below U+1100 we
-- immediately return false.
return -- BMP (Plane 0)
code >= 0x1100 and (code <= 0x11FF or -- Hangul Jamo
(code >= 0x2E80 and code <= 0x9FFF) or -- Numerous CJK Blocks (NB: has some gaps)
(code >= 0xA960 and code <= 0xA97F) or -- Hangul Jamo Extended-A
(code >= 0xAC00 and code <= 0xD7AF) or -- Hangul Syllables
(code >= 0xD7B0 and code <= 0xD7FF) or -- Hangul Jame Extended-B
(code >= 0xF900 and code <= 0xFAFF) or -- CJK Compatibility Ideographs
(code >= 0xFE30 and code <= 0xFE4F) or -- CJK Compatibility Forms
(code >= 0xFF00 and code <= 0xFFEF) or -- Halfwidth and Fullwidth Forms
-- SIP (Plane 2)
(code >= 0x20000 and code <= 0x2A6DF) or -- CJK Unified Ideographs Extension B
(code >= 0x2A700 and code <= 0x2B73F) or -- CJK Unified Ideographs Extension C
(code >= 0x2B740 and code <= 0x2B81F) or -- CJK Unified Ideographs Extension D
(code >= 0x2B820 and code <= 0x2CEAF) or -- CJK Unified Ideographs Extension E
(code >= 0x2CEB0 and code <= 0x2EBEF) or -- CJK Unified Ideographs Extension F
(code >= 0x2F800 and code <= 0x2FA1F) or -- CJK Compatibility Ideographs Supplement
-- TIP (Plane 3)
(code >= 0x30000 and code <= 0x3134F)) -- CJK Unified Ideographs Extension G
end
--- Tests whether str contains CJK characters
---- @string str
---- @treturn boolean true if CJK
function util.hasCJKChar(str)
for c in str:gmatch(util.UTF8_CHAR_PATTERN) do
if util.isCJKChar(c) then
return true
end
end
return false
end
--- Split texts into a list of words, spaces and punctuation marks.
---- @string text text to split
---- @treturn table list of words, spaces and punctuation marks
function util.splitToWords(text)
local wlist = {}
for word in util.gsplit(text, "[%s%p]+", true) do
-- if space split word contains CJK characters
if util.hasCJKChar(word) then
-- split all non-ASCII characters separately (FIXME ideally we
-- would split only the CJK characters, but you cannot define CJK
-- characters trivially with a byte-only Lua pattern).
for char in util.gsplit(word, "[\192-\255][\128-\191]+", true) do
table.insert(wlist, char)
end
else
table.insert(wlist, word)
end
end
return wlist
end
-- We don't want to split on a space if it is followed by some
-- specific punctuation marks : e.g. "word :" or "word )"
-- (In French, there is a non-breaking space before a colon, and it better
-- not be wrapped there.)
local non_splittable_space_tailers = ":;,.!?)]}$%=-+*/|<>»”"
-- Same if a space has some specific other punctuation mark before it
local non_splittable_space_leaders = "([{$=-+*/|<>«“"
-- Similar rules exist for CJK text. Taken from :
-- https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
local cjk_non_splittable_tailers = table.concat( {
-- Simplified Chinese
"!%),.:;?]}¢°·’\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~",
-- Traditional Chinese
"!),.:;?]}¢·–—’\"•、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、",
-- Japanese
")]}〕〉》」』】〙〗〟’\"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.",
-- Korean
"!%),.:;?]}¢°’\"†‡℃〆〈《「『〕!%),.:;?]}",
})
local cjk_non_splittable_leaders = table.concat( {
-- Simplified Chinese
"$(£¥·‘\"〈《「『【〔〖〝﹙﹛$(.[{£¥",
-- Traditional Chinese
"([{£¥‘\"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏",
-- Japanese
"([{〔〈《「『【〘〖〝‘\"⦅«",
-- Korean
"$([{£¥‘\"々〇〉》」〔$([{⦆¥₩#",
})
local cjk_non_splittable = table.concat( {
-- Japanese
"—…‥〳〴〵",
})
--- Test whether a string can be separated by this char for multi-line rendering.
-- Optional next or prev chars may be provided to help make the decision
---- @string c
---- @string next_c
---- @string prev_c
---- @treturn boolean true if splittable, false if not
function util.isSplittable(c, next_c, prev_c)
if util.isCJKChar(c) then
-- a CJKChar is a word in itself, and so is splittable
if cjk_non_splittable:find(c, 1, true) then
-- except a few of them
return false
elseif next_c and cjk_non_splittable_tailers:find(next_c, 1, true) then
-- but followed by a char that is not permitted at start of line
return false
elseif prev_c and cjk_non_splittable_leaders:find(prev_c, 1, true) then
-- but preceded by a char that is not permitted at end of line
return false
else
-- we can split on this CJKchar
return true
end
elseif c == " " then
-- we only split on a space (so a punctuation mark sticks to prev word)
-- if next_c or prev_c is provided, we can make a better decision
if next_c and non_splittable_space_tailers:find(next_c, 1, true) then
-- this space is followed by some punctuation mark that is better kept with us
return false
elseif prev_c and non_splittable_space_leaders:find(prev_c, 1, true) then
-- this space is lead by some punctuation mark that is better kept with us
return false
else
-- we can split on this space
return true
end
end
-- otherwise, not splittable
return false
end
--- Gets filesystem type of a path.
--
-- Checks if the path occurs in <code>/proc/mounts</code>
---- @string path an absolute path
---- @treturn string filesystem type
function util.getFilesystemType(path)
local mounts = io.open("/proc/mounts", "r")
if not mounts then return nil end
local type
for line in mounts:lines() do
local mount = {}
for param in line:gmatch("%S+") do table.insert(mount, param) end
if string.match(path, mount[2]) then
type = mount[3]
if mount[2] ~= '/' then
break
end
end
end
mounts:close()
return type
end
-- For documentation purposes, here's a battle-tested shell version of calcFreeMem,
-- our simplified Lua version follows...
--[[
if grep -q 'MemAvailable' /proc/meminfo ; then
# We'll settle for 85% of available memory to leave a bit of breathing room
tmpfs_size="$(awk '/MemAvailable/ {printf "%d", $2 * 0.85}' /proc/meminfo)"
elif grep -q 'Inactive(file)' /proc/meminfo ; then
# Basically try to emulate the kernel's computation, c.f., https://unix.stackexchange.com/q/261247
# Again, 85% of available memory
tmpfs_size="$(awk -v low=$(grep low /proc/zoneinfo | awk '{k+=$2}END{printf "%d", k}') \
'{a[$1]=$2}
END{
printf "%d", (a["MemFree:"]+a["Active(file):"]+a["Inactive(file):"]+a["SReclaimable:"]-(12*low))*0.85;
}' /proc/meminfo)"
else
# Ye olde crap workaround of Free + Buffers + Cache...
# Take it with a grain of salt, and settle for 80% of that...
tmpfs_size="$(awk \
'{a[$1]=$2}
END{
printf "%d", (a["MemFree:"]+a["Buffers:"]+a["Cached:"])*0.80;
}' /proc/meminfo)"
fi
--]]
--- Computes the currently available memory
---- @treturn tuple of ints: memavailable, memtotal (or nil, nil on unsupported platforms).
function util:calcFreeMem()
local memtotal, memfree, memavailable, buffers, cached
local meminfo = io.open("/proc/meminfo", "r")
if meminfo then
for line in meminfo:lines() do
if not memtotal then
memtotal = line:match("^MemTotal:%s-(%d+) kB")
if memtotal then
-- Next!
goto continue
end
end
if not memfree then
memfree = line:match("^MemFree:%s-(%d+) kB")
if memfree then
-- Next!
goto continue
end
end
if not memavailable then
memavailable = line:match("^MemAvailable:%s-(%d+) kB")
if memavailable then
-- Best case scenario, we're done :)
break
end
end
if not buffers then
buffers = line:match("^Buffers:%s-(%d+) kB")
if buffers then
-- Next!
goto continue
end
end
if not cached then
cached = line:match("^Cached:%s-(%d+) kB")
if cached then
-- Ought to be the last entry we care about, we're done
break
end
end
::continue::
end
meminfo:close()
else
-- Not on Linux?
return nil, nil
end
if memavailable then
-- Leave a bit of margin, and report 85% of that...
return math.floor(memavailable * 0.85) * 1024, memtotal * 1024
else
-- Crappy Free + Buffers + Cache version, because the zoneinfo approach is a tad hairy...
-- So, leave an even larger margin, and only report 75% of that...
return math.floor((memfree + buffers + cached) * 0.75) * 1024, memtotal * 1024
end
end
--- Recursively scan directory for files inside
-- @string path
-- @func callback(fullpath, name, attr)
function util.findFiles(dir, cb)
local function scan(current)
local ok, iter, dir_obj = pcall(lfs.dir, current)
if not ok then return end
for f in iter, dir_obj do
local path = current.."/"..f
-- lfs can return nil here, as it will follow symlinks!
local attr = lfs.attributes(path) or {}
if attr.mode == "directory" then
if f ~= "." and f ~= ".." then
scan(path)
end
elseif attr.mode == "file" or attr.mode == "link" then
cb(path, f, attr)
end
end
end
scan(dir)
end
--- Checks if directory is empty.
---- @string path
---- @treturn bool
function util.isEmptyDir(path)
-- lfs.dir will crash rather than return nil if directory doesn't exist O_o
local ok, iter, dir_obj = pcall(lfs.dir, path)
if not ok then return end
for filename in iter, dir_obj do
if filename ~= '.' and filename ~= '..' then
return false
end
end
return true
end
--- check if the given path is a file
---- @string path
---- @treturn bool
function util.fileExists(path)
local file = io.open(path, "r")
if file ~= nil then
file:close()
return true
end
end
--- Checks if the given path exists. Doesn't care if it's a file or directory.
---- @string path
---- @treturn bool
function util.pathExists(path)
return lfs.attributes(path, "mode") ~= nil
end
--- As `mkdir -p`.
-- Unlike [lfs.mkdir](https://keplerproject.github.io/luafilesystem/manual.html#mkdir)(),
-- does not error if the directory already exists, and creates intermediate directories as needed.
-- @string path the directory to create
-- @treturn bool true on success; nil, err_message on error
function util.makePath(path)
path = path:gsub("/+$", "")
if util.pathExists(path) then return true end
local success, err = util.makePath((util.splitFilePathName(path)))
if not success then
return nil, err.." (creating "..path..")"
end
return lfs.mkdir(path)
end
--- As `rm`
-- @string path of the file to remove
-- @treturn bool true on success; nil, err_message on error
function util.removeFile(file)
if file and lfs.attributes(file, "mode") == "file" then
return os.remove(file)
elseif file then
return nil, file .. " is not a file"
else
return nil, "file is nil"
end
end
-- Gets total, used and available bytes for the mountpoint that holds a given directory.
-- @string path of the directory
-- @treturn table with total, used and available bytes
function util.diskUsage(dir)
-- safe way of testing df & awk
local function doCommand(d)
local handle = io.popen("df -k " .. d .. " 2>&1 | awk '$3 ~ /[0-9]+/ { print $2,$3,$4 }' 2>&1 || echo ::ERROR::")
if not handle then return end
local output = handle:read("*all")
handle:close()
if not output:find "::ERROR::" then
return output
end
end
local err = { total = nil, used = nil, available = nil }
if not dir or lfs.attributes(dir, "mode") ~= "directory" then return err end
local usage = doCommand(dir)
if not usage then return err end
local stage, result = {}, {}
for size in usage:gmatch("%w+") do
table.insert(stage, size)
end
for k, v in pairs({"total", "used", "available"}) do
if stage[k] ~= nil then
-- sizes are in kb, return bytes here
result[v] = stage[k] * 1024
end
end
return result
end
--- Replaces characters that are invalid filenames.
--
-- Replaces the characters <code>\/:*?"<>|</code> with an <code>_</code>.
-- These characters are problematic on Windows filesystems. On Linux only
-- <code>/</code> poses a problem.
---- @string str filename
---- @treturn string sanitized filename
local function replaceAllInvalidChars(str)
if str then
return str:gsub('[\\,%/,:,%*,%?,%",%<,%>,%|]','_')
end
end
--- Replaces slash with an underscore.
---- @string str
---- @treturn string
local function replaceSlashChar(str)
if str then
return str:gsub('%/','_')
end
end
--[[--
Replaces characters that are invalid in filenames.
Replaces the characters `\/:*?"<>|` with an `_` unless an optional path is provided. These characters are problematic on Windows filesystems. On Linux only the `/` poses a problem.
If an optional path is provided, @{util.getFilesystemType}() will be used to determine whether stricter VFAT restrictions should be applied.
]]
---- @string str
---- @string path
---- @int limit
---- @treturn string safe filename
function util.getSafeFilename(str, path, limit, limit_ext)
local filename, suffix = util.splitFileNameSuffix(str)
local replaceFunc = replaceAllInvalidChars
local safe_filename
-- VFAT supports a maximum of 255 UCS-2 characters, although it's probably treated as UTF-16 by Windows
-- default to a slightly lower limit just in case
limit = limit or 240
limit_ext = limit_ext or 10
-- Always assume the worst on Android (#7837)
if path and not BaseUtil.isAndroid() then
local file_system = util.getFilesystemType(path)
if file_system ~= "vfat" and file_system ~= "fuse.fsp" then
replaceFunc = replaceSlashChar
end
end
if suffix:len() > limit_ext then
-- probably not an actual file extension, or at least not one we'd be
-- dealing with, so strip the whole string
filename = str
suffix = nil
end
filename = util.htmlToPlainTextIfHtml(filename)
filename = filename:sub(1, limit)
-- the limit might result in broken UTF-8, which we don't want in the result
filename = util.fixUtf8(filename, "")
if suffix and suffix ~= "" then
safe_filename = replaceFunc(filename) .. "." .. replaceFunc(suffix)
else
safe_filename = replaceFunc(filename)
end
return safe_filename
end
--- Splits a file into its directory path and file name.
--- If the given path has a trailing /, returns the entire path as the directory
--- path and "" as the file name.
---- @string file
---- @treturn string directory, filename
function util.splitFilePathName(file)
if file == nil or file == "" then return "", "" end
if string.find(file, "/") == nil then return "", file end
return file:match("(.*/)(.*)")
end
--- Splits a file name into its pure file name and suffix
---- @string file
---- @treturn string path, extension
function util.splitFileNameSuffix(file)
if file == nil or file == "" then return "", "" end
if string.find(file, "%.") == nil then return file, "" end
return file:match("(.*)%.(.*)")
end
--- Gets file extension
---- @string filename
---- @treturn string extension
function util.getFileNameSuffix(file)
local _, suffix = util.splitFileNameSuffix(file)
return suffix
end
--- Companion helper function that returns the script's language,
--- based on the file extension.
---- @string filename
---- @treturn string (lowercase) (or nil if not Device:canExecuteScript(file))
function util.getScriptType(file)
local file_ext = string.lower(util.getFileNameSuffix(file))
if file_ext == "sh" then
return "shell"
elseif file_ext == "py" then
return "python"
end
end
--- Gets human friendly size as string
---- @int size (bytes)
---- @bool right_align (by padding with spaces on the left)
---- @treturn string
function util.getFriendlySize(size, right_align)
local frac_format = right_align and "%6.1f" or "%.1f"
local deci_format = right_align and "%6d" or "%d"
size = tonumber(size)
if not size or type(size) ~= "number" then return end
if size > 1000*1000*1000 then
return T(C_("Data storage size", "%1 GB"), string.format(frac_format, size/1000/1000/1000))
end
if size > 1000*1000 then
return T(C_("Data storage size", "%1 MB"), string.format(frac_format, size/1000/1000))
end
if size > 1000 then
return T(C_("Data storage size", "%1 kB"), string.format(frac_format, size/1000))
else
return T(C_("Data storage size", "%1 B"), string.format(deci_format, size))
end
end
--- Gets formatted size as string (1273334 => "1,273,334")
---- @int size (bytes)
---- @treturn string
function util.getFormattedSize(size)
local s = tostring(size)
s = s:reverse():gsub("(%d%d%d)", "%1,")
s = s:reverse():gsub("^,", "")
return s
end
--[[--
Replaces invalid UTF-8 characters with a replacement string.
Based on <http://notebook.kulchenko.com/programming/fixing-malformed-utf8-in-lua>.
c.f., FixUTF8 @ <https://github.com/pkulchenko/ZeroBraneStudio/blob/master/src/util.lua>.
@string str the string to be checked for invalid characters
@string replacement the string to replace invalid characters with
@treturn string valid UTF-8
]]
function util.fixUtf8(str, replacement)
local pos = 1
local len = #str
while pos <= len do
if str:find("^[%z\1-\127]", pos) then pos = pos + 1
elseif str:find("^[\194-\223][\128-\191]", pos) then pos = pos + 2
elseif str:find( "^\224[\160-\191][\128-\191]", pos)
or str:find("^[\225-\236][\128-\191][\128-\191]", pos)
or str:find( "^\237[\128-\159][\128-\191]", pos)
or str:find("^[\238-\239][\128-\191][\128-\191]", pos) then pos = pos + 3
elseif str:find( "^\240[\144-\191][\128-\191][\128-\191]", pos)
or str:find("^[\241-\243][\128-\191][\128-\191][\128-\191]", pos)
or str:find( "^\244[\128-\143][\128-\191][\128-\191]", pos) then pos = pos + 4
else
str = str:sub(1, pos - 1) .. replacement .. str:sub(pos + 1)
pos = pos + #replacement
len = len + #replacement - 1
end
end
return str
end
--- Splits input string with the splitter into a table. This function ignores the last empty entity.
--
--- @string str the string to be split
--- @string splitter
--- @bool capture_empty_entity
--- @treturn an array-like table
function util.splitToArray(str, splitter, capture_empty_entity)
local result = {}
for word in util.gsplit(str, splitter, false, capture_empty_entity) do
table.insert(result, word)
end
return result
end
--- Convert a Unicode codepoint (number) to UTF-8 char
--- c.f., <https://stackoverflow.com/a/4609989>
--- & <https://stackoverflow.com/a/38492214>
--- See utf8charcode in ffi/util for a decoder.
--
--- @int c Unicode codepoint
--- @treturn string UTF-8 char
function util.unicodeCodepointToUtf8(c)
if c < 0x80 then
return string.char(c)
elseif c < 0x800 then
return string.char(
bor(0xC0, rshift(c, 6)),
bor(0x80, band(c, 0x3F))
)
elseif c < 0x10000 then
if c >= 0xD800 and c <= 0xDFFF then
return '�' -- Surrogates -> U+FFFD REPLACEMENT CHARACTER
end
return string.char(
bor(0xE0, rshift(c, 12)),
bor(0x80, band(rshift(c, 6), 0x3F)),
bor(0x80, band(c, 0x3F))
)
elseif c < 0x110000 then
return string.char(
bor(0xF0, rshift(c, 18)),
bor(0x80, band(rshift(c, 12), 0x3F)),
bor(0x80, band(rshift(c, 6), 0x3F)),
bor(0x80, band(c, 0x3F))
)
else
return '�' -- Invalid -> U+FFFD REPLACEMENT CHARACTER
end
end
-- we need to use an array of arrays to keep them ordered as written
local HTML_ENTITIES_TO_UTF8 = {
{"<", "<"},
{">", ">"},
{""", '"'},
{"'", "'"},
{" ", "\xC2\xA0"},
{"&#(%d+);", function(x) return util.unicodeCodepointToUtf8(tonumber(x)) end},
{"&#x(%x+);", function(x) return util.unicodeCodepointToUtf8(tonumber(x, 16)) end},
{"&", "&"}, -- must be last
}
--[[--
Replace HTML entities with their UTF-8 encoded equivalent in text.
Supports only basic ones and those with numbers (no support for named entities like `é`).
@int string text with HTML entities
@treturn string UTF-8 text
]]
function util.htmlEntitiesToUtf8(text)
for _, t in ipairs(HTML_ENTITIES_TO_UTF8) do
text = text:gsub(t[1], t[2])
end
return text
end
--[[--
Convert simple HTML to plain text.
This may fail on complex HTML (with styles, scripts, comments), but should be fine enough with simple HTML as found in EPUB's `<dc:description>`.
@string text HTML text
@treturn string plain text
]]
function util.htmlToPlainText(text)
-- Replace <br> with \n
text = text:gsub("%s*<%s*br%s*/?>%s*", "\n") -- <br> and <br/>
-- Replace <p> with \n\t (\t, unlike any combination of spaces,
-- ensures a constant indentation when text is justified.)
text = text:gsub("%s*</%s*p%s*>%s*", "\n") -- </p>
text = text:gsub("%s*<%s*p%s*/>%s*", "\n") -- standalone <p/>
text = text:gsub("%s*<%s*p%s*>%s*", "\n\t") -- <p>
-- (this one last, so \t is not removed by the others' %s)
-- Remove all HTML tags
text = text:gsub("<[^>]*>", "")
-- Convert HTML entities
text = util.htmlEntitiesToUtf8(text)
-- Trim spaces and new lines at start and end, including
-- the \t we added (this looks fine enough with multiple
-- paragraphs, but feels nicer with a single paragraph,
-- whether it contains <br>s or not).
text = text:gsub("^[\n%s]*", "")
text = text:gsub("[\n%s]*$", "")
return text
end
--- Convert HTML to plain text if text seems to be HTML
-- Detection of HTML is simple and may raise false positives
-- or negatives, but seems quite good at guessing content type
-- of text found in EPUB's <dc:description>.
--
--- @string text the string with possibly some HTML
--- @treturn string cleaned text
function util.htmlToPlainTextIfHtml(text)
local is_html = false
-- Quick way to check if text is some HTML:
-- look for html tags
local _, nb_tags
_, nb_tags = text:gsub("<%w+.->", "")
if nb_tags > 0 then
is_html = true
else
-- no <tag> found
-- but we may meet some text badly/twice encoded html containing "<br>"
local nb_encoded_tags
_, nb_encoded_tags = text:gsub("<%a+>", "")
if nb_encoded_tags > 0 then
is_html = true
-- decode one of the two encodes
text = util.htmlEntitiesToUtf8(text)
end
end
if is_html then
text = util.htmlToPlainText(text)
else
-- if text ends with ]]>, it probably comes from <![CDATA[ .. ]]> that
-- crengine has extracted correctly, but let the ending tag in, so
-- let's remove it
text = text:gsub("]]>%s*$", "")
end
return text
end
--- Encode the HTML entities in a string
--- @string text the string to escape
-- Taken from https://github.com/kernelsauce/turbo/blob/e4a35c2e3fb63f07464f8f8e17252bea3a029685/turbo/escape.lua#L58-L70
function util.htmlEscape(text)
return text:gsub("[}{\">/<'&]", {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/",
})
end
--- Prettify a CSS stylesheet
-- Not perfect, but enough to make some ugly CSS readable.
-- By default, each selector and each property is put on its own line.
-- With condensed=true, condense each full declaration on a single line.
--
--- @string CSS string
--- @boolean condensed[opt=false] true to condense each declaration on a line
--- @treturn string the CSS prettified
function util.prettifyCSS(css_text, condensed)
if not condensed then
-- Get rid of \t so we can use it as a replacement/hiding char
css_text = css_text:gsub("\t", " ")
-- Wrap and indent declarations
css_text = css_text:gsub("%s*{%s*", " {\n ")
css_text = css_text:gsub(";%s*}%s*", ";\n}\n")
css_text = css_text:gsub(";%s*([^}])", ";\n %1")
css_text = css_text:gsub("%s*}%s*", "\n}\n")
-- Cleanup declarations
css_text = css_text:gsub("{[^}]*}", function(s)
s = s:gsub("%s*:%s*", ": ")
-- Temporarily hide/replace ',' in declaration so they
-- are not matched and made multi-lines by followup gsub
s = s:gsub("%s*,%s*", "\t")
return s
end)
-- Have each selector (separated by ',') on a new line
css_text = css_text:gsub("%s*,%s*", " ,\n")
-- Restore hidden ',' in declarations
css_text = css_text:gsub("\t", ", ")
else
-- Go thru previous method to have something standard to work on
css_text = util.prettifyCSS(css_text)
-- And condense that
css_text = css_text:gsub(" {\n ", " { ")
css_text = css_text:gsub(";\n ", "; ")
css_text = css_text:gsub("\n}", " }")
css_text = css_text:gsub(" ,\n", ", ")
end
return css_text
end
--- Escape list for shell usage
--- @table args the list of arguments to escape
--- @treturn string the escaped and concatenated arguments
function util.shell_escape(args)
local escaped_args = {}
for _, arg in ipairs(args) do
arg = "'" .. arg:gsub("'", "'\\''") .. "'"
table.insert(escaped_args, arg)
end
return table.concat(escaped_args, " ")
end
--- Clear all the elements from an array without reassignment.
--- @table t the array to be cleared
function util.clearTable(t)
local c = #t
for i = 0, c do t[i] = nil end
end
--- Encode URL also known as percent-encoding see https://en.wikipedia.org/wiki/Percent-encoding
--- @string text the string to encode
--- @treturn encode string
--- Taken from https://gist.github.com/liukun/f9ce7d6d14fa45fe9b924a3eed5c3d99
function util.urlEncode(url)
local char_to_hex = function(c)
return string.format("%%%02X", string.byte(c))
end
if url == nil then
return
end
url = url:gsub("\n", "\r\n")
url = url:gsub("([^%w%-%.%_%~%!%*%'%(%)])", char_to_hex)
return url
end
--- Decode URL (reverse process to util.urlEncode())
--- @string text the string to decode
--- @treturn decode string
--- Taken from https://gist.github.com/liukun/f9ce7d6d14fa45fe9b924a3eed5c3d99
function util.urlDecode(url)
local hex_to_char = function(x)
return string.char(tonumber(x, 16))
end
if url == nil then
return
end
url = url:gsub("%%(%x%x)", hex_to_char)
return url
end
--- Check lua syntax of string
--- @string text lua code text
--- @treturn string with parsing error, nil if syntax ok
function util.checkLuaSyntax(lua_text)
local lua_code_ok, err = loadstring(lua_text)
if lua_code_ok then
return nil
end
-- Replace: [string "blah blah..."]:3: '=' expected near '123'
-- with: Line 3: '=' expected near '123'
err = err and err:gsub("%[string \".-%\"]:", "Line ")
return err
end
--- Simple startsWith string helper.
--
-- C.f., <http://lua-users.org/wiki/StringRecipes>.
-- @string str source string
-- @string start string to match
-- @treturn bool true on success
function util.stringStartsWith(str, start)
return str:sub(1, #start) == start
end
--- Simple endsWith string helper.
-- @string str source string
-- @string ending string to match
-- @treturn bool true on success
function util.stringEndsWith(str, ending)
return ending == "" or str:sub(-#ending) == ending
end
--- Search a string in a text.
-- @string or table txt Text (char list) to search in
-- @string str String to search for
-- @boolean case_sensitive
-- @number start_pos Position number in text to start search from
-- @treturn number Position number or 0 if not found
function util.stringSearch(txt, str, case_sensitive, start_pos)
if not case_sensitive then
str = Utf8Proc.lowercase(util.fixUtf8(str, "?"))
end
local txt_charlist = type(txt) == "table" and txt or util.splitToChars(txt)
local str_charlist = util.splitToChars(str)
local str_len = #str_charlist
local char_pos, found = 0, 0
for i = start_pos - 1, #txt_charlist - str_len do
for j = 1, str_len do
local char_txt = txt_charlist[i + j]
local char_str = str_charlist[j]
if not case_sensitive then
char_txt = Utf8Proc.lowercase(util.fixUtf8(char_txt, "?"))
end
if char_txt ~= char_str then
found = 0
break
end
found = found + 1
end
if found == str_len then
char_pos = i + 1
break
end
end
return char_pos
end
local WrappedFunction_mt = {
__call = function(self, ...)
if self.before_callback then
self.before_callback(self.target_table, ...)
end
if self.func then
return self.func(...)
end
end,
}
--- Wrap (or replace) a table method with a custom method, in a revertable way.
-- This allows you extend the features of an existing module by modifying its
-- internal methods, and then revert them back to normal later if necessary.
--
-- The most notable use-case for this is VirtualKeyboard's inputbox method
-- wrapping to allow keyboards to add more complicated state-machines to modify
-- how characters are input.
--
-- The returned table is the same table `target_table[target_field_name]` is
-- set to. In addition to being callable, the new method has two sub-methods:
--
-- * `:revert()` will un-wrap the method and revert it to the original state.
--
-- Note that if a method is wrapped multiple times, reverting it will revert
-- it to the state of the method when util.wrapMethod was called (and if
-- called on the table returned from util.wrapMethod, that is the state when
-- that particular util.wrapMethod was called).
--
-- * `:raw_call(...)` will call the original method with the given arguments
-- and return whatever it returns.
--
-- This makes it more ergonomic to use the wrapped table methods in the case
-- where you've replaced the regular function with your own implementation
-- but you need to call the original functions inside your implementation.
--
-- * `:raw_method_call(...)` will call the original method with the arguments
-- `(target_table, ...)` and return whatever it returns. Note that the
-- target_table used is the one associated with the util.wrapMethod call.
--
-- This makes it more ergonomic to use the wrapped table methods in the case
-- where you've replaced the regular function with your own implementation
-- but you need to call the original functions inside your implementation.
--
-- This is effectively short-hand for `:raw_call(target_table, ...)`.
--
-- This is loosely based on busted/luassert's spies implementation (MIT).
-- <https://github.com/Olivine-Labs/luassert/blob/v1.7.11/src/spy.lua>
--
-- @tparam table target_table The table whose method will be wrapped.
-- @tparam string target_field_name The name of the field to wrap.
-- @tparam nil|func new_func If non-nil, this function will be called instead of the original function after wrapping.
-- @tparam nil|func before_callback If non-nil, this function will be called (with the arguments (target_table, ...)) before the function is called.
function util.wrapMethod(target_table, target_field_name, new_func, before_callback)
local old_func = target_table[target_field_name]
local wrapped = setmetatable({
target_table = target_table,
target_field_name = target_field_name,
old_func = old_func,
before_callback = before_callback,
func = new_func or old_func,
revert = function(self)
if not self.reverted then
self.target_table[self.target_field_name] = self.old_func
self.reverted = true
end
end,
raw_call = function(self, ...)
if self.old_func then
return self.old_func(...)
end
end,
raw_method_call = function(self, ...)
return self:raw_call(self.target_table, ...)
end,
}, WrappedFunction_mt)
target_table[target_field_name] = wrapped
return wrapped
end
return util
| agpl-3.0 |
tarulas/luadch | scripts/cmd_redirect.lua | 1 | 6610 | --[[
cmd_redirect.lua by pulsar
usage: [+!#]redirect <NICK> <URL>
v0.5:
- added additional ucmd entry to redirect user to default url
- changes in "onbmsg" function
v0.4:
- removed send_report() function, using report import functionality now
- small fix
v0.3:
- renamed script from "usr_redirect.lua" to "cmd_redirect.lua"
- therefore changed import vars from cfg.tbl
v0.2:
- possibility to redirect single users from userlist / requested by Andromeda
- add new table lookups, imports, msgs
v0.1:
- this script redirects users, level specified according to redirect_level table
]]--
--------------
--[SETTINGS]--
--------------
local scriptname = "cmd_redirect"
local scriptversion = "0.5"
local cmd = "redirect"
----------------------------
--[DEFINITION/DECLARATION]--
----------------------------
--// table lookups
local cfg_get = cfg.get
local cfg_loadlanguage = cfg.loadlanguage
local hub_debug = hub.debug
local hub_import = hub.import
local hub_getbot = hub.getbot()
local hub_isnickonline = hub.isnickonline
local utf_format = utf.format
local utf_match = utf.match
local util_getlowestlevel = util.getlowestlevel
--// imports
local scriptlang = cfg_get( "language" )
local lang, err = cfg_loadlanguage( scriptlang, scriptname ); lang = lang or {}; err = err and hub_debug( err )
local levelname = cfg_get( "levels" )
local activate = cfg_get( "cmd_redirect_activate" )
local permission = cfg_get( "cmd_redirect_permission" )
local redirect_level = cfg_get( "cmd_redirect_level" )
local redirect_url = cfg_get( "cmd_redirect_url" )
local report = hub_import( "etc_report" )
local report_activate = cfg_get( "cmd_redirect_report" )
local report_hubbot = cfg_get( "cmd_redirect_report_hubbot" )
local report_opchat = cfg_get( "cmd_redirect_report_opchat" )
local llevel = cfg_get( "cmd_redirect_llevel" )
--// msgs
local help_title = lang.help_title or "usr_redirect.lua"
local help_usage = lang.help_usage or "[+!#]redirect <NICK> <URL>"
local help_desc = lang.help_desc or "Redirect user to url"
local msg_denied = lang.msg_denied or "You are not allowed to use this command."
local msg_usage = lang.msg_usage or "Usage: [+!#]redirect <NICK> <URL>"
local msg_god = lang.msg_god or "You are not allowed to redirect this user."
local msg_isbot = lang.msg_isbot or "User is a bot."
local msg_notonline = lang.msg_notonline or "User is offline."
local msg_redirect = lang.msg_redirect or "User: %s was redirected to: %s"
local msg_report_redirect = lang.msg_report_redirect or "%s has redirected user: %s to: %s"
local ucmd_menu_ct2_1 = lang.ucmd_menu_ct2_1 or { "Redirect", "default URL" }
local ucmd_menu_ct2_2 = lang.ucmd_menu_ct2_2 or { "Redirect", "custom URL" }
local ucmd_url = lang.ucmd_url or "Redirect url:"
local msg_report = lang.msg_report or "User %s with level %s [ %s ] was auto redirected to: %s"
--// functions
local listener
local is_online
local onbmsg
----------
--[CODE]--
----------
local oplevel = util_getlowestlevel( permission )
listener = function( user )
if activate then
local user_nick = user:nick()
local user_level = user:level()
if redirect_level[ user_level ] then
local report_msg = utf_format( msg_report, user_nick, user_level, levelname[ user_level ], redirect_url )
user:redirect( redirect_url )
report.send( report_activate, report_hubbot, report_opchat, llevel, report_msg )
end
end
return nil
end
--// check if target user is online
is_online = function( target )
local target = hub_isnickonline( target )
if target then
if target:isbot() then
return "bot"
else
return target, target:nick(), target:level()
end
end
return nil
end
if activate then
onbmsg = function( user, command, parameters )
local user_nick = user:nick()
local user_level = user:level()
local target_nick, target_level
local param, url = utf_match( parameters, "^(%S+) (%S+)" )
--// [+!#]redirect <NICK> <URL>
if ( param and url ) then
if user_level < oplevel then
user:reply( msg_denied, hub_getbot )
return PROCESSED
end
local target, target_nick, target_level = is_online( param )
if target then
if target ~= "bot" then
if ( ( permission[ user_level ] or 0 ) < target_level ) then
user:reply( msg_god, hub_getbot )
return PROCESSED
end
if url == "default" then url = redirect_url end
target:redirect( url )
user:reply( utf_format( msg_redirect, target_nick, url ), hub_getbot )
report.send( report_activate, report_hubbot, report_opchat, llevel,
utf_format( msg_report_redirect, user_nick, target_nick, url ) )
return PROCESSED
else
user:reply( msg_isbot, hub_getbot )
return PROCESSED
end
else
user:reply( msg_notonline, hub_getbot )
return PROCESSED
end
end
user:reply( msg_usage, hub_getbot )
return PROCESSED
end
--// script start
hub.setlistener( "onStart", {},
function()
--// help, ucmd, hucmd
local help = hub_import( "cmd_help" )
if help then
help.reg( help_title, help_usage, help_desc, oplevel )
end
local ucmd = hub_import( "etc_usercommands" )
if ucmd then
ucmd.add( ucmd_menu_ct2_1, cmd, { "%[userNI]", "default" }, { "CT2" }, oplevel )
ucmd.add( ucmd_menu_ct2_2, cmd, { "%[userNI]", "%[line:" .. ucmd_url .. "]" }, { "CT2" }, oplevel )
end
local hubcmd = hub_import( "etc_hubcommands" )
assert( hubcmd )
assert( hubcmd.add( cmd, onbmsg ) )
return nil
end
)
--// if user connects
hub.setlistener( "onConnect", {}, listener )
end
hub_debug( "** Loaded " .. scriptname .. " " .. scriptversion .. " **" ) | gpl-3.0 |
MalRD/darkstar | scripts/zones/Horlais_Peak/npcs/Armoury_Crate.lua | 9 | 32887 | -----------------------------------
-- Area: Horlais Peak
-- NPC: Armoury Crate
-------------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/bcnm")
-------------------------------------
local loot =
{
-- BCNM Tails of Woe
[1] =
{
{
{itemid = 13553, droprate = 500}, -- blitz_ring
{itemid = 13554, droprate = 500}, -- aegis_ring
},
{
{itemid = 0, droprate = 600}, -- nothing
{itemid = 13238, droprate = 200}, -- druids_rope
{itemid = 13625, droprate = 200}, -- tundra_mantle
},
{
{itemid = 0, droprate = 500}, -- nothing
{itemid = 788, droprate = 250}, -- pearl
{itemid = 792, droprate = 250}, -- peridot
},
{
{itemid = 0, droprate = 900}, -- nothing
{itemid = 4174, droprate = 100}, -- vile_elixir
},
{
{itemid = 0, droprate = 125}, -- nothing
{itemid = 4717, droprate = 125}, -- scroll_of_refresh
{itemid = 4896, droprate = 125}, -- fire_spirit_pact
{itemid = 4751, droprate = 125}, -- scroll_of_erase
{itemid = 4874, droprate = 125}, -- scroll_of_absorb-str
{itemid = 4714, droprate = 125}, -- scroll_of_phalanx
{itemid = 4858, droprate = 125}, -- scroll_of_ice_spikes
{itemid = 4947, droprate = 125}, -- scroll_of_utsusemi_ni
},
},
-- BCNM Dismemberment Brigade
[2] =
{
{
{itemid = 16684, droprate = 250}, -- kabrakans_axe
{itemid = 17190, droprate = 250}, -- sarnga
{itemid = 17648, droprate = 250}, -- dragvandil
{itemid = 17379, droprate = 250}, -- hamelin_flute
},
{
{itemid = 0, droprate = 400}, -- nothing
{itemid = 13128, droprate = 200}, -- spectacles
{itemid = 13403, droprate = 200}, -- assault_earring
{itemid = 13555, droprate = 200}, -- peace_ring
},
{
{itemid = 0, droprate = 200}, -- nothing
{itemid = 773, droprate = 200}, -- translucent_rock
{itemid = 772, droprate = 200}, -- green_rock
{itemid = 771, droprate = 200}, -- yellow_rock
{itemid = 774, droprate = 200}, -- purple_rock
},
{
{itemid = 797, droprate = 100}, -- painite
{itemid = 784, droprate = 100}, -- jadeite
{itemid = 653, droprate = 100}, -- mythril_ingot
{itemid = 652, droprate = 100}, -- steel_ingot
{itemid = 810, droprate = 100}, -- fluorite
{itemid = 745, droprate = 100}, -- gold_ingot
{itemid = 805, droprate = 100}, -- zircon
{itemid = 801, droprate = 100}, -- chrysoberyl
{itemid = 654, droprate = 100}, -- darksteel_ingot
{itemid = 802, droprate = 100}, -- moonstone
},
{
{itemid = 0, droprate = 900}, -- nothing
{itemid = 4175, droprate = 100}, -- vile_elixir_+1
},
},
-- BCNM Hostile Herbivores
[4] =
{
{
{itemid = 0, droprate = 50}, -- Nothing
{itemid = 13251, droprate = 95}, -- Ocean Belt
{itemid = 13254, droprate = 95}, -- Jungle Belt
{itemid = 13253, droprate = 95}, -- Steppe Belt
{itemid = 13255, droprate = 95}, -- Desert Belt
{itemid = 13252, droprate = 95}, -- Forest Belt
{itemid = 13256, droprate = 95}, -- Ocean Stone
{itemid = 13259, droprate = 95}, -- Jungle Stone
{itemid = 13258, droprate = 95}, -- Steppe Stone
{itemid = 13260, droprate = 95}, -- Desert Stone
{itemid = 13257, droprate = 95}, -- Forest Stone
},
{
{itemid = 13292, droprate = 64}, -- Guardians Ring
{itemid = 13287, droprate = 65}, -- Kampfer Ring
{itemid = 13300, droprate = 65}, -- Conjurers Ring
{itemid = 13298, droprate = 65}, -- Shinobi Ring
{itemid = 13293, droprate = 65}, -- Slayers Ring
{itemid = 13289, droprate = 65}, -- Sorcerers Ring
{itemid = 13286, droprate = 64}, -- Soldiers Ring
{itemid = 13294, droprate = 65}, -- Tamers Ring
{itemid = 13296, droprate = 64}, -- Trackers Ring
{itemid = 13299, droprate = 65}, -- Drake Ring
{itemid = 13290, droprate = 65}, -- Fencers Ring
{itemid = 13295, droprate = 65}, -- Minstrels Ring
{itemid = 13288, droprate = 64}, -- Medicine Ring
{itemid = 13291, droprate = 65}, -- Rogues Ring
{itemid = 13297, droprate = 64}, -- Ronin Ring
{itemid = 13447, droprate = 30}, -- Platinum Ring
},
{
{itemid = 0, droprate = 100}, -- Nothing
{itemid = 4818, droprate = 176}, -- Scroll Of Quake
{itemid = 4902, droprate = 10}, -- Light Spirit Pact
{itemid = 4814, droprate = 176}, -- Scroll Of Freeze
{itemid = 4719, droprate = 176}, -- Scroll Of Regen Iii
{itemid = 4172, droprate = 60}, -- Reraiser
{itemid = 4174, droprate = 60}, -- Vile Elixir
{itemid = 4621, droprate = 176}, -- Scroll Of Raise Ii
},
{
{itemid = 0, droprate = 100}, -- Nothing
{itemid = 4818, droprate = 176}, -- Scroll Of Quake
{itemid = 4902, droprate = 10}, -- Light Spirit Pact
{itemid = 4814, droprate = 176}, -- Scroll Of Freeze
{itemid = 4719, droprate = 176}, -- Scroll Of Regen Iii
{itemid = 4172, droprate = 60}, -- Reraiser
{itemid = 4174, droprate = 60}, -- Vile Elixir
{itemid = 4621, droprate = 176}, -- Scroll Of Raise Ii
},
{
{itemid = 895, droprate = 59}, -- Ram Horn
{itemid = 700, droprate = 59}, -- Mahogany Log
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 1116, droprate = 59}, -- Manticore Hide
{itemid = 866, droprate = 90}, -- Handful Of Wyvern Scales
{itemid = 1122, droprate = 90}, -- Wyvern Skin
{itemid = 703, droprate = 176}, -- Petrified Log
{itemid = 654, droprate = 59}, -- Darksteel Ingot
{itemid = 859, droprate = 59}, -- Ram Skin
{itemid = 746, droprate = 90}, -- Platinum Ingot
},
{
{itemid = 0, droprate = 100}, -- Nothing
{itemid = 895, droprate = 59}, -- Ram Horn
{itemid = 700, droprate = 59}, -- Mahogany Log
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 1116, droprate = 59}, -- Manticore Hide
{itemid = 866, droprate = 90}, -- Handful Of Wyvern Scales
{itemid = 1122, droprate = 90}, -- Wyvern Skin
{itemid = 703, droprate = 176}, -- Petrified Log
{itemid = 654, droprate = 59}, -- Darksteel Ingot
{itemid = 859, droprate = 59}, -- Ram Skin
{itemid = 746, droprate = 90}, -- Platinum Ingot
},
},
-- BCNM Carapace Combatants
[8] =
{
{
{itemid = 894, droprate = 1000}, -- beetle_jaw
},
{
{itemid = 889, droprate = 1000}, -- beetle_shell
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 15282, droprate = 150}, -- katana_obi
{itemid = 15274, droprate = 150}, -- staff_belt
{itemid = 15280, droprate = 150}, -- song_belt
{itemid = 15272, droprate = 150}, -- cestus_belt
{itemid = 15279, droprate = 150}, -- pick_belt
},
{
{itemid = 0, droprate = 125}, -- nothing
{itemid = 14736, droprate = 125}, -- genin_earring
{itemid = 14738, droprate = 125}, -- magicians_earring
{itemid = 14729, droprate = 125}, -- pilferers_earring
{itemid = 13439, droprate = 125}, -- warlocks_earring
{itemid = 13436, droprate = 125}, -- wrestlers_earring
{itemid = 14737, droprate = 125}, -- wyvern_earring
{itemid = 14731, droprate = 125}, -- killer_earring
},
{
{itemid = 0, droprate = 160}, -- nothing
{itemid = 645, droprate = 140}, -- chunk_of_darksteel_ore
{itemid = 653, droprate = 140}, -- mythril_ingot
{itemid = 744, droprate = 140}, -- silver_ingot
{itemid = 652, droprate = 140}, -- steel_ingot
{itemid = 644, droprate = 140}, -- chunk_of_mythril_ore
{itemid = 807, droprate = 140}, -- sardonyx
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 4868, droprate = 125}, -- scroll_of_dispel
{itemid = 4947, droprate = 125}, -- scroll_of_utsusemi_ni
{itemid = 4753, droprate = 125}, -- scroll_of_fire_ii
{itemid = 5070, droprate = 125}, -- scroll_of_magic_finale
{itemid = 4877, droprate = 125}, -- scroll_of_absorb-agi
{itemid = 4878, droprate = 125}, -- scroll_of_absorb-int
},
{
{itemid = 0, droprate = 500}, -- nothing
{itemid = 17873, droprate = 500}, -- jug_of_scarlet_sap
},
{
{itemid = 0, droprate = 750}, -- nothing
{itemid = 17873, droprate = 250}, -- jug_of_scarlet_sap
},
{
{itemid = 0, droprate = 900}, -- nothing
{itemid = 4132, droprate = 100}, -- hi-ether
},
},
-- BCNM Shooting Fish
[9] =
{
{
{itemid = 1601, droprate = 1000}, -- mannequin_head
},
{
{itemid = 4484, droprate = 1000}, -- shall_shell
},
{
{itemid = 749, droprate = 300}, -- mythril_beastcoin
{itemid = 775, droprate = 70}, -- black_rock
{itemid = 774, droprate = 30}, -- purple_rock
{itemid = 776, droprate = 100}, -- white_rock
{itemid = 17202, droprate = 100}, -- platoon_bow
{itemid = 17462, droprate = 100}, -- platoon_mace
{itemid = 18171, droprate = 150}, -- platoon_disc
{itemid = 17271, droprate = 150}, -- platoon_gun
},
{
{itemid = 749, droprate = 310}, -- mythril_beastcoin
{itemid = 772, droprate = 50}, -- green_rock
{itemid = 771, droprate = 40}, -- yellow_rock
{itemid = 770, droprate = 40}, -- blue_rock
{itemid = 769, droprate = 40}, -- red_rock
{itemid = 773, droprate = 110}, -- translucent_rock
{itemid = 17519, droprate = 130}, -- platoon_cesti
{itemid = 18209, droprate = 100}, -- platoon_cutter
{itemid = 17692, droprate = 80}, -- platoon_spatha
{itemid = 18045, droprate = 100}, -- platoon_zaghnal
},
{
{itemid = 0, droprate = 670}, -- nothing
{itemid = 868, droprate = 190}, -- handful_of_pugil_scales
{itemid = 4484, droprate = 140}, -- shall_shell
},
{
{itemid = 0, droprate = 930}, -- nothing
{itemid = 1602, droprate = 70}, -- mannequin_body
},
{
{itemid = 4857, droprate = 180}, -- scroll_of_blaze_spikes
{itemid = 4984, droprate = 510}, -- scroll_of_horde_lullaby
{itemid = 4900, droprate = 280}, -- thunder_spirit_pact
{itemid = 4869, droprate = 30}, -- scroll_of_warp
},
},
-- BCNM Dropping Like Flies
[10] =
{
{
{itemid = 65535, droprate = 1000, amount = 4000}, -- Gil
},
{
{itemid = 846, droprate = 1000}, -- Insect Wing
},
{
{itemid = 1601, droprate = 1000},-- Mannequin Head
},
{
{itemid = 0, droprate = 636}, -- Nothing
{itemid = 12486, droprate = 364},-- Emperor Hairpin
},
{
{itemid = 12400, droprate = 175},-- Ashigaru Targe
{itemid = 12399, droprate = 175},-- Beaters Aspis
{itemid = 12395, droprate = 175},-- Varlets Targe
{itemid = 12390, droprate = 175},-- Wrestlers Aspis
{itemid = 809, droprate = 100}, -- Clear Topaz
{itemid = 795, droprate = 100}, -- Lapis Lazuli
{itemid = 796, droprate = 100}, -- Light Opal
},
{
{itemid = 13659, droprate = 250},-- Mercenary Mantle
{itemid = 13668, droprate = 250},-- Singers Mantle
{itemid = 13662, droprate = 250},-- Wizards Mantle
{itemid = 13672, droprate = 250},-- Wyvern Mantle
},
{
{itemid = 4947, droprate = 70}, -- Scroll Of Utsusemi Ni
{itemid = 5070, droprate = 70}, -- Scroll Of Magic Finale
{itemid = 17863, droprate = 150},-- Jug Of Quadav Bug Broth
{itemid = 799, droprate = 100}, -- Onyx
{itemid = 795, droprate = 100}, -- Lapis Lazuli
{itemid = 796, droprate = 100}, -- Light Opal
{itemid = 4868, droprate = 150}, -- Scroll Of Dispel
{itemid = 4751, droprate = 100}, -- Scroll Of Erase
{itemid = 690, droprate = 90}, -- Elm Log
{itemid = 1602, droprate = 70}, -- Mannequin Body
},
},
-- KSNM Horns of War
[11] =
{
{
{itemid = 1441, droprate = 169}, -- Libation Abjuration
{itemid = 17939, droprate = 268}, -- Kriegsbeil
{itemid = 17823, droprate = 99}, -- Shinsoku
{itemid = 18173, droprate = 85}, -- Nokizaru Shuriken
{itemid = 17694, droprate = 70}, -- Guespiere
{itemid = 17464, droprate = 85}, -- Purgatory Mace
{itemid = 18351, droprate = 225}, -- Meteor Cesti
},
{
{itemid = 1442, droprate = 169}, -- Oblation Abjuration
{itemid = 17789, droprate = 14}, -- Unsho
{itemid = 17838, droprate = 239}, -- Harlequins Horn
{itemid = 18088, droprate = 85}, -- Dreizack
{itemid = 18211, droprate = 254}, -- Gawains Axe
{itemid = 17578, droprate = 183}, -- Zen Pole
{itemid = 17695, droprate = 70}, -- Bayards Sword
},
{
{itemid = 703, droprate = 563}, -- Petrified Log
{itemid = 1446, droprate = 296}, -- Lacquer Tree Log
{itemid = 831, droprate = 14}, -- Square Of Shining Cloth
{itemid = 722, droprate = 141}, -- Divine Log
},
{
{itemid = 860, droprate = 535}, -- Behemoth Hide
{itemid = 883, droprate = 366}, -- Behemoth Horn
{itemid = 17108, droprate = 48}, -- Healing Staff
},
{
{itemid = 902, droprate = 99}, -- Demon Horn
{itemid = 703, droprate = 70}, -- Petrified Log
{itemid = 1132, droprate = 70}, -- Square Of Raxa
{itemid = 830, droprate = 28}, -- Square Of Rainbow Cloth
{itemid = 4173, droprate = 113}, -- Hi-reraiser
{itemid = 703, droprate = 211}, -- Petrified Log
{itemid = 942, droprate = 141}, -- Philosophers Stone
{itemid = 737, droprate = 56}, -- Chunk Of Gold Ore
{itemid = 644, droprate = 85}, -- Chunk Of Mythril Ore
{itemid = 887, droprate = 70}, -- Coral Fragment
{itemid = 700, droprate = 85}, -- Mahogany Log
{itemid = 866, droprate = 42}, -- Handful Of Wyvern Scales
{itemid = 645, droprate = 42}, -- Chunk Of Darksteel Ore
{itemid = 895, droprate = 70}, -- Ram Horn
{itemid = 702, droprate = 85}, -- Ebony Log
{itemid = 4172, droprate = 28}, -- Reraiser
{itemid = 738, droprate = 42}, -- Chunk Of Platinum Ore
{itemid = 4174, droprate = 42}, -- Vile Elixir
{itemid = 4175, droprate = 7}, -- Vile Elixir +1
},
{
{itemid = 1527, droprate = 208}, -- Behemoth Tongue
{itemid = 883, droprate = 296}, -- Behemoth Horn
{itemid = 4199, droprate = 155}, -- Strength Potion
{itemid = 4201, droprate = 70}, -- Dexterity Potion
{itemid = 4205, droprate = 141}, -- Agility Potion
{itemid = 4203, droprate = 113}, -- Vitality Potion
},
{
{itemid = 3341, droprate = 1000}, -- Beastly Shank
},
{
{itemid = 4209, droprate = 169}, -- Mind Potion
{itemid = 4207, droprate = 70}, -- Intelligence Potion
{itemid = 4211, droprate = 113}, -- Charisma Potion
{itemid = 4213, droprate = 155}, -- Icarus Wing
{itemid = 17840, droprate = 254}, -- Angel Lyre
{itemid = 785, droprate = 99}, -- Emerald
{itemid = 804, droprate = 42}, -- Spinel
{itemid = 786, droprate = 56}, -- Ruby
{itemid = 787, droprate = 28}, -- Diamond
},
{
{itemid = 4135, droprate = 296}, -- Hi-ether +3
{itemid = 4119, droprate = 225}, -- Hi-potion +3
{itemid = 4173, droprate = 197}, -- Hi-reraiser
{itemid = 4175, droprate = 282}, -- Vile Elixir +1
},
{
{itemid = 887, droprate = 141}, -- Coral Fragment
{itemid = 1132, droprate = 14}, -- Square Of Raxa
{itemid = 902, droprate = 113}, -- Demon Horn
{itemid = 737, droprate = 28}, -- Chunk Of Gold Ore
{itemid = 644, droprate = 85}, -- Chunk Of Mythril Ore
{itemid = 4174, droprate = 56}, -- Vile Elixir
{itemid = 895, droprate = 28}, -- Ram Horn
{itemid = 703, droprate = 296}, -- Petrified Log
{itemid = 738, droprate = 14}, -- Chunk Of Platinum Ore
{itemid = 700, droprate = 56}, -- Mahogany Log
{itemid = 866, droprate = 70}, -- Handful Of Wyvern Scales
{itemid = 1465, droprate = 42}, -- Slab Of Granite
{itemid = 645, droprate = 42}, -- Chunk Of Darksteel Ore
{itemid = 702, droprate = 42}, -- Ebony Log
{itemid = 4173, droprate = 42}, -- Hi-reraiser
{itemid = 823, droprate = 113}, -- Spool Of Gold Thread
{itemid = 830, droprate = 28}, -- Square Of Rainbow Cloth
},
{
{itemid = 1132, droprate = 127}, -- Square Of Raxa
{itemid = 837, droprate = 56}, -- Spool Of Malboro Fiber
{itemid = 942, droprate = 225}, -- Philosophers Stone
{itemid = 844, droprate = 423}, -- Phoenix Feather
{itemid = 836, droprate = 70}, -- Square Of Damascene Cloth
{itemid = 658, droprate = 42}, -- Damascus Ingot
{itemid = 1110, droprate = 85}, -- Vial Of Black Beetle Blood
},
},
-- BCNM Under Observation
[12] =
{
{
{itemid = 0, droprate = 910}, -- Nothing
{itemid = 13056, droprate = 90}, -- Peacock Charm
},
{
{itemid = 0, droprate = 467}, -- Nothing
{itemid = 18086, droprate = 48}, -- Behourd Lance
{itemid = 18046, droprate = 61}, -- Mutilator
{itemid = 18210, droprate = 46}, -- Raifu
{itemid = 15286, droprate = 302},-- Tilt Belt
{itemid = 18350, droprate = 76}, -- Tourney Patas
},
{
{itemid = 0, droprate = 413}, -- Nothing
{itemid = 17696, droprate = 42}, -- Buzzard Tuck
{itemid = 17936, droprate = 77}, -- De Saintres Axe
{itemid = 17693, droprate = 73}, -- Grudge Sword
{itemid = 15287, droprate = 258},-- Mantra Belt
{itemid = 4717, droprate = 68}, -- Scroll Of Refresh
{itemid = 4947, droprate = 55}, -- Scroll Of Utsusemi Ni
{itemid = 4858, droprate = 14}, -- Scroll Of Ice Spikes
},
{
{itemid = 4858, droprate = 114}, -- Scroll Of Ice Spikes
{itemid = 4717, droprate = 174}, -- Scroll Of Refresh
{itemid = 4947, droprate = 138}, -- Scroll Of Utsusemi Ni
{itemid = 769, droprate = 16}, -- Red Rock
{itemid = 770, droprate = 17}, -- Blue Rock
{itemid = 771, droprate = 17}, -- Yellow Rock
{itemid = 772, droprate = 18}, -- Green Rock
{itemid = 773, droprate = 17}, -- Translucent Rock
{itemid = 774, droprate = 16}, -- Purple Rock
{itemid = 775, droprate = 18}, -- Black Rock
{itemid = 776, droprate = 16}, -- White Rock
{itemid = 749, droprate = 102}, -- Mythril Beastcoin
{itemid = 748, droprate = 120}, -- Gold Beastcoin
{itemid = 699, droprate = 22}, -- Oak Log
{itemid = 811, droprate = 18}, -- Ametrine
{itemid = 793, droprate = 18}, -- Black Pearl
{itemid = 790, droprate = 20}, -- Garnet
{itemid = 808, droprate = 19}, -- Goshenite
{itemid = 792, droprate = 21}, -- Pearl
{itemid = 788, droprate = 35}, -- Peridot
{itemid = 815, droprate = 17}, -- Sphene
{itemid = 798, droprate = 23}, -- Turquoise
{itemid = 4172, droprate = 21}, -- Reraiser
{itemid = 4174, droprate = 16}, -- Vile Elixir
},
{
{itemid = 4896, droprate = 116}, -- Fire Spirit Pact
{itemid = 4874, droprate = 113}, -- Scroll Of Absorb-str
{itemid = 4751, droprate = 137}, -- Scroll Of Erase
{itemid = 4858, droprate = 67}, -- Scroll Of Ice Spikes
{itemid = 4714, droprate = 99}, -- Scroll Of Phalanx
{itemid = 811, droprate = 58}, -- Ametrine
{itemid = 793, droprate = 52}, -- Black Pearl
{itemid = 790, droprate = 51}, -- Garnet
{itemid = 808, droprate = 65}, -- Goshenite
{itemid = 792, droprate = 61}, -- Pearl
{itemid = 788, droprate = 63}, -- Peridot
{itemid = 815, droprate = 55}, -- Sphene
{itemid = 798, droprate = 62}, -- Turquoise
},
{
{itemid = 939, droprate = 1000}, -- Hecteyes Eye
},
{
{itemid = 914, droprate = 1000}, -- Vial Of Mercury
},
},
-- BCNM Eye of the Tiger
[13] =
{
{
{itemid = 884, droprate = 1000}, -- black_tiger_fang
},
{
{itemid = 884, droprate = 1000}, -- black_tiger_fang
},
{
{itemid = 0, droprate = 700}, -- nothing
{itemid = 1012, droprate = 300}, -- nue_fang
},
{
{itemid = 0, droprate = 125}, -- nothing
{itemid = 14842, droprate = 125}, -- ivory_mitts
{itemid = 15151, droprate = 125}, -- super_ribbon
{itemid = 15148, droprate = 125}, -- mana_circlet
{itemid = 15149, droprate = 125}, -- rival_ribbon
{itemid = 14845, droprate = 125}, -- sly_gauntlets
{itemid = 15150, droprate = 125}, -- shock_mask
{itemid = 14843, droprate = 125}, -- spiked_finger_gauntlets
},
{
{itemid = 13168, droprate = 125}, -- intellect_torque
{itemid = 13677, droprate = 125}, -- esoteric_mantle
{itemid = 13679, droprate = 125}, -- templars_mantle
{itemid = 13678, droprate = 125}, -- snipers_mantle
{itemid = 13166, droprate = 125}, -- hateful_collar
{itemid = 13167, droprate = 125}, -- storm_gorget
{itemid = 13676, droprate = 125}, -- heavy_mantle
{itemid = 13169, droprate = 125}, -- benign_necklace
},
{
{itemid = 0, droprate = 125}, -- nothing
{itemid = 745, droprate = 125}, -- gold_ingot
{itemid = 895, droprate = 125}, -- ram_horn
{itemid = 1122, droprate = 125}, -- wyvern_skin
{itemid = 702, droprate = 125}, -- ebony_log
{itemid = 653, droprate = 125}, -- mythril_ingot
{itemid = 859, droprate = 125}, -- ram_skin
{itemid = 887, droprate = 125}, -- coral_fragment
},
{
{itemid = 0, droprate = 400}, -- nothing
{itemid = 5152, droprate = 200}, -- slice_of_buffalo_meat
{itemid = 4272, droprate = 200}, -- slice_of_dragon_meat
{itemid = 4377, droprate = 200}, -- slice_of_coeurl_meat
},
{
{itemid = 0, droprate = 625}, -- nothing
{itemid = 4814, droprate = 125}, -- scroll_of_freeze
{itemid = 4621, droprate = 125}, -- scroll_of_raise_ii
{itemid = 4818, droprate = 125}, -- scroll_of_quake
},
},
-- BCNM Shots in the Dark
[14] =
{
{
{itemid = 748, droprate = 500}, -- gold_beastcoin
{itemid = 749, droprate = 500}, -- mythril_beastcoin
},
{
{itemid = 652, droprate = 500}, -- steel_ingot
{itemid = 791, droprate = 500}, -- aquamarine
},
{
{itemid = 0, droprate = 500}, -- nothing
{itemid = 4224, droprate = 500}, -- demon_quiver
},
{
{itemid = 0, droprate = 600}, -- nothing
{itemid = 14661, droprate = 200}, -- teleport_ring_holla
{itemid = 14664, droprate = 200}, -- teleport_ring_vahzl
},
{
{itemid = 0, droprate = 600}, -- nothing
{itemid = 13687, droprate = 200}, -- sapient_cape
{itemid = 14870, droprate = 200}, -- trainers_wristbands
},
},
-- KSNM Double Dragonian
[15] =
{
{
{itemid = 18378, droprate = 222}, -- Subduer
{itemid = 17699, droprate = 302}, -- Dissector
{itemid = 17509, droprate = 245}, -- Destroyers
{itemid = 18005, droprate = 208}, -- Heart Snatcher
},
{
{itemid = 0, droprate = 638}, -- Nothing
{itemid = 1133, droprate = 10}, -- Vial Of Dragon Blood
{itemid = 4486, droprate = 176}, -- Dragon Heart
{itemid = 4272, droprate = 176}, -- Slice Of Dragon Meat
},
{
{itemid = 0, droprate = 638}, -- Nothing
{itemid = 1133, droprate = 10}, -- Vial Of Dragon Blood
{itemid = 4486, droprate = 176}, -- Dragon Heart
{itemid = 4272, droprate = 176}, -- Slice Of Dragon Meat
},
{
{itemid = 0, droprate = 392}, -- Nothing
{itemid = 19026, droprate = 354}, -- Spear Strap
{itemid = 19024, droprate = 165}, -- Sword Strap
{itemid = 19025, droprate = 89}, -- Pole Grip
},
{
{itemid = 14764, droprate = 586}, -- Minuet Earring
{itemid = 655, droprate = 184}, -- Adaman Ingot
{itemid = 747, droprate = 207}, -- Orichalcum Ingot
},
{
{itemid = 17842, droprate = 238}, -- Sorrowful Harp
{itemid = 14762, droprate = 250}, -- Attilas Earring
{itemid = 17700, droprate = 225}, -- Durandal
{itemid = 18006, droprate = 275}, -- Hoplites Harpe
},
{
{itemid = 737, droprate = 122}, -- Chunk Of Gold Ore
{itemid = 4172, droprate = 54}, -- Reraiser
{itemid = 644, droprate = 41}, -- Chunk Of Mythril Ore
{itemid = 902, droprate = 81}, -- Demon Horn
{itemid = 702, droprate = 149}, -- Ebony Log
{itemid = 866, droprate = 54}, -- Handful Of Wyvern Scales
{itemid = 4175, droprate = 27}, -- Vile Elixir +1
{itemid = 700, droprate = 41}, -- Mahogany Log
{itemid = 887, droprate = 95}, -- Coral Fragment
{itemid = 703, droprate = 108}, -- Petrified Log
{itemid = 844, droprate = 135}, -- Phoenix Feather
{itemid = 738, droprate = 54}, -- Chunk Of Platinum Ore
{itemid = 895, droprate = 14}, -- Ram Horn
{itemid = 830, droprate = 14}, -- Square Of Rainbow Cloth
{itemid = 645, droprate = 68}, -- Chunk Of Darksteel Ore
{itemid = 4173, droprate = 14}, -- Hi-reraiser
{itemid = 1132, droprate = 135}, -- Square Of Raxa
},
{
{itemid = 836, droprate = 96}, -- Square Of Damascene Cloth
{itemid = 658, droprate = 27}, -- Damascus Ingot
{itemid = 942, droprate = 164}, -- Philosophers Stone
{itemid = 844, droprate = 260}, -- Phoenix Feather
{itemid = 837, droprate = 96}, -- Spool Of Malboro Fiber
{itemid = 1132, droprate = 288}, -- Square Of Raxa
{itemid = 1110, droprate = 41}, -- Vial Of Black Beetle Blood
},
},
-- KSNM Contaminated Colosseum
[17] =
{
{
{itemid = 837, droprate = 1000}, -- Spool Of Malboro Fiber
},
{
{itemid = 17827, droprate = 217},-- Michishiba-no-tsuyu
{itemid = 17451, droprate = 174},-- Morgenstern
{itemid = 17793, droprate = 333},-- Senjuinrikio
{itemid = 17589, droprate = 174},-- Thyrsusstab
},
{
{itemid = 13402, droprate = 101},-- Cassie Earring
{itemid = 19027, droprate = 43}, -- Claymore Grip
{itemid = 920, droprate = 275}, -- Malboro Vine
{itemid = 1013, droprate = 275}, -- Morbolger Vine
{itemid = 19025, droprate = 203},-- Pole Grip
{itemid = 19026, droprate = 116},-- Spear Strap
},
{
{itemid = 655, droprate = 159}, -- Adaman Ingot
{itemid = 747, droprate = 290}, -- Orichalcum Ingot
{itemid = 13182, droprate = 406},-- Oscar Scarf
},
{
{itemid = 15325, droprate = 159},-- Evokers Boots
{itemid = 14872, droprate = 217},-- Ostreger Mitts
{itemid = 15181, droprate = 145},-- Pineal Hat
{itemid = 15387, droprate = 159},-- Trackers Kecks
},
{
{itemid = 887, droprate = 101}, -- Coral Fragment
{itemid = 645, droprate = 29}, -- Chunk Of Darksteel Ore
{itemid = 902, droprate = 29}, -- Demon Horn
{itemid = 702, droprate = 29}, -- Ebony Log
{itemid = 737, droprate = 101}, -- Chunk Of Gold Ore
{itemid = 823, droprate = 29}, -- Spool Of Gold Thread
{itemid = 1465, droprate = 29}, -- Slab Of Granite
{itemid = 700, droprate = 43}, -- Mahogany Log
{itemid = 644, droprate = 29}, -- Chunk Of Mythril Ore
{itemid = 703, droprate = 58}, -- Petrified Log
{itemid = 738, droprate = 14}, -- Chunk Of Platinum Ore
{itemid = 830, droprate = 58}, -- Square Of Rainbow Cloth
{itemid = 895, droprate = 14}, -- Ram Horn
{itemid = 4174, droprate = 58}, -- Vile Elixir
{itemid = 4175, droprate = 29}, -- Vile Elixir +1
{itemid = 866, droprate = 72}, -- Handful Of Wyvern Scales
},
{
{itemid = 1110, droprate = 87}, -- Vial Of Black Beetle Blood
{itemid = 658, droprate = 14}, -- Damascus Ingot
{itemid = 836, droprate = 29}, -- Square Of Damascene Cloth
{itemid = 837, droprate = 43}, -- Spool Of Malboro Fiber
{itemid = 942, droprate = 174}, -- Philosophers Stone
{itemid = 844, droprate = 246}, -- Phoenix Feather
{itemid = 1132, droprate = 159}, -- Square Of Raxa
},
},
}
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 |
MalRD/darkstar | scripts/zones/Davoi/npcs/_45i.lua | 9 | 1850 | -----------------------------------
-- Area: Davoi
-- NPC: Wailing Pond
-- Used In Quest: Whence Blows the Wind
-- !pos 380 0.1 -181 149
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Davoi/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(52);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 52 and player:getCharVar("miniQuestForORB_CS") == 1) then
local c = player:getCharVar("countRedPoolForORB");
if (c == 0) then
player:setCharVar("countRedPoolForORB", c + 2);
player:delKeyItem(dsp.ki.WHITE_ORB);
player:addKeyItem(dsp.ki.PINK_ORB);
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.PINK_ORB);
elseif (c == 1 or c == 4 or c == 8) then
player:setCharVar("countRedPoolForORB", c + 2);
player:delKeyItem(dsp.ki.PINK_ORB);
player:addKeyItem(dsp.ki.RED_ORB);
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.RED_ORB);
elseif (c == 5 or c == 9 or c == 12) then
player:setCharVar("countRedPoolForORB", c + 2);
player:delKeyItem(dsp.ki.RED_ORB);
player:addKeyItem(dsp.ki.BLOOD_ORB);
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.BLOOD_ORB);
elseif (c == 13) then
player:setCharVar("countRedPoolForORB", c + 2);
player:delKeyItem(dsp.ki.BLOOD_ORB);
player:addKeyItem(dsp.ki.CURSED_ORB);
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.CURSED_ORB);
player:addStatusEffect(dsp.effect.CURSE_I,50,0,900);
end
end
end; | gpl-3.0 |
Lsty/ygopro-scripts | c64319467.lua | 3 | 2409 | --ダブルフィン・シャーク
function c64319467.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(64319467,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCost(c64319467.spcost)
e1:SetTarget(c64319467.sptg)
e1:SetOperation(c64319467.spop)
c:RegisterEffect(e1)
Duel.AddCustomActivityCounter(64319467,ACTIVITY_SPSUMMON,c64319467.counterfilter)
end
function c64319467.counterfilter(c)
return c:IsAttribute(ATTRIBUTE_WATER)
end
function c64319467.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(64319467,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:SetTarget(c64319467.splimit)
Duel.RegisterEffect(e1,tp)
end
function c64319467.splimit(e,c)
return c:GetAttribute()~=ATTRIBUTE_WATER
end
function c64319467.filter(c,e,tp)
local lv=c:GetLevel()
return (lv==3 or lv==4) and c:IsRace(RACE_FISH) and c:IsAttribute(ATTRIBUTE_WATER)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c64319467.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c64319467.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c64319467.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c64319467.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c64319467.spop(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_DEFENCE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e2)
Duel.SpecialSummonComplete()
end
end
| gpl-2.0 |
openwrt/luci | libs/luci-lib-nixio/axTLS/samples/lua/axssl.lua | 176 | 19286 | #!/usr/local/bin/lua
--
-- Copyright (c) 2007, Cameron Rich
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the axTLS project nor the names of its
-- contributors may be used to endorse or promote products derived
-- from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
--
-- Demonstrate the use of the axTLS library in Lua with a set of
-- command-line parameters similar to openssl. In fact, openssl clients
-- should be able to communicate with axTLS servers and visa-versa.
--
-- This code has various bits enabled depending on the configuration. To enable
-- the most interesting version, compile with the 'full mode' enabled.
--
-- To see what options you have, run the following:
-- > [lua] axssl s_server -?
-- > [lua] axssl s_client -?
--
-- The axtls/axtlsl shared libraries must be in the same directory or be found
-- by the OS.
--
--
require "bit"
require("axtlsl")
local socket = require("socket")
-- print version?
if #arg == 1 and arg[1] == "version" then
print("axssl.lua "..axtlsl.ssl_version())
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the basic options.
--
function print_options(option)
print("axssl: Error: '"..option.."' is an invalid command.")
print("usage: axssl [s_server|s_client|version] [args ...]")
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the server options.
--
function print_server_options(build_mode, option)
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.ssl_get_config(
axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
print("unknown option "..option)
print("usage: s_server [args ...]")
print(" -accept\t- port to accept on (default is 4433)")
print(" -quiet\t\t- No server output")
if build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then
print(" -cert arg\t- certificate file to add (in addition to "..
"default) to chain -")
print("\t\t Can repeat up to "..cert_size.." times")
print(" -key arg\t- Private key file to use - default DER format")
print(" -pass\t\t- private key file pass phrase source")
end
if build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then
print(" -verify\t- turn on peer certificate verification")
print(" -CAfile arg\t- Certificate authority - default DER format")
print("\t\t Can repeat up to "..ca_cert_size.." times")
end
if build_mode == axtlsl.SSL_BUILD_FULL_MODE then
print(" -debug\t\t- Print more output")
print(" -state\t\t- Show state messages")
print(" -show-rsa\t- Show RSA state")
end
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the client options.
--
function print_client_options(build_mode, option)
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.ssl_get_config(
axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
print("unknown option "..option)
if build_mode >= axtlsl.SSL_BUILD_ENABLE_CLIENT then
print("usage: s_client [args ...]")
print(" -connect host:port - who to connect to (default "..
"is localhost:4433)")
print(" -verify\t- turn on peer certificate verification")
print(" -cert arg\t- certificate file to use - default DER format")
print(" -key arg\t- Private key file to use - default DER format")
print("\t\t Can repeat up to "..cert_size.." times")
print(" -CAfile arg\t- Certificate authority - default DER format")
print("\t\t Can repeat up to "..ca_cert_size.."times")
print(" -quiet\t\t- No client output")
print(" -pass\t\t- private key file pass phrase source")
print(" -reconnect\t- Drop and re-make the connection "..
"with the same Session-ID")
if build_mode == axtlsl.SSL_BUILD_FULL_MODE then
print(" -debug\t\t- Print more output")
print(" -state\t\t- Show state messages")
print(" -show-rsa\t- Show RSA state")
end
else
print("Change configuration to allow this feature")
end
os.exit(1)
end
-- Implement the SSL server logic.
function do_server(build_mode)
local i = 2
local v
local port = 4433
local options = axtlsl.SSL_DISPLAY_CERTS
local quiet = false
local password = ""
local private_key_file = nil
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.
ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
local cert = {}
local ca_cert = {}
while i <= #arg do
if arg[i] == "-accept" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
port = arg[i]
elseif arg[i] == "-quiet" then
quiet = true
options = bit.band(options, bit.bnot(axtlsl.SSL_DISPLAY_CERTS))
elseif build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then
if arg[i] == "-cert" then
if i >= #arg or #cert >= cert_size then
print_server_options(build_mode, arg[i])
end
i = i + 1
table.insert(cert, arg[i])
elseif arg[i] == "-key" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
private_key_file = arg[i]
options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY)
elseif arg[i] == "-pass" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
password = arg[i]
elseif build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then
if arg[i] == "-verify" then
options = bit.bor(options, axtlsl.SSL_CLIENT_AUTHENTICATION)
elseif arg[i] == "-CAfile" then
if i >= #arg or #ca_cert >= ca_cert_size then
print_server_options(build_mode, arg[i])
end
i = i + 1
table.insert(ca_cert, arg[i])
elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then
if arg[i] == "-debug" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES)
elseif arg[i] == "-state" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_STATES)
elseif arg[i] == "-show-rsa" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_RSA)
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
i = i + 1
end
-- Create socket for incoming connections
local server_sock = socket.try(socket.bind("*", port))
---------------------------------------------------------------------------
-- This is where the interesting stuff happens. Up until now we've
-- just been setting up sockets etc. Now we do the SSL handshake.
---------------------------------------------------------------------------
local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_SVR_SESS)
if ssl_ctx == nil then error("Error: Server context is invalid") end
if private_key_file ~= nil then
local obj_type = axtlsl.SSL_OBJ_RSA_KEY
if string.find(private_key_file, ".p8") then
obj_type = axtlsl.SSL_OBJ_PKCS8
end
if string.find(private_key_file, ".p12") then
obj_type = axtlsl.SSL_OBJ_PKCS12
end
if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file,
password) ~= axtlsl.SSL_OK then
error("Private key '" .. private_key_file .. "' is undefined.")
end
end
for _, v in ipairs(cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .. "' is undefined.")
end
end
for _, v in ipairs(ca_cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .."' is undefined.")
end
end
while true do
if not quiet then print("ACCEPT") end
local client_sock = server_sock:accept();
local ssl = axtlsl.ssl_server_new(ssl_ctx, client_sock:getfd())
-- do the actual SSL handshake
local connected = false
local res
local buf
while true do
socket.select({client_sock}, nil)
res, buf = axtlsl.ssl_read(ssl)
if res == axtlsl.SSL_OK then -- connection established and ok
if axtlsl.ssl_handshake_status(ssl) == axtlsl.SSL_OK then
if not quiet and not connected then
display_session_id(ssl)
display_cipher(ssl)
end
connected = true
end
end
if res > axtlsl.SSL_OK then
for _, v in ipairs(buf) do
io.write(string.format("%c", v))
end
elseif res < axtlsl.SSL_OK then
if not quiet then
axtlsl.ssl_display_error(res)
end
break
end
end
-- client was disconnected or the handshake failed.
print("CONNECTION CLOSED")
axtlsl.ssl_free(ssl)
client_sock:close()
end
axtlsl.ssl_ctx_free(ssl_ctx)
end
--
-- Implement the SSL client logic.
--
function do_client(build_mode)
local i = 2
local v
local port = 4433
local options =
bit.bor(axtlsl.SSL_SERVER_VERIFY_LATER, axtlsl.SSL_DISPLAY_CERTS)
local private_key_file = nil
local reconnect = 0
local quiet = false
local password = ""
local session_id = {}
local host = "127.0.0.1"
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.
ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
local cert = {}
local ca_cert = {}
while i <= #arg do
if arg[i] == "-connect" then
if i >= #arg then
print_client_options(build_mode, arg[i])
end
i = i + 1
local t = string.find(arg[i], ":")
host = string.sub(arg[i], 1, t-1)
port = string.sub(arg[i], t+1)
elseif arg[i] == "-cert" then
if i >= #arg or #cert >= cert_size then
print_client_options(build_mode, arg[i])
end
i = i + 1
table.insert(cert, arg[i])
elseif arg[i] == "-key" then
if i >= #arg then
print_client_options(build_mode, arg[i])
end
i = i + 1
private_key_file = arg[i]
options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY)
elseif arg[i] == "-CAfile" then
if i >= #arg or #ca_cert >= ca_cert_size then
print_client_options(build_mode, arg[i])
end
i = i + 1
table.insert(ca_cert, arg[i])
elseif arg[i] == "-verify" then
options = bit.band(options,
bit.bnot(axtlsl.SSL_SERVER_VERIFY_LATER))
elseif arg[i] == "-reconnect" then
reconnect = 4
elseif arg[i] == "-quiet" then
quiet = true
options = bit.band(options, bnot(axtlsl.SSL_DISPLAY_CERTS))
elseif arg[i] == "-pass" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
password = arg[i]
elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then
if arg[i] == "-debug" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES)
elseif arg[i] == "-state" then
options = bit.bor(axtlsl.SSL_DISPLAY_STATES)
elseif arg[i] == "-show-rsa" then
options = bit.bor(axtlsl.SSL_DISPLAY_RSA)
else -- don't know what this is
print_client_options(build_mode, arg[i])
end
else -- don't know what this is
print_client_options(build_mode, arg[i])
end
i = i + 1
end
local client_sock = socket.try(socket.connect(host, port))
local ssl
local res
if not quiet then print("CONNECTED") end
---------------------------------------------------------------------------
-- This is where the interesting stuff happens. Up until now we've
-- just been setting up sockets etc. Now we do the SSL handshake.
---------------------------------------------------------------------------
local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_CLNT_SESS)
if ssl_ctx == nil then
error("Error: Client context is invalid")
end
if private_key_file ~= nil then
local obj_type = axtlsl.SSL_OBJ_RSA_KEY
if string.find(private_key_file, ".p8") then
obj_type = axtlsl.SSL_OBJ_PKCS8
end
if string.find(private_key_file, ".p12") then
obj_type = axtlsl.SSL_OBJ_PKCS12
end
if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file,
password) ~= axtlsl.SSL_OK then
error("Private key '"..private_key_file.."' is undefined.")
end
end
for _, v in ipairs(cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .. "' is undefined.")
end
end
for _, v in ipairs(ca_cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .."' is undefined.")
end
end
-- Try session resumption?
if reconnect ~= 0 then
local session_id = nil
local sess_id_size = 0
while reconnect > 0 do
reconnect = reconnect - 1
ssl = axtlsl.ssl_client_new(ssl_ctx,
client_sock:getfd(), session_id, sess_id_size)
res = axtlsl.ssl_handshake_status(ssl)
if res ~= axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
axtlsl.ssl_free(ssl)
os.exit(1)
end
display_session_id(ssl)
session_id = axtlsl.ssl_get_session_id(ssl)
sess_id_size = axtlsl.ssl_get_session_id_size(ssl)
if reconnect > 0 then
axtlsl.ssl_free(ssl)
client_sock:close()
client_sock = socket.try(socket.connect(host, port))
end
end
else
ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), nil, 0)
end
-- check the return status
res = axtlsl.ssl_handshake_status(ssl)
if res ~= axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
os.exit(1)
end
if not quiet then
local common_name = axtlsl.ssl_get_cert_dn(ssl,
axtlsl.SSL_X509_CERT_COMMON_NAME)
if common_name ~= nil then
print("Common Name:\t\t\t"..common_name)
end
display_session_id(ssl)
display_cipher(ssl)
end
while true do
local line = io.read()
if line == nil then break end
local bytes = {}
for i = 1, #line do
bytes[i] = line.byte(line, i)
end
bytes[#line+1] = 10 -- add carriage return, null
bytes[#line+2] = 0
res = axtlsl.ssl_write(ssl, bytes, #bytes)
if res < axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
break
end
end
axtlsl.ssl_ctx_free(ssl_ctx)
client_sock:close()
end
--
-- Display what cipher we are using
--
function display_cipher(ssl)
io.write("CIPHER is ")
local cipher_id = axtlsl.ssl_get_cipher_id(ssl)
if cipher_id == axtlsl.SSL_AES128_SHA then
print("AES128-SHA")
elseif cipher_id == axtlsl.SSL_AES256_SHA then
print("AES256-SHA")
elseif axtlsl.SSL_RC4_128_SHA then
print("RC4-SHA")
elseif axtlsl.SSL_RC4_128_MD5 then
print("RC4-MD5")
else
print("Unknown - "..cipher_id)
end
end
--
-- Display what session id we have.
--
function display_session_id(ssl)
local session_id = axtlsl.ssl_get_session_id(ssl)
local v
if #session_id > 0 then
print("-----BEGIN SSL SESSION PARAMETERS-----")
for _, v in ipairs(session_id) do
io.write(string.format("%02x", v))
end
print("\n-----END SSL SESSION PARAMETERS-----")
end
end
--
-- Main entry point. Doesn't do much except works out whether we are a client
-- or a server.
--
if #arg == 0 or (arg[1] ~= "s_server" and arg[1] ~= "s_client") then
print_options(#arg > 0 and arg[1] or "")
end
local build_mode = axtlsl.ssl_get_config(axtlsl.SSL_BUILD_MODE)
_ = arg[1] == "s_server" and do_server(build_mode) or do_client(build_mode)
os.exit(0)
| apache-2.0 |
weshoke/DSL | test/test.lust.json.lua | 1 | 1663 | LuaAV.addmodulepath(script.path.."/..")
LuaAV.addmodulepath(script.path.."/../../Lust")
local DSL = require"DSL"
local utils = require"DSL.utilities"
local Lust = require"Lust"
local dsl = DSL{
tokens = [=[
NUMBER = float+integer
STRING = string
TRUE = P"true"
FALSE = P"false"
NULL = P"null"
]=],
rules = [==[
value = object + array + values
entry = STRING * T":" * Assert(value, "entry.value")
object = T"{" * (entry * (T"," * entry)^0)^-1 * Assert(T"}", "object.RIGHT_BRACE")
array = T"[" * (value * (T"," * value)^0)^-1 * Assert(T"]", "array.RIGHT_BRACKET")
]==],
annotations = {
-- value tokens
NUMBER = { value=true },
STRING = { value=true },
TRUE = { value=true },
FALSE = { value=true },
NULL = { value=true },
-- rule annotations
value = { collapsable=true },
values = { collapsable=true },
},
}
local parser = dsl:parser{
root = "object",
mark_position = false,
trace = true,
--token_trace = true,
--anonymous_token_trace = true,
--token_event = utils.token_event,
--rule_event = utils.rule_event,
}
local function nl(str) return string.gsub(str, [[\n]], "\n"):gsub([[\t]], "\t") end
local lust = Lust{
[1] = "@dispatch",
dispatch = [[@if(rule)<{{@(rule)}}>else<{{$1}}>]],
object = nl[[
{
@map{., _=",\n"}:dispatch
}]],
array = '[@map{., _=", "}:dispatch]',
entry = [[@1:dispatch : @2:dispatch]],
}
local code = [[
{
"list" : [1, 2, 3],
"vec3" : {
"x": 1, "y": 0, "z": 0.5
}
}
]]
local ok, ast = pcall(parser.parse, parser, code)
if(ok and ast) then
--utils.printt(ast, "AST")
print"Resynthesized code:"
print"*******************"
print(lust:gen(ast))
print"*******************"
end | mit |
Lsty/ygopro-scripts | c96099959.lua | 7 | 1342 | --X-セイバー パロムロ
function c96099959.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(96099959,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_GRAVE)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c96099959.condition)
e1:SetCost(c96099959.cost)
e1:SetTarget(c96099959.target)
e1:SetOperation(c96099959.operation)
c:RegisterEffect(e1)
end
function c96099959.filter(c,ec,tp)
return c~=ec and c:IsSetCard(0xd) and c:IsLocation(LOCATION_GRAVE) and c:GetPreviousControler()==tp
and c:IsReason(REASON_BATTLE)
end
function c96099959.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c96099959.filter,1,nil,e:GetHandler(),tp)
end
function c96099959.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,500) end
Duel.PayLPCost(tp,500)
end
function c96099959.target(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.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c96099959.operation(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
wzb56/lua-resty-kafka | lib/resty/kafka/ringbuffer.lua | 2 | 1476 | -- Copyright (C) Dejiang Zhu(doujiang24)
local setmetatable = setmetatable
local ngx_null = ngx.null
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
local _M = { _VERSION = "0.01" }
local mt = { __index = _M }
function _M.new(self, batch_num, max_buffering)
local sendbuffer = {
queue = new_tab(max_buffering * 3, 0),
batch_num = batch_num,
size = max_buffering * 3,
start = 1,
num = 0,
}
return setmetatable(sendbuffer, mt)
end
function _M.add(self, topic, key, message)
local num = self.num
local size = self.size
if num >= size then
return nil, "buffer overflow"
end
local index = (self.start + num) % size
local queue = self.queue
queue[index] = topic
queue[index + 1] = key
queue[index + 2] = message
self.num = num + 3
return true, nil, (self.num / 3 >= self.batch_num)
end
function _M.pop(self)
local num = self.num
if num <= 0 then
return nil, "empty buffer"
end
self.num = num - 3
local start = self.start
local queue = self.queue
self.start = (start + 3) % self.size
local key, topic, message = queue[start], queue[start + 1], queue[start + 2]
queue[start], queue[start + 1], queue[start + 2] = ngx_null, ngx_null, ngx_null
return key, topic, message
end
function _M.left_num(self)
return self.num / 3
end
return _M
| bsd-3-clause |
SJoshua/Project-Small-R | src/commands/flight.lua | 1 | 3140 | local utils = require("utils")
local flight = {
func = function(msg)
local fnum = msg.text:match("/flight%s*(%a+%d+)"):upper()
local page = utils.wget("http://m.baidu.com/s?word=" .. fnum)
if not page then
return bot.sendMessage(msg.chat.id, "Sorry, network error.")
end
local html = page:match(("<em>.-%s</em>.-航班动态(.-flight.-)飞常准"):format(fnum))
if not html then
return bot.sendMessage(msg.chat.id, "Sorry, not found.")
end
local t = {}
for k in html:gmatch(">([^<>]+)<") do
table.insert(t, k)
end
-- return bot.sendMessage(msg.chat.id, table.encode(t))
-- local divMark = html:match("(flight%-deptime%-text%S+)")
-- local status = html:match("flight%-status%-text[^>]+>(.-)<")
-- local depTime = html:match(divMark .. " c%-span3\"[^>]+>(%d%d:%d%d)")
-- local arrTime = html:match(divMark .. " flight[^>]+>(%d%d:%d%d)")
-- local planDepTime, planArrTime = html:match("计划(%d%d%d%d%-%d%d%-%d%d %d%d:%d%d).-计划(%d%d%d%d%-%d%d%-%d%d %d%d:%d%d)")
--[[
{
[1] = "预计起飞",
[2] = "预计到达",
[3] = "15:15",
[4] = "-计划-",
[5] = "17:53",
[6] = "计划2020-09-12 15:15",
[7] = "计划2020-09-12 18:20",
[8] = "天津滨海T2",
[9] = "广州白云T2",
[10] = "晴天 24℃",
[11] = "少云 28℃",
[12] = "值机柜台",
[13] = "G13-G18,H03-H08",
[14] = "登机口",
[15] = "221",
[16] = "到达口",
[17] = "--",
[18] = "行李转盘",
[19] = "--",
[20] = "综合准点率:26.67%",
[21] = "平均晚点:139分钟",
[22] = "前序航班:CZ3301 计划",
}
]]
if not t[22] then
return bot.sendMessage(msg.chat.id, "Sorry, not found.")
end
local resp = {
"*[Flight@" .. fnum .. "]*",
"",
"*" .. t[4] .. "*",
"From *" .. t[8] .. "* (" .. t[10] .. ") To *" .. t[9] .. "* (" .. t[11] ..")",
"`Departure Time `: `" .. t[3] .. "` _" .. t[6] .. "_",
"`Arrival Time `: `" .. t[5] .. "` _" .. t[7] .. "_",
"`Check-in Counter `: `" .. t[13] .. "`",
"`Boarding Gate `: `" .. t[15] .. "`",
"`Arrival Gate `: `" .. t[17] .. "`",
"`Baggage Claim `: `" .. t[19] .. "`",
"",
"\\[\\*] " .. t[20],
"\\[\\*] " .. t[21],
"\\[\\*] " .. t[22],
}
bot.sendMessage(msg.chat.id, table.concat(resp, "\n"), "Markdown")
end,
desc = "Query flight information.",
form = "/flight <flight_number>",
help = "e.g. `/flight CZ3305`",
limit = {
match = "/flight%s*(%a+%d+)"
}
}
return flight
| apache-2.0 |
adan830/luacheck | src/luacheck/stds.lua | 3 | 3735 | local utils = require "luacheck.utils"
local stds = {}
stds.busted = {
"describe", "insulate", "expose", "it", "pending", "before_each", "after_each",
"lazy_setup", "lazy_teardown", "strict_setup", "strict_teardown", "setup", "teardown",
"context", "spec", "test", "assert", "spy", "mock", "stub", "finally"}
stds.lua51 = {
_G = true, package = true, "_VERSION", "arg", "assert", "collectgarbage", "coroutine",
"debug", "dofile", "error", "gcinfo", "getfenv", "getmetatable", "io", "ipairs", "load",
"loadfile", "loadstring", "math", "module", "newproxy", "next", "os", "pairs", "pcall",
"print", "rawequal", "rawget", "rawset", "require", "select", "setfenv", "setmetatable",
"string", "table", "tonumber", "tostring", "type", "unpack", "xpcall"}
stds.lua52 = {
_ENV = true, _G = true, package = true, "_VERSION", "arg", "assert", "bit32",
"collectgarbage", "coroutine", "debug", "dofile", "error", "getmetatable", "io", "ipairs",
"load", "loadfile", "math", "next", "os", "pairs", "pcall", "print", "rawequal", "rawget",
"rawlen", "rawset", "require", "select", "setmetatable", "string", "table", "tonumber",
"tostring", "type", "xpcall"}
stds.lua52c = {
_ENV = true, _G = true, package = true, "_VERSION", "arg", "assert", "bit32",
"collectgarbage", "coroutine", "debug", "dofile", "error", "getmetatable", "io", "ipairs",
"load", "loadfile", "loadstring", "math", "module", "next", "os", "pairs", "pcall", "print",
"rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "string",
"table", "tonumber", "tostring", "type", "unpack", "xpcall"}
stds.lua53 = {
_ENV = true, _G = true, package = true, "_VERSION", "arg", "assert", "collectgarbage",
"coroutine", "debug", "dofile", "error", "getmetatable", "io", "ipairs", "load", "loadfile",
"math", "next", "os", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset",
"require", "select", "setmetatable", "string", "table", "tonumber", "tostring", "type",
"utf8", "xpcall"}
stds.lua53c = {
_ENV = true, _G = true, package = true, "_VERSION", "arg", "assert", "bit32",
"collectgarbage", "coroutine", "debug", "dofile", "error", "getmetatable", "io", "ipairs",
"load", "loadfile", "math", "next", "os", "pairs", "pcall", "print", "rawequal", "rawget",
"rawlen", "rawset", "require", "select", "setmetatable", "string", "table", "tonumber",
"tostring", "type", "utf8", "xpcall"}
stds.luajit = {
_G = true, package = true, "_VERSION", "arg", "assert", "bit", "collectgarbage", "coroutine",
"debug", "dofile", "error", "gcinfo", "getfenv", "getmetatable", "io", "ipairs", "jit",
"load", "loadfile", "loadstring", "math", "module", "newproxy", "next", "os", "pairs",
"pcall", "print", "rawequal", "rawget", "rawset", "require", "select", "setfenv",
"setmetatable", "string", "table", "tonumber", "tostring", "type", "unpack", "xpcall"}
local min = {_G = true, package = true}
local std_sets = {}
for name, std in pairs(stds) do
std_sets[name] = utils.array_to_set(std)
end
for global in pairs(std_sets.lua51) do
if std_sets.lua52[global] and std_sets.lua53[global] and std_sets.luajit[global] then
table.insert(min, global)
end
end
stds.min = min
stds.max = utils.concat_arrays {stds.lua51, stds.lua52, stds.lua53, stds.luajit}
stds.max._G = true
stds.max._ENV = true
stds.max.package = true
stds._G = {}
for global in pairs(_G) do
if global == "_G" or global == "package" then
stds._G[global] = true
else
table.insert(stds._G, global)
end
end
local function has_env()
local _ENV = {} -- luacheck: ignore
return not _G
end
if has_env() then
stds._G._ENV = true
end
stds.none = {}
return stds
| mit |
Lsty/ygopro-scripts | c45215453.lua | 3 | 1388 | --ヴァイロン・デルタ
function c45215453.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsAttribute,ATTRIBUTE_LIGHT),1)
c:EnableReviveLimit()
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(45215453,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetCondition(c45215453.thcon)
e1:SetTarget(c45215453.thtg)
e1:SetOperation(c45215453.thop)
c:RegisterEffect(e1)
end
function c45215453.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsDefencePos()
end
function c45215453.filter(c)
return c:IsType(TYPE_EQUIP) and c:IsAbleToHand()
end
function c45215453.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c45215453.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c45215453.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or c:IsAttackPos() or not c:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c45215453.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 |
Lsty/ygopro-scripts | c13438207.lua | 9 | 1134 | --ブロッサム・ボンバー
function c13438207.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetCondition(c13438207.condition)
e1:SetTarget(c13438207.target)
e1:SetOperation(c13438207.activate)
c:RegisterEffect(e1)
end
function c13438207.condition(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
return tc:IsRelateToBattle() and tc:IsStatus(STATUS_OPPO_BATTLE) and tc:IsControler(tp) and tc:IsRace(RACE_PLANT)
and bc:IsLocation(LOCATION_GRAVE) and bc:IsReason(REASON_BATTLE)
end
function c13438207.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
local atk=eg:GetFirst():GetBattleTarget():GetAttack()
if atk<0 then atk=0 end
Duel.SetTargetParam(atk)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,atk)
end
function c13438207.activate(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 |
Mkalo/forgottenserver | data/lib/core/player.lua | 14 | 2590 | local foodCondition = Condition(CONDITION_REGENERATION, CONDITIONID_DEFAULT)
function Player.feed(self, food)
local condition = self:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT)
if condition then
condition:setTicks(condition:getTicks() + (food * 1000))
else
local vocation = self:getVocation()
if not vocation then
return nil
end
foodCondition:setTicks(food * 1000)
foodCondition:setParameter(CONDITION_PARAM_HEALTHGAIN, vocation:getHealthGainAmount())
foodCondition:setParameter(CONDITION_PARAM_HEALTHTICKS, vocation:getHealthGainTicks() * 1000)
foodCondition:setParameter(CONDITION_PARAM_MANAGAIN, vocation:getManaGainAmount())
foodCondition:setParameter(CONDITION_PARAM_MANATICKS, vocation:getManaGainTicks() * 1000)
self:addCondition(foodCondition)
end
return true
end
function Player.getClosestFreePosition(self, position, extended)
if self:getAccountType() >= ACCOUNT_TYPE_GOD then
return position
end
return Creature.getClosestFreePosition(self, position, extended)
end
function Player.getDepotItems(self, depotId)
return self:getDepotChest(depotId, true):getItemHoldingCount()
end
function Player.getLossPercent(self)
local blessings = 0
local lossPercent = {
[0] = 100,
[1] = 70,
[2] = 45,
[3] = 25,
[4] = 10,
[5] = 0
}
for i = 1, 5 do
if self:hasBlessing(i) then
blessings = blessings + 1
end
end
return lossPercent[blessings]
end
function Player.isPremium(self)
return self:getPremiumDays() > 0 or configManager.getBoolean(configKeys.FREE_PREMIUM)
end
function Player.sendCancelMessage(self, message)
if type(message) == "number" then
message = Game.getReturnMessage(message)
end
return self:sendTextMessage(MESSAGE_STATUS_SMALL, message)
end
function Player.isUsingOtClient(self)
return self:getClient().os >= CLIENTOS_OTCLIENT_LINUX
end
function Player.sendExtendedOpcode(self, opcode, buffer)
if not self:isUsingOtClient() then
return false
end
local networkMessage = NetworkMessage()
networkMessage:addByte(0x32)
networkMessage:addByte(opcode)
networkMessage:addString(buffer)
networkMessage:sendToPlayer(self)
networkMessage:delete()
return true
end
APPLY_SKILL_MULTIPLIER = true
local addSkillTriesFunc = Player.addSkillTries
function Player.addSkillTries(...)
APPLY_SKILL_MULTIPLIER = false
local ret = addSkillTriesFunc(...)
APPLY_SKILL_MULTIPLIER = true
return ret
end
local addManaSpentFunc = Player.addManaSpent
function Player.addManaSpent(...)
APPLY_SKILL_MULTIPLIER = false
local ret = addManaSpentFunc(...)
APPLY_SKILL_MULTIPLIER = true
return ret
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Xarcabard/mobs/Boreal_Hound.lua | 9 | 1030 | -----------------------------------
-- Area: Xarcabard
-- NM: Boreal Hound
-- Involved in Quests: Atop the Highest Mountains
-- !pos -21 -25 -490 112
-----------------------------------
local ID = require("scripts/zones/Xarcabard/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/quests")
-----------------------------------
function onMobSpawn(mob)
-- Failsafe to make sure NPC is down when NM is up
if OldSchoolG2 then
GetNPCByID(ID.npc.BOREAL_HOUND_QM):showNPC(0)
end
end
function onMobDeath(mob, player, isKiller)
if OldSchoolG2 then
-- show ??? for desired duration
-- notify people on the quest who need the KI
GetNPCByID(ID.npc.BOREAL_HOUND_QM):showNPC(FrigiciteDuration)
if player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.ATOP_THE_HIGHEST_MOUNTAINS) == QUEST_ACCEPTED and not player:hasKeyItem(dsp.ki.TRIANGULAR_FRIGICITE) then
player:messageSpecial(ID.text.BLOCKS_OF_ICE)
end
end
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/items/bowl_of_optical_soup.lua | 11 | 1268 | -----------------------------------------
-- ID: 4340
-- Item: bowl_of_optical_soup
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP % 6 (cap 75)
-- Charisma -15
-- HP Recovered While Healing 5
-- Accuracy 15
-- Ranged Accuracy 15
-----------------------------------------
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,14400,4340)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 6)
target:addMod(dsp.mod.FOOD_HP_CAP, 75)
target:addMod(dsp.mod.CHR, -15)
target:addMod(dsp.mod.HPHEAL, 5)
target:addMod(dsp.mod.ACC, 15)
target:addMod(dsp.mod.RACC, 15)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 6)
target:delMod(dsp.mod.FOOD_HP_CAP, 75)
target:delMod(dsp.mod.CHR, -15)
target:delMod(dsp.mod.HPHEAL, 5)
target:delMod(dsp.mod.ACC, 15)
target:delMod(dsp.mod.RACC, 15)
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Konschtat_Highlands/npcs/Cavernous_Maw.lua | 10 | 1400 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: Cavernous Maw
-- !pos 96.344, -69.080, -580.008 108
-- Teleports Players to Abyssea - Konschtat
-----------------------------------
local ID = require("scripts/zones/Konschtat_Highlands/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/abyssea")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30 then
if
getTravStonesTotal(player) >= 1 and
player:getQuestStatus(ABYSSEA, dsp.quest.id.abyssea.DAWN_OF_DEATH) == QUEST_ACCEPTED and
player:getQuestStatus(ABYSSEA, dsp.quest.id.abyssea.TO_PASTE_A_PEISTE) == QUEST_AVAILABLE
then
player:startEvent(0)
else
player:startEvent(107, 0, 1) -- No param = no entry.
end
else
player:messageSpecial(ID.text.NOTHING_HAPPENS)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 0 then
player:addQuest(ABYSSEA, dsp.quest.id.abyssea.TO_PASTE_A_PEISTE)
elseif csid == 1 then
-- Killed Kukulkan
elseif csid == 107 and option == 1 then
player:setPos(153, -72, -840, 140, 15)
end
end | gpl-3.0 |
Lsty/ygopro-scripts | c25090294.lua | 6 | 1379 | --ブルーメンブラット
function c25090294.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:SetCost(c25090294.cost)
e1:SetTarget(c25090294.target)
e1:SetOperation(c25090294.activate)
c:RegisterEffect(e1)
end
function c25090294.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsCode,1,nil,62107981) end
local g=Duel.SelectReleaseGroup(tp,Card.IsCode,1,1,nil,62107981)
Duel.Release(g,REASON_COST)
end
function c25090294.filter(c,e,tp)
return c:IsCode(51085303) and c:IsCanBeSpecialSummoned(e,0,tp,true,false)
end
function c25090294.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c25090294.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c25090294.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,c25090294.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)
g:GetFirst():CompleteProcedure()
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Cloister_of_Tides/bcnms/trial_by_water.lua | 9 | 1506 | -----------------------------------
-- Area: Cloister of Tides
-- BCNM: Trial by Water
-----------------------------------
local ID = require("scripts/zones/Cloister_of_Tides/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:hasCompletedQuest(OUTLANDS, dsp.quest.id.outlands.TRIAL_BY_WATER)) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
player:delKeyItem(dsp.ki.TUNING_FORK_OF_WATER)
player:addKeyItem(dsp.ki.WHISPER_OF_TIDES)
player:addTitle(dsp.title.HEIR_OF_THE_GREAT_WATER)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.WHISPER_OF_TIDES)
end
end
| gpl-3.0 |
Lsty/ygopro-scripts | c12181376.lua | 5 | 1950 | --トライアングル・X・スパーク
function c12181376.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c12181376.target)
e1:SetOperation(c12181376.activate)
c:RegisterEffect(e1)
end
function c12181376.filter(c)
return c:IsFaceup() and c:IsCode(12206212)
end
function c12181376.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c12181376.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
end
function c12181376.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(c12181376.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(2700)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
--cannot activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetTargetRange(0,1)
e1:SetValue(c12181376.aclimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
--disable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(0,LOCATION_SZONE)
e2:SetTarget(c12181376.distg)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
--disable trap monster
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_DISABLE_TRAPMONSTER)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetTarget(c12181376.distg)
e3:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e3,tp)
end
function c12181376.aclimit(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_TRAP)
end
function c12181376.distg(e,c)
return c:IsType(TYPE_TRAP)
end
| gpl-2.0 |
openwrt/luci | build/luadoc/luadoc/lp.lua | 175 | 4389 | ----------------------------------------------------------------------------
-- Lua Pages Template Preprocessor.
--
-- @release $Id: lp.lua,v 1.7 2007/04/18 14:28:39 tomas Exp $
----------------------------------------------------------------------------
local assert, error, getfenv, loadstring, setfenv = assert, error, getfenv, loadstring, setfenv
local find, format, gsub, strsub = string.find, string.format, string.gsub, string.sub
local concat, tinsert = table.concat, table.insert
local open = io.open
module (...)
----------------------------------------------------------------------------
-- function to do output
local outfunc = "io.write"
-- accepts the old expression field: `$| <Lua expression> |$'
local compatmode = true
--
-- Builds a piece of Lua code which outputs the (part of the) given string.
-- @param s String.
-- @param i Number with the initial position in the string.
-- @param f Number with the final position in the string (default == -1).
-- @return String with the correspondent Lua code which outputs the part of the string.
--
local function out (s, i, f)
s = strsub(s, i, f or -1)
if s == "" then return s end
-- we could use `%q' here, but this way we have better control
s = gsub(s, "([\\\n\'])", "\\%1")
-- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it
s = gsub(s, "\r", "\\r")
return format(" %s('%s'); ", outfunc, s)
end
----------------------------------------------------------------------------
-- Translate the template to Lua code.
-- @param s String to translate.
-- @return String with translated code.
----------------------------------------------------------------------------
function translate (s)
if compatmode then
s = gsub(s, "$|(.-)|%$", "<?lua = %1 ?>")
s = gsub(s, "<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>")
end
s = gsub(s, "<%%(.-)%%>", "<?lua %1 ?>")
local res = {}
local start = 1 -- start of untranslated part in `s'
while true do
local ip, fp, target, exp, code = find(s, "<%?(%w*)[ \t]*(=?)(.-)%?>", start)
if not ip then break end
tinsert(res, out(s, start, ip-1))
if target ~= "" and target ~= "lua" then
-- not for Lua; pass whole instruction to the output
tinsert(res, out(s, ip, fp))
else
if exp == "=" then -- expression?
tinsert(res, format(" %s(%s);", outfunc, code))
else -- command
tinsert(res, format(" %s ", code))
end
end
start = fp + 1
end
tinsert(res, out(s, start))
return concat(res)
end
----------------------------------------------------------------------------
-- Defines the name of the output function.
-- @param f String with the name of the function which produces output.
function setoutfunc (f)
outfunc = f
end
----------------------------------------------------------------------------
-- Turns on or off the compatibility with old CGILua 3.X behavior.
-- @param c Boolean indicating if the compatibility mode should be used.
function setcompatmode (c)
compatmode = c
end
----------------------------------------------------------------------------
-- Internal compilation cache.
local cache = {}
----------------------------------------------------------------------------
-- Translates a template into a Lua function.
-- Does NOT execute the resulting function.
-- Uses a cache of templates.
-- @param string String with the template to be translated.
-- @param chunkname String with the name of the chunk, for debugging purposes.
-- @return Function with the resulting translation.
function compile (string, chunkname)
local f, err = cache[string]
if f then return f end
f, err = loadstring (translate (string), chunkname)
if not f then error (err, 3) end
cache[string] = f
return f
end
----------------------------------------------------------------------------
-- Translates and executes a template in a given file.
-- The translation creates a Lua function which will be executed in an
-- optionally given environment.
-- @param filename String with the name of the file containing the template.
-- @param env Table with the environment to run the resulting function.
function include (filename, env)
-- read the whole contents of the file
local fh = assert (open (filename))
local src = fh:read("*a")
fh:close()
-- translates the file into a function
local prog = compile (src, '@'..filename)
local _env
if env then
_env = getfenv (prog)
setfenv (prog, env)
end
prog ()
end
| apache-2.0 |
maxrio/luci981213 | build/luadoc/luadoc/lp.lua | 175 | 4389 | ----------------------------------------------------------------------------
-- Lua Pages Template Preprocessor.
--
-- @release $Id: lp.lua,v 1.7 2007/04/18 14:28:39 tomas Exp $
----------------------------------------------------------------------------
local assert, error, getfenv, loadstring, setfenv = assert, error, getfenv, loadstring, setfenv
local find, format, gsub, strsub = string.find, string.format, string.gsub, string.sub
local concat, tinsert = table.concat, table.insert
local open = io.open
module (...)
----------------------------------------------------------------------------
-- function to do output
local outfunc = "io.write"
-- accepts the old expression field: `$| <Lua expression> |$'
local compatmode = true
--
-- Builds a piece of Lua code which outputs the (part of the) given string.
-- @param s String.
-- @param i Number with the initial position in the string.
-- @param f Number with the final position in the string (default == -1).
-- @return String with the correspondent Lua code which outputs the part of the string.
--
local function out (s, i, f)
s = strsub(s, i, f or -1)
if s == "" then return s end
-- we could use `%q' here, but this way we have better control
s = gsub(s, "([\\\n\'])", "\\%1")
-- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it
s = gsub(s, "\r", "\\r")
return format(" %s('%s'); ", outfunc, s)
end
----------------------------------------------------------------------------
-- Translate the template to Lua code.
-- @param s String to translate.
-- @return String with translated code.
----------------------------------------------------------------------------
function translate (s)
if compatmode then
s = gsub(s, "$|(.-)|%$", "<?lua = %1 ?>")
s = gsub(s, "<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>")
end
s = gsub(s, "<%%(.-)%%>", "<?lua %1 ?>")
local res = {}
local start = 1 -- start of untranslated part in `s'
while true do
local ip, fp, target, exp, code = find(s, "<%?(%w*)[ \t]*(=?)(.-)%?>", start)
if not ip then break end
tinsert(res, out(s, start, ip-1))
if target ~= "" and target ~= "lua" then
-- not for Lua; pass whole instruction to the output
tinsert(res, out(s, ip, fp))
else
if exp == "=" then -- expression?
tinsert(res, format(" %s(%s);", outfunc, code))
else -- command
tinsert(res, format(" %s ", code))
end
end
start = fp + 1
end
tinsert(res, out(s, start))
return concat(res)
end
----------------------------------------------------------------------------
-- Defines the name of the output function.
-- @param f String with the name of the function which produces output.
function setoutfunc (f)
outfunc = f
end
----------------------------------------------------------------------------
-- Turns on or off the compatibility with old CGILua 3.X behavior.
-- @param c Boolean indicating if the compatibility mode should be used.
function setcompatmode (c)
compatmode = c
end
----------------------------------------------------------------------------
-- Internal compilation cache.
local cache = {}
----------------------------------------------------------------------------
-- Translates a template into a Lua function.
-- Does NOT execute the resulting function.
-- Uses a cache of templates.
-- @param string String with the template to be translated.
-- @param chunkname String with the name of the chunk, for debugging purposes.
-- @return Function with the resulting translation.
function compile (string, chunkname)
local f, err = cache[string]
if f then return f end
f, err = loadstring (translate (string), chunkname)
if not f then error (err, 3) end
cache[string] = f
return f
end
----------------------------------------------------------------------------
-- Translates and executes a template in a given file.
-- The translation creates a Lua function which will be executed in an
-- optionally given environment.
-- @param filename String with the name of the file containing the template.
-- @param env Table with the environment to run the resulting function.
function include (filename, env)
-- read the whole contents of the file
local fh = assert (open (filename))
local src = fh:read("*a")
fh:close()
-- translates the file into a function
local prog = compile (src, '@'..filename)
local _env
if env then
_env = getfenv (prog)
setfenv (prog, env)
end
prog ()
end
| apache-2.0 |
Lsty/ygopro-scripts | c4756629.lua | 5 | 3865 | --ヴェルズ・ケルキオン
function c4756629.initial_effect(c)
--salvage
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetDescription(aux.Stringid(4756629,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,4756629)
e1:SetCost(c4756629.thcost)
e1:SetTarget(c4756629.thtg)
e1:SetOperation(c4756629.thop)
c:RegisterEffect(e1)
--summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(4756629,1))
e2:SetCategory(CATEGORY_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c4756629.sumcon)
e2:SetTarget(c4756629.sumtg)
e2:SetOperation(c4756629.sumop)
c:RegisterEffect(e2)
--decrease tribute
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetOperation(c4756629.decop)
c:RegisterEffect(e3)
end
function c4756629.rmfilter(c,tp)
return c:IsSetCard(0xa) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost()
and Duel.IsExistingTarget(c4756629.filter,tp,LOCATION_GRAVE,0,1,c)
end
function c4756629.filter(c)
return c:IsSetCard(0xa) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c4756629.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c4756629.rmfilter,tp,LOCATION_GRAVE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c4756629.rmfilter,tp,LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c4756629.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c4756629.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,c4756629.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c4756629.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
if c:IsRelateToEffect(e) and c:IsFaceup() then
c:RegisterFlagEffect(4756629,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
end
function c4756629.sumcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(4756629)~=0
end
function c4756629.sumfilter(c)
return c:IsSetCard(0xa) and c:IsSummonable(true,nil)
end
function c4756629.sumtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c4756629.sumfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0)
end
function c4756629.sumop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON)
local g=Duel.SelectMatchingCard(tp,c4756629.sumfilter,tp,LOCATION_HAND,0,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.Summon(tp,tc,true,nil)
end
end
function c4756629.decop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetFlagEffect(tp,4756630)~=0 then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DECREASE_TRIBUTE)
e1:SetTargetRange(LOCATION_HAND,LOCATION_HAND)
e1:SetTarget(c4756629.rfilter)
e1:SetCondition(c4756629.econ)
e1:SetCountLimit(1)
e1:SetValue(0x1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(0x10000000+4756631)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetRange(LOCATION_GRAVE)
e2:SetTargetRange(1,0)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e2)
Duel.RegisterFlagEffect(tp,4756630,RESET_PHASE+PHASE_END,0,1)
end
function c4756629.econ(e)
return Duel.GetFlagEffect(e:GetHandlerPlayer(),4756631)~=0
end
function c4756629.rfilter(e,c)
return c:IsSetCard(0xa)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c39980304.lua | 3 | 2277 | --チェーン・マテリアル
function c39980304.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c39980304.cost)
e1:SetOperation(c39980304.activate)
c:RegisterEffect(e1)
end
function c39980304.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_ATTACK)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetProperty(EFFECT_FLAG_OATH+EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c39980304.activate(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(39980304,0))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHAIN_MATERIAL)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTarget(c39980304.chain_target)
e1:SetOperation(c39980304.chain_operation)
e1:SetValue(aux.TRUE)
Duel.RegisterEffect(e1,tp)
end
function c39980304.filter(c,e)
return c:IsCanBeFusionMaterial() and c:IsAbleToRemove() and not c:IsImmuneToEffect(e)
end
function c39980304.chain_target(e,te,tp)
return Duel.GetMatchingGroup(c39980304.filter,tp,LOCATION_MZONE+LOCATION_GRAVE+LOCATION_HAND+LOCATION_DECK,0,nil,te)
end
function c39980304.chain_operation(e,te,tp,tc,mat,sumtype)
if not sumtype then sumtype=SUMMON_TYPE_FUSION end
tc:SetMaterial(mat)
Duel.Remove(mat,POS_FACEUP,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
Duel.BreakEffect()
Duel.SpecialSummon(tc,sumtype,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(39980304,RESET_EVENT+0x1fc0000+RESET_PHASE+RESET_END,0,1)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetOwnerPlayer(tp)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetOperation(c39980304.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e1:SetCountLimit(1)
tc:RegisterEffect(e1)
end
function c39980304.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end | gpl-2.0 |
MalRD/darkstar | scripts/zones/Nyzul_Isle/mobs/Amnaf_BLU.lua | 9 | 3898 | -----------------------------------
-- Area: Nyzul Isle (Path of Darkness)
-- Mob: Amnaf BLU
-----------------------------------
local ID = require("scripts/zones/Nyzul_Isle/IDs")
require("scripts/globals/status");
-----------------------------------
function onMobSpawn(mob)
local instance = mob:getInstance();
-- Stage 2 Adjustments
if (instance:getProgress() >= 10) then
-- Don't let Amnaf wander back to the original spawn position
mob:setMobMod(dsp.mobMod.NO_MOVE, 1);
-- Stage 2 starts at 50%
local hp = mob:getHP();
mob:setHP(hp / 2);
-- Stage 2 Position
mob:setPos(499,0,-491,66);
-- Stage 2 AI Flag
mob:setLocalVar("SegmentChanged",1);
end
mob:setLocalVar("DespawnSignal",0);
mob:setUnkillable(true);
mob:addListener("WEAPONSKILL_STATE_ENTER", "WS_START_MSG", function(mob, skillID)
-- Circle Blade
if (skillID == 38) then
mob:showText(mob,ID.text.I_WILL_SINK_YOUR_CORPSES);
end
end);
end;
function onMobEngaged(mob,target)
-- Relax movement lock
mob:setMobMod(dsp.mobMod.NO_MOVE, 0);
-- Stage AI flags
local form = mob:getLocalVar("SegmentChanged");
local form1Gears = mob:getLocalVar("Form1Gears");
local form1Gears = mob:getLocalVar("Form2Gears");
-- 4 gears spawn on Stage 1 of the Fight
if (form1Gears == 0) then
mob:showText(mob,ID.text.FORMATION_GELINCIK);
local instance = mob:getInstance();
SpawnMob(ID.mob[58].IMPERIAL_GEAR1,instance):updateEnmity(target);
SpawnMob(ID.mob[58].IMPERIAL_GEAR2,instance):updateEnmity(target);
SpawnMob(ID.mob[58].IMPERIAL_GEAR3,instance):updateEnmity(target);
SpawnMob(ID.mob[58].IMPERIAL_GEAR4,instance):updateEnmity(target);
mob:setLocalVar("Form1Gears", 1);
end
-- 4 more gears spawn on Stage 2 of the Fight
if (form == 1 and form2Gears == 0) then
mob:showText(mob,ID.text.SURRENDER);
local gear = SpawnMob(ID.mob[58].IMPERIAL_GEAR1,instance)
gear:updateEnmity(target);
gear = SpawnMob(ID.mob[58].IMPERIAL_GEAR2,instance);
gear:updateEnmity(target);
gear = SpawnMob(ID.mob[58].IMPERIAL_GEAR3,instance);
gear:updateEnmity(target);
gear = SpawnMob(ID.mob[58].IMPERIAL_GEAR4,instance);
gear:updateEnmity(target);
gear:setLocalVar("Form2Gears", 1);
end
end;
function onMobFight(mob,target)
local segment = mob:getLocalVar("SegmentChanged");
if (mob:getHPP() <= 30 and mob:getLocalVar("RenameThisVar") == 0) then
mob:showText(mob,ID.text.CURSED_ESSENCES);
-- Azure Lore (or Chain Affinity?) needs to happen here followed by ws+cast. https://youtu.be/7jsXnwkqMM4?t=4m4s
mob:setLocalVar("RenameThisVar", 1)
-- At 50% and 20% respectively, Amnaf disappears and the fight advances to the next stage
elseif ((mob:getHPP() <= 50 and segment == 0) or (mob:getHPP() <= 20 and segment == 1)) then
if (segment == 0) then -- It was less duplicate code to just check segment again.
mob:showText(mob,ID.text.UGH);
elseif (segment == 1) then
mob:showText(mob,ID.text.CANNOT_WIN);
end
if (mob:getLocalVar("DespawnSignal") == 0) then
mob:setLocalVar("DespawnSignal", 1);
local instance = mob:getInstance();
instance:setProgress(instance:getProgress() + 10);
end
end
end;
function onSpellPrecast(mob, spell)
-- Hysteric Barrage
if (spell == 641) then
mob:showText(mob,ID.text.AWAKEN);
-- Tail Slap
elseif (spell == 640) then
mob:showText(mob,ID.text.MANIFEST);
end
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
local instance = mob:getInstance();
instance:setProgress(instance:getProgress() + 10);
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c13504844.lua | 3 | 1625 | --ガトムズの緊急指令
function c13504844.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetCondition(c13504844.condition)
e1:SetTarget(c13504844.target)
e1:SetOperation(c13504844.activate)
c:RegisterEffect(e1)
end
function c13504844.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x100d)
end
function c13504844.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c13504844.cfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
end
function c13504844.filter(c,e,tp)
return c:IsSetCard(0x100d) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c13504844.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:GetControler()==tp and chkc:GetLocation()==LOCATION_GRAVE and c13504844.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsExistingTarget(c13504844.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,2,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c13504844.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,2,2,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,2,0,0)
end
function c13504844.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(Card.IsRelateToEffect,nil,e)
if sg:GetCount()~=2 then return end
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Ghelsba_Outpost/bcnms/toadal_recall.lua | 9 | 1062 | -----------------------------------
-- Toadal Recall
-- Ghelsba Outpost BCNM30, Sky Orb
-- !additem 1552
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 2, battlefield:getLocalVar("[cs]bit"), 2)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c44397496.lua | 7 | 1164 | --レッドアイズ・スピリッツ
function c44397496.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c44397496.target)
e1:SetOperation(c44397496.activate)
c:RegisterEffect(e1)
end
function c44397496.filter(c,e,tp)
return c:IsSetCard(0x3b) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c44397496.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c44397496.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c44397496.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c44397496.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c44397496.activate(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/globals/keyitems.lua | 11 | 156259 | ---------------------------------------------
--
-- KEYITEMS IDS
--
---------------------------------------------
dsp = dsp or {}
dsp.keyItem =
{
ZERUHN_REPORT = 1,
PALBOROUGH_MINES_LOGS = 2,
BLUE_ACIDITY_TESTER = 3,
RED_ACIDITY_TESTER = 4,
LETTER_TO_THE_CONSULS_SANDORIA = 5,
LETTER_TO_THE_CONSULS_BASTOK = 6,
LETTER_TO_THE_CONSULS_WINDURST = 7,
AIRSHIP_PASS = 8,
AIRSHIP_PASS_FOR_KAZHAM = 9,
OVERDUE_BOOK_NOTIFICATIONS = 10,
LETTERS_FROM_DOMIEN = 11,
C_L_REPORTS = 12,
KINDRED_CREST = 13,
MAGICITE_OPTISTONE = 14,
MAGICITE_AURASTONE = 15,
MAGICITE_ORASTONE = 16,
FOOD_OFFERINGS = 17,
DRINK_OFFERINGS = 18,
CLOCK_TOWER_OIL = 19,
YAGUDO_TORCH = 20,
CREST_OF_DAVOI_KI = 21,
LETTERS_TO_ALDO = 22,
BOUQUETS_FOR_THE_PIONEERS = 23,
OLD_TOOLBOX = 24,
NOTES_FROM_HARIGAORIGA = 25,
NOTES_FROM_IPUPU = 26,
ART_FOR_EVERYONE = 27,
CRACKED_MANA_ORBS = 28,
KINDRED_REPORT = 29,
LETTER_TO_THE_AMBASSADOR = 30,
SWORD_OFFERING = 31,
SHIELD_OFFERING = 32,
DULL_SWORD = 33,
DARK_KEY = 34,
ADVENTURERS_CERTIFICATE = 35,
STARWAY_STAIRWAY_BAUBLE = 36,
FIRST_DARK_MANA_ORB = 37,
CREATURE_COUNTER_MAGIC_DOLL = 38,
OFF_OFFERING = 39,
WINDURST_WATERS_SCOOP = 40,
WINDURST_WALLS_SCOOP = 41,
PORT_WINDURST_SCOOP = 42,
WINDURST_WOODS_SCOOP = 43,
TEMPLE_KNIGHTS_DAVOI_REPORT = 44,
SILVER_BELL = 45,
CORUSCANT_ROSARY = 46,
BLACK_MATINEE_NECKLACE = 47,
DUCAL_GUARDS_LANTERN = 48,
DUCAL_GUARDS_LANTERN_LIT = 49,
HOLY_CANDLE = 50,
SECOND_DARK_MANA_ORB = 51,
THIRD_DARK_MANA_ORB = 52,
FOURTH_DARK_MANA_ORB = 53,
FIFTH_DARK_MANA_ORB = 54,
SIXTH_DARK_MANA_ORB = 55,
ARCHDUCAL_AUDIENCE_PERMIT = 56,
SUPER_SOUP_POT = 57,
TWO_OF_SWORDS = 58,
FIRST_GLOWING_MANA_ORB = 59,
SECOND_GLOWING_MANA_ORB = 60,
THIRD_GLOWING_MANA_ORB = 61,
FOURTH_GLOWING_MANA_ORB = 62,
FIFTH_GLOWING_MANA_ORB = 63,
SIXTH_GLOWING_MANA_ORB = 64,
RESCUE_TRAINING_CERTIFICATE = 65,
CHARM_OF_LIGHT = 66,
HIDEOUT_KEY = 67,
LAPIS_CORAL = 68,
MESSAGE_TO_JEUNO_SANDORIA = 69,
MESSAGE_TO_JEUNO_BASTOK = 70,
MESSAGE_TO_JEUNO_WINDURST = 71,
NEW_FEIYIN_SEAL = 72,
BURNT_SEAL = 73,
SHADOW_FRAGMENT = 74,
RONFAURE_SUPPLIES = 75,
ZULKHEIM_SUPPLIES = 76,
NORVALLEN_SUPPLIES = 77,
GUSTABERG_SUPPLIES = 78,
DERFLAND_SUPPLIES = 79,
SARUTABARUTA_SUPPLIES = 80,
KOLSHUSHU_SUPPLIES = 81,
ARAGONEU_SUPPLIES = 82,
FAUREGANDI_SUPPLIES = 83,
VALDEAUNIA_SUPPLIES = 84,
LITELOR_SUPPLIES = 85,
KUZOTZ_SUPPLIES = 86,
VOLLBOW_SUPPLIES = 87,
LAPIS_MONOCLE = 88,
DONATION_ENVELOPE = 89,
ARAGONEU_PIZZA = 90,
LAND_CRAB_BISQUE = 91,
MHAURAN_COUSCOUS = 92,
ETCHED_RING = 93,
TRADERS_SACK = 94,
FAKE_MOUSTACHE = 95,
GARDENIA_PASS = 96,
WEAPONS_ORDER = 97,
WEAPONS_RECEIPT = 98,
SMALL_BAG = 99,
RANPIMONPIS_SPECIAL_STEW = 100,
FERRY_TICKET = 101,
STAMP_SHEET = 102,
LOST_DOCUMENT = 103,
EAST_BLOCK_CODE = 104,
SOUTH_BLOCK_CODE = 105,
NORTH_BLOCK_CODE = 106,
LETTER_FROM_ROH_LATTEH = 107,
PAINTING_OF_A_WINDMILL = 108,
TATTERED_MISSION_ORDERS = 109,
MONASTIC_CAVERN_KEY = 110,
MOON_CRYSTAL = 111,
SOUTHEASTERN_STAR_CHARM = 112,
WONDER_MAGIC_SET = 113,
UNFINISHED_LETTER = 114,
NEW_MODEL_HAT = 115,
ANGELICAS_AUTOGRAPH = 116,
OLD_TIGERS_FANG = 117,
TENSHODO_MEMBERS_CARD = 118,
RECEIPT_FOR_THE_PRINCE = 119,
MAGIC_TRASH = 120,
TENSHODO_APPLICATION_FORM = 121,
SHARP_GRAY_STONE = 122,
CATHEDRAL_DONATION = 123,
QUFIM_SUPPLIES = 124,
TATTERED_TEST_SHEET = 125,
A_SONG_OF_LOVE = 126,
STEAMING_SHEEP_INVITATION = 127,
BROKEN_WAND = 128,
GULEMONTS_DOCUMENT = 129,
OLD_RING = 130,
WHITE_ORB = 131,
PINK_ORB = 132,
RED_ORB = 133,
BLOOD_ORB = 134,
CURSED_ORB = 135,
CRIMSON_ORB = 136,
KEY_TO_THE_OZTROJA_MINES = 137,
CHOCOBO_LICENSE = 138,
CURSEPAPER = 139,
CORRUPTED_DIRT = 140,
STALACTITE_DEW = 141,
SQUIRE_CERTIFICATE = 142,
BOOK_OF_TASKS = 143,
BOOK_OF_THE_EAST = 144,
BOOK_OF_THE_WEST = 145,
KNIGHTS_SOUL = 146,
COLD_MEDICINE = 147,
AMAURAS_FORMULA = 148,
OVERDUE_BOOK_NOTIFICATION = 149,
SCRIPTURE_OF_WATER = 150,
SCRIPTURE_OF_WIND = 151,
TAMIS_NOTE = 152,
THYME_MOSS = 153,
COUGH_MEDICINE = 154,
SCROLL_OF_TREASURE = 155,
CODE_OF_BEASTMASTERS = 156,
ORCISH_HUT_KEY = 157,
STAR_CRESTED_SUMMONS = 158,
BRUGAIRE_GOODS = 159,
SMALL_TEACUP = 160,
SUSPICIOUS_ENVELOPE = 161,
CARRIER_PIGEON_LETTER = 162,
CARMELOS_SONG_SHEET = 163,
CURILLAS_BOTTLE_EMPTY = 164,
CURILLAS_BOTTLE_FULL = 165,
NEUTRALIZER = 166,
GOLDSMITHING_ORDER = 167,
MYTHRIL_HEARTS = 168,
TESTIMONIAL = 169,
LETTER_FROM_ZEID = 170,
SHANTOTTOS_NEW_SPELL = 171,
SHANTOTTOS_EXSPELL = 172,
BUCKET_OF_DIVINE_PAINT = 173,
LETTER_FROM_VIRNAGE = 174,
SPIRIT_INCENSE = 175,
GANTINEUXS_LETTER = 176,
SEAL_OF_BANISHING = 177,
MAGICAL_PATTERN = 178,
FEIYIN_MAGIC_TOME = 179,
SLUICE_SURVEYOR_MK_I = 180,
FOE_FINDER_MK_I = 181,
EARTHEN_CHARM = 182,
LETTER_FROM_THE_TENSHODO = 183,
TENSHODO_ENVELOPE = 184,
SIGNED_ENVELOPE = 185,
GANG_WHEREABOUTS_NOTE = 186,
FIRST_FORGED_ENVELOPE = 187,
SECOND_FORGED_ENVELOPE = 188,
FIRST_SIGNED_FORGED_ENVELOPE = 189,
SECOND_SIGNED_FORGED_ENVELOPE = 190,
LETTER_FROM_DALZAKK = 191,
SANDORIAN_MARTIAL_ARTS_SCROLL = 192,
BOMB_INCENSE = 193,
PERCHONDS_ENVELOPE = 194,
PORTAL_CHARM = 195,
ORCISH_DRIED_FOOD = 196,
OLD_POCKET_WATCH = 197,
OLD_BOOTS = 198,
BALGA_CHAMPION_CERTIFICATE = 199,
HOLY_ONES_OATH = 200,
CRAWLER_BLOOD = 201,
CAT_BURGLARS_NOTE = 202,
CHIEFTAINNESS_TWINSTONE_EARRING = 203,
NORTHERN_VINE = 204,
SOUTHERN_VINE = 205,
EASTERN_VINE = 206,
WESTERN_VINE = 207,
SWORD_GRIP_MATERIAL = 208,
YASINS_SWORD = 209,
OLD_GAUNTLETS = 210,
SHADOW_FLAMES = 211,
FIREBLOOM_TREE_WOOD = 212,
LETTER_TO_ANGELICA = 213,
FINAL_FANTASY = 214,
RIPPED_FINAL_FANTASY_PAINTING = 215,
FINAL_FANTASY_PART_II = 216,
TAMERS_WHISTLE = 217,
KNIGHTS_BOOTS = 218,
MIQUES_PAINTBRUSH = 219,
STRANGE_SHEET_OF_PAPER = 220,
KNIGHTS_CONFESSION = 221,
ROUND_FRIGICITE = 222,
SQUARE_FRIGICITE = 223,
TRIANGULAR_FRIGICITE = 224,
STAR_RING1 = 225,
STAR_RING2 = 226,
MOON_RING = 227,
MERTAIRES_BRACELET = 228,
AQUAFLORA1 = 229,
AQUAFLORA2 = 230,
AQUAFLORA3 = 231,
GUIDING_BELL = 232,
ORDELLE_WHETSTONE = 233,
LETTER_FROM_THE_DARKSTEEL_FORGE = 234,
DARKSTEEL_FORMULA = 235,
KOHS_LETTER = 236,
ROYAL_KNIGHTS_DAVOI_REPORT = 237,
SACRIFICIAL_CHAMBER_KEY = 238,
FIRE_FRAGMENT = 239,
WATER_FRAGMENT = 240,
EARTH_FRAGMENT = 241,
WIND_FRAGMENT = 242,
LIGHTNING_FRAGMENT = 243,
ICE_FRAGMENT = 244,
LIGHT_FRAGMENT = 245,
DARK_FRAGMENT = 246,
PRISMATIC_FRAGMENT = 247,
SOUTHWESTERN_STAR_CHARM = 248,
HOLY_ONES_INVITATION = 249,
OPTISTERY_RING = 250,
BLANK_BOOK_OF_THE_GODS = 251,
BOOK_OF_THE_GODS = 252,
NONBERRYS_KNIFE = 253,
SUBLIME_STATUE_OF_THE_GODDESS = 254,
RAUTEINOTS_PARCEL = 255,
TREASURE_MAP = 256,
STRANGELY_SHAPED_CORAL = 257,
SEALED_DAGGER = 258,
ANGELICAS_LETTER = 259,
EMPTY_BARREL = 260,
BARREL_OF_OPOOPO_BREW = 261,
ELSHIMO_LOWLANDS_SUPPLIES = 262,
ELSHIMO_UPLANDS_SUPPLIES = 263,
JOKER_CARD = 264,
ORASTERY_RING = 265,
ALTEPA_MOONPEBBLE = 266,
RHINOSTERY_CERTIFICATE = 267,
DREAMROSE = 268,
ANCIENT_SANDORIAN_BOOK = 269,
PIECE_OF_PAPER = 270,
INVISIBLE_MAN_STICKER = 271,
PAINTBRUSH_OF_SOULS = 272,
OLD_RUSTY_KEY = 273,
ANCIENT_TABLET_FRAGMENT = 274,
STAR_SEEKER = 275,
AURASTERY_RING = 276,
TABLET_OF_ANCIENT_MAGIC = 277,
LETTER_FROM_ALFESAR = 278,
MAGIC_DRAINED_STAR_SEEKER = 279,
RHINOSTERY_RING = 280,
MANUSTERY_RING = 281,
GLOVE_OF_PERPETUAL_TWILIGHT = 282,
ANCIENT_SANDORIAN_TABLET = 283,
CRYSTAL_DOWSER = 284,
PIECE_OF_A_BROKEN_KEY1 = 285,
PIECE_OF_A_BROKEN_KEY2 = 286,
PIECE_OF_A_BROKEN_KEY3 = 287,
DROPS_OF_AMNIO = 288,
REINFORCED_CERMET = 289,
LETTER_FROM_WEREI = 290,
TONBERRY_PRIEST_KEY = 291,
THESIS_ON_ALCHEMY = 292,
OLD_PIECE_OF_WOOD = 293,
DRAGON_CURSE_REMEDY = 294,
SEALED_IRON_BOX = 295,
SEA_SERPENT_STATUE = 296,
ALTEPA_POLISHING_STONE = 297,
CHALLENGE_TO_THE_ROYAL_KNIGHTS = 298,
RANCHURIOMES_LEGACY = 299,
RONFAURE_EF_INSIGNIA = 300,
ZULKHEIM_EF_INSIGNIA = 301,
NORVALLEN_EF_INSIGNIA = 302,
GUSTABERG_EF_INSIGNIA = 303,
DERFLAND_EF_INSIGNIA = 304,
SARUTABARUTA_EF_INSIGNIA = 305,
KOLSHUSHU_EF_INSIGNIA = 306,
ARAGONEU_EF_INSIGNIA = 307,
FAUREGANDI_EF_INSIGNIA = 308,
VALDEAUNIA_EF_INSIGNIA = 309,
QUFIM_EF_INSIGNIA = 310,
LITELOR_EF_INSIGNIA = 311,
KUZOTZ_EF_INSIGNIA = 312,
VOLLBOW_EF_INSIGNIA = 313,
ELSHIMO_LOWLANDS_EF_INSIGNIA = 314,
ELSHIMO_UPLANDS_EF_INSIGNIA = 315,
KEY_ITEM316 = 316,
KEY_ITEM317 = 317,
KEY_ITEM318 = 318,
KEY_ITEM319 = 319,
WHISPER_OF_FLAMES = 320,
WHISPER_OF_TREMORS = 321,
WHISPER_OF_TIDES = 322,
WHISPER_OF_GALES = 323,
WHISPER_OF_FROST = 324,
WHISPER_OF_STORMS = 325,
WHISPER_OF_THE_MOON = 326,
WHISPER_OF_DREAMS = 327,
TUNING_FORK_OF_FIRE = 328,
TUNING_FORK_OF_EARTH = 329,
TUNING_FORK_OF_WATER = 330,
TUNING_FORK_OF_WIND = 331,
TUNING_FORK_OF_ICE = 332,
TUNING_FORK_OF_LIGHTNING = 333,
MOON_BAUBLE = 334,
VIAL_OF_DREAM_INCENSE = 335,
ORCISH_CREST = 336,
QUADAV_CREST = 337,
YAGUDO_CREST = 338,
UN_MOMENT = 339,
LEPHEMERE = 340,
LANCIENNE = 341,
CHANSON_DE_LIBERTE = 342,
WEAPON_TRAINING_GUIDE = 343,
MAP_TO_THE_ANNALS_OF_TRUTH = 344,
ANNALS_OF_TRUTH = 345,
COMPLETION_CERTIFICATE = 346,
DYNAMIS_DEBUGGER = 347,
DROPPED_ITEM = 348,
WHITE_CARD = 349,
RED_CARD = 350,
BLACK_CARD = 351,
HOLLA_GATE_CRYSTAL = 352,
DEM_GATE_CRYSTAL = 353,
MEA_GATE_CRYSTAL = 354,
VAHZL_GATE_CRYSTAL = 355,
YHOATOR_GATE_CRYSTAL = 356,
ALTEPA_GATE_CRYSTAL = 357,
PROMYVION_HOLLA_SLIVER = 358,
PROMYVION_DEM_SLIVER = 359,
PROMYVION_MEA_SLIVER = 360,
WHISPER_OF_THE_WYRMKING = 361,
NOTE_WRITTEN_BY_ESHANTARL = 362,
RAINBOW_RESONATOR = 363,
FADED_RUBY = 364,
TATTERED_MAZE_MONGER_POUCH = 365,
CRIMSON_STRATUM_ABYSSITE = 366,
CRIMSON_STRATUM_ABYSSITE_II = 367,
CRIMSON_STRATUM_ABYSSITE_III = 368,
CRIMSON_STRATUM_ABYSSITE_IV = 369,
INDIGO_STRATUM_ABYSSITE = 370,
INDIGO_STRATUM_ABYSSITE_II = 371,
INDIGO_STRATUM_ABYSSITE_III = 372,
INDIGO_STRATUM_ABYSSITE_IV = 373,
JADE_STRATUM_ABYSSITE = 374,
JADE_STRATUM_ABYSSITE_II = 375,
JADE_STRATUM_ABYSSITE_III = 376,
JADE_STRATUM_ABYSSITE_IV = 377,
SHODDY_METAL_CLASP = 378,
BUNDLE_OF_SUNDRY_PLANTS = 379,
SQUARE_OF_ULTIMATE_CLOTH = 380,
PLIABLE_LIZARD_SKIN = 381,
SQUARE_OF_LIZARD_LEATHER = 382,
MAP_OF_ABDH_ISLE_PURGONORGO = 383,
MAP_OF_THE_SAN_DORIA_AREA = 385,
MAP_OF_THE_BASTOK_AREA = 386,
MAP_OF_THE_WINDURST_AREA = 387,
MAP_OF_THE_JEUNO_AREA = 388,
MAP_OF_QUFIM_ISLAND = 389,
MAP_OF_THE_NORTHLANDS_AREA = 390,
MAP_OF_KING_RANPERRES_TOMB = 391,
MAP_OF_THE_DANGRUF_WADI = 392,
MAP_OF_THE_HORUTOTO_RUINS = 393,
MAP_OF_BOSTAUNIEUX_OUBLIETTE = 394,
MAP_OF_THE_ZERUHN_MINES = 395,
MAP_OF_THE_TORAIMARAI_CANAL = 396,
MAP_OF_ORDELLES_CAVES = 397,
MAP_OF_THE_GUSGEN_MINES = 398,
MAP_OF_THE_MAZE_OF_SHAKHRAMI = 399,
MAP_OF_THE_ELDIEME_NECROPOLIS = 400,
MAP_OF_THE_CRAWLERS_NEST = 401,
MAP_OF_THE_GARLAIGE_CITADEL = 402,
MAP_OF_THE_RANGUEMONT_PASS = 403,
MAP_OF_GHELSBA = 404,
MAP_OF_DAVOI = 405,
MAP_OF_THE_PALBOROUGH_MINES = 406,
MAP_OF_BEADEAUX = 407,
MAP_OF_GIDDEUS = 408,
MAP_OF_CASTLE_OZTROJA = 409,
MAP_OF_DELKFUTTS_TOWER = 410,
MAP_OF_FEIYIN = 411,
MAP_OF_CASTLE_ZVAHL = 412,
MAP_OF_THE_ELSHIMO_REGIONS = 413,
MAP_OF_THE_KUZOTZ_REGION = 414,
MAP_OF_THE_LITELOR_REGION = 415,
MAP_OF_THE_RUAUN_GARDENS = 416,
MAP_OF_NORG = 417,
MAP_OF_THE_TEMPLE_OF_UGGALEPIH = 418,
MAP_OF_THE_DEN_OF_RANCOR = 419,
MAP_OF_THE_KORROLOKA_TUNNEL = 420,
MAP_OF_THE_KUFTAL_TUNNEL = 421,
MAP_OF_THE_BOYAHDA_TREE = 422,
MAP_OF_THE_VELUGANNON_PALACE = 423,
MAP_OF_IFRITS_CAULDRON = 424,
MAP_OF_THE_QUICKSAND_CAVES = 425,
MAP_OF_THE_SEA_SERPENT_GROTTO = 426,
MAP_OF_THE_VOLLBOW_REGION = 427,
MAP_OF_THE_LABYRINTH_OF_ONZOZO = 428,
MAP_OF_CARPENTERS_LANDING = 429,
MAP_OF_BIBIKI_BAY = 430,
MAP_OF_THE_ULEGUERAND_RANGE = 431,
MAP_OF_THE_ATTOHWA_CHASM = 432,
MAP_OF_PSOXJA = 433,
MAP_OF_OLDTON_MOVALPOLOS = 434,
MAP_OF_NEWTON_MOVALPOLOS = 435,
MAP_OF_PROMYVION_HOLLA = 436,
MAP_OF_PROMYVION_DEM = 437,
MAP_OF_PROMYVION_MEA = 438,
MAP_OF_PROMYVION_VAHZL = 439,
MAP_OF_TAVNAZIA = 440,
MAP_OF_THE_AQUEDUCTS = 441,
MAP_OF_THE_SACRARIUM = 442,
MAP_OF_CAPE_RIVERNE = 443,
MAP_OF_ALTAIEU = 444,
MAP_OF_HUXZOI = 445,
MAP_OF_RUHMET = 446,
MAP_OF_DIO_ABDHALJS_GHELSBA = 447,
DAZEBREAKER_CHARM = 448,
SHINY_EARRING = 449,
CARBUNCLES_TEAR = 450,
SCRAP_OF_PAPYRUS = 451,
CERULEAN_CRYSTAL = 452,
HANDFUL_OF_CRYSTAL_SCALES = 453,
CHARRED_HELM = 454,
SHARD_OF_APATHY = 455,
SHARD_OF_ARROGANCE = 456,
SHARD_OF_COWARDICE = 457,
SHARD_OF_ENVY = 458,
SHARD_OF_RAGE = 459,
TRICK_BOX = 460,
WASHUS_TASTY_WURST = 461,
YOMOTSU_FEATHER = 462,
YOMOTSU_HIRASAKA = 463,
FADED_YOMOTSU_HIRASAKA = 464,
SEANCE_STAFF = 465,
SMILING_STONE = 466,
SCOWLING_STONE = 467,
SOMBER_STONE = 468,
SPIRITED_STONE = 469,
OLD_TRICK_BOX = 470,
LARGE_TRICK_BOX = 471,
INDIGESTED_STALAGMITE = 472,
INDIGESTED_ORE = 473,
INDIGESTED_MEAT = 474,
LETTER_FROM_ZONPAZIPPA = 475,
MOONDROP = 476,
MIRACLESALT = 477,
ANCIENT_VERSE_OF_ROMAEVE = 478,
ANCIENT_VERSE_OF_ALTEPA = 479,
ANCIENT_VERSE_OF_UGGALEPIH = 480,
FIGURE_OF_LEVIATHAN = 481,
FIGURE_OF_GARUDA = 482,
FIGURE_OF_TITAN = 483,
DARK_MANA_ORB = 484,
MOONGATE_PASS = 485,
HYDRA_CORPS_COMMAND_SCEPTER = 486,
HYDRA_CORPS_EYEGLASS = 487,
HYDRA_CORPS_LANTERN = 488,
HYDRA_CORPS_TACTICAL_MAP = 489,
HYDRA_CORPS_INSIGNIA = 490,
HYDRA_CORPS_BATTLE_STANDARD = 491,
VIAL_OF_SHROUDED_SAND = 492,
DIARY_OF_MUKUNDA = 493,
LETTER_TO_THE_BAS_CONFLICT_CMD1 = 494,
LETTER_TO_THE_WIN_CONFLICT_CMD1 = 495,
LETTER_TO_THE_SAN_CONFLICT_CMD1 = 496,
LETTER_TO_THE_WIN_CONFLICT_CMD2 = 497,
LETTER_TO_THE_SAN_CONFLICT_CMD2 = 498,
LETTER_TO_THE_BAS_CONFLICT_CMD2 = 499,
BALLISTA_EARRING = 500,
DRAWING_OF_A_MALE_HUME = 501,
DRAWING_OF_A_FEMALE_HUME = 502,
DRAWING_OF_A_MALE_ELVAAN = 503,
DRAWING_OF_A_FEMALE_ELVAAN = 504,
DRAWING_OF_A_MALE_TARUTARU = 505,
DRAWING_OF_A_FEMALE_TARUTARU = 506,
DRAWING_OF_A_MITHRA = 507,
DRAWING_OF_A_GALKA = 508,
YE_OLDE_MANNEQUIN_CATALOGUE = 509,
MANNEQUIN_JOINT_DIAGRAMS = 510,
CLAMMING_KIT = 511,
MOGHANCEMENT_FIRE = 512,
MOGHANCEMENT_ICE = 513,
MOGHANCEMENT_WIND = 514,
MOGHANCEMENT_EARTH = 515,
MOGHANCEMENT_LIGHTNING = 516,
MOGHANCEMENT_WATER = 517,
MOGHANCEMENT_LIGHT = 518,
MOGHANCEMENT_DARK = 519,
MOGHANCEMENT_EXPERIENCE = 520,
MOGHANCEMENT_GARDENING = 521,
MOGHANCEMENT_DESYNTHESIS = 522,
MOGHANCEMENT_FISHING = 523,
MOGHANCEMENT_WOODWORKING = 524,
MOGHANCEMENT_SMITHING = 525,
MOGHANCEMENT_GOLDSMITHING = 526,
MOGHANCEMENT_CLOTHCRAFT = 527,
MOGHANCEMENT_LEATHERCRAFT = 528,
MOGHANCEMENT_BONECRAFT = 529,
MOGHANCEMENT_ALCHEMY = 530,
MOGHANCEMENT_COOKING = 531,
MOGHANCEMENT_CONQUEST = 532,
MOGHANCEMENT_REGION = 533,
MOGHANCEMENT_FISHINGITEMS = 534,
MOGHANCEMENT_SAN_CONQUEST = 535,
MOGHANCEMENT_BAS_CONQUEST = 536,
MOGHANCEMENT_WIN_CONQUEST = 537,
MOGHANCEMENT_MONEY = 538,
MOGHANCEMENT_CAMPAIGN = 539,
MOGHANCEMENT_MONEY_II = 540,
MOGHANCEMENT_SKILL_GAINS = 541,
MOGHANCEMENT_BOUNTY = 542,
MOGLIFICATION_FISHING = 544,
MOGLIFICATION_WOODWORKING = 545,
MOGLIFICATION_SMITHING = 546,
MOGLIFICATION_GOLDSMITHING = 547,
MOGLIFICATION_CLOTHCRAFT = 548,
MOGLIFICATION_LEATHERCRAFT = 549,
MOGLIFICATION_BONECRAFT = 550,
MOGLIFICATION_ALCHEMY = 551,
MOGLIFICATION_COOKING = 552,
MEGA_MOGLIFICATION_FISHING = 553,
MEGA_MOGLIFICATION_WOODWORK = 554,
MEGA_MOGLIFICATION_SMITHING = 555,
MEGA_MOGLIFICATION_GOLDSMITH = 556,
MEGA_MOGLIFICATION_CLOTHCRAFT = 557,
MEGA_MOGLIFICATION_LEATHRCRFT = 558,
MEGA_MOGLIFICATION_BONECRAFT = 559,
MEGA_MOGLIFICATION_ALCHEMY = 560,
MEGA_MOGLIFICATION_COOKING = 561,
MOGLIFICATION_EXPERIENCE_BOOST = 562,
MOGLIFICATION_CAPACITY_BOOST = 563,
BALLISTA_LICENSE = 576,
BALLISTA_INSTAWARP = 577,
BALLISTA_INSTAPORT = 578,
MYSTERIOUS_AMULET = 579,
MYSTERIOUS_AMULET_DRAINED = 580,
CRACKED_MIMEO_MIRROR = 581,
RELIQUIARIUM_KEY = 582,
MIMEO_STONE = 583,
MYSTIC_ICE = 584,
KEY_ITEM585 = 585,
MIMEO_JEWEL = 586,
MIMEO_FEATHER = 587,
SECOND_MIMEO_FEATHER = 588,
THIRD_MIMEO_FEATHER = 589,
LIGHT_OF_HOLLA = 590,
LIGHT_OF_DEM = 591,
LIGHT_OF_MEA = 592,
LIGHT_OF_VAHZL = 593,
LIGHT_OF_ALTAIEU = 594,
BLUE_BRACELET = 595,
GREEN_BRACELET = 596,
DUSTY_TOME = 597,
POINTED_JUG = 598,
CRACKED_CLUB = 599,
PEELING_HAIRPIN = 600,
OLD_NAMETAG = 601,
TINY_WRISTLET = 602,
WHISPERING_CONCH = 603,
PSOXJA_PASS = 604,
PIECE_OF_RIPPED_FLOORPLANS = 605,
LIMIT_BREAKER = 606,
HYPER_ALTIMETER = 607,
MOLYBDENUM_BOX = 608,
ALABASTER_HAIRPIN = 609,
DAWN_TALISMAN = 610,
SILVER_COMETS_COLLAR = 611,
ENVELOPE_FROM_MONBERAUX = 612,
DELKFUTT_RECOGNITION_DEVICE = 613,
DEED_TO_PURGONORGO_ISLE = 614,
PHOENIX_ARMLET = 615,
PHOENIX_PEARL = 616,
MANACLIPPER_TICKET = 617,
BARGE_TICKET = 618,
ALLYOUCANRIDEPASS = 619,
TAVNAZIAN_ARCHIPELAGO_SUPPLIES = 620,
RIVERNEWORT = 621,
TAVNAZIAN_COOKBOOK = 622,
WASHUS_FLASK = 623,
FLASK_OF_CLAM_WATER = 624,
PUNGENT_PROVIDENCE_POT = 625,
TORN_OUT_PAGES = 626,
TONBERRY_BLACKBOARD = 627,
LETTER_FROM_MUCKVIX = 628,
LETTER_FROM_MAGRIFFON = 629,
PROVIDENCE_POT = 630,
CARE_PACKAGE = 631,
GLITTERING_FRAGMENT = 632,
STOREROOM_KEY = 633,
ZEELOZOKS_EARPLUG = 634,
POTION_VOUCHER = 635,
HIPOTION_VOUCHER = 636,
XPOTION_VOUCHER = 637,
ETHER_VOUCHER = 638,
HIETHER_VOUCHER = 639,
SUPER_ETHER_VOUCHER = 640,
ELIXER_VOUCHER = 641,
REVITALIZER_VOUCHER = 642,
BODY_BOOST_VOUCHER = 643,
MANA_BOOST_VOUCHER = 644,
DRACHENESSENCE_VOUCHER = 645,
BARFIRE_OINTMENT_VOUCHER = 646,
BARBLIZZARD_OINTMENT_VOUCHER = 647,
BARAERO_OINTMENT_VOUCHER = 648,
BARSTONE_OINTMENT_VOUCHER = 649,
BARTHUNDER_OINTMENT_VOUCHER = 650,
BARWATER_OINTMENT_VOUCHER = 651,
BARGE_MULTITICKET = 652,
MANACLIPPER_MULTITICKET = 653,
FIGHTERS_ARMOR_CLAIM_SLIP = 654,
TEMPLE_ATTIRE_CLAIM_SLIP = 655,
HEALERS_ATTIRE_CLAIM_SLIP = 656,
WIZARDS_ATTIRE_CLAIM_SLIP = 657,
WARLOCKS_ARMOR_CLAIM_SLIP = 658,
ROGUES_ATTIRE_CLAIM_SLIP = 659,
GALLANT_ARMOR_CLAIM_SLIP = 660,
CHAOS_ARMOR_CLAIM_SLIP = 661,
BEAST_ARMOR_CLAIM_SLIP = 662,
CHORAL_ATTIRE_CLAIM_SLIP = 663,
HUNTERS_ATTIRE_CLAIM_SLIP = 664,
MYOCHIN_ARMOR_CLAIM_SLIP = 665,
NINJAS_GARB_CLAIM_SLIP = 666,
DRACHEN_ARMOR_CLAIM_SLIP = 667,
EVOKERS_ATTIRE_CLAIM_SLIP = 668,
VESSEL_OF_LIGHT_KI = 669,
CENSER_OF_ABANDONMENT = 670,
CENSER_OF_ANTIPATHY = 671,
CENSER_OF_ANIMUS = 672,
CENSER_OF_ACRIMONY = 673,
MONARCH_BEARD = 674,
ASTRAL_COVENANT = 675,
SHAFT_2716_OPERATING_LEVER = 676,
ZEPHYR_FAN = 677,
MIASMA_FILTER = 678,
PARTICULARLY_POIGNANT_PETAL = 679,
ANTIQUE_AMULET = 680,
CATHEDRAL_MEDALLION = 681,
GOLD_BALLISTA_CHEVRON = 682,
MYTHRIL_BALLISTA_CHEVRON = 683,
SILVER_BALLISTA_CHEVRON = 684,
BRONZE_BALLISTA_CHEVRON = 685,
BLOODY_BALLISTA_CHEVRON = 686,
ORANGE_BALLISTA_CHEVRON = 687,
WHITE_BALLISTA_CHEVRON = 688,
BLACK_BALLISTA_CHEVRON = 689,
RED_BALLISTA_CHEVRON = 690,
GREEN_BALLISTA_CHEVRON = 691,
SPARKING_BALLISTA_CHEVRON = 692,
EBON_BALLISTA_CHEVRON = 693,
FURRY_BALLISTA_CHEVRON = 694,
BROWN_BALLISTA_CHEVRON = 695,
OCHRE_BALLISTA_CHEVRON = 696,
JADE_BALLISTA_CHEVRON = 697,
TRANSPARENT_BALLISTA_CHEVRON = 698,
PURPLE_BALLISTA_CHEVRON = 699,
RAINBOW_BALLISTA_CHEVRON = 700,
LETTERS_FROM_ULMIA_AND_PRISHE = 701,
PETRA_EATER_VOUCHER = 702,
CATHOLICON_VOUCHER = 703,
RED_OIL = 704,
MARBLE_BRIDGE_COASTER = 705,
LAMP_LIGHTERS_MEMBERSHIP_CARD = 706,
SHAFT_GATE_OPERATING_DIAL = 707,
MYSTERIOUS_AMULET = 708,
MIRE_INCENSE = 709,
BRAND_OF_DAWN = 710,
BRAND_OF_TWILIGHT = 711,
ORNAMENTED_SCROLL = 712,
BETTER_HUMES_AND_MANNEQUINS = 713,
PETRA_SHOVEL = 714,
CALIGINOUS_BLADE = 715,
TEAR_OF_ALTANA = 716,
BALLISTA_BAND = 717,
SHADED_CRUSE = 718,
LETTER_FROM_SHIKAREE_X = 719,
MONARCH_LINN_PATROL_PERMIT = 720,
LETTER_FROM_SHIKAREE_Y = 721,
LETTER_FROM_THE_MITHRAN_TRACKER = 722,
COMMUNICATION_FROM_TZEE_XICU = 723,
ORCISH_SEEKER_BATS = 724,
VAULT_QUIPUS = 725,
GOBLIN_RECOMMENDATION_LETTER = 726,
COSTUME_KIT = 727,
JAR_OF_REVERSION_DUST = 728,
REMEDY_VOUCHER = 729,
PANACEA_VOUCHER = 730,
SMELLING_SALTS_VOUCHER = 731,
VITRALLUM = 732,
OPALESCENT_STONE = 733,
COSMOCLEANSE = 734,
OLD_WOMANS_PORTRAIT = 735,
GLIMMERING_MICA = 736,
MISTROOT = 737,
LUNASCENT_LOG = 738,
DYNAMIS_VALKURM_SLIVER = 739,
DYNAMIS_BUBURIMU_SLIVER = 740,
DYNAMIS_QUFIM_SLIVER = 741,
DYNAMIS_TAVNAZIA_SLIVER = 742,
RED_SENTINEL_BADGE = 743,
BLUE_SENTINEL_BADGE = 744,
GREEN_SENTINEL_BADGE = 745,
WHITE_SENTINEL_BADGE = 746,
EYE_OF_FLAMES = 747,
EYE_OF_TREMORS = 748,
EYE_OF_TIDES = 749,
EYE_OF_GALES = 750,
EYE_OF_FROST = 751,
EYE_OF_STORMS = 752,
RED_INVITATION_CARD = 753,
BLUE_INVITATION_CARD = 754,
GREEN_INVITATION_CARD = 755,
WHITE_INVITATION_CARD = 756,
HEALING_POWDER_VOUCHER = 757,
BRENNER_SHOVEL = 758,
BRENNER_BAND = 759,
SILVER_SEA_FERRY_TICKET = 760,
MOONLIGHT_ORE = 761,
LEUJAOAM_ASSAULT_ORDERS = 762,
MAMOOL_JA_ASSAULT_ORDERS = 763,
LEBROS_ASSAULT_ORDERS = 764,
PERIQIA_ASSAULT_ORDERS = 765,
ILRUSI_ASSAULT_ORDERS = 766,
DKHAAYAS_RESEARCH_JOURNAL = 767,
ELECTROCELL = 768,
ELECTROPOT = 769,
ELECTROLOCOMOTIVE = 770,
MARK_OF_ZAHAK = 771,
VIAL_OF_LUMINOUS_WATER = 772,
IMAGE_RECORDER = 773,
CAST_METAL_PLATE = 774,
SUPPLIES_PACKAGE = 775,
RAINBOW_BERRY = 776,
SAPPHIRE_BALLISTA_CHEVRON = 777,
CORAL_BALLISTA_CHEVRON = 778,
SILK_BALLISTA_CHEVRON = 779,
PSC_WILDCAT_BADGE = 780,
BOARDING_PERMIT = 781,
RUNIC_PORTAL_USE_PERMIT = 782,
PFC_WILDCAT_BADGE = 783,
SP_WILDCAT_BADGE = 784,
RAILLEFALS_LETTER = 785,
EPHRAMADIAN_GOLD_COIN = 786,
IMPERIAL_ARMY_ID_TAG = 787,
RAILLEFALS_NOTE = 788,
DARK_RIDER_HOOFPRINT = 789,
BAG_OF_GOLD_PIECES = 790,
FORGOTTEN_HEXAGUN = 791,
PLASMA_OIL = 792,
PLASMA_ROCK = 793,
LC_WILDCAT_BADGE = 794,
C_WILDCAT_BADGE = 795,
POT_OF_TSETSEROONS_STEW = 796,
ASSAULT_ARMBAND = 797,
ANTIQUE_AUTOMATON = 798,
RED_BELL = 799,
BLUE_BELL = 800,
MUSICAL_SCORE_1ST_PAGE = 801,
MUSICAL_SCORE_2ND_PAGE = 802,
MERROW_HOMUNCULUS = 803,
LAMIA_HOMUNCULUS = 804,
MUNAHDAS_PACKAGE = 805,
WHITE_HANDKERCHIEF = 806,
CONFIDENTIAL_IMPERIAL_ORDER = 807,
SECRET_IMPERIAL_ORDER = 808,
HANDKERCHIEF = 809,
DIRTY_HANDKERCHIEF = 810,
REPLAY_DEBUGGER = 811,
ASTRAL_COMPASS = 812,
VIAL_OF_SPECTRAL_SCENT = 813,
EMPTY_TEST_TUBE_1 = 814,
EMPTY_TEST_TUBE_2 = 815,
EMPTY_TEST_TUBE_3 = 816,
EMPTY_TEST_TUBE_4 = 817,
EMPTY_TEST_TUBE_5 = 818,
TEST_TUBE_1 = 819,
TEST_TUBE_2 = 820,
TEST_TUBE_3 = 821,
TEST_TUBE_4 = 822,
TEST_TUBE_5 = 823,
QUARTZ_TRANSMITTER = 824,
S_WILDCAT_BADGE = 825,
SM_WILDCAT_BADGE = 826,
CS_WILDCAT_BADGE = 827,
CHUNK_OF_GLITTERING_ORE = 828,
BRAND_OF_THE_SPRINGSERPENT = 829,
BRAND_OF_THE_GALESERPENT = 830,
BRAND_OF_THE_FLAMESERPENT = 831,
BRAND_OF_THE_SKYSERPENT = 832,
BRAND_OF_THE_STONESERPENT = 833,
MAGUS_ORDER_SLIP = 834,
SEALED_IMMORTAL_ENVELOPE = 835,
STORY_OF_AN_IMPATIENT_CHOCOBO = 837,
STORY_OF_A_CURIOUS_CHOCOBO = 838,
STORY_OF_A_WORRISOME_CHOCOBO = 839,
STORY_OF_A_YOUTHFUL_CHOCOBO = 840,
STORY_OF_A_HAPPY_CHOCOBO = 841,
MAMOOL_JA_MANDATE = 842,
VALKENGS_MEMORY_CHIP = 843,
TOGGLE_SWITCH = 844,
LELEROONS_LETTER_GREEN = 845,
LELEROONS_LETTER_BLUE = 846,
LELEROONS_LETTER_RED = 847,
LIFE_FLOAT = 848,
WHEEL_LOCK_TRIGGER = 849,
STORY_OF_A_DILIGENT_CHOCOBO = 850,
PRAIRIE_CHOCOGRAPH = 851,
BUSH_CHOCOGRAPH = 852,
LETTER_FROM_BERNAHN = 853,
REMNANTS_PERMIT = 854,
LILAC_RIBBON = 855,
COASTAL_CHOCOGRAPH = 856,
DUNE_CHOCOGRAPH = 857,
JUNGLE_CHOCOGRAPH = 858,
DESERT_CHOCOGRAPH = 859,
PERIQIA_ASSAULT_AREA_ENTRY_PERMIT = 860,
WARRIORS_ARMOR_CLAIM_SLIP = 861,
MELEE_ATTIRE_CLAIM_SLIP = 862,
CLERICS_ATTIRE_CLAIM_SLIP = 863,
SORCERERS_ATTIRE_CLAIM_SLIP = 864,
DUELISTS_ARMOR_CLAIM_SLIP = 865,
ASSASSINS_ATTIRE_CLAIM_SLIP = 866,
VALOR_ARMOR_CLAIM_SLIP = 867,
ABYSS_ARMOR_CLAIM_SLIP = 868,
MONSTER_ARMOR_CLAIM_SLIP = 869,
BARDS_ATTIRE_CLAIM_SLIP = 870,
SCOUTS_ATTIRE_CLAIM_SLIP = 871,
SAOTOME_ARMOR_CLAIM_SLIP = 872,
KOGA_GARB_CLAIM_SLIP = 873,
WYRM_ARMOR_CLAIM_SLIP = 874,
SUMMONERS_ATTIRE_CLAIM_SLIP = 875,
SCOURSHROOM = 876,
PERCIPIENT_EYE = 877,
NYZUL_ISLE_ASSAULT_ORDERS = 878,
RUNIC_DISC = 879,
RUNIC_KEY = 880,
GYSAHL_MEDAL = 881,
ROSSWEISSES_FEATHER = 882,
GRIMGERDES_FEATHER = 883,
SIEGRUNES_FEATHER = 884,
HELMWIGES_FEATHER = 885,
SCHWERTLEITES_FEATHER = 886,
WALTRAUTES_FEATHER = 887,
ORTLINDES_FEATHER = 888,
GERHILDES_FEATHER = 889,
BRUNHILDES_FEATHER = 890,
MARK_OF_THE_EINHERJAR = 891,
PHOTOPTICATOR = 892,
LUMINIAN_DAGGER = 893,
SL_WILDCAT_BADGE = 894,
BIYAADAS_LETTER = 895,
OFFICER_ACADEMY_MANUAL = 896,
ALLIED_COUNCIL_SUMMONS = 897,
NYZUL_ISLE_ROUTE = 898,
MYTHRIL_MIRROR = 899,
FL_WILDCAT_BADGE = 900,
CHOCOBO_CIRCUIT_GRANDSTAND_PASS = 908,
CAPTAIN_WILDCAT_BADGE = 909,
PURE_WHITE_FEATHER = 910,
STARDUST_PEBBLE = 911,
LEFT_MAP_PIECE = 912,
MIDDLE_MAP_PIECE = 913,
RIGHT_MAP_PIECE = 914,
SEQUINED_BALLISTA_CHEVRON = 915,
VELVET_BALLISTA_CHEVRON = 916,
BATTLE_RATIONS = 917,
CLUMP_OF_ANIMAL_HAIR = 918,
XHIFHUT = 919,
WARNING_LETTER = 920,
RED_RECOMMENDATION_LETTER = 921,
BLUE_RECOMMENDATION_LETTER = 922,
GREEN_RECOMMENDATION_LETTER = 923,
BRONZE_RIBBON_OF_SERVICE = 924,
BRASS_RIBBON_OF_SERVICE = 925,
ALLIED_RIBBON_OF_BRAVERY = 926,
ALLIED_RIBBON_OF_GLORY = 927,
BRONZE_STAR = 928,
STERLING_STAR = 929,
MYTHRIL_STAR = 930,
GOLDEN_STAR = 931,
COPPER_EMBLEM_OF_SERVICE = 932,
IRON_EMBLEM_OF_SERVICE = 933,
STEELKNIGHT_EMBLEM = 934,
HOLYKNIGHT_EMBLEM = 935,
BRASS_WINGS_OF_SERVICE = 936,
MYTHRIL_WINGS_OF_SERVICE = 937,
WINGS_OF_INTEGRITY = 938,
WINGS_OF_HONOR = 939,
STARLIGHT_MEDAL = 940,
MOONLIGHT_MEDAL = 941,
DAWNLIGHT_MEDAL = 942,
MEDAL_OF_ALTANA = 943,
SLICED_POLE = 944,
SUPPLY_ORDER = 945,
GRIMOIRE = 946,
ZONPAZIPPAS_ALLPURPOSE_PUTTY = 947,
SCOOPDEDICATED_LINKPEARL = 948,
FIREPOWER_CASE = 949,
CHARRED_PROPELLER = 950,
PIECE_OF_SHATTERED_LUMBER = 951,
OXIDIZED_PLATE = 952,
PIECE_OF_KIONITE = 953,
RANPIMONPI_SPECIALTY = 954,
CULINARY_KNIFE = 955,
FIREBLOSSOM = 956,
THE_HEALING_HERB = 957,
SMALL_STARFRUIT = 958,
INKY_BLACK_YAGUDO_FEATHER = 959,
CAMPAIGN_SUPPLIES = 960,
MINE_SHAFT_KEY = 961,
THE_ESSENCE_OF_DANCE = 962,
JUGNER_GATE_CRYSTAL = 963,
PASHHOW_GATE_CRYSTAL = 964,
MERIPHATAUD_GATE_CRYSTAL = 965,
VUNKERL_HERB = 966,
VUNKERL_HERB_MEMO = 967,
EVIL_WARDING_SEAL = 968,
ORNATE_PACKAGE = 969,
SHEAF_OF_HANDMADE_INCENSE = 970,
LEATHERBOUND_BOOK = 971,
LYNX_PELT = 972,
WYATTS_PROPOSAL = 973,
FORT_KEY = 974,
ULBRECHTS_SEALED_LETTER = 975,
SCHULTS_SEALED_LETTER = 976,
UNADDRESSED_SEALED_LETTER = 977,
PORTING_MAGIC_TRANSCRIPT = 978,
SAMPLE_OF_GRAUBERG_CHERT = 979,
DROGAROGAN_BONEMEAL = 980,
SLUG_MUCUS = 981,
DJINN_EMBER = 982,
RAFFLESIA_DREAMSPIT = 983,
PEISTE_DUNG = 984,
ULBRECHTS_MORTARBOARD = 985,
BEASTMEN_CONFEDERATE_CRATE = 986,
MILITARY_SCRIP = 987,
SILVERMINE_KEY = 988,
RED_PRIZE_BALLOON = 989,
BLUE_PRIZE_BALLOON = 990,
GREEN_PRIZE_BALLOON = 991,
TRAVONCES_ESCORT_AWARD = 992,
KENS_ESCORT_AWARD = 993,
EMPTINESS_INVESTIGATION_NOTE = 994,
TIGRIS_STONE = 995,
DIAMOND_SEAL = 996,
XICUS_ROSARY = 997,
MAROON_SEAL = 998,
APPLE_GREEN_SEAL = 999,
CHARCOAL_GREY_SEAL = 1000,
DEEP_PURPLE_SEAL = 1001,
CHESTNUT_COLORED_SEAL = 1002,
LILAC_COLORED_SEAL = 1003,
CERISE_SEAL = 1004,
SALMON_COLORED_SEAL = 1005,
PURPLISH_GREY_SEAL = 1006,
GOLD_COLORED_SEAL = 1007,
COPPER_COLORED_SEAL = 1008,
BRIGHT_BLUE_SEAL = 1009,
PINE_GREEN_SEAL = 1010,
AMBER_COLORED_SEAL = 1011,
FALLOW_COLORED_SEAL = 1012,
TAUPE_COLORED_SEAL = 1013,
SIENNA_COLORED_SEAL = 1014,
LAVENDER_COLORED_SEAL = 1015,
SICKLEMOON_SALT = 1016,
SILVER_SEA_SALT = 1017,
CYAN_DEEP_SALT = 1018,
ORCISH_WARMACHINE_BODY = 1019,
PAPAROONS_SEALED_INVITATION = 1020,
DATA_ANALYZER_AND_LOGGER_EX = 1021,
MAYAKOV_SHOW_TICKET = 1022,
SERPENTKING_ZAHAK_RELIEF = 1023,
SAKURA_RACING_BADGE = 1024,
SERPENTKING_ZAHAK_RELIEF_SHARD = 1025,
IMPERIAL_LINEAGE_CHAPTER_I = 1026,
IMPERIAL_LINEAGE_CHAPTER_II = 1027,
IMPERIAL_LINEAGE_CHAPTER_III = 1028,
IMPERIAL_LINEAGE_CHAPTER_IV = 1029,
IMPERIAL_LINEAGE_CHAPTER_V = 1030,
IMPERIAL_LINEAGE_CHAPTER_VI = 1031,
IMPERIAL_LINEAGE_CHAPTER_VII = 1032,
IMPERIAL_LINEAGE_CHAPTER_VIII = 1033,
THE_WORDS_OF_DONHU_I = 1034,
THE_WORDS_OF_DONHU_II = 1035,
THE_WORDS_OF_DONHU_III = 1036,
THE_WORDS_OF_DONHU_IV = 1037,
THE_WORDS_OF_DONHU_V = 1038,
THE_WORDS_OF_DONHU_VI = 1039,
THE_WORDS_OF_DONHU_VII = 1040,
THE_WORDS_OF_DONHU_VIII = 1041,
HABALOS_ECLOGUE_VERSE_I = 1042,
HABALOS_ECLOGUE_VERSE_II = 1043,
HABALOS_ECLOGUE_VERSE_III = 1044,
HABALOS_ECLOGUE_VERSE_IV = 1045,
HABALOS_ECLOGUE_VERSE_V = 1046,
HABALOS_ECLOGUE_VERSE_VI = 1047,
HABALOS_ECLOGUE_VERSE_VII = 1048,
HABALOS_ECLOGUE_VERSE_VIII = 1049,
SIGNAL_FIRECRACKER = 1050,
NUMBER_EIGHT_SHELTER_KEY = 1051,
TORN_PATCHES_OF_LEATHER = 1052,
REPAIRED_HANDBAG = 1053,
MIRAGE_ATTIRE_CLAIM_SLIP = 1054,
COMMODORE_ATTIRE_CLAIM_SLIP = 1055,
PANTIN_ATTIRE_CLAIM_SLIP = 1056,
ETOILE_ATTIRE_CLAIM_SLIP = 1057,
ARGUTE_ATTIRE_CLAIM_SLIP = 1058,
ARGENT_ATTIRE_CLAIM_SLIP = 1059,
CONQUEST_PROMOTION_VOUCHER = 1060,
CERNUNNOS_RESIN = 1061,
COUNT_BORELS_LETTER = 1062,
UNDERPASS_HATCH_KEY = 1063,
BOTTLE_OF_TREANT_TONIC = 1064,
TIMBER_SURVEY_CHECKLIST = 1065,
SNOWTHEMED_GIFT_TOKEN = 1066,
STARTHEMED_GIFT_TOKEN = 1067,
BELLTHEMED_GIFT_TOKEN = 1068,
FLARE_GRENADE = 1069,
RONFAURE_MAPLE_SYRUP = 1070,
LONGLIFE_BISCUITS = 1071,
FLASK_OF_KINGDOM_WATER = 1072,
BISCUIT_A_LA_RHOLONT = 1073,
LETTER_TO_COUNT_AURCHIAT = 1074,
LENGTH_OF_JUGNER_IVY = 1075,
DARKFIRE_CINDER = 1076,
FLOELIGHT_STONE = 1077,
LIQUID_QUICKSILVER = 1078,
GELID_SULFUR = 1079,
BEASTBANE_BULLETS = 1080,
GLEIPNIR = 1081,
SCINTILLANT_STRAND = 1082,
REFULGENT_STRAND = 1083,
IRRADIANT_STRAND = 1084,
BOWL_OF_BLAND_GOBLIN_SALAD = 1085,
JUG_OF_GREASY_GOBLIN_JUICE = 1086,
CHUNK_OF_SMOKED_GOBLIN_GRUB = 1087,
SEEDSPALL_ROSEUM = 1088,
SEEDSPALL_CAERULUM = 1089,
SEEDSPALL_VIRIDIS = 1090,
MARK_OF_SEED = 1091,
AMICITIA_STONE = 1092,
VERITAS_STONE = 1093,
SAPIENTIA_STONE = 1094,
SANCTITAS_STONE = 1095,
FELICITAS_STONE = 1096,
DIVITIA_STONE = 1097,
STUDIUM_STONE = 1098,
AMORIS_STONE = 1099,
CARITAS_STONE = 1100,
CONSTANTIA_STONE = 1101,
SPEI_STONE = 1102,
SALUS_STONE = 1103,
OMNIS_STONE = 1104,
CRIMSON_KEY = 1105,
VIRIDIAN_KEY = 1106,
AMBER_KEY = 1107,
AZURE_KEY = 1108,
IVORY_KEY = 1109,
EBON_KEY = 1110,
DELKFUTT_KEY = 1111,
BEASTBANE_ARROWHEADS = 1112,
RED_LABELED_CRATE = 1113,
BLUE_LABELED_CRATE = 1114,
GREEN_LABELED_CRATE = 1115,
ELITE_TRAINING_INTRODUCTION = 1116,
ELITE_TRAINING_CHAPTER_1 = 1117,
ELITE_TRAINING_CHAPTER_2 = 1118,
ELITE_TRAINING_CHAPTER_3 = 1119,
ELITE_TRAINING_CHAPTER_4 = 1120,
ELITE_TRAINING_CHAPTER_5 = 1121,
ELITE_TRAINING_CHAPTER_6 = 1122,
ELITE_TRAINING_CHAPTER_7 = 1123,
UNADORNED_RING = 1124,
MOG_KUPON_A_DBCD = 1125,
MOG_KUPON_A_DXAR = 1126,
PRISMATIC_KEY = 1127,
SHADOW_BUG = 1128,
WHITE_CORAL_KEY = 1129,
BLUE_CORAL_KEY = 1130,
PEACH_CORAL_KEY = 1131,
BLACK_CORAL_KEY = 1132,
RED_CORAL_KEY = 1133,
ANGEL_SKIN_KEY = 1134,
OXBLOOD_KEY = 1135,
STURDY_METAL_STRIP = 1136,
PIECE_OF_RUGGED_TREE_BARK = 1137,
SAVORY_LAMB_ROAST = 1138,
ORB_OF_SWORDS = 1139,
ORB_OF_CUPS = 1140,
ORB_OF_BATONS = 1141,
ORB_OF_COINS = 1142,
RIPE_STARFRUIT = 1143,
MOLDY_WORMEATEN_CHEST = 1144,
STONE_OF_SURYA = 1145,
STONE_OF_CHANDRA = 1146,
STONE_OF_MANGALA = 1147,
STONE_OF_BUDHA = 1148,
STONE_OF_BRIHASPATI = 1149,
STONE_OF_SHUKRA = 1150,
STONE_OF_SHANI = 1151,
STONE_OF_RAHU = 1152,
STONE_OF_KETU = 1153,
TRIVIA_CHALLENGE_KUPON = 1154,
GAUNTLET_CHALLENGE_KUPON = 1155,
FESTIVAL_SOUVENIR_KUPON = 1156,
POCKET_MOGBOMB = 1157,
NAVARATNA_TALISMAN = 1158,
MEGA_BONANZA_KUPON = 1159,
AROMA_BUG = 1160,
UMBRA_BUG = 1161,
NORTHBOUND_PETITION = 1162,
PONONOS_CHARM = 1163,
DELICATE_WOOL_THREAD = 1164,
DELICATE_LINEN_THREAD = 1165,
DELICATE_COTTON_THREAD = 1166,
ENCHANTED_WOOL_THREAD = 1167,
ENCHANTED_LINEN_THREAD = 1168,
ENCHANTED_COTTON_THREAD = 1169,
WAX_SEAL = 1170,
SACK_OF_VICTUALS = 1171,
COMMANDERS_ENDORSEMENT = 1172,
SUCCULENT_DRAGON_FRUIT = 1173,
SHARD_OF_OPTISTONE = 1174,
SHARD_OF_AURASTONE = 1175,
SHARD_OF_ORASTONE = 1176,
PROSPECTORS_PAN = 1177,
CORKED_AMPOULE = 1178,
AMPOULE_OF_GOLD_DUST = 1179,
VIAL_OF_MILITARY_PRISM_POWDER = 1180,
LANCE_FISH = 1181,
PALADIN_LOBSTER = 1182,
SCUTUM_CRAB = 1183,
MOOGLE_KEY = 1184,
BIRD_KEY = 1185,
CACTUAR_KEY = 1186,
BOMB_KEY = 1187,
CHOCOBO_KEY = 1188,
TONBERRY_KEY = 1189,
BEHEMOTH_KEY = 1190,
DOMINAS_SCARLET_SEAL = 1191,
DOMINAS_CERULEAN_SEAL = 1192,
DOMINAS_EMERALD_SEAL = 1193,
DOMINAS_AMBER_SEAL = 1194,
DOMINAS_VIOLET_SEAL = 1195,
DOMINAS_AZURE_SEAL = 1196,
SCARLET_COUNTERSEAL = 1197,
CERULEAN_COUNTERSEAL = 1198,
EMERALD_COUNTERSEAL = 1199,
AMBER_COUNTERSEAL = 1200,
VIOLET_COUNTERSEAL = 1201,
AZURE_COUNTERSEAL = 1202,
BLACK_BOOK = 1203,
LUMINOUS_RED_FRAGMENT = 1204,
LUMINOUS_BEIGE_FRAGMENT = 1205,
LUMINOUS_GREEN_FRAGMENT = 1206,
LUMINOUS_YELLOW_FRAGMENT = 1207,
LUMINOUS_PURPLE_FRAGMENT = 1208,
LUMINOUS_BLUE_FRAGMENT = 1209,
FIRE_SAP_CRYSTAL = 1210,
WATER_SAP_CRYSTAL = 1211,
WIND_SAP_CRYSTAL = 1212,
EARTH_SAP_CRYSTAL = 1213,
LIGHTNING_SAP_CRYSTAL = 1214,
ICE_SAP_CRYSTAL = 1215,
LIGHT_SAP_CRYSTAL = 1216,
DARK_SAP_CRYSTAL = 1217,
TABLET_OF_HEXES_GREED = 1218,
TABLET_OF_HEXES_ENVY = 1219,
TABLET_OF_HEXES_MALICE = 1220,
TABLET_OF_HEXES_DECEIT = 1221,
TABLET_OF_HEXES_PRIDE = 1222,
TABLET_OF_HEXES_BALE = 1223,
TABLET_OF_HEXES_DESPAIR = 1224,
TABLET_OF_HEXES_REGRET = 1225,
TABLET_OF_HEXES_RAGE = 1226,
TABLET_OF_HEXES_AGONY = 1227,
TABLET_OF_HEXES_DOLOR = 1228,
TABLET_OF_HEXES_RANCOR = 1229,
TABLET_OF_HEXES_STRIFE = 1230,
TABLET_OF_HEXES_PENURY = 1231,
TABLET_OF_HEXES_BLIGHT = 1232,
TABLET_OF_HEXES_DEATH = 1233,
SYNERGY_CRUCIBLE = 1234,
MOG_KUPON_AW_ABS = 1235,
MOG_KUPON_AW_PAN = 1236,
MAGELIGHT_SIGNAL_FLARE = 1237,
ALCHEMICAL_SIGNAL_FLARE = 1238,
DISTRESS_SIGNAL_FLARE = 1239,
IMPERIAL_MISSIVE = 1240,
SANDORIAN_APPROVAL_LETTER = 1241,
BASTOKAN_APPROVAL_LETTER = 1242,
WINDURSTIAN_APPROVAL_LETTER = 1243,
JEUNOAN_APPROVAL_LETTER = 1244,
PRESENT_FOR_MEGOMAK = 1245,
LIGHTNING_CELL = 1246,
MEGOMAKS_SHOPPING_LIST = 1247,
WHISPER_OF_RADIANCE = 1248,
TALISMAN_OF_THE_REBEL_GODS = 1249,
MESSAGE_FROM_YOYOROON = 1250,
WHISPER_OF_GLOOM = 1251,
SPATIAL_PRESSURE_BAROMETER = 1252,
CLEAR_ABYSSITE = 1253,
COLORFUL_ABYSSITE = 1254,
BLUE_ABYSSITE = 1255,
ORANGE_ABYSSITE = 1256,
BROWN_ABYSSITE = 1257,
YELLOW_ABYSSITE = 1258,
PURPLE_ABYSSITE = 1259,
BLACK_ABYSSITE = 1260,
MAGIAN_TRIAL_LOG = 1261,
MOG_KUPON_A_LUM = 1262,
TALISMAN_KEY = 1263,
LETTER_FROM_HALVER = 1264,
LETTER_FROM_NAJI = 1265,
LETTER_FROM_ZUBABA = 1266,
LETTER_FROM_MAAT = 1267,
LETTER_FROM_DESPACHIAIRE = 1268,
LETTER_FROM_JAKOH_WAHCONDALO = 1269,
ZVAHL_PASSKEY = 1270,
TRAVERSER_STONE1 = 1271,
TRAVERSER_STONE2 = 1272,
TRAVERSER_STONE3 = 1273,
TRAVERSER_STONE4 = 1274,
TRAVERSER_STONE5 = 1275,
TRAVERSER_STONE6 = 1276,
POET_GODS_KEY = 1277,
ORCISH_INFILTRATION_KIT = 1278,
ATMA_OF_THE_LION = 1279,
ATMA_OF_THE_STOUT_ARM = 1280,
ATMA_OF_THE_TWIN_CLAW = 1281,
ATMA_OF_ALLURE = 1282,
ATMA_OF_ETERNITY = 1283,
ATMA_OF_THE_HEAVENS = 1284,
ATMA_OF_THE_BAYING_MOON = 1285,
ATMA_OF_THE_EBON_HOOF = 1286,
ATMA_OF_TREMORS = 1287,
ATMA_OF_THE_SAVAGE_TIGER = 1288,
ATMA_OF_THE_VORACIOUS_VIOLET = 1289,
ATMA_OF_CLOAK_AND_DAGGER = 1290,
ATMA_OF_THE_STORMBIRD = 1291,
ATMA_OF_THE_NOXIOUS_FANG = 1292,
ATMA_OF_VICISSITUDE = 1293,
ATMA_OF_THE_BEYOND = 1294,
ATMA_OF_STORMBREATH = 1295,
ATMA_OF_GALES = 1296,
ATMA_OF_THRASHING_TENDRILS = 1297,
ATMA_OF_THE_DRIFTER = 1298,
ATMA_OF_THE_STRONGHOLD = 1299,
ATMA_OF_THE_HARVESTER = 1300,
ATMA_OF_DUNES = 1301,
ATMA_OF_THE_COSMOS = 1302,
ATMA_OF_THE_SIREN_SHADOW = 1303,
ATMA_OF_THE_IMPALER = 1304,
ATMA_OF_THE_ADAMANTINE = 1305,
ATMA_OF_CALAMITY = 1306,
ATMA_OF_THE_CLAW = 1307,
ATMA_OF_BALEFUL_BONES = 1308,
ATMA_OF_THE_CLAWED_BUTTERFLY = 1309,
ATMA_OF_THE_DESERT_WORM = 1310,
ATMA_OF_THE_UNDYING = 1311,
ATMA_OF_THE_IMPREGNABLE_TOWER = 1312,
ATMA_OF_THE_SMOLDERING_SKY = 1313,
ATMA_OF_THE_DEMONIC_SKEWER = 1314,
ATMA_OF_THE_GOLDEN_CLAW = 1315,
ATMA_OF_THE_GLUTINOUS_OOZE = 1316,
ATMA_OF_THE_LIGHTNING_BEAST = 1317,
ATMA_OF_THE_NOXIOUS_BLOOM = 1318,
ATMA_OF_THE_GNARLED_HORN = 1319,
ATMA_OF_THE_STRANGLING_WIND = 1320,
ATMA_OF_THE_DEEP_DEVOURER = 1321,
ATMA_OF_THE_MOUNTED_CHAMPION = 1322,
ATMA_OF_THE_RAZED_RUINS = 1323,
ATMA_OF_THE_BLUDGEONING_BRUTE = 1324,
ATMA_OF_THE_RAPID_REPTILIAN = 1325,
ATMA_OF_THE_WINGED_ENIGMA = 1326,
ATMA_OF_THE_CRADLE = 1327,
ATMA_OF_THE_UNTOUCHED = 1328,
ATMA_OF_THE_SANGUINE_SCYTHE = 1329,
ATMA_OF_THE_TUSKED_TERROR = 1330,
ATMA_OF_THE_MINIKIN_MONSTROSITY = 1331,
ATMA_OF_THE_WOULD_BE_KING = 1332,
ATMA_OF_THE_BLINDING_HORN = 1333,
ATMA_OF_THE_DEMONIC_LASH = 1334,
ATMA_OF_APPARITIONS = 1335,
ATMA_OF_THE_SHIMMERING_SHELL = 1336,
ATMA_OF_THE_MURKY_MIASMA = 1337,
ATMA_OF_THE_AVARICIOUS_APE = 1338,
ATMA_OF_THE_MERCILESS_MATRIARCH = 1339,
ATMA_OF_THE_BROTHER_WOLF = 1340,
ATMA_OF_THE_EARTH_WYRM = 1341,
ATMA_OF_THE_ASCENDING_ONE = 1342,
ATMA_OF_THE_SCORPION_QUEEN = 1343,
ATMA_OF_A_THOUSAND_NEEDLES = 1344,
ATMA_OF_THE_BURNING_EFFIGY = 1345,
ATMA_OF_THE_SMITING_BLOW = 1346,
ATMA_OF_THE_LONE_WOLF = 1347,
ATMA_OF_THE_CRIMSON_SCALE = 1348,
ATMA_OF_THE_SCARLET_WING = 1349,
ATMA_OF_THE_RAISED_TAIL = 1350,
ATMA_OF_THE_SAND_EMPEROR = 1351,
ATMA_OF_THE_OMNIPOTENT = 1352,
ATMA_OF_THE_WAR_LION = 1353,
ATMA_OF_THE_FROZEN_FETTERS = 1354,
ATMA_OF_THE_PLAGUEBRINGER = 1355,
ATMA_OF_THE_SHRIEKING_ONE = 1356,
ATMA_OF_THE_HOLY_MOUNTAIN = 1357,
ATMA_OF_THE_LAKE_LURKER = 1358,
ATMA_OF_THE_CRUSHING_CUDGEL = 1359,
ATMA_OF_PURGATORY = 1360,
ATMA_OF_BLIGHTED_BREATH = 1361,
ATMA_OF_THE_PERSISTENT_PREDATOR = 1362,
ATMA_OF_THE_STONE_GOD = 1363,
ATMA_OF_THE_SUN_EATER = 1364,
ATMA_OF_THE_DESPOT = 1365,
ATMA_OF_THE_SOLITARY_ONE = 1366,
ATMA_OF_THE_WINGED_GLOOM = 1367,
ATMA_OF_THE_SEA_DAUGHTER = 1368,
ATMA_OF_THE_HATEFUL_STREAM = 1369,
ATMA_OF_THE_FOE_FLAYER = 1370,
ATMA_OF_THE_ENDLESS_NIGHTMARE = 1371,
ATMA_OF_THE_SUNDERING_SLASH = 1372,
ATMA_OF_ENTWINED_SERPENTS = 1373,
ATMA_OF_THE_HORNED_BEAST = 1374,
ATMA_OF_AQUATIC_ARDOR = 1375,
ATMA_OF_THE_FALLEN_ONE = 1376,
ATMA_OF_FIRES_AND_FLARES = 1377,
ATMA_OF_THE_APOCALYPSE = 1378,
IVORY_ABYSSITE_OF_SOJOURN = 1379,
SCARLET_ABYSSITE_OF_SOJOURN = 1380,
JADE_ABYSSITE_OF_SOJOURN = 1381,
SAPPHIRE_ABYSSITE_OF_SOJOURN = 1382,
INDIGO_ABYSSITE_OF_SOJOURN = 1383,
EMERALD_ABYSSITE_OF_SOJOURN = 1384,
AZURE_ABYSSITE_OF_CELERITY = 1385,
CRIMSON_ABYSSITE_OF_CELERITY = 1386,
IVORY_ABYSSITE_OF_CELERITY = 1387,
VIRIDIAN_ABYSSITE_OF_AVARICE = 1388,
IVORY_ABYSSITE_OF_AVARICE = 1389,
VERMILLION_ABYSSITE_OF_AVARICE = 1390,
IVORY_ABYSSITE_OF_CONFLUENCE = 1391,
CRIMSON_ABYSSITE_OF_CONFLUENCE = 1392,
INDIGO_ABYSSITE_OF_CONFLUENCE = 1393,
IVORY_ABYSSITE_OF_EXPERTISE = 1394,
JADE_ABYSSITE_OF_EXPERTISE = 1395,
EMERALD_ABYSSITE_OF_EXPERTISE = 1396,
IVORY_ABYSSITE_OF_FORTUNE = 1397,
SAPPHIRE_ABYSSITE_OF_FORTUNE = 1398,
EMERALD_ABYSSITE_OF_FORTUNE = 1399,
SCARLET_ABYSSITE_OF_KISMET = 1400,
IVORY_ABYSSITE_OF_KISMET = 1401,
VERMILLION_ABYSSITE_OF_KISMET = 1402,
AZURE_ABYSSITE_OF_PROSPERITY = 1403,
JADE_ABYSSITE_OF_PROSPERITY = 1404,
IVORY_ABYSSITE_OF_PROSPERITY = 1405,
VIRIDIAN_ABYSSITE_OF_DESTINY = 1406,
CRIMSON_ABYSSITE_OF_DESTINY = 1407,
IVORY_ABYSSITE_OF_DESTINY = 1408,
IVORY_ABYSSITE_OF_ACUMEN = 1409,
CRIMSON_ABYSSITE_OF_ACUMEN = 1410,
EMERALD_ABYSSITE_OF_ACUMEN = 1411,
SCARLET_ABYSSITE_OF_LENITY = 1412,
AZURE_ABYSSITE_OF_LENITY = 1413,
VIRIDIAN_ABYSSITE_OF_LENITY = 1414,
JADE_ABYSSITE_OF_LENITY = 1415,
SAPPHIRE_ABYSSITE_OF_LENITY = 1416,
CRIMSON_ABYSSITE_OF_LENITY = 1417,
VERMILLION_ABYSSITE_OF_LENITY = 1418,
INDIGO_ABYSSITE_OF_LENITY = 1419,
EMERALD_ABYSSITE_OF_LENITY = 1420,
SCARLET_ABYSSITE_OF_PERSPICACITY = 1421,
IVORY_ABYSSITE_OF_PERSPICACITY = 1422,
VERM_ABYSSITE_OF_PERSPICACITY = 1423,
AZURE_ABYSSITE_OF_THE_REAPER = 1424,
IVORY_ABYSSITE_OF_THE_REAPER = 1425,
INDIGO_ABYSSITE_OF_THE_REAPER = 1426,
VIRIDIAN_ABYSSITE_OF_GUERDON = 1427,
IVORY_ABYSSITE_OF_GUERDON = 1428,
VERMILLION_ABYSSITE_OF_GUERDON = 1429,
SCARLET_ABYSSITE_OF_FURTHERANCE = 1430,
SAPPHIRE_ABYSSITE_OF_FURTHERANCE = 1431,
IVORY_ABYSSITE_OF_FURTHERANCE = 1432,
AZURE_ABYSSITE_OF_MERIT = 1433,
VIRIDIAN_ABYSSITE_OF_MERIT = 1434,
JADE_ABYSSITE_OF_MERIT = 1435,
SAPPHIRE_ABYSSITE_OF_MERIT = 1436,
IVORY_ABYSSITE_OF_MERIT = 1437,
INDIGO_ABYSSITE_OF_MERIT = 1438,
LUNAR_ABYSSITE1 = 1439,
LUNAR_ABYSSITE2 = 1440,
LUNAR_ABYSSITE3 = 1441,
ABYSSITE_OF_DISCERNMENT = 1442,
ABYSSITE_OF_THE_COSMOS = 1443,
WHITE_STRATUM_ABYSSITE = 1444,
WHITE_STRATUM_ABYSSITE_II = 1445,
WHITE_STRATUM_ABYSSITE_III = 1446,
ASHEN_STRATUM_ABYSSITE = 1447,
ASHEN_STRATUM_ABYSSITE_II = 1448,
ASHEN_STRATUM_ABYSSITE_III = 1449,
WHITE_STRATUM_ABYSSITE_IV = 1450,
WHITE_STRATUM_ABYSSITE_V = 1451,
WHITE_STRATUM_ABYSSITE_VI = 1452,
LEGION_TOME_PAGE_MAXIMUS = 1453,
LEGION_MEDAL_AN = 1454,
LEGION_MEDAL_KI = 1455,
LEGION_MEDAL_IM = 1456,
LEGION_MEDAL_MURU = 1457,
LEGION_TOME_PAGE_MINIMUS = 1458,
FRAGRANT_TREANT_PETAL = 1459,
FETID_RAFFLESIA_STALK = 1460,
DECAYING_MORBOL_TOOTH = 1461,
TURBID_SLIME_OIL = 1462,
VENOMOUS_PEISTE_CLAW = 1463,
TATTERED_HIPPOGRYPH_WING = 1464,
CRACKED_WIVRE_HORN = 1465,
MUCID_AHRIMAN_EYEBALL = 1466,
TWISTED_TONBERRY_CROWN = 1467,
VEINOUS_HECTEYES_EYELID = 1468,
TORN_BAT_WING = 1469,
GORY_SCORPION_CLAW = 1470,
MOSSY_ADAMANTOISE_SHELL = 1471,
FAT_LINED_COCKATRICE_SKIN = 1472,
SODDEN_SANDWORM_HUSK = 1473,
LUXURIANT_MANTICORE_MANE = 1474,
STICKY_GNAT_WING = 1475,
OVERGROWN_MANDRAGORA_FLOWER = 1476,
CHIPPED_SANDWORM_TOOTH = 1477,
MARBLED_MUTTON_CHOP = 1478,
BLOODIED_SABER_TOOTH = 1479,
BLOOD_SMEARED_GIGAS_HELM = 1480,
GLITTERING_PIXIE_CHOKER = 1481,
DENTED_GIGAS_SHIELD = 1482,
WARPED_GIGAS_ARMBAND = 1483,
SEVERED_GIGAS_COLLAR = 1484,
PELLUCID_FLY_EYE = 1485,
SHIMMERING_PIXIE_PINION = 1486,
SMOLDERING_CRAB_SHELL = 1487,
VENOMOUS_WAMOURA_FEELER = 1488,
BULBOUS_CRAWLER_COCOON = 1489,
DISTENDED_CHIGOE_ABDOMEN = 1490,
MUCID_WORM_SEGMENT = 1491,
SHRIVELED_HECTEYES_STALK = 1492,
BLOTCHED_DOOMED_TONGUE = 1493,
CRACKED_SKELETON_CLAVICLE = 1494,
WRITHING_GHOST_FINGER = 1495,
RUSTED_HOUND_COLLAR = 1496,
HOLLOW_DRAGON_EYE = 1497,
BLOODSTAINED_BUGARD_FANG = 1498,
GNARLED_LIZARD_NAIL = 1499,
MOLTED_PEISTE_SKIN = 1500,
JAGGED_APKALLU_BEAK = 1501,
CLIPPED_BIRD_WING = 1502,
BLOODIED_BAT_FUR = 1503,
GLISTENING_OROBON_LIVER = 1504,
DOFFED_POROGGO_HAT = 1505,
SCALDING_IRONCLAD_SPIKE = 1506,
BLAZING_CLUSTER_SOUL = 1507,
INGROWN_TAURUS_NAIL = 1508,
OSSIFIED_GARGOUILLE_HAND = 1509,
IMBRUED_VAMPYR_FANG = 1510,
GLOSSY_SEA_MONK_SUCKER = 1511,
SHIMMERING_PUGIL_SCALE = 1512,
DECAYED_DVERGR_TOOTH = 1513,
PULSATING_SOULFLAYER_BEARD = 1514,
CHIPPED_IMPS_OLIFANT = 1515,
WARPED_SMILODON_CHOKER = 1516,
MALODOROUS_MARID_FUR = 1517,
BROKEN_IRON_GIANT_SPIKE = 1518,
RUSTED_CHARIOT_GEAR = 1519,
STEAMING_CERBERUS_TONGUE = 1520,
BLOODIED_DRAGON_EAR = 1521,
RESPLENDENT_ROC_QUILL = 1522,
WARPED_IRON_GIANT_NAIL = 1523,
DENTED_CHARIOT_SHIELD = 1524,
TORN_KHIMAIRA_WING = 1525,
BEGRIMED_DRAGON_HIDE = 1526,
DECAYING_DIREMITE_FANG = 1527,
SHATTERED_IRON_GIANT_CHAIN = 1528,
WARPED_CHARIOT_PLATE = 1529,
VENOMOUS_HYDRA_FANG = 1530,
VACANT_BUGARD_EYE = 1531,
VARIEGATED_URAGNITE_SHELL = 1532,
BATTLE_TROPHY_1ST_ECHELON = 1533,
BATTLE_TROPHY_2ND_ECHELON = 1534,
BATTLE_TROPHY_3RD_ECHELON = 1535,
BATTLE_TROPHY_4TH_ECHELON = 1536,
BATTLE_TROPHY_5TH_ECHELON = 1537,
CRIMSON_TRAVERSER_STONE = 1538,
VOIDSTONE1 = 1539,
VOIDSTONE2 = 1540,
VOIDSTONE3 = 1541,
VOIDSTONE4 = 1542,
VOIDSTONE5 = 1543,
VOIDSTONE6 = 1544,
CRIMSON_GRANULES_OF_TIME = 1545,
AZURE_GRANULES_OF_TIME = 1546,
AMBER_GRANULES_OF_TIME = 1547,
ALABASTER_GRANULES_OF_TIME = 1548,
OBSIDIAN_GRANULES_OF_TIME = 1549,
PRISMATIC_HOURGLASS = 1550,
MOG_KUPON_W_R90 = 1551,
MOG_KUPON_W_M90 = 1552,
MOG_KUPON_W_E90 = 1553,
MOG_KUPON_A_E2 = 1554,
MOG_KUPON_I_SEAL = 1555,
BEGUILING_PETRIFACT = 1556,
SEDUCTIVE_PETRIFACT = 1557,
MADDENING_PETRIFACT = 1558,
VAT_OF_MARTELLO_FUEL = 1559,
FUEL_RESERVOIR = 1560,
EMPTY_FUEL_VAT = 1561,
CRACKED_FUEL_RESERVOIR = 1562,
VIAL_OF_LAMBENT_POTION = 1563,
CLEAR_DEMILUNE_ABYSSITE = 1564,
COLORFUL_DEMILUNE_ABYSSITE = 1565,
SCARLET_DEMILUNE_ABYSSITE = 1566,
AZURE_DEMILUNE_ABYSSITE = 1567,
VIRIDIAN_DEMILUNE_ABYSSITE = 1568,
ANTI_ABYSSEAN_GRENADE_01 = 1569,
ANTI_ABYSSEAN_GRENADE_02 = 1570,
ANTI_ABYSSEAN_GRENADE_03 = 1571,
RAINBOW_PEARL = 1572,
CHIPPED_WIND_CLUSTER = 1573,
PIECE_OF_DRIED_EBONY_LUMBER = 1574,
CAPTAIN_RASHIDS_LINKPEARL = 1575,
CAPTAIN_ARGUSS_LINKPEARL = 1576,
CAPTAIN_HELGAS_LINKPEARL = 1577,
SEAL_OF_THE_RESISTANCE = 1578,
SUNBEAM_FRAGMENT = 1579,
LUGARHOOS_EYEBALL = 1580,
VIAL_OF_PURIFICATION_AGENT_BLK = 1581,
VIAL_OF_PURIFICATION_AGENT_BRZ = 1582,
VIAL_OF_PURIFICATION_AGENT_SLV = 1583,
VIAL_OF_PURIFICATION_AGENT_GLD = 1584,
BLACK_LABELED_VIAL = 1585,
BRONZE_LABELED_VIAL = 1586,
SILVER_LABELED_VIAL = 1587,
GOLD_LABELED_VIAL = 1588,
RAINBOW_COLORED_LINKPEARL = 1589,
GREY_ABYSSITE = 1590,
RIPE_STARFRUIT_ABYSSEA = 1591,
VIAL_OF_FLOWER_WOWER_FERTILIZER = 1592,
TAHRONGI_TREE_NUT = 1593,
BUCKET_OF_COMPOUND_COMPOST = 1594,
CUP_OF_TAHRONGI_CACTUS_WATER = 1595,
HASTILY_SCRAWLED_POSTER = 1596,
BLOODIED_ARROW = 1597,
CRIMSON_BLOODSTONE = 1598,
KUPOFRIEDS_MEDALLION = 1599,
PINCH_OF_MOIST_DANGRUF_SULFUR = 1600,
NAJIS_GAUGER_PLATE = 1601,
NAJIS_LINKPEARL = 1602,
POT_OF_MARTIAL_RELISH = 1603,
THIERRIDES_BEAN_CREATION = 1604,
TINY_MEMORY_FRAGMENT1 = 1605,
LARGE_MEMORY_FRAGMENT1 = 1606,
FEY_STONE = 1607,
LARGE_MEMORY_FRAGMENT2 = 1608,
TORN_RECIPE_PAGE = 1609,
MINERAL_GAUGE_FOR_DUMMIES = 1610,
TUBE_OF_ALCHEMICAL_FERTILIZER = 1611,
LARGE_MEMORY_FRAGMENT3 = 1612,
LARGE_MEMORY_FRAGMENT4 = 1613,
PULSE_MARTELLO_REPAIR_PACK = 1614,
CLONE_WARD_REINFORCEMENT_PACK = 1615,
PACK_OF_OUTPOST_REPAIR_TOOLS = 1616,
PARRADAMO_SUPPLY_PACK1 = 1617,
PARRADAMO_SUPPLY_PACK2 = 1618,
PARRADAMO_SUPPLY_PACK3 = 1619,
PARRADAMO_SUPPLY_PACK4 = 1620,
PARRADAMO_SUPPLY_PACK5 = 1621,
GASPONIA_STAMEN = 1622,
ROCKHOPPER = 1623,
PHIAL_OF_COUNTERAGENT = 1624,
DAMAGED_STEWPOT = 1625,
NARURUS_STEWPOT = 1626,
MAGICKED_HEMPEN_SACK = 1627,
MAGICKED_FLAXEN_SACK = 1628,
PARALYSIS_TRAP_FLUID = 1629,
PARALYSIS_TRAP_FLUID_BOTTLE = 1630,
WEAKENING_TRAP_FLUID = 1631,
WEAKENING_TRAP_FLUID_BOTTLE = 1632,
IRON_EATERS_PEARLSACK = 1633,
MEDICAL_SUPPLY_CHEST = 1635,
WOODWORKERS_BELT = 1636,
ESPIONAGE_PEARLSACK = 1637,
CHIPPED_LINKSHELL = 1638,
GRIMY_LINKSHELL = 1639,
CRACKED_LINKSHELL = 1640,
POCKET_SUPPLY_PACK = 1641,
STANDARD_SUPPLY_PACK = 1642,
HEFTY_SUPPLY_PACK = 1643,
PACK_OF_MOLTEN_SLAG = 1644,
LETTER_OF_RECEIPT = 1645,
SMUDGED_LETTER = 1646,
YELLOW_LINKPEARL = 1647,
JESTERS_HAT = 1648,
JADE_DEMILUNE_ABYSSITE = 1649,
SAPPHIRE_DEMILUNE_ABYSSITE = 1650,
CRIMSON_DEMILUNE_ABYSSITE = 1651,
EMERALD_DEMILUNE_ABYSSITE = 1652,
VERMILLION_DEMILUNE_ABYSSITE = 1653,
INDIGO_DEMILUNE_ABYSSITE = 1654,
ATMA_OF_THE_HEIR = 1655,
ATMA_OF_THE_HERO = 1656,
ATMA_OF_THE_FULL_MOON = 1657,
ATMA_OF_ILLUSIONS = 1658,
ATMA_OF_THE_BANISHER = 1659,
ATMA_OF_THE_SELLSWORD = 1660,
ATMA_OF_A_FUTURE_FABULOUS = 1661,
ATMA_OF_CAMARADERIE = 1662,
ATMA_OF_THE_TRUTHSEEKER = 1663,
ATMA_OF_THE_AZURE_SKY = 1664,
ATMA_OF_ECHOES = 1665,
ATMA_OF_DREAD = 1666,
ATMA_OF_AMBITION = 1667,
ATMA_OF_THE_BEAST_KING = 1668,
ATMA_OF_THE_KIRIN = 1669,
ATMA_OF_HELLS_GUARDIAN = 1670,
ATMA_OF_LUMINOUS_WINGS = 1671,
ATMA_OF_THE_DRAGON_RIDER = 1672,
ATMA_OF_THE_IMPENETRABLE = 1673,
ATMA_OF_ALPHA_AND_OMEGA = 1674,
ATMA_OF_THE_ULTIMATE = 1675,
ATMA_OF_THE_HYBRID_BEAST = 1676,
ATMA_OF_THE_DARK_DEPTHS = 1677,
ATMA_OF_THE_ZENITH = 1678,
ATMA_OF_PERFECT_ATTENDANCE = 1679,
ATMA_OF_THE_RESCUER = 1680,
ATMA_OF_NIGHTMARES = 1681,
ATMA_OF_THE_EINHERJAR = 1682,
ATMA_OF_THE_ILLUMINATOR = 1683,
ATMA_OF_THE_BUSHIN = 1684,
ATMA_OF_THE_ACE_ANGLER = 1685,
ATMA_OF_THE_MASTER_CRAFTER = 1686,
ATMA_OF_INGENUITY = 1687,
ATMA_OF_THE_GRIFFONS_CLAW = 1688,
ATMA_OF_THE_FETCHING_FOOTPAD = 1689,
ATMA_OF_UNDYING_LOYALTY = 1690,
ATMA_OF_THE_ROYAL_LINEAGE = 1691,
ATMA_OF_THE_SHATTERING_STAR = 1692,
ATMA_OF_THE_COBRA_COMMANDER = 1693,
ATMA_OF_ROARING_LAUGHTER = 1694,
ATMA_OF_THE_DARK_BLADE = 1695,
ATMA_OF_THE_DUCAL_GUARD = 1696,
ATMA_OF_HARMONY = 1697,
ATMA_OF_REVELATIONS = 1698,
ATMA_OF_THE_SAVIOR = 1699,
TINY_MEMORY_FRAGMENT2 = 1700,
TINY_MEMORY_FRAGMENT3 = 1701,
EX_01_MARTELLO_CORE = 1702,
EX_02_MARTELLO_CORE = 1703,
EX_03_MARTELLO_CORE = 1704,
EX_04_MARTELLO_CORE = 1705,
EX_05_MARTELLO_CORE = 1706,
EX_06_MARTELLO_CORE = 1707,
EX_07_MARTELLO_CORE = 1708,
MOG_KUPON_W_E85 = 1709,
MOG_KUPON_A_RJOB = 1710,
SILVER_POCKET_WATCH = 1711,
ELEGANT_GEMSTONE = 1712,
WIVRE_EGG1 = 1713,
WIVRE_EGG2 = 1714,
WIVRE_EGG3 = 1715,
TORCH_COAL = 1716,
SUBNIVEAL_MINES = 1717,
PIECE_OF_SODDEN_OAK_LUMBER = 1718,
SODDEN_LINEN_CLOTH = 1719,
DHORME_KHIMAIRAS_MANE = 1720,
IMPERIAL_PEARL = 1721,
RONFAURE_DAWNDROP = 1722,
LA_VAULE_DAWNDROP = 1723,
JUGNER_DAWNDROP = 1724,
BEAUCEDINE_DAWNDROP = 1725,
XARCABARD_DAWNDROP = 1726,
THRONE_ROOM_DAWNDROP = 1727,
WALK_OF_ECHOES_DAWNDROP = 1728,
SANDORIA_DAWNDROP = 1729,
BOTTLED_PUNCH_BUG = 1730,
PRIMAL_GLOW = 1731,
MOONSHADE_EARRING = 1732,
PINCH_OF_PIXIE_DUST = 1733,
WEDDING_INVITATION = 1734,
SNOLL_REFLECTOR = 1735,
FROSTED_SNOLL_REFLECTOR = 1736,
EXPERIMENT_CHEAT_SHEET = 1737,
JOB_GESTURE_WARRIOR = 1738,
JOB_GESTURE_MONK = 1739,
JOB_GESTURE_WHITE_MAGE = 1740,
JOB_GESTURE_BLACK_MAGE = 1741,
JOB_GESTURE_RED_MAGE = 1742,
JOB_GESTURE_THIEF = 1743,
JOB_GESTURE_PALADIN = 1744,
JOB_GESTURE_DARK_KNIGHT = 1745,
JOB_GESTURE_BEASTMASTER = 1746,
JOB_GESTURE_BARD = 1747,
JOB_GESTURE_RANGER = 1748,
JOB_GESTURE_SAMURAI = 1749,
JOB_GESTURE_NINJA = 1750,
JOB_GESTURE_DRAGOON = 1751,
JOB_GESTURE_SUMMONER = 1752,
JOB_GESTURE_BLUE_MAGE = 1753,
JOB_GESTURE_CORSAIR = 1754,
JOB_GESTURE_PUPPETMASTER = 1755,
JOB_GESTURE_DANCER = 1756,
JOB_GESTURE_SCHOLAR = 1757,
FROSTBLOOM1 = 1758,
FROSTBLOOM2 = 1759,
FROSTBLOOM3 = 1760,
MOON_PENDANT = 1761,
WYVERN_EGG = 1762,
WYVERN_EGG_SHELL = 1763,
WAUGYLS_CLAW = 1764,
BOTTLE_OF_MILITARY_INK = 1765,
MILITARY_INK_PACKAGE = 1766,
MAGIAN_LEARNERS_LOG = 1767,
MAGIAN_MOOGLEHOOD_MISSIVE1 = 1768,
MAGIAN_MOOGLEHOOD_MISSIVE2 = 1769,
MAGIAN_MOOGLEHOOD_MISSIVE3 = 1770,
MAGIAN_MOOGLEHOOD_MISSIVE4 = 1771,
MAGIAN_MOOGLEHOOD_MISSIVE5 = 1772,
MAGIAN_MOOGLEHOOD_MISSIVE6 = 1773,
PERIAPT_OF_EMERGENCE1 = 1774,
PERIAPT_OF_EMERGENCE2 = 1775,
PERIAPT_OF_EMERGENCE3 = 1776,
PERIAPT_OF_GUIDANCE = 1777,
PERIAPT_OF_PERCIPIENCE = 1778,
VIVID_PERIAPT_OF_CONCORD = 1779,
DUSKY_PERIAPT_OF_CONCORD = 1780,
VIVID_PERIAPT_OF_CATALYSIS = 1781,
DUSKY_PERIAPT_OF_CATALYSIS = 1782,
VIVID_PERIAPT_OF_EXPLORATION = 1783,
DUSKY_PERIAPT_OF_EXPLORATION = 1784,
VIVID_PERIAPT_OF_FRONTIERS = 1785,
DUSKY_PERIAPT_OF_FRONTIERS = 1786,
NEUTRAL_PERIAPT_OF_FRONTIERS = 1787,
VIVID_PERIAPT_OF_CONCENTRATION = 1788,
DUSKY_PERIAPT_OF_CONCENTRATION = 1789,
VIVID_PERIAPT_OF_GLORY = 1790,
DUSKY_PERIAPT_OF_GLORY = 1791,
VIVID_PERIAPT_OF_FOCUS = 1792,
DUSKY_PERIAPT_OF_FOCUS = 1793,
VIVID_PERIAPT_OF_INTENSITY = 1794,
DUSKY_PERIAPT_OF_INTENSITY = 1795,
VIVID_PERIAPT_OF_READINESS = 1796,
DUSKY_PERIAPT_OF_READINESS = 1797,
VIVID_PERIAPT_OF_ADAPTABILITY = 1798,
DUSKY_PERIAPT_OF_ADAPTABILITY = 1799,
VIVID_PERIAPT_OF_VIGILANCE = 1800,
DUSKY_PERIAPT_OF_VIGILANCE = 1801,
VIVID_PERIAPT_OF_PRUDENCE = 1802,
DUSKY_PERIAPT_OF_PRUDENCE = 1803,
PERIAPT_OF_RECOMPENSE = 1804,
VOID_CLUSTER = 1805,
ATMACITE_OF_DEVOTION = 1806,
ATMACITE_OF_PERSISTENCE = 1807,
ATMACITE_OF_EMINENCE = 1808,
ATMACITE_OF_ONSLAUGHT = 1809,
ATMACITE_OF_INCURSION = 1810,
ATMACITE_OF_ENTICEMENT = 1811,
ATMACITE_OF_DESTRUCTION = 1812,
ATMACITE_OF_TEMPERANCE = 1813,
ATMACITE_OF_DISCIPLINE = 1814,
ATMACITE_OF_COERCION = 1815,
ATMACITE_OF_FINESSE = 1816,
ATMACITE_OF_LATITUDE = 1817,
ATMACITE_OF_MYSTICISM = 1818,
ATMACITE_OF_RAPIDITY = 1819,
ATMACITE_OF_PREPAREDNESS = 1820,
ATMACITE_OF_DELUGES = 1821,
ATMACITE_OF_UNITY = 1822,
ATMACITE_OF_EXHORTATION = 1823,
ATMACITE_OF_SKYBLAZE = 1824,
ATMACITE_OF_THE_SLAYER = 1825,
ATMACITE_OF_THE_ADAMANT = 1826,
ATMACITE_OF_THE_VALIANT = 1827,
ATMACITE_OF_THE_SHREWD = 1828,
ATMACITE_OF_THE_VANGUARD = 1829,
ATMACITE_OF_ASSAILMENT = 1830,
ATMACITE_OF_CATAPHRACT = 1831,
ATMACITE_OF_THE_PARAPET = 1832,
ATMACITE_OF_IMPERIUM = 1833,
ATMACITE_OF_THE_SOLIPSIST = 1834,
ATMACITE_OF_PROVENANCE = 1835,
ATMACITE_OF_DARK_DESIGNS = 1836,
ATMACITE_OF_THE_FORAGER = 1837,
ATMACITE_OF_GLACIERS = 1838,
ATMACITE_OF_AFFINITY = 1839,
ATMACITE_OF_THE_DEPTHS = 1840,
ATMACITE_OF_THE_ASSASSIN = 1841,
ATMACITE_OF_APLOMB = 1842,
ATMACITE_OF_THE_TROPICS = 1843,
ATMACITE_OF_CURSES = 1844,
ATMACITE_OF_PRESERVATION = 1845,
POUCH_OF_WEIGHTED_STONES = 1846,
GOSSAMER_BALLISTA_CHEVRON = 1847,
STEEL_BALLISTA_CHEVRON = 1848,
MOG_KUPON_AWVGR = 1849,
MOG_KUPON_AWVGRII = 1850,
MOG_KUPON_WPULSE = 1851,
MOG_KUPON_ISTONE = 1852,
MOG_KUPON_AWGFIII = 1853,
PERIAPT_OF_SAPIENCE = 1854,
PERIAPT_OF_CLARITY = 1855,
MAP_OF_AL_ZAHBI = 1856,
MAP_OF_NASHMAU = 1857,
MAP_OF_WAJAOM_WOODLANDS = 1858,
MAP_OF_CAEDARVA_MIRE = 1859,
MAP_OF_MOUNT_ZHAYOLM = 1860,
MAP_OF_AYDEEWA_SUBTERRANE = 1861,
MAP_OF_MAMOOK = 1862,
MAP_OF_HALVUNG = 1863,
MAP_OF_ARRAPAGO_REEF = 1864,
MAP_OF_ALZADAAL_RUINS = 1865,
MAP_OF_LEUJAOAM_SANCTUM = 1866,
MAP_OF_THE_TRAINING_GROUNDS = 1867,
MAP_OF_LEBROS_CAVERN = 1868,
MAP_OF_ILRUSI_ATOLL = 1869,
MAP_OF_PERIQIA = 1870,
MAP_OF_NYZUL_ISLE = 1871,
MAP_OF_THE_CHOCOBO_CIRCUIT = 1872,
MAP_OF_THE_COLOSSEUM = 1873,
MAP_OF_BHAFLAU_THICKETS = 1874,
MAP_OF_ZHAYOLM_REMNANTS = 1875,
MAP_OF_ARRAPAGO_REMNANTS = 1876,
MAP_OF_BHAFLAU_REMNANTS = 1877,
MAP_OF_SILVER_SEA_REMNANTS = 1878,
MAP_OF_VUNKERL_INLET = 1879,
MAP_OF_EVERBLOOM_HOLLOW = 1880,
MAP_OF_GRAUBERG = 1881,
MAP_OF_RUHOTZ_SILVERMINES = 1882,
MAP_OF_FORT_KARUGONARUGO = 1883,
MAP_OF_GHOYUS_REVERIE = 1884,
MAP_OF_ABYSSEA_LA_THEINE = 1885,
MAP_OF_ABYSSEA_KONSCHTAT = 1886,
MAP_OF_ABYSSEA_TAHRONGI = 1887,
MAP_OF_ABYSSEA_ATTOHWA = 1888,
MAP_OF_ABYSSEA_MISAREAUX = 1889,
MAP_OF_ABYSSEA_VUNKERL = 1890,
MAP_OF_ABYSSEA_ALTEPA = 1891,
MAP_OF_ABYSSEA_ULEGUERAND = 1892,
MAP_OF_ABYSSEA_GRAUBERG = 1893,
MAP_OF_DYNAMIS_SANDORIA = 1894,
MAP_OF_DYNAMIS_BASTOK = 1895,
MAP_OF_DYNAMIS_WINDURST = 1896,
MAP_OF_DYNAMIS_JEUNO = 1897,
MAP_OF_DYNAMIS_BEAUCEDINE = 1898,
MAP_OF_DYNAMIS_XARCABARD = 1899,
MAP_OF_DYNAMIS_VALKURM = 1900,
MAP_OF_DYNAMIS_BUBURIMU = 1901,
MAP_OF_DYNAMIS_QUFIM = 1902,
MAP_OF_DYNAMIS_TAVNAZIA = 1903,
MAP_OF_ADOULIN = 1904,
MAP_OF_RALA_WATERWAYS = 1905,
MAP_OF_YAHSE_HUNTING_GROUNDS = 1906,
MAP_OF_CEIZAK_BATTLEGROUNDS = 1907,
MAP_OF_FORET_DE_HENNETIEL = 1908,
MAP_OF_YORCIA_WEALD = 1909,
MAP_OF_MORIMAR_BASALT_FIELDS = 1910,
MAP_OF_MARJAMI_RAVINE = 1911,
MAP_OF_KAMIHR_DRIFTS = 1912,
MAP_OF_SIH_GATES = 1913,
MAP_OF_MOH_GATES = 1914,
MAP_OF_CIRDAS_CAVERNS = 1915,
MAP_OF_DHO_GATES = 1916,
MAP_OF_WOH_GATES = 1917,
MAP_OF_OUTER_RAKAZNAR = 1918,
IRON_CHAINMAIL_CLAIM_SLIP = 1920,
SHADE_HARNESS_CLAIM_SLIP = 1921,
BRASS_SCALE_MAIL_CLAIM_SLIP = 1922,
WOOL_ROBE_CLAIM_SLIP = 1923,
EISENPLATTE_ARMOR_CLAIM_SLIP = 1924,
SOIL_GI_CLAIM_SLIP = 1925,
SEERS_TUNIC_CLAIM_SLIP = 1926,
STUDDED_ARMOR_CLAIM_SLIP = 1927,
CENTURION_SCALE_MAIL_CLAIM_SLIP = 1928,
MRCCPT_DOUBLET_CLAIM_SLIP = 1929,
GARISH_TUNIC_CLAIM_SLIP = 1930,
NOCT_DOUBLET_CLAIM_SLIP = 1931,
CUSTOM_ARMOR_MALE_CLAIM_SLIP = 1932,
CUSTOM_ARMOR_FEMALE_CLAIM_SLIP = 1933,
MAGNA_ARMOR_MALE_CLAIM_SLIP = 1934,
MAGNA_ARMOR_FEMALE_CLAIM_SLIP = 1935,
WONDER_ARMOR_CLAIM_SLIP = 1936,
SAVAGE_ARMOR_CLAIM_SLIP = 1937,
ELDER_ARMOR_CLAIM_SLIP = 1938,
LINEN_CLOAK_CLAIM_SLIP = 1939,
PADDED_ARMOR_CLAIM_SLIP = 1940,
SILVER_CHAINMAIL_CLAIM_SLIP = 1941,
GAMBISON_CLAIM_SLIP = 1942,
IRON_SCALE_ARMOR_CLAIM_SLIP = 1943,
CUIR_ARMOR_CLAIM_SLIP = 1944,
VELVET_ROBE_CLAIM_SLIP = 1945,
OPALINE_DRESS_CLAIM_SLIP = 1946,
RYLSQR_CHAINMAIL_CLAIM_SLIP = 1947,
PLATE_ARMOR_CLAIM_SLIP = 1948,
COMBAT_CASTERS_CLOAK_CLAIM_SLIP = 1949,
ALUMINE_HAUBERT_CLAIM_SLIP = 1950,
CARAPACE_HARNESS_CLAIM_SLIP = 1951,
BANDED_MAIL_CLAIM_SLIP = 1952,
HARA_ATE_CLAIM_SLIP = 1953,
RAPTOR_ARMOR_CLAIM_SLIP = 1954,
STEEL_SCALE_CLAIM_SLIP = 1955,
WOOL_GAMBISON_CLAIM_SLIP = 1956,
SHINOBI_GI_CLAIM_SLIP = 1957,
IRNMSK_CUIRASS_CLAIM_SLIP = 1958,
TCTMGC_CLOAK_CLAIM_SLIP = 1959,
WHITE_CLOAK_CLAIM_SLIP = 1960,
AUSTERE_ROBE_CLAIM_SLIP = 1961,
MYTHRIL_PLATE_ARMOR_CLAIM_SLIP = 1962,
CROW_JUPON_CLAIM_SLIP = 1963,
MAGUS_ATTIRE_CLAIM_SLIP = 1964,
CORSAIRS_ATTIRE_CLAIM_SLIP = 1965,
PUPPETRY_ATTIRE_CLAIM_SLIP = 1966,
DANCERS_ATTIRE_CLAIM_SLIP = 1967,
DANCERS_ATTIRE_CLAIM_SLIP = 1968,
SCHOLARS_ATTIRE_CLAIM_SLIP = 1969,
AMIR_ARMOR_CLAIM_SLIP = 1970,
PAHLUWAN_ARMOR_CLAIM_SLIP = 1971,
YIGIT_ARMOR_CLAIM_SLIP = 1972,
FROG_FISHING = 1976,
SERPENT_RUMORS = 1977,
MOOCHING = 1978,
ANGLERS_ALMANAC = 1979,
SPIFFY_SYNTH1 = 1980,
SPIFFY_SYNTH2 = 1981,
ALCHEMISTS_ARGENTUM_TOME = 1982,
ALCHEMISTS_AURUM_TOME = 1983,
WOOD_PURIFICATION = 1984,
WOOD_ENSORCELLMENT = 1985,
LUMBERJACK = 1986,
BOLTMAKER = 1987,
WAY_OF_THE_CARPENTER = 1988,
CARPENTERS_ARGENTUM_TOME = 1989,
CARPENTERS_AURUM_TOME = 1990,
SPIFFY_SYNTH7 = 1991,
METAL_PURIFICATION = 1992,
METAL_ENSORCELLMENT = 1993,
CHAINWORK = 1994,
SHEETING = 1995,
WAY_OF_THE_BLACKSMITH = 1996,
BLACKSMITHS_ARGENTUM_TOME = 1997,
BLACKSMITHS_AURUM_TOME = 1998,
SPIFFY_SYNTH10 = 1999,
GOLD_PURIFICATION = 2000,
GOLD_ENSORCELLMENT = 2001,
CLOCKMAKING = 2002,
WAY_OF_THE_GOLDSMITH = 2003,
GOLDSMITHS_ARGENTUM_TOME = 2004,
GOLDSMITHS_AURUM_TOME = 2005,
SPIFFY_SYNTH13 = 2006,
SPIFFY_SYNTH14 = 2007,
CLOTH_PURIFICATION = 2008,
CLOTH_ENSORCELLMENT = 2009,
SPINNING = 2010,
FLETCHING = 2011,
WAY_OF_THE_WEAVER = 2012,
WEAVERS_ARGENTUM_TOME = 2013,
WEAVERS_AURUM_TOME = 2014,
SPIFFY_SYNTH17 = 2015,
LEATHER_PURIFICATION = 2016,
LEATHER_ENSORCELLMENT = 2017,
TANNING = 2018,
WAY_OF_THE_TANNER = 2019,
TANNERS_ARGENTUM_TOME = 2020,
TANNERS_AURUM_TOME = 2021,
SPIFFY_SYNTH20 = 2022,
SPIFFY_SYNTH21 = 2023,
BONE_PURIFICATION = 2024,
BONE_ENSORCELLMENT = 2025,
FILING = 2026,
WAY_OF_THE_BONEWORKER = 2027,
BONEWORKERS_ARGENTUM_TOME = 2028,
BONEWORKERS_AURUM_TOME = 2029,
SPIFFY_SYNTH24 = 2030,
SPIFFY_SYNTH25 = 2031,
ANIMA_SYNTHESIS = 2032,
ALCHEMIC_PURIFICATION = 2033,
ALCHEMIC_ENSORCELLMENT = 2034,
TRITURATION = 2035,
CONCOCTION = 2036,
IATROCHEMISTRY = 2037,
MIASMAL_COUNTERAGENT_RECIPE = 2038,
WAY_OF_THE_ALCHEMIST = 2039,
RAW_FISH_HANDLING = 2040,
NOODLE_KNEADING = 2041,
PATISSIER = 2042,
STEWPOT_MASTERY = 2043,
WAY_OF_THE_CULINARIAN = 2044,
CULINARIANS_ARGENTUM_TOME = 2045,
CULINARIANS_AURUM_TOME = 2046,
SPIFFY_SYNTH28 = 2047,
VOIDWATCH_ALARUM = 2048,
VOIDWATCHERS_EMBLEM_JEUNO = 2049,
VOIDWATCHERS_EMBLEM_QUFIM = 2050,
LOADSTONE = 2051,
SOUL_GEM = 2052,
SOUL_GEM_CLASP = 2053,
TRICOLOR_VOIDWATCHERS_EMBLEM = 2054,
STARLIGHT_VOIDWATCHERS_EMBLEM = 2055,
RED_PRESENT = 2056,
BLUE_PRESENT = 2057,
GREEN_PRESENT = 2058,
HEART_OF_THE_BUSHIN = 2059,
HYACINTH_STRATUM_ABYSSITE = 2060,
HYACINTH_STRATUM_ABYSSITE_II = 2061,
AMBER_STRATUM_ABYSSITE = 2062,
AMBER_STRATUM_ABYSSITE_II = 2063,
CLAIRVOY_ANT = 2064,
KUPOFRIEDS_CORUNDUM = 2065,
KUPOFRIEDS_CORUNDUM = 2066,
KUPOFRIEDS_CORUNDUM = 2067,
BRONZE_ASTRARIUM = 2068,
SILVER_ASTRARIUM = 2069,
MYTHRIL_ASTRARIUM = 2070,
GOLD_ASTRARIUM = 2071,
PLATINUM_ASTRARIUM = 2072,
DEMONS_IN_THE_RYE_CHRONICLE = 2073,
MONSTROUS_MAYHEM_REPORT = 2074,
CULLING_IS_CARING_POSTER = 2075,
MERRY_MOOGLE_MEMORIAL_GUIDE = 2076,
CONNORS_COMMUNIQUE = 2077,
PERNICIOUS_PRESENTS_BRIEF = 2078,
LITTLE_GOBLINS_ADVENTURE_VOL1 = 2079,
LITTLE_GOBLINS_ADVENTURE_VOL2 = 2080,
LITTLE_GOBLINS_ADVENTURE_VOL3 = 2081,
LITTLE_GOBLINS_ADVENTURE_VOL4 = 2082,
LITTLE_GOBLINS_ADVENTURE_VOL5 = 2083,
LITTLE_GOBLINS_ADVENTURE_VOL6 = 2084,
LITTLE_GOBLINS_ADVENTURE_VOL7 = 2085,
LITTLE_GOBLINS_ADVENTURE_VOL8 = 2086,
VANADIEL_TRIBUNE_VOL00 = 2087,
VANADIEL_TRIBUNE_VOL01 = 2088,
VANADIEL_TRIBUNE_VOL02 = 2089,
VANADIEL_TRIBUNE_VOL03 = 2090,
VANADIEL_TRIBUNE_VOL04 = 2091,
VANADIEL_TRIBUNE_VOL05 = 2092,
VANADIEL_TRIBUNE_VOL06 = 2093,
VANADIEL_TRIBUNE_VOL07 = 2094,
VANADIEL_TRIBUNE_VOL08 = 2095,
VANADIEL_TRIBUNE_VOL09 = 2096,
VANADIEL_TRIBUNE_VOL10 = 2097,
VANADIEL_TRIBUNE_VOL11 = 2098,
VANADIEL_TRIBUNE_VOL12 = 2099,
VANADIEL_TRIBUNE_VOL13 = 2100,
VANADIEL_TRIBUNE_VOL15 = 2102,
VANADIEL_TRIBUNE_VOL16 = 2103,
VANADIEL_TRIBUNE_VOL17 = 2104,
VANADIEL_TRIBUNE_VOL18 = 2105,
VANADIEL_TRIBUNE_VOL19 = 2106,
VANADIEL_TRIBUNE_VOL20 = 2107,
VANADIEL_TRIBUNE_VOL21 = 2108,
VANADIEL_TRIBUNE_VOL22 = 2109,
VANADIEL_TRIBUNE_VOL23 = 2110,
VANADIEL_TRIBUNE_VOL24 = 2111,
VANADIEL_TRIBUNE_VOL25 = 2112,
VANADIEL_TRIBUNE_VOL26 = 2113,
VANADIEL_TRIBUNE_VOL27 = 2114,
VANADIEL_TRIBUNE_II_NO01 = 2115,
VANADIEL_TRIBUNE_II_NO02 = 2116,
VANADIEL_TRIBUNE_II_NO03 = 2117,
VANADIEL_TRIBUNE_II_NO04 = 2118,
VANADIEL_TRIBUNE_II_NO05 = 2119,
VANADIEL_TRIBUNE_II_NO06 = 2120,
VANADIEL_TRIBUNE_II_NO07 = 2121,
VANADIEL_TRIBUNE_II_NO08 = 2122,
VANADIEL_TRIBUNE_II_NO09 = 2123,
VANADIEL_TRIBUNE_II_NO10 = 2124,
VANADIEL_TRIBUNE_II_NO11 = 2125,
VANADIEL_TRIBUNE_II_NO12 = 2126,
VANADIEL_TRIBUNE_II_NO13 = 2127,
VANADIEL_TRIBUNE_II_NO14 = 2128,
VANADIEL_TRIBUNE_II_NO15 = 2129,
VANADIEL_TRIBUNE_II_NO16 = 2130,
HANDCRAFTED_SPATULA = 2131,
TRANSMUTED_CANDLE = 2132,
GOURMET_WHIPPED_CREAM = 2133,
ANCIENT_PAPYRUS_SHRED1 = 2134,
ANCIENT_PAPYRUS_SHRED2 = 2135,
ANCIENT_PAPYRUS_SHRED3 = 2136,
EXORAY_MOLD_CRUMB1 = 2137,
EXORAY_MOLD_CRUMB2 = 2138,
EXORAY_MOLD_CRUMB3 = 2139,
BOMB_COAL_FRAGMENT1 = 2140,
BOMB_COAL_FRAGMENT2 = 2141,
BOMB_COAL_FRAGMENT3 = 2142,
SHINING_FRAGMENT = 2143,
GLOSSY_FRAGMENT = 2144,
GRIMOIRE_PAGE = 2145,
MOBLIN_PHEROMONE_SACK = 2146,
GOLDEN_WING = 2147,
MOSS_COVERED_SHARD = 2148,
ESSENCE_OF_PERFERVIDITY = 2149,
BRANDED_WING = 2150,
MALICIOUS_HORN = 2151,
SHEET_OF_SAN_DORIAN_TUNES = 2152,
SHEET_OF_BASTOKAN_TUNES = 2153,
SHEET_OF_WINDURSTIAN_TUNES = 2154,
GEOMAGNETRON = 2155,
ADOULINIAN_CHARTER_PERMIT = 2156,
PIONEERS_BADGE = 2157,
TEMPORARY_GEOMAGNETRON = 2158,
AGED_MATRIARCH_NAAKUAL_CREST = 2159,
AGED_RIPTIDE_NAAKUAL_CREST = 2160,
AGED_FIREBRAND_NAAKUAL_CREST = 2161,
AGED_LIGNEOUS_NAAKUAL_CREST = 2162,
AGED_BOOMING_NAAKUAL_CREST = 2163,
AGED_FLASHFROST_NAAKUAL_CREST = 2164,
PROTOTYPE_ATTUNER = 2166,
WATERCRAFT = 2167,
RESTRAINMENT_RESILIENCE = 2171,
CUPFUL_OF_DUST_LADEN_SAP = 2179,
MANTID_BAIT = 2180,
VIAL_OF_TOXIC_ZOLDEFF_WATER = 2185,
FISTFUL_OF_PRISTINE_SAND = 2186,
RIME_ICE_FRAGMENT = 2190,
BROKEN_HARPOON = 2192,
EXTRAVAGANT_HARPOON = 2193,
GEOMAGNETIC_COMPASS = 2196,
OCULAR_ORB = 2197,
PILE_OF_NOXIOUS_GRIME = 2198,
PULSATING_SHARD = 2199,
DINNER_INVITATION = 2200,
ROCKBERRY1 = 2201,
ROCKBERRY2 = 2202,
ROCKBERRY3 = 2203,
LOGGING = 2204,
WATERCRAFTING = 2205,
DEMOLISHING = 2206,
TOXIN_RESILIENCE = 2207,
PARESIS_RESILIENCE = 2208,
CALOR_RESILIENCE = 2209,
HEN_FS_BUILDING_MAT_CONTAINER = 2210,
MOR_FS_BUILDING_MAT_CONTAINER = 2211,
HEN_FS_RESOURCE_CONTAINER = 2212,
MOR_FS_RESOURCE_CONTAINER = 2213,
CEI_FB_OP_MATERIALS_CONTAINER = 2214,
HEN_FB_OP_MATERIALS_CONTAINER = 2215,
MOR_FB_OP_MATERIALS_CONTAINER = 2216,
LOST_ARTICLE1 = 2217,
LOST_ARTICLE2 = 2218,
FLAYED_MANTID_CORPSE = 2220,
CHAPULI_HORN = 2221,
HOT_SPRING_REPORT_1 = 2225,
HOT_SPRING_REPORT_2 = 2226,
HOT_SPRING_REPORT_3 = 2227,
HOT_SPRING_REPORT_4 = 2228,
HOT_SPRING_REPORT_5 = 2229,
MAGMA_SURVEY_REPORT = 2232,
REIVE_UNITY = 2234,
CRITICAL_CHOP = 2236,
CHERISHED_AXE = 2237,
CRITICAL_SMASH = 2238,
CHERISHED_PICK = 2239,
CRITICAL_SLICE = 2240,
CHERISHED_SICKLE = 2241,
SAN_DORIA_WARP_RUNE = 2248,
BASTOK_WARP_RUNE = 2249,
WINDURST_WARP_RUNE = 2250,
SELBINA_WARP_RUNE = 2251,
MHAURA_WARP_RUNE = 2252,
KAZHAM_WARP_RUNE = 2253,
RABAO_WARP_RUNE = 2254,
NORG_WARP_RUNE = 2255,
TAVNAZIA_WARP_RUNE = 2256,
WHITEGATE_WARP_RUNE = 2257,
NASHMAU_WARP_RUNE = 2258,
RUSTED_PICKAXE = 2261,
TINY_SEED = 2262,
BOTTLE_OF_FERTILIZER_X = 2263,
WAYPOINT_SCANNER_KIT = 2264,
ROYAL_FIAT_BANNING_COLONIZATION = 2265,
RECORD_OF_THE_17TH_ASSEMBLY = 2266,
COPY_OF_THE_ALLIANCE_AGREEMENT = 2267,
ULBUKAN_NAVIGATION_CHART = 2268,
COPY_OF_ADOULINS_PATRONESS = 2269,
MEMO_FROM_MIDRAS = 2270,
CIDS_CATALYST = 2271,
CHUNK_OF_MILKY_WHITE_MINERALS = 2272,
FAIL_BADGE = 2273,
WESTERN_ADOULIN_PATROL_ROUTE = 2274,
MISDELIVERED_PARCEL = 2275,
EASTERN_ADOULIN_PATROL_ROUTE = 2276,
HOT_SPRINGS_CARE_PACKAGE = 2277,
FISTFUL_OF_HOMELAND_SOIL = 2278,
YAHSE_WILDFLOWER_PETAL = 2279,
HABITUAL_BEHAVIOR_BAROMETER = 2280,
BRIER_PROOF_NET = 2281,
COMPASS_OF_TRANSFERENCE = 2282,
MAGMA_MITIGATION_SET = 2283,
RESURRECTION_RETARDANT_AXE = 2284,
INSULATOR_TABLET = 2285,
ANTI_GLACIATION_GEAR = 2286,
LAND_OF_MILK_AND_HONEY_HIVE = 2288,
FULL_LAND_OF_MILK_AND_HONEY_HIVE = 2289,
LUOPAN = 2290,
RALA_SIMULACRUM = 2291,
YORCIA_SIMULACRUM = 2292,
CIRDAS_SIMULACRUM = 2293,
RAKAZNAR_SIMULACRUM = 2294,
CELADON_YANTRIC_PLANCHETTE = 2296,
ZAFFRE_YANTRIC_PLANCHETTE = 2297,
ALIZARIN_YANTRIC_PLANCHETTE = 2298,
DETACHED_STINGER = 2299,
CRAGGY_FIN = 2300,
FLAME_SCARRED_SKULL = 2301,
MAP_OF_RALA_WATERWAYS_U = 2302,
MAP_OF_YORCIA_WEALD_U = 2303,
MAP_OF_CIRDAS_CAVERNS_U = 2304,
MAP_OF_OUTER_RAKAZNAR_U = 2305,
MAP_OF_ESCHA_ZITAH = 2307,
MAP_OF_ESCHA_RUAUN = 2308,
MAP_OF_REISENJIMA = 2309,
MOG_KUPON_A_DEII = 2334,
MOG_KUPON_A_DE = 2335,
MOG_KUPON_A_SAL = 2336,
MOG_KUPON_A_NYZ = 2337,
MOG_KUPON_I_S5 = 2338,
MOG_KUPON_I_S2 = 2339,
MOG_KUPON_I_ORCHE = 2340,
SHEET_OF_E_ADOULINIAN_TUNES = 2341,
SHEET_OF_W_ADOULINIAN_TUNES = 2342,
HENNEBLOOM_LEAF = 2343,
IMPURE_CELADON_YGGZI = 2344,
SEMI_PURE_CELADON_YGGZI = 2345,
IMPURE_ZAFFRE_YGGZI = 2346,
SEMI_PURE_ZAFFRE_YGGZI = 2347,
IMPURE_ALIZARIN_YGGZI = 2348,
SEMI_PURE_ALIZARIN_YGGZI = 2349,
RING_OF_SUPERNAL_DISJUNCTION = 2350,
EPHEMERAL_ENDEAVOR = 2352,
ENLIGHTENED_ENDEAVOR = 2353,
RUNE_SABER = 2354,
FLASK_OF_FRUISERUM = 2355,
FROST_ENCRUSTED_FLAME_GEM = 2356,
LETTER_FROM_OCTAVIEN = 2357,
STONE_OF_IGNIS = 2358,
STONE_OF_GELUS = 2359,
STONE_OF_FLABRA = 2360,
STONE_OF_TELLUS = 2361,
STONE_OF_SULPOR = 2362,
STONE_OF_UNDA = 2363,
STONE_OF_LUX = 2364,
STONE_OF_TENEBRAE = 2365,
STONE_OF_UNKNOWN_RUNIC_ORIGINS1 = 2366,
STONE_OF_UNKNOWN_RUNIC_ORIGINS2 = 2367,
STONE_OF_UNKNOWN_RUNIC_ORIGINS3 = 2368,
SECRETS_OF_RUNIC_ENHANCEMENT = 2369,
RUNIC_KINEGRAVER = 2370,
VIAL_OF_VIVID_RAINBOW_EXTRACT = 2371,
INSIDIOS_EXTINGUISHED_LANTERN = 2372,
VESSEL_OF_SUMMONING = 2373,
SILVER_LUOPAN = 2374,
LHAISO_NEFTEREHS_BELL = 2375,
MIDRASS_EXPLOSIVE_SAMPLE = 2376,
REPORT_ON_MIDRASS_EXPLOSIVE = 2377,
TRAY_OF_ADOULINIAN_DELICACIES = 2378,
SMALL_BAG_OF_ADOULINIAN_DELICACIES = 2379,
WAYPOINT_RECALIBRATION_KIT = 2380,
TWELVE_ORDERS_DOSSIER = 2381,
RAVINE_WATER_TESTING_KIT = 2382,
FISTFUL_OF_NUMBING_SOIL = 2383,
HUNK_OF_BEDROCK = 2384,
YORCIAS_TEAR = 2385,
BLIGHTBERRY = 2386,
LARGE_STRIP_OF_VELKK_HIDE = 2387,
CLIMBING = 2388,
BOX_OF_ADOULINIAN_TOMATOES = 2389,
KALEIDOSCOPIC_CLAM = 2390,
GLASS_PENDULUM = 2391,
IVORY_WING_TALISMAN = 2393,
BRONZE_MATTOCK_CORDON = 2394,
BRONZE_SHOVEL_CORDON = 2395,
TARUTARU_SAUCE_INVOICE = 2396,
TARUTARU_SAUCE_RECEIPT = 2397,
GPS_CRYSTAL = 2398,
PAIR_OF_VELKK_GLOVES = 2399,
LOST_ARTICLE1 = 2400,
LOST_ARTICLE2 = 2401,
GEOMANCER_CLAIM_TICKET = 2402,
MAR_FB_OP_MATERIALS_CONTAINER = 2403,
YOR_FB_OP_MATERIALS_CONTAINER = 2404,
MAR_FS_BUILDING_MAT_CONTAINER = 2405,
YOR_FS_BUILDING_MAT_CONTAINER = 2406,
PROOF_OF_ORDER_RUNIC_HEADGEAR1 = 2407,
PROOF_OF_ORDER_RUNIC_HANDGEAR2 = 2408,
PROOF_OF_ORDER_RUNIC_FOOTGEAR4 = 2409,
ROSULATIAS_POME = 2410,
CELENNIA_MEMORIAL_LIBRARY_CARD = 2411,
SOWYOURSEED = 2412,
MY_FIRST_FURROW = 2413,
FIELDS_AND_FERTILIZING = 2414,
DESIGNER_FARMING = 2415,
HOMESTEADERS_COMPENDIUM = 2416,
MHMU_TREATISE_ON_AGRONOMY = 2417,
GIVE_MY_REGARDS_TO_REODOAN = 2419,
ADOULINS_TOPIARY_TREASURES = 2420,
GRANDILOQUENT_GROVES = 2421,
ARBOREAL_ABRACADABRA = 2422,
VERDANT_AND_VERDONTS = 2423,
MHMU_TREATISE_ON_FORESTRY = 2424,
MYTHRIL_MARATHON_QUARTERLY = 2426,
TAKE_A_LODE_OFF = 2427,
VARICOSE_MINERAL_VEINS = 2428,
TALES_FROM_THE_TUNNEL = 2429,
THE_GUSGEN_MINES_TRAGEDY = 2430,
MHMU_TREATISE_ON_MINERALOGY = 2431,
A_FAREWELL_TO_FRESHWATER = 2433,
WATER_WATER_EVERYWHERE = 2434,
DREDGINGS_NO_DRUDGERY = 2435,
ALL_THE_WAYS_TO_SKIN_A_CARP = 2436,
ANATOMY_OF_AN_ANGLER = 2437,
MHMU_TREATISE_ON_FISH_I = 2438,
THE_OLD_MEN_OF_THE_SEA = 2440,
BLACK_FISH_OF_THE_FAMILY = 2442,
TWENTY_THOUSAND_YALMS_UNDER_THE_SEA = 2443,
ENCYCLOPEDIA_ICTHYONNICA = 2444,
MHMU_TREATISE_ON_FISH_II = 2445,
MAR_FS_RESOURCE_CONTAINER = 2447,
YOR_FS_RESOURCE_CONTAINER = 2448,
NOTE_DETAILING_SEDITIOUS_PLANS = 2449,
WATERWAY_FACILITY_CRANK = 2450,
VIAL_OF_TRANSLURRY = 2451,
GIL_REPOSITORY = 2452,
CRAB_CALLER = 2453,
PIECE_OF_A_STONE_WALL = 2454,
VIAL_OF_UNTAINTED_HOLY_WATER = 2455,
ETERNAL_FLAME = 2456,
WEATHER_VANE_WINGS = 2457,
AUREATE_BALL_OF_FUR = 2458,
INVENTORS_COALITION_PICKAXE = 2459,
TINTINNABULUM = 2460,
FRAGMENTING = 2461,
PAIR_OF_FUZZY_EARMUFFS = 2462,
KAM_FB_OP_MATERIALS_CONTAINER = 2463,
KAM_FS_BUILDING_MAT_CONTAINER = 2464,
KAM_FS_RESOURCE_CONTAINER = 2465,
MEMORANDOLL = 2466,
SHADOW_LORD_PHANTOM_GEM = 2468,
CELESTIAL_NEXUS_PHANTOM_GEM = 2469,
STELLAR_FULCRUM_PHANTOM_GEM = 2470,
PHANTOM_GEM_OF_APATHY = 2471,
PHANTOM_GEM_OF_ARROGANCE = 2472,
PHANTOM_GEM_OF_ENVY = 2473,
PHANTOM_GEM_OF_COWARDICE = 2474,
PHANTOM_GEM_OF_RAGE = 2475,
P_PERPETRATOR_PHANTOM_GEM = 2476,
COPPER_AMAN_VOUCHER = 2477,
MATRIARCH_NAAKUAL_PARAGON = 2482,
RIPTIDE_NAAKUAL_PARAGON = 2483,
FIREBRAND_NAAKUAL_PARAGON = 2484,
LIGNEOUS_NAAKUAL_PARAGON = 2485,
BOOMING_NAAKUAL_PARAGON = 2486,
FLASHFROST_NAAKUAL_PARAGON = 2487,
MOG_KUPON_I_AF109 = 2489,
MOG_KUPON_W_EWS = 2490,
MOG_KUPON_AW_WK = 2491,
MOG_KUPON_I_S3 = 2492,
MOG_KUPON_A_PK109 = 2493,
MOG_KUPON_I_S1 = 2494,
MOG_KUPON_I_SKILL = 2495,
GREEN_INSTITUTE_CARD = 2496,
WINDURST_TRUST_PERMIT = 2497,
BLUE_INSTITUTE_CARD = 2498,
BASTOK_TRUST_PERMIT = 2499,
RED_INSTITUTE_CARD = 2500,
SAN_DORIA_TRUST_PERMIT = 2501,
MOG_KUPON_I_RME = 2502,
PULVERIZING = 2503,
LERENES_PATEN = 2504,
AMCHUCHUS_MISSIVE = 2505,
TEMPLE_KNIGHT_KEY = 2506,
UNBLEMISHED_PIONEERS_BADGE = 2507,
SILVERY_PLATE = 2508,
SOUL_SIPHON = 2509,
TAPESTRY_OF_BAGUA_POETRY = 2511,
FUTHARKIC_CONCEPTS_IN_FLUX = 2512,
CRYSTALLIZED_LIFESTREAM_ESSENCE = 2513,
STRAND_OF_RAKAZNAR_FILAMENT = 2514,
ORDER_SLIP_LIFESTREAM_HEADGEAR = 2515,
ORDER_SLIP_LIFESTREAM_BODYGEAR = 2516,
ORDER_SLIP_LIFESTREAM_HANDGEAR = 2517,
ORDER_SLIP_LIFESTREAM_LEGGEAR = 2518,
ORDER_SLIP_LIFESTREAM_FOOTGEAR = 2519,
ORDER_SLIP_LOGOMORPH_HEADGEAR = 2520,
ORDER_SLIP_LOGOMORPH_BODYGEAR = 2521,
ORDER_SLIP_LOGOMORPH_HANDGEAR = 2522,
ORDER_SLIP_LOGOMORPH_LEGGEAR = 2523,
ORDER_SLIP_LOGOMORPH_FOOTGEAR = 2524,
PRISTINE_HAIR_RIBBON = 2525,
VIAL_OF_TRANSMELANGE = 2526,
LOST_ARTICLE = 2527,
BREATH_OF_DAWN = 2528,
PHLOX_YANTRIC_PLANCHETTE = 2529,
RUSSET_YANTRIC_PLANCHETTE = 2530,
ASTER_YANTRIC_PLANCHETTE = 2531,
SPARKING_TAIL_FEATHER = 2532,
PIECE_OF_INVIOLABLE_BARK = 2533,
FROSTED_INCISOR = 2534,
IMPURE_PHLOX_YGGZI = 2535,
SEMI_PURE_PHLOX_YGGZI = 2536,
IMPURE_RUSSET_YGGZI = 2537,
SEMI_PURE_RUSSET_YGGZI = 2538,
IMPURE_ASTER_YGGZI = 2539,
SEMI_PURE_ASTER_YGGZI = 2540,
BREATH_OF_DAWN1 = 2541,
BREATH_OF_DAWN2 = 2542,
BREATH_OF_DAWN3 = 2543,
JOB_BREAKER = 2544,
SAVAGES_PHANTOM_GEM = 2545,
WARRIORS_PATH_PHANTOM_GEM = 2546,
PEPPEALEPPES_SUPERLATIVE_TONIC = 2547,
SAJJAKAS_PROTECTIVE_WARD = 2548,
SUNKISSED_SCALE = 2549,
MOONTOUCHED_SCALE = 2550,
STARBLESSED_SCALE = 2551,
TUFT_OF_GOLDEN_FUR = 2552,
IVORY_WING_TALISMAN = 2553,
SILVER_MATTOCK_CORDON = 2554,
SILVER_SHOVEL_CORDON = 2555,
PUPPET_IN_PERIL_PHANTOM_GEM = 2556,
LEGACY_PHANTOM_GEM = 2557,
WORLD_TREE_SAPLING = 2558,
MOG_KUPON_I = 2559,
MOG_KUPON_WJOB = 2560,
MOG_KUPON_IMAT = 2561,
MOG_KUPON_IWDEIII = 2562,
MOG_KUPON_IAWMIS = 2563,
SHEET_OF_ZILART_TUNES = 2564,
RUSTED_HANDBELL = 2565,
EMBLAZONED_HANDBELL = 2566,
RIPPLE_PROMINENCE_CONCRETION = 2567,
INFERNO_CONCRETION = 2568,
CYCLONE_CONCRETION = 2569,
NUMBING_BLOSSOM_SEED = 2570,
BROKEN_RAPIER_HILT = 2571,
VIAL_OF_CRIMSON_CATALYST = 2572,
QUIESCENCE = 2573,
SUPERLATIVE_RUNIC_RING_OF_DELUGE = 2574,
SUPERLATIVE_RUNIC_RING_OF_LUSTER = 2575,
SUPERLATIVE_RUNIC_RING_OF_VISION = 2576,
NICKED_DAGGER = 2577,
MAGICKED_ASTROLABE = 2578,
BRACELET_OF_VERVE = 2579,
COPY_OF_WRATH_OF_THE_LAND = 2580,
COPY_OF_HALLOWED_WOOD = 2581,
HALLOWED_WOOD_REPLICA = 2582,
COPY_OF_SHROUDED_IN_ENIGMA = 2583,
REPORT_OF_A_SORCEROUS_NATION = 2584,
COPY_OF_THE_VERDANCY = 2585,
GIANT_SHEEP_EXPORT_RECORD = 2586,
DICTUM_ON_COLONIZATION = 2587,
ADOULINIAN_AGRICULTURAL_TREATISE = 2588,
MYSTIFYING_METAL_ROD = 2589,
RUSTY_KATANA = 2590,
TRADITIONAL_ADOULINIAN_KATANA = 2591,
PIECE_OF_A_SCT_COALITION_REPORT = 2592,
CRYPTIC_MEMORANDUM = 2593,
MEMO_FOUND_IN_RALA_WATERWAYS = 2594,
HEAD_WIND_PHANTOM_GEM = 2595,
BUTTERFLYSHAPED_KEY = 2596,
STURDY_HIDE_POUCH = 2597,
SUFFERING_SACCHARIFEROUS = 2598,
SEPULCHER_ENSIGN = 2599,
CONSUMMATE_SIMULACRUM = 2600,
BROKEN_FUSE = 2601,
RALA_EUDAEMON = 2602,
YORCIA_EUDAEMON = 2603,
CIRDAS_EUDAEMON = 2604,
VELKK_FETISH = 2606,
YMMRULVIDS_NECKLACE = 2607,
IGNORMNTS_BRACELET = 2608,
DURSVIKES_EARRING = 2609,
TRYLWUJS_BELT = 2610,
PAIR_OF_LIIJVOKS_GLOVES = 2611,
GRAMKDROOGS_CIRCLET = 2612,
ELDER_WOODEN_BOX = 2613,
IMPRINT_DEVICE_S = 2614,
RECORD_OF_THE_GENERALS_FORAY = 2615,
RECORD_OF_A_CAVERNOUS_FORAY = 2616,
RECORD_OF_THE_KNIGHT_IN_BLACK = 2617,
RECORD_OF_A_THOUSAND_LIGHTS = 2618,
AVATAR_PHANTOM_GEM = 2619,
HEROES_AND_LEGENDS_OF_ADOULIN = 2620,
HASTILY_SCRIBBLED_NOTE = 2621,
SKY_BLUE_POME = 2622,
SUN_YELLOW_POME = 2623,
ASHRAKKS_BLOOD_SIGIL = 2624,
DHOKMAKS_BLOOD_SIGIL = 2625,
ASH_RUNIC_BOARD = 2626,
TEODORS_BLOOD_SIGIL = 2627,
AWAKENED_CRYSTALLIZED_PSYCHE = 2628,
ARCIELAS_SPARE_BONNET = 2629,
ARCIELAS_SKIRT = 2630,
CONCORDOLL = 2631,
CRYSTALLIZED_PSYCHE = 2632,
SAKURA_AND_THE_MAGIC_SPOON = 2633,
BLANK_ASH_RUNIC_BOARD = 2640,
PROTOTYPE_SIGIL_PEARL = 2641,
LAMB_MEMENTO = 2642,
SHEEP_MEMENTO = 2643,
KARAKUL_MEMENTO = 2644,
RAM_MEMENTO = 2645,
SAPLING_MEMENTO = 2646,
GREEN_FOLIAGE_TREANT_MEMENTO = 2647,
RED_FOLIAGE_TREANT_MEMENTO = 2648,
BABY_RABBIT_MEMENTO = 2649,
RABBIT_MEMENTO = 2650,
WHITE_RABBIT_MEMENTO = 2651,
BABY_LIZARD_MEMENTO = 2652,
LIZARD_MEMENTO = 2653,
ALABASTER_LIZARD_MEMENTO = 2654,
BABY_COCKATRICE_MEMENTO = 2655,
COCKATRICE_MEMENTO = 2656,
ZIZ_MEMENTO = 2657,
BABY_RAPTOR_MEMENTO = 2658,
RAPTOR_MEMENTO = 2659,
RED_RAPTOR_MEMENTO = 2660,
BABY_EFT_MEMENTO = 2661,
EFT_MEMENTO = 2662,
TARICHUK_MEMENTO = 2663,
DHALMEL_CALF_MEMENTO = 2664,
DHALMEL_MEMENTO = 2665,
GREAT_DHALMEL_MEMENTO = 2666,
SEA_MONK_LARVA_MEMENTO = 2667,
SEA_MONK_MEMENTO = 2668,
BLUE_SEA_MONK_MEMENTO = 2669,
URAGNITE_YOUNGLING_MEMENTO = 2670,
URAGNITE_MEMENTO = 2671,
LIMASCABRA_MEMENTO = 2672,
IMMATURE_CRAB_MEMENTO = 2673,
CRAB_MEMENTO = 2674,
PORTER_CRAB_MEMENTO = 2675,
COLIBRI_CHICK_MEMENTO = 2676,
COLIBRI_MEMENTO = 2677,
TOUCALIBRI_MEMENTO = 2678,
COEURL_CUB_MEMENTO = 2679,
COEURL_MEMENTO = 2680,
LYNX_MEMENTO = 2681,
BUFFALO_CALF_MEMENTO = 2682,
BUFFALO_MEMENTO = 2683,
MINI_SLIME_MEMENTO = 2684,
SLIME_MEMENTO = 2685,
CLOT_MEMENTO = 2686,
HECTEYES_MEMENTO = 2687,
TINY_BUGARD_MEMENTO = 2688,
BUGARD_MEMENTO = 2689,
ABYSSOBUGARD_MEMENTO = 2690,
BABY_ADAMANTOISE_MEMENTO = 2691,
ADAMANTOISE_MEMENTO = 2692,
GREAT_ADAMANTOISE_MEMENTO = 2693,
WHITE_ADAMANTOISE_MEMENTO = 2694,
FERROMANTOISE_MEMENTO = 2695,
GREAT_FERROMANTOISE_MEMENTO = 2696,
CLUSTER_MEMENTO = 2697,
BOMB_MEMENTO = 2698,
DJINN_MEMENTO = 2699,
SNOLL_MEMENTO = 2700,
BEHEMOTH_CUB_MEMENTO = 2701,
BEHEMOTH_MEMENTO = 2702,
KING_BEHEMOTH_MEMENTO = 2703,
ELASMOTH_MEMENTO = 2704,
SKORMOTH_MEMENTO = 2705,
DRAGON_HATCHLING_MEMENTO = 2706,
WYVERN_MEMENTO = 2707,
BLUE_WYVERN_MEMENTO = 2708,
GREEN_WYVERN_MEMENTO = 2709,
ABYSSAL_WYRM_MEMENTO = 2710,
LUNAR_WYRM_MEMENTO = 2711,
BLAZING_WYRM_MEMENTO = 2712,
PEQUETENDER_MEMENTO = 2713,
SABOTENDER_MEMENTO = 2714,
JUMBOTENDER_MEMENTO = 2715,
CHEER_LAMB = 2716,
CHEER_SHEEP = 2717,
CHEER_KARAKUL = 2718,
CHEER_RAM = 2719,
CHEER_SAPLING = 2720,
CHEER_G_FOL_TREANT = 2721,
CHEER_R_FOL_TREANT = 2722,
CHEER_BABY_RABBIT = 2723,
CHEER_RABBIT = 2724,
CHEER_WHITE_RABBIT = 2725,
CHEER_BABY_LIZARD = 2726,
CHEER_LIZARD = 2727,
CHEER_ALABASTER_LIZARD = 2728,
CHEER_BABY_COCKATRICE = 2729,
CHEER_COCKATRICE = 2730,
CHEER_ZIZ = 2731,
CHEER_BABY_RAPTOR = 2732,
CHEER_RAPTOR = 2733,
CHEER_RED_RAPTOR = 2734,
CHEER_BABY_EFT = 2735,
CHEER_EFT = 2736,
CHEER_TARICHUK = 2737,
CHEER_DHALMEL_CALF = 2738,
CHEER_DHALMEL = 2739,
CHEER_GREAT_DHALMEL = 2740,
CHEER_SEA_MONK_LARVA = 2741,
CHEER_SEA_MONK = 2742,
CHEER_BLUE_SEA_MONK = 2743,
CHEER_URAGNITE_YOUNGLING = 2744,
CHEER_URAGNITE = 2745,
CHEER_LIMASCABRA = 2746,
CHEER_IMMATURE_CRAB = 2747,
CHEER_CRAB = 2748,
CHEER_PORTER_CRAB = 2749,
CHEER_BABY_COLIBRI = 2750,
CHEER_COLIBRI = 2751,
CHEER_TOUCALIBRI = 2752,
CHEER_COEURL_CUB = 2753,
CHEER_COEURL = 2754,
CHEER_LYNX = 2755,
CHEER_BUFFALO_CALF = 2756,
CHEER_BUFFALO = 2757,
CHEER_MINI_SLIME = 2758,
CHEER_SLIME = 2759,
CHEER_CLOT = 2760,
CHEER_HECTEYES = 2761,
CHEER_TINY_BUGARD = 2762,
CHEER_BUGARD = 2763,
CHEER_ABYSSOBUGARD = 2764,
CHEER_BABY_ADAMANTOISE = 2765,
CHEER_ADAMANTOISE = 2766,
CHEER_GREAT_ADAMANTOISE = 2767,
CHEER_WHITE_ADAMANTOISE = 2768,
CHEER_FERROMANTOISE = 2769,
CHEER_GREAT_FERROMANTOISE = 2770,
CHEER_CLUSTER = 2771,
CHEER_BOMB = 2772,
CHEER_DJINN = 2773,
CHEER_SNOLL = 2774,
CHEER_BEHEMOTH_CUB = 2775,
CHEER_BEHEMOTH = 2776,
CHEER_KING_BEHEMOTH = 2777,
CHEER_ELASMOTH = 2778,
CHEER_SKORMOTH = 2779,
CHEER_DRAGON_HATCHLING = 2780,
CHEER_WYVERN = 2781,
CHEER_BLUE_WYVERN = 2782,
CHEER_GREEN_WYVERN = 2783,
CHEER_ABYSSAL_WYRM = 2784,
CHEER_LUNAR_WYRM = 2785,
CHEER_BLAZING_WYRM = 2786,
CHEER_PEQUETENDER = 2787,
CHEER_SABOTENDER = 2788,
CHEER_JUMBOTENDER = 2789,
SHEET_OF_CONFLICT_TUNES = 2790,
SHEET_OF_PROMATHIA_TUNES = 2791,
SHEET_OF_ADOULINIAN_TUNES = 2792,
SAKURA_AND_THE_FOUNTAIN = 2793,
TREATISE_ON_AZIMUTH_CLOTHCRAFT = 2794,
HOLLA_CRYSTAL_OF_GALES = 2795,
DEM_CRYSTAL_OF_DUNES = 2796,
MEA_CRYSTAL_OF_FLAMES = 2797,
PALE_AZURE_CLOTH = 2798,
ORDER_SLIP_AZIMUTH_HOOD = 2799,
ORDER_SLIP_AZIMUTH_COAT = 2800,
ORDER_SLIP_AZIMUTH_GLOVES = 2801,
ORDER_SLIP_AZIMUTH_TIGHTS = 2802,
ORDER_SLIP_AZIMUTH_GAITERS = 2803,
REFINED_RAKAZNAR_FIBER = 2804,
ORDER_SLIP_ERILAZ_GALEA = 2805,
ORDER_SLIP_ERILAZ_SURCOAT = 2806,
ORDER_SLIP_ERILAZ_GAUNTLETS = 2807,
ORDER_SLIP_ERILAZ_LEG_GUARDS = 2808,
ORDER_SLIP_ERILAZ_GREAVES = 2809,
PURPLE_PURGATION_CLOTH = 2810,
MARGRETS_WRIT_OF_SUMMONS = 2811,
PORTRAIT_OF_MELVIEN = 2812,
MELVIENS_TURN = 2813,
MELVIENS_DEATH = 2814,
MARGRETS_MEMO = 2815,
MARGRETS_IMPOSTERS_CIPHER = 2816,
MARGRETS_IMPOSTERS_CIPHER_REDUX = 2817,
FABRICATED_PEARL_OF_IMPURITY = 2818,
FABRICATED_PEARL_OF_MIASMA = 2819,
FABRICATED_PEARL_OF_BITING_WINDS = 2820,
FABRICATED_PEARL_OF_ASHEN_WINGS = 2821,
FABRICATED_PEARL_OF_THE_FALSE_KING = 2822,
PROTOTYPE_PEARL_OF_ASHEN_WINGS = 2823,
PROTOTYPE_PEARL_OF_THE_FALSE_KING = 2824,
GILGAMESHS_INTRODUCTORY_LETTER = 2825,
IMPERIAL_CHAIR = 2826,
DECORATIVE_CHAIR = 2827,
ORNATE_STOOL = 2828,
REFINED_CHAIR = 2829,
PORTABLE_CONTAINER = 2830,
CHOCOBO_CHAIR = 2831,
EPHRAMADIAN_THRONE = 2832,
SHADOW_THRONE = 2833,
LEAF_BENCH = 2834,
ASTRAL_CUBE = 2835,
REISENJIMA_SANCTORIUM_ORB = 2837,
SAKURA_AND_THE_MAGICKED_NET = 2838,
REAPER = 2839,
FORGOTTEN_MEMORY = 2840,
WEATHERED_HAVERTON_HAT = 2842,
LIGHTSWORM = 2843,
SAKURAS_EXCELLENT_ADVENTURE = 2844,
SAKURA_AND_THE_CACTUS_CORPS = 2845,
SAKURA_AND_THE_HOLY_GRAIL = 2846,
SIRENS_PLUME = 2847,
MOGLIFICATION_RESIST_POISON = 2849,
MOGLIFICATION_RESIST_PARALYSIS = 2850,
MOGLIFICATION_RESIST_SILENCE = 2852,
MOGLIFICATION_RESIST_PETRIFICATION = 2853,
MOGLIFICATION_RESIST_VIRUS = 2854,
MOGLIFICATION_RESIST_CURSE = 2855,
IRIDAL_CORE_OF_THE_RUINS = 2880,
IRIDAL_CORE_OF_THE_TOMB = 2881,
IRIDAL_CORE_OF_THE_PASS = 2882,
ARCUS_FIBER = 2883,
RHAPSODY_IN_WHITE = 2884,
RHAPSODY_IN_UMBER = 2885,
RHAPSODY_IN_AZURE = 2886,
RHAPSODY_IN_CRIMSON = 2887,
RHAPSODY_IN_EMERALD = 2888,
RHAPSODY_IN_MAUVE = 2889,
RHAPSODY_IN_FUCHSIA = 2890,
RHAPSODY_IN_PUCE = 2891,
RHAPSODY_IN_OCHRE = 2892,
SCINTILLATING_RHAPSODY = 2893,
TRIBULENS = 2894,
WEPWAWETS_TOOTH = 2895,
LYDIAS_VINE = 2896,
AGLAOPHOTIS_BUD = 2897,
TANGATAS_WING = 2898,
VIDALAS_CLAW = 2899,
GESTALTS_RETINA = 2900,
ANGRBODAS_NECKLACE = 2901,
CUNNASTS_TALON = 2902,
REVETAURS_HORN = 2903,
FERRODONS_SCALE = 2904,
GULLTOPS_SHELL = 2905,
VYALAS_PREY = 2906,
BLAZEWINGS_PINCER = 2907,
COVENS_DUST = 2908,
PAZUZUS_BLADE_HILT = 2909,
WRATHARES_CARROT = 2910,
IONOSS_WEBBING = 2911,
SANDYS_LASHER = 2912,
NOSOIS_FEATHER = 2913,
BRITTLISS_RING = 2914,
KAMOHOALIIS_FIN = 2915,
UMDHLEBIS_FLOWER = 2916,
FLEETSTALKERS_CLAW = 2917,
SHOCKMAWS_BLUBBER = 2918,
URMAHLULLUS_ARMOR = 2919,
ESCHAN_URN = 2920,
ESCHAN_CELLAR = 2921,
ESCHAN_NEF = 2922,
MOONLIT_PATH_PHANTOM_GEM = 2923,
WAKING_THE_BEAST_PHANTOM_GEM = 2924,
WAKING_DREAMS_PHANTOM_GEM = 2925,
CARD_JAILER_TEODOR = 2926,
BIAS_GLOVE = 2927,
RUEAS_STONE = 2928,
MAS_LANCE = 2929,
KHONS_SCEPTER = 2930,
METS_RING = 2931,
KHUNS_CROWN = 2932,
WASSERSPEIERS_HORN = 2933,
EMPUTAS_WING = 2934,
PEIRITHOOSS_HOOF = 2935,
ASIDAS_GEL = 2936,
TENODERAS_SCYTHE = 2937,
SAVA_SAVANOVICS_CAPE = 2938,
PALILAS_TALON = 2939,
HANBIS_NAIL = 2940,
YILANS_SCALE = 2941,
AMYMONES_TOOTH = 2942,
NAPHULAS_BRACELET = 2943,
KAMMAVACAS_BINDING = 2944,
PAKECETS_BLUBBER = 2945,
DUKE_VEPARS_SIGNET = 2946,
VIRAVAS_STALK = 2947,
BYAKKOS_PRIDE = 2948,
GENBUS_HONOR = 2949,
SEIRYUS_NOBILITY = 2950,
SUZAKUS_BENEFACTION = 2951,
KIRINS_FERVOR = 2952,
ARK_ANGEL_HMS_COAT = 2953,
ARK_ANGEL_TTS_NECKLACE = 2954,
ARK_ANGEL_MRS_BUCKLE = 2955,
ARK_ANGEL_EVS_SASH = 2956,
ARK_ANGEL_GKS_BANGLE = 2957,
MOST_CURIOUS_CURIO = 2958,
MOST_CONFOUNDING_CURIO = 2959,
MACABRE_SIMULACRUM = 2960,
MOTIONLESS_PLUME = 2961,
GUFFAWSHROOM = 2962,
JOB_GESTURE_GEOMANCER = 2963,
JOB_GESTURE_RUNE_FENCER = 2964,
GOLDEN_SHOVEL_CORDON = 2965,
FABRICATED_WARD_OF_IMPURITY = 2966,
FABRICATED_WARD_OF_MIASMA = 2967,
FABRICATED_WARD_OF_BITING_WINDS = 2968,
FABRICATED_WARD_OF_ASHEN_WINGS = 2969,
FABRICATED_WARD_OF_THE_FALSE_KING = 2970,
SONG_OF_HOPE = 2971,
FOUNDER_KINGS_ORB = 2972,
CAIT_SITHS_WHISKER = 2973,
EXTRADIMENSIONAL_SCAR = 2974,
BREATH_OF_THE_AVATARS = 2975,
PRIMARY_NAZAR = 2976,
SECONDARY_NAZAR = 2977,
TERTIARY_NAZAR = 2978,
QUATERNARY_NAZAR = 2979,
QUINARY_NAZAR = 2980,
SENARY_NAZAR = 2981,
SEPTENARY_NAZAR = 2982,
OCTONARY_NAZAR = 2983,
NONARY_NAZAR = 2984,
DENARY_NAZAR = 2985,
PRIMAL_NAZAR = 2986,
FEARED_ONE_PHANTOM_GEM = 2987,
DAWN_PHANTOM_GEM = 2988,
DIMENSIONAL_COMPASS = 2989,
CHACHAROONS_SACK_OF_SUPPLIES = 2990,
CROM_DUBHS_HELM = 2991,
GOLDEN_KISTS_KEY = 2992,
MAUVEWRISTED_GOMBERRYS_KNIFE = 2993,
DAZZLING_DOLORESS_VINE = 2994,
TAELMOTHS_STAFF = 2995,
BELPHEGORS_CROWN = 2996,
KABANDHAS_WING = 2997,
SELKITS_PINCER = 2998,
SANG_BUAYAS_TUSK = 2999,
SABOTENDER_ROYALS_NEEDLE = 3000,
ZDUHACS_TALON = 3001,
ORYXS_PLUMAGE = 3002,
STROPHADIAS_PEARL = 3003,
GAJASIMHAS_MANE = 3004,
IRONSIDES_MAUL = 3005,
SARSAOKS_HOARD = 3006,
OLD_SHUCKS_TUFT = 3007,
BASHMUS_TRINKET = 3008,
MAJUS_CLAW = 3009,
YAKSHIS_SCROLL = 3010,
NEAKS_TREASURE = 3011,
TELESS_HYMN = 3012,
ZERDES_CUP = 3013,
VINIPATAS_BLADE = 3014,
SCHAHS_GAMBIT = 3015,
ALBUMENS_FLOWER = 3016,
ONYCHOPHORAS_SOIL = 3017,
ERINYSS_BEAK = 3018,
MOG_KUPON_AWGFII = 3019,
MOG_KUPON_AWGF = 3020,
MOG_KUPON_AWUWIII = 3021,
MOG_KUPON_AWUWII = 3022,
MOG_KUPON_AWUW = 3023,
MOG_KUPON_AAB = 3024,
MOG_KUPON_AWCOS = 3025,
PHOENIXS_BLESSING = 3026,
PACKET_OF_MIDRASS_EXPLOSIVES = 3027,
TARNISHED_RING = 3028,
RUSTY_LOCKET = 3029,
INVITATION_TO_A_FEAST_MOST_DIRE = 3030,
RADIALENS = 3031,
MOLLIFIER = 3032,
MOG_KUPON_AWKUPO = 3033,
DRAINED_ORB = 3034,
MALFORMED_KNUCKLES = 3035,
MALFORMED_DAGGER = 3036,
MALFORMED_SWORD = 3037,
MALFORMED_GREAT_SWORD = 3038,
MALFORMED_AXE = 3039,
MALFORMED_GREAT_AXE = 3040,
MALFORMED_POLEARM = 3041,
MALFORMED_SCYTHE = 3042,
MALFORMED_KATANA = 3043,
MALFORMED_GREAT_KATANA = 3044,
MALFORMED_CLUB = 3045,
MALFORMED_STAFF = 3046,
MALFORMED_BOW = 3047,
MALFORMED_GUN = 3048,
MALFORMED_SHIELD = 3049,
MALFORMED_FLUTE = 3050,
MOG_PATIO_DESIGN_DOCUMENT = 3051,
AMBUSCADE_PRIMER_VOLUME_ONE = 3052,
AMBUSCADE_PRIMER_VOLUME_TWO = 3053,
TRAINERS_WHISTLE = 3055,
MOG_KUPON_WEMI = 3056,
MOG_KUPON_AEMI = 3057,
MOG_KUPON_WSRW = 3058,
MOG_KUPON_WSCC = 3059,
MOG_KUPON_ASYW = 3060,
MOG_KUPON_WASRW = 3061,
MOG_KUPON_WASCC = 3062,
MOG_KUPON_AASYW = 3063,
MOG_KUPON_WR119 = 3064,
MOG_KUPON_WM119 = 3065,
MOG_KUPON_WE119 = 3066,
MOG_KUPON_WA119 = 3067,
MOG_KUPON_AWGEIV = 3068,
SHIMMERING_INVITATION = 3069,
GRUNT_HEARD_ROUND_THE_WORLD = 3070,
CHOCOBO_COMPANION = 3072,
RAPTOR_COMPANION = 3073,
TIGER_COMPANION = 3074,
CRAB_COMPANION = 3075,
RED_CRAB_COMPANION = 3076,
BOMB_COMPANION = 3077,
RAM_COMPANION = 3078,
MORBOL_COMPANION = 3079,
CRAWLER_COMPANION = 3080,
FENRIR_WHISTLE = 3081,
BEETLE_COMPANION = 3082,
MOOGLE_COMPANION = 3083,
MAGIC_POT_COMPANION = 3084,
TULFAIRE_COMPANION = 3085,
WARMACHINE_COMPANION = 3086,
XZOMIT_COMPANION = 3087,
HIPPOGRYPH_COMPANION = 3088,
SPECTRAL_CHAIR_COMPANION = 3089,
SPHEROID_COMPANION = 3090,
OMEGA_COMPANION = 3091,
SHEET_OF_SHADOW_LORD_TUNES = 3136,
MYSTICAL_CANTEEN = 3137,
YGNASS_INSIGNIA = 3138,
MOG_KUPON_AOMII = 3139,
MOG_KUPON_IAF119 = 3140,
MOG_KUPON_AWOM = 3141,
FUS_BEAD = 3142,
KEIS_BEAD = 3143,
KYOUS_BEAD = 3144,
GINS_BEAD = 3145,
KINS_BEAD = 3146,
YGNASS_LEAF = 3147,
ANCIENT_MELODY_O = 3148,
ANCIENT_MELODY_M = 3149,
ANCIENT_MELODY_E = 3150,
AFTERPARTY_PASS = 3153,
REASSEMBLING_TECHNIQUE = 3154,
EMPTY_HOURGLASS = 3156,
}
dsp.ki = dsp.keyItem
| gpl-3.0 |
thebracket/bgame | world_defs/items_food.lua | 1 | 16605 | -- This file defines items that one can eat or drink.
-----------------------------------------------------------------------------------------------------------------
items["tiny_marshmallow"] = {
name = "Tiny Marshmallow",
description = "A tiny lump of congealed sugar",
itemtype = {"food-prepared"},
glyph = glyphs['squared'],
glyph_ascii = glyphs['squared'],
foreground = colors['magenta'],
background = colors['black'],
stockpile = stockpiles['food'].id
};
items["tea_replicated"] = {
name = "Tea, Earl-Grey Lukewarm",
description = "A replicated substance that tastes somewhat like tea",
itemtype = {"drink"},
glyph = glyphs['squared'],
glyph_ascii = glyphs['squared'],
foreground = colors['wood_brown'],
background = colors['black'],
stockpile = stockpiles['food'].id
};
items["sandwich_replicated"] = {
name = "Stale-tasting sandwich",
description = "A replicated sandwich that sort-of tastes like chicken",
itemtype = {"food-prepared"},
glyph = glyphs['squared'],
glyph_ascii = glyphs['squared'],
foreground = colors['wood_brown'],
background = colors['black'],
stockpile = stockpiles['food'].id
};
-- Raw meat, turns into a food-stuff
items["meat"] = {
name = "Meat",
description = "Raw Meat",
itemtype = {"food"},
glyph = glyphs['double_pillar'],
glyph_ascii = glyphs['double_pillar'],
foreground = colors['red'],
background = colors['black'],
stockpile = stockpiles['food'].id,
vox = voxelId("meat")
};
-- Cooked Food
items["roast_simple"] = {
name="Roasted",
description = "Roasted food",
itemtype = { "food-prepared" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['brown'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("foodplate")
};
items["wine"] = {
name="Alcoholic Beverage",
description = "Fermented food",
itemtype = { "drink" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("liquid")
};
------------- Raw herb and veg
items["artichoke_veg"] = {
name="Raw Artichoke",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["asparagus_veg"] = {
name="Raw Asparagus",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["string_bean_veg"] = {
name="Raw String Bean",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["broad_bean_veg"] = {
name="Raw Broad Bean",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["beetroot_veg"] = {
name="Raw Beetroot",
description = "A root vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['purple'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["goya_veg"] = {
name="Raw Goya",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["cabbage_veg"] = {
name="Raw Cabbage",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["caper_veg"] = {
name="Raw Caper",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["carrot_veg"] = {
name="Raw Carrot",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['orange'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["cassava_veg"] = {
name="Raw Cassava",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["celery_veg"] = {
name="Raw Celery",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["chickpea_veg"] = {
name="Raw Chickpea",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["cowpea_veg"] = {
name="Raw Cowpea",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["cucumber_veg"] = {
name="Raw Cucumber",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["eggplant_veg"] = {
name="Raw Eggplant",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["cress_veg"] = {
name="Raw Cress",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["melon_veg"] = {
name="Raw Melon",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["leek_veg"] = {
name="Raw Leek",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["lentil_veg"] = {
name="Raw Lentils",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["lettuce_veg"] = {
name="Raw Lettuce",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["mung_bean_veg"] = {
name="Raw Mung Bean",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["onion_veg"] = {
name="Raw Onion",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["parsnip_veg"] = {
name="Raw Parsnip",
description = "A root vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["pea_veg"] = {
name="Raw Peas",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["pepper_veg"] = {
name="Raw Bell Pepper",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["potato_veg"] = {
name="Raw Potato",
description = "A root vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["radish_veg"] = {
name="Raw Radish",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["red_bean_veg"] = {
name="Raw Red Beans",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["spinach_veg"] = {
name="Raw Spinach",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["soybean_veg"] = {
name="Raw Soy",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["squash_veg"] = {
name="Raw Squash",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["sweet_potato_veg"] = {
name="Raw Sweet Potato",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['orange'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["tomato_veg"] = {
name="Raw Tomato",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['red'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["tomatillo_veg"] = {
name="Raw Tomatillo",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["turnip_veg"] = {
name="Raw Turnip",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["watermelon_veg"] = {
name="Raw Watermelon",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["yam_veg"] = {
name="Raw Yam",
description = "A green vegetable",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['yellow'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["strawberry_fruit"] = {
name="Raw Strawberry",
description = "A red fruit",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['red'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["bambara_nut"] = {
name="Bambara Nut",
description = "A tasty nut",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['red'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["peanut_nut"] = {
name="Peanut",
description = "A tasty nut",
itemtype = { "food" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['brown'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["chickory_herb"] = {
name="Raw Chickory",
description = "A tasty herb",
itemtype = { "spice" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['brown'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["garlic_herb"] = {
name="Raw Garlic",
description = "A tasty herb",
itemtype = { "spice" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['brown'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["rhubarb_herb"] = {
name="Raw Rhubarb",
description = "A tasty herb",
itemtype = { "spice" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['brown'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["lavendar_herb"] = {
name="Raw Lavendar",
description = "A tasty herb",
itemtype = { "spice" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['purple'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["sage_herb"] = {
name="Raw Sage",
description = "A tasty herb",
itemtype = { "spice" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['inv_exclaim'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['food'],
vox = voxelId("veggie")
};
items["seed"] = {
name="Seeds",
description = "Seeds that when tended properly will grow into a lovely plant",
itemtype = { "seed" }, glyph = glyphs["inv_exclaim"],
glyph_ascii = glyphs['colon'],
foreground=colors['green'], background=colors['black'],
stockpile=stockpiles['seeds'],
vox = voxelId("seed")
};
| gpl-3.0 |
rotmanmi/nn | MulConstant.lua | 11 | 1119 | local MulConstant, parent = torch.class('nn.MulConstant', 'nn.Module')
function MulConstant:__init(constant_scalar,ip)
parent.__init(self)
assert(type(constant_scalar) == 'number', 'input is not scalar!')
self.constant_scalar = constant_scalar
-- default for inplace is false
self.inplace = ip or false
if (ip and type(ip) ~= 'boolean') then
error('in-place flag must be boolean')
end
end
function MulConstant:updateOutput(input)
if self.inplace then
input:mul(self.constant_scalar)
self.output = input
else
self.output:resizeAs(input)
self.output:copy(input)
self.output:mul(self.constant_scalar)
end
return self.output
end
function MulConstant:updateGradInput(input, gradOutput)
if self.gradInput then
if self.inplace then
gradOutput:mul(self.constant_scalar)
self.gradInput = gradOutput
-- restore previous input value
input:div(self.constant_scalar)
else
self.gradInput:resizeAs(gradOutput)
self.gradInput:copy(gradOutput)
self.gradInput:mul(self.constant_scalar)
end
return self.gradInput
end
end
| bsd-3-clause |
Frenzie/koreader | frontend/device/pocketbook/powerd.lua | 4 | 2300 | local BasePowerD = require("device/generic/powerd")
local ffi = require("ffi")
local inkview = ffi.load("inkview")
local PocketBookPowerD = BasePowerD:new{
is_charging = nil,
fl_min = 0,
fl_max = 100,
fl_warmth_min = 0,
fl_warmth_max = 100,
}
function PocketBookPowerD:frontlightIntensityHW()
-- Always update fl_intensity (and perhaps fl_warmth) from the OS value whenever queried (it's fast).
-- This way koreader settings can stay in sync even if the value is changed behind its back.
self.fl_intensity = math.max(0, inkview.GetFrontlightState())
if self.device:hasNaturalLight() then
self.fl_warmth = math.max(0, inkview.GetFrontlightColor())
end
return self.fl_intensity
end
function PocketBookPowerD:frontlightIntensity()
if not self.device:hasFrontlight() then return 0 end
if self:isFrontlightOff() then return 0 end
--- @note: We actually have a working frontlightIntensityHW implementation,
--- use it instead of returning a cached self.fl_intensity like BasePowerD.
return self:frontlightIntensityHW()
end
function PocketBookPowerD:setIntensityHW(intensity)
local v2api = pcall(function()
inkview.SetFrontlightEnabled(intensity == 0 and 0 or 1)
end)
if intensity == 0 then
-- -1 is valid only for the old api, on newer firmwares that's just a bogus brightness level
if not v2api then
inkview.SetFrontlightState(-1)
end
else
inkview.SetFrontlightState(intensity)
end
end
function PocketBookPowerD:isFrontlightOn()
if not self.device:hasFrontlight() then return false end
-- Query directly instead of assuming from cached value.
local enabled = inkview.GetFrontlightState() >= 0
pcall(function()
enabled = inkview.GetFrontlightEnabled() > 0
end)
return enabled
end
function PocketBookPowerD:setWarmthHW(level)
return inkview.SetFrontlightColor(level)
end
function PocketBookPowerD:frontlightWarmthHW()
return inkview.GetFrontlightColor()
end
function PocketBookPowerD:getCapacityHW()
return inkview.GetBatteryPower()
end
function PocketBookPowerD:isChargingHW()
if inkview.IsCharging() > 0 then
return true
else
return false
end
end
return PocketBookPowerD
| agpl-3.0 |
moody2020/TH3_BOSS | plugins/TH3BOSS7.lua | 3 | 1723 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ dev : dev ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
function run(msg, matches)
return [[
▫️الـبـوت الـذي يـعـمـل عـلـى مـجـمـوعـات الـسـوبـر
▫️يـعـمـل الـبـوت عـلـى مـجـمـوعـات سـوبـر تـصـل الـى 5 K عـضـو
≪ تـم صـنـع الـبـوت بـواسـطـه الـمـطـور ≫
『 @TH3BOSS 』
▫️الـمـطـور : الـزعـيـم > @TH3BOSS
▫️كـل مـا هـو جـديـد عـلـى قـنـاه الـسـورس
[ @llDEV1ll ]
▫️للاسـتفـسـار راسـل الـمـطـور :
@TH3BOSS
Programmable bot : @TH3BOSS▫️
Bot continues coder : @ll60Kllbot ▫️
]]
end
return {
description = "Shows bot q",
usage = "spam Shows bot q",
patterns = {
"^(dev)$",
},
run = run
}
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/weaponskills/hot_shot.lua | 10 | 1522 | -----------------------------------
-- Hot Shot
-- Marksmanship weapon skill
-- Skill Level: 5
-- Deals fire elemental damage to enemy.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: Fire
-- Modifiers: AGI:30%
-- 100%TP 200%TP 300%TP
-- 0.50 0.75 1.00
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 0.5 params.ftp200 = 0.75 params.ftp300 = 1
params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.3 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
params.hybridWS = true
params.ele = dsp.magic.ele.FIRE
params.skill = dsp.skill.MARKSMANSHIP
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp200 = 1.55 params.ftp300 = 2.1
params.agi_wsc = 0.7
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Port_San_dOria/npcs/Anton.lua | 11 | 1299 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Anton
-- !pos -19 -8 27 232
-----------------------------------
local ID = require("scripts/zones/Port_San_dOria/IDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(ID.text.FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
if (player:hasKeyItem(dsp.ki.AIRSHIP_PASS) == false) then
player:startEvent(517);
elseif (player:getGil() < 200) then
player:startEvent(716);
else
player:startEvent(604);
end
return 1;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 604) then
X = player:getXPos();
if (X >= -13 and X <= -8) then
player:delGil(200);
end
end
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c59718521.lua | 3 | 2137 | --ブローニング・パワー
function c59718521.initial_effect(c)
--Activate(summon)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_SUMMON)
e1:SetCondition(c59718521.condition1)
e1:SetCost(c59718521.cost)
e1:SetTarget(c59718521.target1)
e1:SetOperation(c59718521.activate1)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON)
c:RegisterEffect(e2)
--Activate(effect)
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_ACTIVATE)
e3:SetCode(EVENT_CHAINING)
e3:SetCondition(c59718521.condition2)
e3:SetCost(c59718521.cost)
e3:SetTarget(c59718521.target2)
e3:SetOperation(c59718521.activate2)
c:RegisterEffect(e3)
end
function c59718521.condition1(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentChain()==0
end
function c59718521.filter(c)
return c:IsRace(RACE_PSYCHO) and not c:IsStatus(STATUS_BATTLE_DESTROYED)
end
function c59718521.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c59718521.filter,1,nil) end
local g=Duel.SelectReleaseGroup(tp,c59718521.filter,1,1,nil)
Duel.Release(g,REASON_COST)
end
function c59718521.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0)
end
function c59718521.activate1(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateSummon(eg)
Duel.Destroy(eg,REASON_EFFECT)
end
function c59718521.condition2(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev)
end
function c59718521.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c59718521.activate2(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c49398568.lua | 7 | 1315 | --連続魔法
function c49398568.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c49398568.condition)
e1:SetCost(c49398568.cost)
e1:SetTarget(c49398568.target)
e1:SetOperation(c49398568.activate)
c:RegisterEffect(e1)
end
function c49398568.condition(e,tp,eg,ep,ev,re,r,rp)
return re:GetActiveType()==TYPE_SPELL and re:IsHasType(EFFECT_TYPE_ACTIVATE) and rp==tp
end
function c49398568.cfilter(c)
return c:IsDiscardable() and c:IsAbleToGraveAsCost()
end
function c49398568.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local hg=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
hg:RemoveCard(e:GetHandler())
if chk==0 then return hg:GetCount()>0 and hg:FilterCount(c49398568.cfilter,nil)==hg:GetCount() end
Duel.SendtoGrave(hg,REASON_COST+REASON_DISCARD)
end
function c49398568.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local ftg=re:GetTarget()
if chkc then return ftg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) end
if chk==0 then return not ftg or ftg(e,tp,eg,ep,ev,re,r,rp,chk) end
if re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then
e:SetProperty(EFFECT_FLAG_CARD_TARGET)
end
if ftg then
ftg(e,tp,eg,ep,ev,re,r,rp,chk)
end
end
function c49398568.activate(e,tp,eg,ep,ev,re,r,rp)
local fop=re:GetOperation()
fop(e,tp,eg,ep,ev,re,r,rp)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c68144350.lua | 9 | 1962 | --BK スイッチヒッター
function c68144350.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(68144350,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCost(c68144350.spcost)
e1:SetTarget(c68144350.sptg)
e1:SetOperation(c68144350.spop)
c:RegisterEffect(e1)
Duel.AddCustomActivityCounter(68144350,ACTIVITY_SPSUMMON,c68144350.counterfilter)
end
function c68144350.counterfilter(c)
return c:IsSetCard(0x84)
end
function c68144350.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(68144350,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:SetTarget(c68144350.splimit)
e1:SetLabelObject(e)
Duel.RegisterEffect(e1,tp)
end
function c68144350.splimit(e,c,sump,sumtype,sumpos,targetp,se)
return not c:IsSetCard(0x84)
end
function c68144350.filter(c,e,tp)
return c:IsSetCard(0x84) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c68144350.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c68144350.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and
Duel.IsExistingTarget(c68144350.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c68144350.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c68144350.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 | c52558805.lua | 5 | 2192 | --太鼓魔人テンテンテンポ
function c52558805.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,3,2)
c:EnableReviveLimit()
--atkchange
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(52558805,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetHintTiming(TIMING_DAMAGE_STEP+0x1c0)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c52558805.atkcon)
e1:SetCost(c52558805.atkcost)
e1:SetTarget(c52558805.atktg)
e1:SetOperation(c52558805.atkop)
c:RegisterEffect(e1)
end
function c52558805.atkcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c52558805.atkcost(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 c52558805.filter(c,tp)
return c:CheckRemoveOverlayCard(tp,1,REASON_EFFECT)
end
function c52558805.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c52558805.filter(chkc,tp) end
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT)
and Duel.IsExistingTarget(c52558805.filter,tp,0,LOCATION_MZONE,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c52558805.filter,tp,0,LOCATION_MZONE,1,1,nil,tp)
end
function c52558805.atkfilter(c)
return c:IsFaceup() and c:IsType(TYPE_XYZ) and c:IsSetCard(0x6d)
end
function c52558805.atkop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) or tc:GetOverlayCount()==0 then return end
tc:RemoveOverlayCard(tp,1,1,REASON_EFFECT)
local g=Duel.GetMatchingGroup(c52558805.atkfilter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(500)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c48009503.lua | 9 | 1249 | --H-C ガーンデーヴァ
function c48009503.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_WARRIOR),4,2)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(48009503,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c48009503.cost)
e1:SetTarget(c48009503.target)
e1:SetOperation(c48009503.operation)
c:RegisterEffect(e1)
end
function c48009503.filter(c,e,tp)
return c:IsFaceup() and c:IsControler(1-tp) and c:IsLevelBelow(4) and (not e or c:IsRelateToEffect(e))
end
function c48009503.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 c48009503.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return eg:IsExists(c48009503.filter,1,nil,nil,tp) end
Duel.SetTargetCard(eg)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0)
end
function c48009503.operation(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c48009503.filter,nil,e,tp)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/globals.lua | 12 | 1104 | -- Zone: Grand Palace of Hu'Xzoi (34)
-- Desc: this file contains functions that are shared by multiple luas in this zone's directory
-----------------------------------
local ID = require("scripts/zones/Grand_Palace_of_HuXzoi/IDs");
require("scripts/globals/status");
-----------------------------------
GRAND_PALACE_OF_HUXZOI = {
--[[..............................................................................................
pick new Jailer of Temperance placeholder every 15 minutes
..............................................................................................]]
pickTemperancePH = function()
local nm = GetMobByID(ID.mob.JAILER_OF_TEMPERANCE);
local phTable = ID.mob.JAILER_OF_TEMPERANCE_PH
if (not nm:isSpawned()) then
nm:setLocalVar("ph", phTable[math.random(#phTable)]);
nm:timer(900000, function(mob)
if (not mob:isSpawned()) then
GRAND_PALACE_OF_HUXZOI.pickTemperancePH();
end
end);
end
end
}
return GRAND_PALACE_OF_HUXZOI;
| gpl-3.0 |
Lsty/ygopro-scripts | c76589815.lua | 3 | 2676 | --BK チート・コミッショナー
function c76589815.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,3,2)
c:EnableReviveLimit()
--must attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetCode(EFFECT_MUST_ATTACK)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_CANNOT_EP)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetTargetRange(0,1)
e2:SetCondition(c76589815.becon)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e3:SetCondition(c76589815.atcon)
e3:SetValue(1)
c:RegisterEffect(e3)
--atk
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(76589815,0))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_ATTACK_ANNOUNCE)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c76589815.cfcon)
e3:SetCost(c76589815.cfcost)
e3:SetTarget(c76589815.cftg)
e3:SetOperation(c76589815.cfop)
c:RegisterEffect(e3)
end
function c76589815.becon(e)
return Duel.IsExistingMatchingCard(Card.IsAttackable,e:GetHandlerPlayer(),0,LOCATION_MZONE,1,nil)
end
function c76589815.atfilter(c)
return c:IsFaceup() and c:IsSetCard(0x84)
end
function c76589815.atcon(e)
return Duel.IsExistingMatchingCard(c76589815.atfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,e:GetHandler())
end
function c76589815.cfcon(e,tp,eg,ep,ev,re,r,rp)
local a=Duel.GetAttacker()
local at=Duel.GetAttackTarget()
return (a:IsControler(tp) and a~=e:GetHandler() and a:IsSetCard(0x84))
or (at and at:IsControler(tp) and at:IsFaceup() and at~=e:GetHandler() and at:IsSetCard(0x84))
end
function c76589815.cfcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,2,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,2,2,REASON_COST)
end
function c76589815.cftg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0
and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 end
end
function c76589815.cffilter(c)
return c:IsType(TYPE_SPELL) and c:IsSSetable()
end
function c76589815.cfop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND)
if g:GetCount()==0 then return end
Duel.ConfirmCards(tp,g)
if Duel.GetLocationCount(tp,LOCATION_SZONE)>0 then
local sg=g:Filter(c76589815.cffilter,nil)
if sg:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local setg=sg:Select(tp,1,1,nil)
Duel.SSet(tp,setg:GetFirst())
Duel.ConfirmCards(1-tp,setg)
end
end
Duel.ShuffleHand(1-tp)
end
| gpl-2.0 |
robertbrook/Penlight | lua/pl/func.lua | 14 | 10456 | --- Functional helpers like composition, binding and placeholder expressions.
-- Placeholder expressions are useful for short anonymous functions, and were
-- inspired by the Boost Lambda library.
--
-- > utils.import 'pl.func'
-- > ls = List{10,20,30}
-- > = ls:map(_1+1)
-- {11,21,31}
--
-- They can also be used to _bind_ particular arguments of a function.
--
-- > p = bind(print,'start>',_0)
-- > p(10,20,30)
-- > start> 10 20 30
--
-- See @{07-functional.md.Creating_Functions_from_Functions|the Guide}
--
-- Dependencies: `pl.utils`, `pl.tablex`
-- @module pl.func
local type,select,setmetatable,getmetatable,rawset = type,select,setmetatable,getmetatable,rawset
local concat,append = table.concat,table.insert
local tostring = tostring
local utils = require 'pl.utils'
local pairs,ipairs,loadstring,rawget,unpack = pairs,ipairs,loadstring,rawget,utils.unpack
local tablex = require 'pl.tablex'
local map = tablex.map
local _DEBUG = rawget(_G,'_DEBUG')
local assert_arg = utils.assert_arg
local func = {}
-- metatable for Placeholder Expressions (PE)
local _PEMT = {}
local function P (t)
setmetatable(t,_PEMT)
return t
end
func.PE = P
local function isPE (obj)
return getmetatable(obj) == _PEMT
end
func.isPE = isPE
-- construct a placeholder variable (e.g _1 and _2)
local function PH (idx)
return P {op='X',repr='_'..idx, index=idx}
end
-- construct a constant placeholder variable (e.g _C1 and _C2)
local function CPH (idx)
return P {op='X',repr='_C'..idx, index=idx}
end
func._1,func._2,func._3,func._4,func._5 = PH(1),PH(2),PH(3),PH(4),PH(5)
func._0 = P{op='X',repr='...',index=0}
function func.Var (name)
local ls = utils.split(name,'[%s,]+')
local res = {}
for i = 1, #ls do
append(res,P{op='X',repr=ls[i],index=0})
end
return unpack(res)
end
function func._ (value)
return P{op='X',repr=value,index='wrap'}
end
local repr
func.Nil = func.Var 'nil'
function _PEMT.__index(obj,key)
return P{op='[]',obj,key}
end
function _PEMT.__call(fun,...)
return P{op='()',fun,...}
end
function _PEMT.__tostring (e)
return repr(e)
end
function _PEMT.__unm(arg)
return P{op='-',arg}
end
function func.Not (arg)
return P{op='not',arg}
end
function func.Len (arg)
return P{op='#',arg}
end
local function binreg(context,t)
for name,op in pairs(t) do
rawset(context,name,function(x,y)
return P{op=op,x,y}
end)
end
end
local function import_name (name,fun,context)
rawset(context,name,function(...)
return P{op='()',fun,...}
end)
end
local imported_functions = {}
local function is_global_table (n)
return type(_G[n]) == 'table'
end
--- wrap a table of functions. This makes them available for use in
-- placeholder expressions.
-- @string tname a table name
-- @tab context context to put results, defaults to environment of caller
function func.import(tname,context)
assert_arg(1,tname,'string',is_global_table,'arg# 1: not a name of a global table')
local t = _G[tname]
context = context or _G
for name,fun in pairs(t) do
import_name(name,fun,context)
imported_functions[fun] = name
end
end
--- register a function for use in placeholder expressions.
-- @func fun a function
-- @string[opt] name an optional name
-- @return a placeholder functiond
function func.register (fun,name)
assert_arg(1,fun,'function')
if name then
assert_arg(2,name,'string')
imported_functions[fun] = name
end
return function(...)
return P{op='()',fun,...}
end
end
function func.lookup_imported_name (fun)
return imported_functions[fun]
end
local function _arg(...) return ... end
function func.Args (...)
return P{op='()',_arg,...}
end
-- binary and unary operators, with their precedences (see 2.5.6)
local operators = {
['or'] = 0,
['and'] = 1,
['=='] = 2, ['~='] = 2, ['<'] = 2, ['>'] = 2, ['<='] = 2, ['>='] = 2,
['..'] = 3,
['+'] = 4, ['-'] = 4,
['*'] = 5, ['/'] = 5, ['%'] = 5,
['not'] = 6, ['#'] = 6, ['-'] = 6,
['^'] = 7
}
-- comparisons (as prefix functions)
binreg (func,{And='and',Or='or',Eq='==',Lt='<',Gt='>',Le='<=',Ge='>='})
-- standard binary operators (as metamethods)
binreg (_PEMT,{__add='+',__sub='-',__mul='*',__div='/',__mod='%',__pow='^',__concat='..'})
binreg (_PEMT,{__eq='=='})
--- all elements of a table except the first.
-- @tab ls a list-like table.
function func.tail (ls)
assert_arg(1,ls,'table')
local res = {}
for i = 2,#ls do
append(res,ls[i])
end
return res
end
--- create a string representation of a placeholder expression.
-- @param e a placeholder expression
-- @param lastpred not used
function repr (e,lastpred)
local tail = func.tail
if isPE(e) then
local pred = operators[e.op]
local ls = map(repr,e,pred)
if pred then --unary or binary operator
if #ls ~= 1 then
local s = concat(ls,' '..e.op..' ')
if lastpred and lastpred > pred then
s = '('..s..')'
end
return s
else
return e.op..' '..ls[1]
end
else -- either postfix, or a placeholder
if e.op == '[]' then
return ls[1]..'['..ls[2]..']'
elseif e.op == '()' then
local fn
if ls[1] ~= nil then -- was _args, undeclared!
fn = ls[1]
else
fn = ''
end
return fn..'('..concat(tail(ls),',')..')'
else
return e.repr
end
end
elseif type(e) == 'string' then
return '"'..e..'"'
elseif type(e) == 'function' then
local name = func.lookup_imported_name(e)
if name then return name else return tostring(e) end
else
return tostring(e) --should not really get here!
end
end
func.repr = repr
-- collect all the non-PE values in this PE into vlist, and replace each occurence
-- with a constant PH (_C1, etc). Return the maximum placeholder index found.
local collect_values
function collect_values (e,vlist)
if isPE(e) then
if e.op ~= 'X' then
local m = 0
for i = 1,#e do
local subx = e[i]
local pe = isPE(subx)
if pe then
if subx.op == 'X' and subx.index == 'wrap' then
subx = subx.repr
pe = false
else
m = math.max(m,collect_values(subx,vlist))
end
end
if not pe then
append(vlist,subx)
e[i] = CPH(#vlist)
end
end
return m
else -- was a placeholder, it has an index...
return e.index
end
else -- plain value has no placeholder dependence
return 0
end
end
func.collect_values = collect_values
--- instantiate a PE into an actual function. First we find the largest placeholder used,
-- e.g. _2; from this a list of the formal parameters can be build. Then we collect and replace
-- any non-PE values from the PE, and build up a constant binding list.
-- Finally, the expression can be compiled, and e.__PE_function is set.
-- @param e a placeholder expression
-- @return a function
function func.instantiate (e)
local consts,values,parms = {},{},{}
local rep, err, fun
local n = func.collect_values(e,values)
for i = 1,#values do
append(consts,'_C'..i)
if _DEBUG then print(i,values[i]) end
end
for i =1,n do
append(parms,'_'..i)
end
consts = concat(consts,',')
parms = concat(parms,',')
rep = repr(e)
local fstr = ('return function(%s) return function(%s) return %s end end'):format(consts,parms,rep)
if _DEBUG then print(fstr) end
fun,err = utils.load(fstr,'fun')
if not fun then return nil,err end
fun = fun() -- get wrapper
fun = fun(unpack(values)) -- call wrapper (values could be empty)
e.__PE_function = fun
return fun
end
--- instantiate a PE unless it has already been done.
-- @param e a placeholder expression
-- @return the function
function func.I(e)
if rawget(e,'__PE_function') then
return e.__PE_function
else return func.instantiate(e)
end
end
utils.add_function_factory(_PEMT,func.I)
--- bind the first parameter of the function to a value.
-- @function func.bind1
-- @func fn a function of one or more arguments
-- @param p a value
-- @return a function of one less argument
-- @usage (bind1(math.max,10))(20) == math.max(10,20)
func.bind1 = utils.bind1
func.curry = func.bind1
--- create a function which chains two functions.
-- @func f a function of at least one argument
-- @func g a function of at least one argument
-- @return a function
-- @usage printf = compose(io.write,string.format)
function func.compose (f,g)
return function(...) return f(g(...)) end
end
--- bind the arguments of a function to given values.
-- `bind(fn,v,_2)` is equivalent to `bind1(fn,v)`.
-- @func fn a function of at least one argument
-- @param ... values or placeholder variables
-- @return a function
-- @usage (bind(f,_1,a))(b) == f(a,b)
-- @usage (bind(f,_2,_1))(a,b) == f(b,a)
function func.bind(fn,...)
local args = table.pack(...)
local holders,parms,bvalues,values = {},{},{'fn'},{}
local nv,maxplace,varargs = 1,0,false
for i = 1,args.n do
local a = args[i]
if isPE(a) and a.op == 'X' then
append(holders,a.repr)
maxplace = math.max(maxplace,a.index)
if a.index == 0 then varargs = true end
else
local v = '_v'..nv
append(bvalues,v)
append(holders,v)
append(values,a)
nv = nv + 1
end
end
for np = 1,maxplace do
append(parms,'_'..np)
end
if varargs then append(parms,'...') end
bvalues = concat(bvalues,',')
parms = concat(parms,',')
holders = concat(holders,',')
local fstr = ([[
return function (%s)
return function(%s) return fn(%s) end
end
]]):format(bvalues,parms,holders)
if _DEBUG then print(fstr) end
local res,err = utils.load(fstr)
res = res()
return res(fn,unpack(values))
end
return func
| mit |
Lsty/ygopro-scripts | c8632967.lua | 7 | 1175 | --進化の宿命
function c8632967.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--act limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetOperation(c8632967.sucop)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_CHAIN_END)
e3:SetOperation(c8632967.cedop)
e3:SetLabelObject(e2)
c:RegisterEffect(e3)
end
function c8632967.chainlm(e,rp,tp)
return tp==rp
end
function c8632967.sucfilter(c)
local st=c:GetSummonType()
return c:IsSetCard(0x304e) and st>=(SUMMON_TYPE_SPECIAL+150) and st<(SUMMON_TYPE_SPECIAL+180)
end
function c8632967.sucop(e,tp,eg,ep,ev,re,r,rp)
if eg:IsExists(c8632967.sucfilter,1,nil) then
e:SetLabel(1)
else e:SetLabel(0) end
end
function c8632967.cedop(e,tp,eg,ep,ev,re,r,rp)
if Duel.CheckEvent(EVENT_SPSUMMON_SUCCESS) and e:GetLabelObject():GetLabel()==1 then
Duel.SetChainLimitTillChainEnd(c8632967.chainlm)
end
end
| gpl-2.0 |
openwrt/luci | applications/luci-app-dockerman/luasrc/model/cbi/dockerman/overview.lua | 3 | 3316 | --[[
LuCI - Lua Configuration Interface
Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman>
]]--
local docker = require "luci.model.docker"
local m, s, o
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
m = Map("dockerd",
translate("Docker - Overview"),
translate("An overview with the relevant data is displayed here with which the LuCI docker client is connected."))
local docker_info_table = {}
docker_info_table['3ServerVersion'] = {_key=translate("Docker Version"),_value='-'}
docker_info_table['4ApiVersion'] = {_key=translate("Api Version"),_value='-'}
docker_info_table['5NCPU'] = {_key=translate("CPUs"),_value='-'}
docker_info_table['6MemTotal'] = {_key=translate("Total Memory"),_value='-'}
docker_info_table['7DockerRootDir'] = {_key=translate("Docker Root Dir"),_value='-'}
docker_info_table['8IndexServerAddress'] = {_key=translate("Index Server Address"),_value='-'}
docker_info_table['9RegistryMirrors'] = {_key=translate("Registry Mirrors"),_value='-'}
s = m:section(Table, docker_info_table)
s:option(DummyValue, "_key", translate("Info"))
s:option(DummyValue, "_value")
s = m:section(SimpleSection)
s.template = "dockerman/overview"
s.containers_running = '-'
s.images_used = '-'
s.containers_total = '-'
s.images_total = '-'
s.networks_total = '-'
s.volumes_total = '-'
if docker.new():_ping().code == 200 then
local dk = docker.new()
local containers_list = dk.containers:list({query = {all=true}}).body
local images_list = dk.images:list().body
local vol = dk.volumes:list()
local volumes_list = vol and vol.body and vol.body.Volumes or {}
local networks_list = dk.networks:list().body or {}
local docker_info = dk:info()
docker_info_table['3ServerVersion']._value = docker_info.body.ServerVersion
docker_info_table['4ApiVersion']._value = docker_info.headers["Api-Version"]
docker_info_table['5NCPU']._value = tostring(docker_info.body.NCPU)
docker_info_table['6MemTotal']._value = byte_format(docker_info.body.MemTotal)
if docker_info.body.DockerRootDir then
local statvfs = nixio.fs.statvfs(docker_info.body.DockerRootDir)
local size = statvfs and (statvfs.bavail * statvfs.bsize) or 0
docker_info_table['7DockerRootDir']._value = docker_info.body.DockerRootDir .. " (" .. tostring(byte_format(size)) .. " " .. translate("Available") .. ")"
end
docker_info_table['8IndexServerAddress']._value = docker_info.body.IndexServerAddress
for i, v in ipairs(docker_info.body.RegistryConfig.Mirrors) do
docker_info_table['9RegistryMirrors']._value = docker_info_table['9RegistryMirrors']._value == "-" and v or (docker_info_table['9RegistryMirrors']._value .. ", " .. v)
end
s.images_used = 0
for i, v in ipairs(images_list) do
for ci,cv in ipairs(containers_list) do
if v.Id == cv.ImageID then
s.images_used = s.images_used + 1
break
end
end
end
s.containers_running = tostring(docker_info.body.ContainersRunning)
s.images_used = tostring(s.images_used)
s.containers_total = tostring(docker_info.body.Containers)
s.images_total = tostring(#images_list)
s.networks_total = tostring(#networks_list)
s.volumes_total = tostring(#volumes_list)
end
return m
| apache-2.0 |
Lsty/ygopro-scripts | c75252099.lua | 3 | 1452 | --ローズ・バード
function c75252099.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(75252099,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c75252099.spcon)
e1:SetTarget(c75252099.sptg)
e1:SetOperation(c75252099.spop)
c:RegisterEffect(e1)
end
function c75252099.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE) and c==Duel.GetAttackTarget()
and c:GetPreviousControler()==tp and c:GetBattlePosition()==POS_FACEUP_ATTACK
end
function c75252099.filter(c,e,tp)
return c:IsRace(RACE_PLANT) and c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c75252099.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsExistingMatchingCard(c75252099.filter,tp,LOCATION_DECK,0,2,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c75252099.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end
local g=Duel.GetMatchingGroup(c75252099.filter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()<2 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,2,2,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP_DEFENCE)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Southern_San_dOria/npcs/Femitte.lua | 9 | 2758 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Femitte
-- Involved in Quest: Lure of the Wildcat (San d'Oria), Distant Loyalties
-- !pos -17 2 10 230
-------------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Southern_San_dOria/IDs");
-----------------------------------
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)
local DistantLoyaltiesProgress = player:getCharVar("DistantLoyaltiesProgress");
local DistantLoyalties = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
local WildcatSandy = player:getCharVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,3) == false) then
player:startEvent(807);
elseif (player:getFameLevel(SANDORIA) >= 4 and DistantLoyalties == 0) then
player:startEvent(663);
elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 1) then
player:startEvent(664);
elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 4 and player:hasKeyItem(dsp.ki.MYTHRIL_HEARTS)) then
player:startEvent(665);
else
player:startEvent(661);
end;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 807) then
player:setMaskBit(player:getCharVar("WildcatSandy"),"WildcatSandy",3,true);
elseif (csid == 663 and option == 0) then
player:addKeyItem(dsp.ki.GOLDSMITHING_ORDER);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.GOLDSMITHING_ORDER);
player:addQuest(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
player:setCharVar("DistantLoyaltiesProgress",1);
elseif (csid == 665) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13585);
else
player:delKeyItem(dsp.ki.MYTHRIL_HEARTS);
player:addItem(13585,1);
player:messageSpecial(ID.text.ITEM_OBTAINED,13585);
player:setCharVar("DistantLoyaltiesProgress",0);
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
end;
end;
end;
--------Other CS
--32692
--0
--661 Standard dialog
--663
--664
--665
--725
--747
--748
--807 Lure of the Wildcat
--945 CS with small mythra dancer | gpl-3.0 |
MalRD/darkstar | scripts/zones/Quicksand_Caves/Zone.lua | 8 | 4217 | -----------------------------------
--
-- Zone: Quicksand_Caves (208)
--
-----------------------------------
local ID = require("scripts/zones/Quicksand_Caves/IDs")
require("scripts/globals/conquest")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/settings")
require("scripts/globals/treasure")
require("scripts/globals/status")
-----------------------------------
function onInitialize(zone)
-- Weight Door System (RegionID, X, Radius, Z)
zone:registerRegion(1, -15, 5, -60, 0,0,0);
zone:registerRegion(3, 15, 5,-180, 0,0,0);
zone:registerRegion(5, -580, 5,-420, 0,0,0);
zone:registerRegion(7, -700, 5,-420, 0,0,0);
zone:registerRegion(9, -700, 5,-380, 0,0,0);
zone:registerRegion(11, -780, 5,-460, 0,0,0);
zone:registerRegion(13, -820, 5,-380, 0,0,0);
zone:registerRegion(15, -260, 5, 740, 0,0,0);
zone:registerRegion(17, -340, 5, 660, 0,0,0);
zone:registerRegion(19, -420, 5, 740, 0,0,0);
zone:registerRegion(21, -340, 5, 820, 0,0,0);
zone:registerRegion(23, -409, 5, 800, 0,0,0);
zone:registerRegion(25, -400, 5, 670, 0,0,0);
-- Hole in the Sand
zone:registerRegion(30,495,-9,-817,497,-7,-815); -- E-11 (Map 2)
zone:registerRegion(31,815,-9,-744,817,-7,-742); -- M-9 (Map 2)
zone:registerRegion(32,215,6,-17,217,8,-15); -- K-6 (Map 3)
zone:registerRegion(33,-297,6,415,-295,8,417); -- E-7 (Map 6)
zone:registerRegion(34,-137,6,-177,-135,8,-175); -- G-7 (Map 8)
dsp.treasure.initZone(zone)
npcUtil.UpdateNPCSpawnPoint(ID.npc.ANTICAN_TAG_QM, 60, 120, ID.npc.ANTICAN_TAG_POSITIONS, "[POP]Antican_Tag");
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-980.193,14.913,-282.863,60);
end
return cs;
end;
function getWeight(player)
local race = player:getRace()
if race == dsp.race.GALKA then
return 3
elseif race == dsp.race.TARU_M or race == dsp.race.TARU_F then
return 1
else
return 2
end
end
function onRegionEnter(player,region)
local RegionID = region:GetRegionID();
-- holes in the sand
if (RegionID >= 30) then
switch (RegionID): caseof
{
[30] = function (x)
player:setPos(496,-6,-816);
end,
[31] = function (x)
player:setPos(816,-6,-743);
end,
[32] = function (x)
player:setPos(216,9,-16);
end,
[33] = function (x)
player:setPos(-296,9,416);
end,
[34] = function (x)
player:setPos(-136,9,-176);
end,
}
-- ornate door pressure plates
else
local door = GetNPCByID(ID.npc.ORNATE_DOOR_OFFSET + RegionID - 1);
local plate = GetNPCByID(ID.npc.ORNATE_DOOR_OFFSET + RegionID);
local totalWeight = plate:getLocalVar("weight");
totalWeight = totalWeight + getWeight(player);
plate:setLocalVar("weight", totalWeight);
if (player:hasKeyItem(dsp.ki.LOADSTONE) or totalWeight >= 3) then
door:openDoor(15); -- open door with a 15 second time delay.
plate:setAnimation(dsp.anim.OPEN_DOOR); -- this is supposed to light up the platform but it's not working. Tried other values too.
end
end
end;
function onRegionLeave(player,region)
local RegionID = region:GetRegionID();
if (RegionID < 30) then
local door = GetNPCByID(ID.npc.ORNATE_DOOR_OFFSET + RegionID - 1);
local plate = GetNPCByID(ID.npc.ORNATE_DOOR_OFFSET + RegionID);
local totalWeight = plate:getLocalVar("weight");
totalWeight = totalWeight - getWeight(player);
plate:setLocalVar("weight", totalWeight);
if (plate:getAnimation() == dsp.anim.OPEN_DOOR and totalWeight < 3) then
plate:setAnimation(dsp.anim.CLOSE_DOOR);
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
mamadkiller2/anti-spam | libs/dkjson.lua | 31 | 19917 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
-->
-- کد های پایین در ربات نشان داده نمیشوند
-- http://permag.ir
-- @permag_ir
-- @permag_bots
-- @permag | gpl-3.0 |
MalRD/darkstar | scripts/globals/mobskills/sledgehammer.lua | 11 | 1041 | ---------------------------------------------
-- Sledgehammer
-- Description: Delivers a sledgehammer blow to all targets in front. Additional effect: Petrification
-- Type: Physical
-- Utsusemi/Blink absorb: 3 shadows
-- Range: Front cone
-- Notes: Only used by Gurfurlur the Menacing.
---------------------------------------------
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 3.2
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,3 * info.hitslanded)
MobPhysicalStatusEffectMove(mob, target, skill, dsp.effect.PETRIFICATION, 1, 0, 60)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT)
return dmg
end
| gpl-3.0 |
Distrotech/vlc | share/lua/modules/common.lua | 48 | 4964 | --[[ This code is public domain (since it really isn't very interesting) ]]--
module("common",package.seeall)
-- Iterate over a table in the keys' alphabetical order
function pairs_sorted(t)
local s = {}
for k,_ in pairs(t) do table.insert(s,k) end
table.sort(s)
local i = 0
return function () i = i + 1; return s[i], t[s[i]] end
end
-- Return a function such as skip(foo)(a,b,c) = foo(b,c)
function skip(foo)
return function(discard,...) return foo(...) end
end
-- Return a function such as setarg(foo,a)(b,c) = foo(a,b,c)
function setarg(foo,a)
return function(...) return foo(a,...) end
end
-- Trigger a hotkey
function hotkey(arg)
local id = vlc.misc.action_id( arg )
if id ~= nil then
vlc.var.set( vlc.object.libvlc(), "key-action", id )
return true
else
return false
end
end
-- Take a video snapshot
function snapshot()
local vout = vlc.object.vout()
if not vout then return end
vlc.var.set(vout,"video-snapshot",nil)
end
-- Naive (non recursive) table copy
function table_copy(t)
c = {}
for i,v in pairs(t) do c[i]=v end
return c
end
-- tonumber() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tonumber(str)
local s, i, d = string.match(str, "^([+-]?)(%d*)%.?(%d*)$")
if not s or not i or not d then
return nil
end
if s == "-" then
s = -1
else
s = 1
end
if i == "" then
i = "0"
end
if d == nil or d == "" then
d = "0"
end
return s * (tonumber(i) + tonumber(d)/(10^string.len(d)))
end
-- tostring() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tostring(n)
s = tostring(n):gsub(",", ".", 1)
return s
end
-- strip leading and trailing spaces
function strip(str)
return string.gsub(str, "^%s*(.-)%s*$", "%1")
end
-- print a table (recursively)
function table_print(t,prefix)
local prefix = prefix or ""
if not t then
print(prefix.."/!\\ nil")
return
end
for a,b in pairs_sorted(t) do
print(prefix..tostring(a),b)
if type(b)==type({}) then
table_print(b,prefix.."\t")
end
end
end
-- print the list of callbacks registered in lua
-- useful for debug purposes
function print_callbacks()
print "callbacks:"
table_print(vlc.callbacks)
end
-- convert a duration (in seconds) to a string
function durationtostring(duration)
return string.format("%02d:%02d:%02d",
math.floor(duration/3600),
math.floor(duration/60)%60,
math.floor(duration%60))
end
-- realpath
function realpath(path)
return string.gsub(string.gsub(string.gsub(string.gsub(path,"/%.%./[^/]+","/"),"/[^/]+/%.%./","/"),"/%./","/"),"//","/")
end
-- parse the time from a string and return the seconds
-- time format: [+ or -][<int><H or h>:][<int><M or m or '>:][<int><nothing or S or s or ">]
function parsetime(timestring)
local seconds = 0
local hourspattern = "(%d+)[hH]"
local minutespattern = "(%d+)[mM']"
local secondspattern = "(%d+)[sS\"]?$"
local _, _, hoursmatch = string.find(timestring, hourspattern)
if hoursmatch ~= nil then
seconds = seconds + tonumber(hoursmatch) * 3600
end
local _, _, minutesmatch = string.find(timestring, minutespattern)
if minutesmatch ~= nil then
seconds = seconds + tonumber(minutesmatch) * 60
end
local _, _, secondsmatch = string.find(timestring, secondspattern)
if secondsmatch ~= nil then
seconds = seconds + tonumber(secondsmatch)
end
if string.sub(timestring,1,1) == "-" then
seconds = seconds * -1
end
return seconds
end
-- seek
function seek(value)
local input = vlc.object.input()
if input ~= nil and value ~= nil then
if string.sub(value,-1) == "%" then
local number = us_tonumber(string.sub(value,1,-2))
if number ~= nil then
local posPercent = number/100
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"position",vlc.var.get(input,"position") + posPercent)
else
vlc.var.set(input,"position",posPercent)
end
end
else
local posTime = parsetime(value)
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"time",vlc.var.get(input,"time") + posTime)
else
vlc.var.set(input,"time",posTime)
end
end
end
end
function volume(value)
if type(value)=="string" and string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.volume.set(vlc.volume.get()+tonumber(value))
else
vlc.volume.set(tostring(value))
end
end
| gpl-2.0 |
openwrt/luci | modules/luci-mod-rpc/luasrc/jsonrpc.lua | 3 | 1973 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.jsonrpc", package.seeall)
require "luci.json"
function resolve(mod, method)
local path = luci.util.split(method, ".")
for j=1, #path-1 do
if not type(mod) == "table" then
break
end
mod = rawget(mod, path[j])
if not mod then
break
end
end
mod = type(mod) == "table" and rawget(mod, path[#path]) or nil
if type(mod) == "function" then
return mod
end
end
function handle(tbl, rawsource, ...)
local decoder = luci.json.Decoder()
local stat = luci.ltn12.pump.all(rawsource, decoder:sink())
local json = decoder:get()
local response
local success = false
if stat then
if type(json.method) == "string"
and (not json.params or type(json.params) == "table") then
local method = resolve(tbl, json.method)
if method then
response = reply(json.jsonrpc, json.id,
proxy(method, unpack(json.params or {})))
else
response = reply(json.jsonrpc, json.id,
nil, {code=-32601, message="Method not found."})
end
else
response = reply(json.jsonrpc, json.id,
nil, {code=-32600, message="Invalid request."})
end
else
response = reply("2.0", nil,
nil, {code=-32700, message="Parse error."})
end
return luci.json.Encoder(response, ...):source()
end
function reply(jsonrpc, id, res, err)
require "luci.json"
id = id or luci.json.null
-- 1.0 compatibility
if jsonrpc ~= "2.0" then
jsonrpc = nil
res = res or luci.json.null
err = err or luci.json.null
end
return {id=id, result=res, error=err, jsonrpc=jsonrpc}
end
function proxy(method, ...)
local res = {luci.util.copcall(method, ...)}
local stat = table.remove(res, 1)
if not stat then
return nil, {code=-32602, message="Invalid params.", data=table.remove(res, 1)}
else
if #res <= 1 then
return res[1] or luci.json.null
else
return res
end
end
end
| apache-2.0 |
MalRD/darkstar | scripts/globals/items/elshimo_frog.lua | 11 | 1212 | -----------------------------------------
-- ID: 4290
-- Item: elshimo_frog
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Agility 2
-- Mind -4
-- Evasion 5
-----------------------------------------
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,4290)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.AGI, 2)
target:addMod(dsp.mod.MND, -4)
target:addMod(dsp.mod.EVA, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.AGI, 2)
target:delMod(dsp.mod.MND, -4)
target:delMod(dsp.mod.EVA, 5)
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Horlais_Peak/bcnms/tails_of_woe.lua | 9 | 1059 | -----------------------------------
-- Tails of Woe
-- Horlais Peak BCNM40, Star Orb
-- !additem 1131
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/abilities/wizards_roll.lua | 12 | 2988 | -----------------------------------
-- Ability: Wizard's Roll
-- Enhances magic attack for party members within area of effect
-- Optimal Job: Black Mage
-- Lucky Number: 5
-- Unlucky Number: 9
-- Level 58
-- Phantom Roll +1 Value: 2
--
-- Die Roll |No BLM |With BLM
-- -------- -------- -----------
-- 1 |+4 |+14
-- 2 |+6 |+16
-- 3 |+8 |+18
-- 4 |+10 |+20
-- 5 |+25 |+35
-- 6 |+12 |+22
-- 7 |+14 |+24
-- 8 |+17 |+27
-- 9 |+2 |+12
-- 10 |+20 |+10
-- 11 |+30 |+40
-- Bust |-10 |-10
--
-- If the Corsair is a lower level than the player receiving Wizard's Roll, the +MAB will be reduced
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/ability")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = dsp.effect.WIZARDS_ROLL
ability:setRange(ability:getRange() + player:getMod(dsp.mod.ROLL_RANGE))
if (player:hasStatusEffect(effectID)) then
return dsp.msg.basic.ROLL_ALREADY_ACTIVE,0
elseif atMaxCorsairBusts(player) then
return dsp.msg.basic.CANNOT_PERFORM,0
else
return 0,0
end
end
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, dsp.effect.WIZARDS_ROLL, dsp.job.BLM)
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(dsp.merit.WINNING_STREAK) + caster:getMod(dsp.mod.PHANTOM_DURATION)
local effectpowers = {4, 6, 8, 10, 25, 12, 14, 17, 2, 20, 30, 10}
local effectpower = effectpowers[total]
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 10
end
-- Apply Additional Phantom Roll+ Buff
local phantomBase = 2 -- Base increment buff
local effectpower = effectpower + (phantomBase * phantombuffMultiple(caster))
-- Check if COR Main or Sub
if (caster:getMainJob() == dsp.job.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl())
elseif (caster:getSubJob() == dsp.job.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl())
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(dsp.merit.BUST_DURATION), dsp.effect.WIZARDS_ROLL, effectpower, 0, duration, caster:getID(), total, dsp.mod.MATT) == false) then
ability:setMsg(dsp.msg.basic.ROLL_MAIN_FAIL)
elseif total > 11 then
ability:setMsg(dsp.msg.basic.DOUBLEUP_BUST)
end
return total
end
| gpl-3.0 |
Lsty/ygopro-scripts | c74153887.lua | 9 | 2130 | --黒蠍-棘のミーネ
function c74153887.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(74153887,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DAMAGE)
e1:SetCondition(c74153887.condition)
e1:SetTarget(c74153887.target)
e1:SetOperation(c74153887.operation)
c:RegisterEffect(e1)
end
function c74153887.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c74153887.filter(c)
return c:IsSetCard(0x1a) and c:IsAbleToHand()
end
function c74153887.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c74153887.filter(chkc) end
if chk==0 then return Duel.IsExistingMatchingCard(c74153887.filter,tp,LOCATION_DECK,0,1,nil)
or Duel.IsExistingTarget(c74153887.filter,tp,LOCATION_GRAVE,0,1,nil) end
local op=0
if Duel.IsExistingMatchingCard(c74153887.filter,tp,LOCATION_DECK,0,1,nil)
and Duel.IsExistingTarget(c74153887.filter,tp,LOCATION_GRAVE,0,1,nil) then
op=Duel.SelectOption(tp,aux.Stringid(74153887,1),aux.Stringid(74153887,2))
elseif Duel.IsExistingTarget(c74153887.filter,tp,LOCATION_GRAVE,0,1,nil) then
Duel.SelectOption(tp,aux.Stringid(74153887,2))
op=1
else
Duel.SelectOption(tp,aux.Stringid(74153887,1))
op=0
end
e:SetLabel(op)
if op==1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c74153887.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
e:SetProperty(EFFECT_FLAG_CARD_TARGET)
else
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
e:SetProperty(0)
end
end
function c74153887.operation(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabel()==1 then
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c74153887.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
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/mobskills/chaos_blade.lua | 11 | 1088 | ---------------------------------------------
-- Chaos Blade
--
-- Description: Deals Dark damage to enemies within a fan-shaped area. Additional effect: Curse
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores Shadows
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local dmgmod = 2
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 3,dsp.magic.ele.DARK,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.DARK)
-- curse LAST so you don't die
local typeEffect = dsp.effect.CURSE_I
MobStatusEffectMove(mob, target, typeEffect, 25, 0, 420)
return dmg
end
| gpl-3.0 |
gallenmu/MoonGen | libmoon/lua/proto/dns.lua | 4 | 17416 | ------------------------------------------------------------------------
--- @file dns.lua
--- @brief (dns) utility.
--- Utility functions for the dns_header structs
--- - dns constants
--- - dns header utility
--- - Definition of dns packets
---
--- Copyright (c) Santiago R.R. <santiago.ruano-rincon@telecom-bretagne.eu>
------------------------------------------------------------------------
local ffi = require "ffi"
require "proto.template"
local initHeader = initHeader
local ntoh, hton = ntoh, hton
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
require "math"
---------------------------------------------------------------------------
---- dns constants
---------------------------------------------------------------------------
--- dns protocol constants
local dns = {}
---------------------------------------------------------------------------
---- dns header
---------------------------------------------------------------------------
--[[ From the RFC 1035, https://www.ietf.org/rfc/rfc1035.txt
The header contains the following fields:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
ID A 16 bit identifier assigned by the program that
generates any kind of query. This identifier is copied
the corresponding reply and can be used by the requester
to match up replies to outstanding queries.
QR A one bit field that specifies whether this message is a
query (0), or a response (1).
OPCODE A four bit field that specifies kind of query in this
message. This value is set by the originator of a query
and copied into the response. The values are:
0 a standard query (QUERY)
1 an inverse query (IQUERY)
2 a server status request (STATUS)
3-15 reserved for future use
AA Authoritative Answer - this bit is valid in responses,
and specifies that the responding name server is an
authority for the domain name in question section.
Note that the contents of the answer section may have
multiple owner names because of aliases. The AA bit
corresponds to the name which matches the query name, or
the first owner name in the answer section.
TC TrunCation - specifies that this message was truncated
due to length greater than that permitted on the
transmission channel.
RD Recursion Desired - this bit may be set in a query and
is copied into the response. If RD is set, it directs
the name server to pursue the query recursively.
Recursive query support is optional.
RA Recursion Available - this be is set or cleared in a
response, and denotes whether recursive query support is
available in the name server.
Z Reserved for future use. Must be zero in all queries
and responses.
RCODE Response code - this 4 bit field is set as part of
responses. The values have the following
interpretation:
0 No error condition
1 Format error - The name server was
unable to interpret the query.
2 Server failure - The name server was
unable to process this query due to a
problem with the name server.
3 Name Error - Meaningful only for
responses from an authoritative name
server, this code signifies that the
domain name referenced in the query does
not exist.
4 Not Implemented - The name server does
not support the requested kind of query.
5 Refused - The name server refuses to
perform the specified operation for
policy reasons. For example, a name
server may not wish to provide the
information to the particular requester,
or a name server may not wish to perform
a particular operation (e.g., zone
transfer) for particular data.
6-15 Reserved for future use.
QDCOUNT an unsigned 16 bit integer specifying the number of
entries in the question section.
ANCOUNT an unsigned 16 bit integer specifying the number of
resource records in the answer section.
NSCOUNT an unsigned 16 bit integer specifying the number of name
server resource records in the authority records
section.
ARCOUNT an unsigned 16 bit integer specifying the number of
resource records in the additional records section.
]]--
-- definition of the header format
dns.headerFormat = [[
uint16_t id;
uint16_t hdrflags;
uint16_t qdcount;
uint16_t ancount;
uint16_t nscount;
uint16_t arcount;
uint8_t body[];
]]
--- Variable sized member
dns.headerVariableMember = body
local dnsHeader = initHeader()
dnsHeader.__index = dnsHeader
--- Set the query id.
--- @param int Id of the dns header as A bit integer.
function dnsHeader:setId(int)
int = int or math.random(10000,65335)
self.id = hton16(int)
end
--- Retrieve the id.
--- @return the qurey id as a bit integer.
function dnsHeader:getId()
return hton16(self.id)
end
--- Retrieve the id as string.
--- @return the qurey id as string.
function dnsHeader:getIdString()
return self:getId()
end
--- Set Question/Response bit:
--- 0 Question, 1 = Answer.
function dnsHeader:setQR()
self.hdrflags = bor(self.hdrflags, 0x8000)
end
--- Unset Question/Response bit:
--- 0 Question, 1 = Answer.
function dnsHeader:unsetQR()
self.hdrflags = band(self.hdrflags, 0x7FFF)
end
--- Retrieve the QR.
--- @return QR as 1 bit integer.
function dnsHeader:getQR()
return rshift(band(self.hdrflags, 0x8000), 1)
end
--- Retrieve the QR as string.
--- @return QR as string.
function dnsHeader:getQRString()
if self:getQR() == 1 then
return "R"
else
return "Q"
end
end
--- Set the OPCode: Kind of query.
--- 0 a standard query (QUERY)
--- 1 an inverse query (IQUERY)
--- 2 a server status request (STATUS)
--- 3-15 reserved for future use
--- @param int OPCode of the dns header as A bit integer.
function dnsHeader:setOPCode(int)
int = int or 0
if int >= 0 and int <= 15 then
opcode = int
--- X0000XXX XXXXXXXX
opcode = lshift(opcode,11)
self.hdrflags = bor(self.hdrflags, opcode)
end
-- TODO: handle invalid args
end
--- Retrieve the OPCode.
--- @return OPCode as A bit integer.
function dnsHeader:getOPCode()
res = rshift(band(self.hdrflags, 0x7800), 11)
return res
end
--- Retrieve the OPCode as string.
--- @return OPCode as string.
function dnsHeader:getOPCodeString()
opcode = self.getOPCode
if opcode == 0 then
return "StandardQuery"
elseif opcode == 1 then
return "InverseQuery"
elseif opcode == 2 then
return "ServerStatus"
else
return -1
end
end
--- Set Authoritative answer bit:
function dnsHeader:setAA()
self.hdrflags = bor(self.hdrflags, 0x0400)
end
--- Unset Authoritative answer bit:
function dnsHeader:unsetAA()
self.hdrflags = band(self.hdrflags, 0xFBFF)
end
--- Retrieve the AA.
--- @return AA as 1 bit integer.
function dnsHeader:getAA()
return rshift(band(self.hdrflags, 0x0400), 1)
end
--- Retrieve the AA as string.
--- @return AA as string.
function dnsHeader:getAAString()
if self:getAA() == 1 then
return "Authoritative answer"
else
return "Non-Authoritative answer"
end
end
--- Set Truncated message
function dnsHeader:setTC()
self.hdrflags = bor(self.hdrflags, 0x0200)
end
--- Unset Truncated message bit:
function dnsHeader:unsetTC()
self.hdrflags = band(self.hdrflags, 0xFDFF)
end
--- Retrieve the TA.
--- @return TA as 1 bit integer.
function dnsHeader:getTC()
return rshift(band(self.hdrflags, 0x0200), 1)
end
--- Retrieve the TA as string.
--- @return TA as string.
function dnsHeader:getTCString()
if self:getTC() == 1 then
return "Truncated message"
else
return "Non-truncated message"
end
end
--- Set Recursion Desired
function dnsHeader:setRD()
self.hdrflags = bor(self.hdrflags, 0x0100)
end
--- Unset Recursion Desired bit:
function dnsHeader:unsetRD()
self.hdrflags = band(self.hdrflags, 0xFEFF)
end
--- Retrieve the RD.
--- @return RD as 1 bit integer.
function dnsHeader:getRD()
return rshift(band(self.hdrflags, 0x0100), 1)
end
--- Retrieve the RD as string.
--- @return RD as string.
function dnsHeader:getRDString()
if self:getRD() == 1 then
return "Recursion desired"
else
return "Recursion undesired"
end
end
--- Set Recursion Available
function dnsHeader:setRA()
self.hdrflags = bor(self.hdrflags, 0x0080)
end
--- Unset Recursion Available bit:
function dnsHeader:unsetRA()
self.hdrflags = band(self.hdrflags, 0xFF7F)
end
--- Retrieve the RA.
--- @return RA as 1 bit integer.
function dnsHeader:getRA()
return rshift(band(self.hdrflags, 0x0080), 1)
end
--- Retrieve the RA as string.
--- @return RA as string.
function dnsHeader:getRAString()
if self:getRA() == 1 then
return "Recursion available"
else
return "Recursion unavailable"
end
end
--- Set the 4-bit Response code
--- 0 No error condition
--- 1 Format error
--- 2 Server failure
--- 3 Name Error
--- 4 Not Implemented
--- 5 Refused
--- 6-15 Reserved for future use.
--- @param int RCode of the dns header as A bit integer.
function dnsHeader:setRCode(int)
int = int or 0
if int >= 0 and int <= 15 then
rcode = int
--- XXXXXXXX XXXX0000
self.hdrflags = bor(self.hdrflags, rcode)
end
-- TODO: handle invalid args
end
--- Retrieve the RCode.
--- @return RCode as A bit integer.
function dnsHeader:getRCode()
res = band(self.hdrflags, 0x000F)
return res
end
--- Retrieve the RCode as string.
--- @return RCode as string.
function dnsHeader:getRCodeString()
rcode = self.getRCode
if rcode == 0 then
return "NOERROR"
elseif rcode == 1 then
return "FORMERR"
elseif rcode == 2 then
return "SERVFAIL"
elseif rcode == 3 then
return "NXDOMAIN"
elseif rcode == 4 then
return "NOTIMP"
elseif rcode == 5 then
return "REFUSED"
else
return -1
end
end
--- Set the QDCount.
--- @param int QDCount of the dns header as A bit integer.
function dnsHeader:setQDCount(int)
int = int or 0
self.qdcount = hton16(int)
end
--- Retrieve the QDCount.
--- @return QDCount as A bit integer.
function dnsHeader:getQDCount()
return hton16(self.qdcount)
end
--- Retrieve the QDCount as string.
--- @return QDCount as string.
function dnsHeader:getQDCountString()
return self:getQDCount()
end
--- Set the ANCount.
--- @param int ANCount of the dns header as A bit integer.
function dnsHeader:setANCount(int)
int = int or 0
self.ancount = hton16(int)
end
--- Retrieve the ANCount.
--- @return ANCount as A bit integer.
function dnsHeader:getANCount()
return hton16(self.ancount)
end
--- Retrieve the ANCount as string.
--- @return ANCount as string.
function dnsHeader:getANCountString()
return self:getANCount()
end
--- Set the NSCount.
--- @param int NSCount of the dns header as A bit integer.
function dnsHeader:setNSCount(int)
int = int or 0
self.nscount = hton16(int)
end
--- Retrieve the NSCount.
--- @return NSCount as A bit integer.
function dnsHeader:getNSCount()
return hton16(self.nscount)
end
--- Retrieve the NSCount as string.
--- @return NSCount as string.
function dnsHeader:getNSCountString()
return self:getNSCount()
end
--- Set the ARCount.
--- @param int ARCount of the dns header as A bit integer.
function dnsHeader:setARCount(int)
int = int or 0
self.arcount = hton16(int)
end
--- Retrieve the ARCount.
--- @return ARCount as A bit integer.
function dnsHeader:getARCount()
return hton16(self.arcount)
end
--- Retrieve the ARCount as string.
--- @return ARCount as string.
function dnsHeader:getARCountString()
return self:getARCount()
end
--- Set the Data for the remaining sections in the DNS Message.
--function dnsHeader:setMessageContent(...)
function dnsHeader:setMessageContent(...)
local args = {...}
if type(args[1]) == "table" then
self.body = args[1]
elseif type(args[1]) == "function" then
func = args[1]
self.body = func()
end
end
--- Retrieve the QueryBody.
--- @return QueryBody as bit integer array?.
function dnsHeader:getMessageContent()
-- TODO implement!
return self.body
end
--- Retrieve the QueryBody as string.
--- @return QueryBody as string.
function dnsHeader:getMessageContentString()
return self:getMessageContent()
end
--- Set all members of the dns header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- @param args Table of named arguments. Available arguments: dnsXYZ
--- @param pre prefix for namedArgs. Default 'dns'.
--- @code
--- fill() -- only default values
--- fill{ dnsXYZ=1 } -- all members are set to default values with the exception of dnsXYZ, ...
--- @endcode
function dnsHeader:fill(args, pre)
args = args or {}
pre = pre or "dns"
self:setId(args[pre .. "Id"])
if args[pre .. "Resp"] and args[pre .. "Resp"] ~= 0 then
self:setQR()
end
self:setOPCode(args[pre .. "QueryType"])
if args[pre .. "AuthAnswer"] and args[pre .. "AuthAnswer"] ~= 0 then
self:setAA()
end
if args[pre .. "Truncated"] and args[pre .. "Truncated"] ~= 0 then
self:setTC()
end
if args[pre .. "RecDesired"] and args[pre .. "RecDesired"] ~= 0 then
self:setRD()
end
if args[pre .. "RecAvailable"] and args[pre .. "RecAvailable"] ~= 0 then
self:setRA()
end
self:setRCode(args[pre .. "RCode"])
self.hdrflags = hton16(self.hdrflags)
self:setQDCount(args[pre .. "QDCount"])
self:setANCount(args[pre .. "ANCount"])
self:setNSCount(args[pre .. "NSCount"])
self:setARCount(args[pre .. "ARCount"])
self:setMessageContent(args[pre .."MessageContent"])
end
--- Retrieve the values of all members.
--- @param pre prefix for namedArgs. Default 'dns'.
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see dnsHeader:fill
function dnsHeader:get(pre)
pre = pre or "dns"
args[pre .. "Id"] = self:getId()
args[pre .. "Resp"] = self:getQR()
args[pre .. "QueryType"] = self:getOPCode()
args[pre .. "AuthoritativeAnswer"] = self:getAA()
args[pre .. "Truncation"] = self:getTC()
args[pre .. "RecursionDesired"] = self:getRD()
args[pre .. "RecursionAvailable"] = self:getRA()
args[pre .. "RCode"] = self:getRCode()
args[pre .. "QDCount"] = self:getQDCount()
args[pre .. "ANCount"] = self:getANCount()
args[pre .. "NSCount"] = self:getNSCount()
args[pre .. "ARCount"] = self:getARCount()
args[pre .. "MessageContent"] = self:getMessageContent()
--[[
-- TODO: it would be nice to implenet function to directly get
-- content something like:
args[pre .. "QuerySection" ] = self:getQuerySection()
args[pre .. "AnswerSection" ] = self:getAnswerSection()
args[pre .. "AuthoritativeNSSection" ] = self:getNSSection()
args[pre .. "AdditionalRRSection" ] = self:getARSection()
]]--
return args
end
--- Retrieve the values of all members.
--- @return Values in string format.
function dnsHeader:getString()
return "DNS"
.. " Transation ID: " .. self:getIdString()
.. " Response/Query: " .. self:getQRString()
.. " Kind of query: " .. self:getOPCodeString()
.. " Authoritative Answer: " .. self:getAAString()
.. " Truncated message: " .. self:getTCString()
.. " Recursion desired: " .. self:getRDString()
.. " Recursion available: " .. self:getRAString()
.. " Response Code: " .. self:getRCodeString()
.. " QDCount: " .. self:getQDCountString()
.. " ANCount: " .. self:getANCountString()
.. " NSCount: " .. self:getNSCountString()
.. " ARCount: " .. self:getARCountString()
.. " MessageContent: " .. self:getMessageContentString()
end
------------------------------------------------------------------------
---- Metatypes
------------------------------------------------------------------------
dns.metatype = dnsHeader
return dns
| mit |
takaaptech/nightmaretris | 3rdparty/underscore.lua | 22 | 9838 | -- Copyright (c) 2009 Marcus Irven
--
-- 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.
--- Underscore is a set of utility functions for dealing with
-- iterators, arrays, tables, and functions.
local Underscore = { funcs = {} }
Underscore.__index = Underscore
function Underscore.__call(_, value)
return Underscore:new(value)
end
function Underscore:new(value, chained)
return setmetatable({ _val = value, chained = chained or false }, self)
end
function Underscore.iter(list_or_iter)
if type(list_or_iter) == "function" then return list_or_iter end
return coroutine.wrap(function()
for i=1,#list_or_iter do
coroutine.yield(list_or_iter[i])
end
end)
end
function Underscore.range(start_i, end_i, step)
if end_i == nil then
end_i = start_i
start_i = 1
end
step = step or 1
local range_iter = coroutine.wrap(function()
for i=start_i, end_i, step do
coroutine.yield(i)
end
end)
return Underscore:new(range_iter)
end
--- Identity function. This function looks useless, but is used throughout Underscore as a default.
-- @name _.identity
-- @param value any object
-- @return value
-- @usage _.identity("foo")
-- => "foo"
function Underscore.identity(value)
return value
end
-- chaining
function Underscore:chain()
self.chained = true
return self
end
function Underscore:value()
return self._val
end
-- iter
function Underscore.funcs.each(list, func)
for i in Underscore.iter(list) do
func(i)
end
return list
end
function Underscore.funcs.map(list, func)
local mapped = {}
for i in Underscore.iter(list) do
mapped[#mapped+1] = func(i)
end
return mapped
end
function Underscore.funcs.reduce(list, memo, func)
for i in Underscore.iter(list) do
memo = func(memo, i)
end
return memo
end
function Underscore.funcs.detect(list, func)
for i in Underscore.iter(list) do
if func(i) then return i end
end
return nil
end
function Underscore.funcs.select(list, func)
local selected = {}
for i in Underscore.iter(list) do
if func(i) then selected[#selected+1] = i end
end
return selected
end
function Underscore.funcs.reject(list, func)
local selected = {}
for i in Underscore.iter(list) do
if not func(i) then selected[#selected+1] = i end
end
return selected
end
function Underscore.funcs.all(list, func)
func = func or Underscore.identity
-- TODO what should happen with an empty list?
for i in Underscore.iter(list) do
if not func(i) then return false end
end
return true
end
function Underscore.funcs.any(list, func)
func = func or Underscore.identity
-- TODO what should happen with an empty list?
for i in Underscore.iter(list) do
if func(i) then return true end
end
return false
end
function Underscore.funcs.include(list, value)
for i in Underscore.iter(list) do
if i == value then return true end
end
return false
end
function Underscore.funcs.invoke(list, function_name, ...)
local args = {...}
Underscore.funcs.each(list, function(i) i[function_name](i, unpack(args)) end)
return list
end
function Underscore.funcs.pluck(list, propertyName)
return Underscore.funcs.map(list, function(i) return i[propertyName] end)
end
function Underscore.funcs.min(list, func)
func = func or Underscore.identity
return Underscore.funcs.reduce(list, { item = nil, value = nil }, function(min, item)
if min.item == nil then
min.item = item
min.value = func(item)
else
local value = func(item)
if value < min.value then
min.item = item
min.value = value
end
end
return min
end).item
end
function Underscore.funcs.max(list, func)
func = func or Underscore.identity
return Underscore.funcs.reduce(list, { item = nil, value = nil }, function(max, item)
if max.item == nil then
max.item = item
max.value = func(item)
else
local value = func(item)
if value > max.value then
max.item = item
max.value = value
end
end
return max
end).item
end
function Underscore.funcs.to_array(list)
local array = {}
for i in Underscore.iter(list) do
array[#array+1] = i
end
return array
end
function Underscore.funcs.reverse(list)
local reversed = {}
for i in Underscore.iter(list) do
table.insert(reversed, 1, i)
end
return reversed
end
function Underscore.funcs.sort(iter, comparison_func)
local array = iter
if type(iter) == "function" then
array = Underscore.funcs.to_array(iter)
end
table.sort(array, comparison_func)
return array
end
-- arrays
function Underscore.funcs.first(array, n)
if n == nil then
return array[1]
else
local first = {}
n = math.min(n,#array)
for i=1,n do
first[i] = array[i]
end
return first
end
end
function Underscore.funcs.rest(array, index)
index = index or 2
local rest = {}
for i=index,#array do
rest[#rest+1] = array[i]
end
return rest
end
function Underscore.funcs.slice(array, start_index, length)
local sliced_array = {}
start_index = math.max(start_index, 1)
local end_index = math.min(start_index+length-1, #array)
for i=start_index, end_index do
sliced_array[#sliced_array+1] = array[i]
end
return sliced_array
end
function Underscore.funcs.flatten(array)
local all = {}
for ele in Underscore.iter(array) do
if type(ele) == "table" then
local flattened_element = Underscore.funcs.flatten(ele)
Underscore.funcs.each(flattened_element, function(e) all[#all+1] = e end)
else
all[#all+1] = ele
end
end
return all
end
function Underscore.funcs.push(array, item)
table.insert(array, item)
return array
end
function Underscore.funcs.pop(array)
return table.remove(array)
end
function Underscore.funcs.shift(array)
return table.remove(array, 1)
end
function Underscore.funcs.unshift(array, item)
table.insert(array, 1, item)
return array
end
function Underscore.funcs.join(array, separator)
return table.concat(array, separator)
end
-- objects
function Underscore.funcs.keys(obj)
local keys = {}
for k,v in pairs(obj) do
keys[#keys+1] = k
end
return keys
end
function Underscore.funcs.values(obj)
local values = {}
for k,v in pairs(obj) do
values[#values+1] = v
end
return values
end
function Underscore.funcs.extend(destination, source)
for k,v in pairs(source) do
destination[k] = v
end
return destination
end
function Underscore.funcs.is_empty(obj)
return next(obj) == nil
end
-- Originally based on penlight's deepcompare() -- http://luaforge.net/projects/penlight/
function Underscore.funcs.is_equal(o1, o2, ignore_mt)
local ty1 = type(o1)
local ty2 = type(o2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' then return o1 == o2 end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(o1)
if not ignore_mt and mt and mt.__eq then return o1 == o2 end
local is_equal = Underscore.funcs.is_equal
for k1,v1 in pairs(o1) do
local v2 = o2[k1]
if v2 == nil or not is_equal(v1,v2, ignore_mt) then return false end
end
for k2,v2 in pairs(o2) do
local v1 = o1[k2]
if v1 == nil then return false end
end
return true
end
-- functions
function Underscore.funcs.compose(...)
local function call_funcs(funcs, ...)
if #funcs > 1 then
return funcs[1](call_funcs(_.rest(funcs), ...))
else
return funcs[1](...)
end
end
local funcs = {...}
return function(...)
return call_funcs(funcs, ...)
end
end
function Underscore.funcs.wrap(func, wrapper)
return function(...)
return wrapper(func, ...)
end
end
function Underscore.funcs.curry(func, argument)
return function(...)
return func(argument, ...)
end
end
function Underscore.functions()
return Underscore.keys(Underscore.funcs)
end
-- add aliases
Underscore.methods = Underscore.functions
Underscore.funcs.for_each = Underscore.funcs.each
Underscore.funcs.collect = Underscore.funcs.map
Underscore.funcs.inject = Underscore.funcs.reduce
Underscore.funcs.foldl = Underscore.funcs.reduce
Underscore.funcs.filter = Underscore.funcs.select
Underscore.funcs.every = Underscore.funcs.all
Underscore.funcs.some = Underscore.funcs.any
Underscore.funcs.head = Underscore.funcs.first
Underscore.funcs.tail = Underscore.funcs.rest
local function wrap_functions_for_oo_support()
local function value_and_chained(value_or_self)
local chained = false
if getmetatable(value_or_self) == Underscore then
chained = value_or_self.chained
value_or_self = value_or_self._val
end
return value_or_self, chained
end
local function value_or_wrap(value, chained)
if chained then value = Underscore:new(value, true) end
return value
end
for fn, func in pairs(Underscore.funcs) do
Underscore[fn] = function(obj_or_self, ...)
local obj, chained = value_and_chained(obj_or_self)
return value_or_wrap(func(obj, ...), chained)
end
end
end
wrap_functions_for_oo_support()
return Underscore:new()
| gpl-3.0 |
ASDF482/TeleTak | plugins/welcome.lua | 1 | 3620 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi im TeleTak. Best Anti spammer bot. "..nama.." Welcome to [ "..string.gsub(msg.to.print_name, "_", " ").." ]"
local text = sambutan.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye Bye '..bye_name..' ???'
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
} | gpl-2.0 |
MalRD/darkstar | scripts/globals/items/roll_of_sylvan_excursion.lua | 11 | 1300 | -----------------------------------------
-- ID: 5551
-- Item: Roll of Sylvan Excursion
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10
-- MP +3% Cap 15
-- Intelligence +3
-- HP Recovered while healing +2
-- MP Recovered while healing +5
-----------------------------------------
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,14400,5551)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_MPP, 3)
target:addMod(dsp.mod.FOOD_MP_CAP, 15)
target:addMod(dsp.mod.HP, 10)
target:addMod(dsp.mod.INT, 3)
target:addMod(dsp.mod.HPHEAL, 2)
target:addMod(dsp.mod.MPHEAL, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_MPP, 3)
target:delMod(dsp.mod.FOOD_MP_CAP, 15)
target:delMod(dsp.mod.HP, 10)
target:delMod(dsp.mod.INT, 3)
target:delMod(dsp.mod.HPHEAL, 2)
target:delMod(dsp.mod.MPHEAL, 5)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c48653261.lua | 3 | 1412 | --ガードペナルティ
function c48653261.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c48653261.target)
e1:SetOperation(c48653261.activate)
c:RegisterEffect(e1)
end
function c48653261.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) end
if chk==0 then return Duel.IsExistingTarget(nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c48653261.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHANGE_POS)
e1:SetCountLimit(1)
e1:SetCondition(c48653261.drcon)
e1:SetOperation(c48653261.drop)
e1:SetLabel(tc:GetRealFieldID())
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
end
function c48653261.filter(c,fid)
return c:GetRealFieldID()==fid and c:IsDefencePos() and c:IsPreviousPosition(POS_ATTACK)
end
function c48653261.drcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c48653261.filter,1,nil,e:GetLabel())
end
function c48653261.drop(e,tp,eg,ep,ev,re,r,rp)
Duel.Draw(tp,1,REASON_EFFECT)
e:Reset()
end
| gpl-2.0 |
gallenmu/MoonGen | interface/devmgr.lua | 4 | 1348 | local device = require "device"
local devicesClass = {}
function devicesClass:reserveTx(tx)
self[tx].txq = self[tx].txq + 1
end
function devicesClass:reserveRx(rx)
self[rx].rxq = self[rx].rxq + 1
end
function devicesClass:reserveRss(rss)
self[rss].rxq = self[rss].rxq + 1
self[rss].rsq = self[rss].rsq + 1
end
local function _inc(tbl, key)
local result = tbl[key]
tbl[key] = result + 1
return result
end
function devicesClass:txQueue(tx)
return self[tx].dev:getTxQueue(_inc(self[tx], "txqi"))
end
function devicesClass:rxQueue(rx)
return self[rx].dev:getRxQueue(self[rx].rsq + _inc(self[rx], "rxqi"))
end
function devicesClass:rssQueue(rx)
return self[rx].dev:getRxQueue(_inc(self[rx], "rsqi"))
end
function devicesClass:configure()
for i,v in pairs(self) do
local txq, rxq = v.txq, v.rxq
txq, rxq = (txq == 0) and 1 or txq, (rxq == 0) and 1 or rxq
v.dev = device.config{ port = i, rxQueues = rxq, rssQueues = v.rsq, txQueues = txq }
end
device.waitForLinks()
end
local mod = {}
function mod.newDevmgr()
return setmetatable({ }, {
__index = function(tbl, key)
if key == "max" then
return device.numDevices()
elseif type(key) ~= "number" then
return devicesClass[key]
end
local r = { rxq = 0, rsq = 0, txq = 0, rxqi = 0, rsqi = 0, txqi = 0 }
tbl[key] = r; return r
end
})
end
return mod
| mit |
MalRD/darkstar | scripts/zones/Waughroon_Shrine/bcnms/up_in_arms.lua | 9 | 1061 | -----------------------------------
-- Up in Arms
-- Waughroon Shrine BCNM60, Moon Orb
-- !additem 1130
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c63422098.lua | 3 | 1031 | --鬼岩城
function c63422098.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(c63422098.val)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENCE)
c:RegisterEffect(e2)
--
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetOperation(c63422098.regop)
c:RegisterEffect(e3)
end
function c63422098.val(e,c)
local ct=e:GetHandler():GetFlagEffectLabel(63422098)
if not ct then return 0 end
return ct
end
function c63422098.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:GetSummonType()==SUMMON_TYPE_SYNCHRO then
local ct=c:GetMaterialCount()-1
c:RegisterFlagEffect(63422098,RESET_EVENT+0x1fe0000,0,0,ct*200)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c78734254.lua | 7 | 1821 | --N・マリン・ドルフィン
function c78734254.initial_effect(c)
c:EnableReviveLimit()
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--Activate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(78734254,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCost(c78734254.cost)
e2:SetTarget(c78734254.target)
e2:SetOperation(c78734254.activate)
c:RegisterEffect(e2)
--add code
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EFFECT_ADD_CODE)
e4:SetValue(17955766)
c:RegisterEffect(e4)
end
function c78734254.cost(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_COST+REASON_DISCARD)
end
function c78734254.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
end
function c78734254.filter(c,atk)
return c:IsFaceup() and c:IsAttackAbove(atk)
end
function c78734254.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND)
if g:GetCount()>0 then
Duel.ConfirmCards(tp,g)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(78734254,1))
local tg=g:FilterSelect(tp,Card.IsType,1,1,nil,TYPE_MONSTER)
local tc=tg:GetFirst()
if tc then
local atk=tc:GetAttack()
if atk>=0 and Duel.IsExistingMatchingCard(c78734254.filter,tp,LOCATION_MZONE,0,1,nil,atk) then
Duel.Destroy(tc,REASON_EFFECT)
Duel.Damage(1-tp,500,REASON_EFFECT)
end
end
Duel.ShuffleHand(1-tp)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Southern_San_dOria/npcs/Daggao.lua | 9 | 1489 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Daggao
-- Involved in Quest: Peace for the Spirit, Lure of the Wildcat (San d'Oria)
-- !pos 89 0 119 230
-----------------------------------
require("scripts/globals/quests");
local ID = require("scripts/zones/Southern_San_dOria/IDs");
-----------------------------------
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)
local WildcatSandy = player:getCharVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,0) == false) then
player:startEvent(810);
elseif (player:getCharVar("peaceForTheSpiritCS") == 3) then
player:startEvent(72);
elseif (player:getCharVar("peaceForTheSpiritCS") == 5) then
player:startEvent(73);
else
player:startEvent(60);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 810) then
player:setMaskBit(player:getCharVar("WildcatSandy"),"WildcatSandy",0,true);
elseif (csid == 72) then
player:setCharVar("peaceForTheSpiritCS",4);
end
end; | gpl-3.0 |
Frenzie/koreader | frontend/document/canvascontext.lua | 4 | 3273 | --[[
CanvasContext is introduced to abstract out screen hardware code from document
render module. This abstraction makes it possible to use core document module
in headless mode.
You can think of canvas as a virtual screen. It provides render related
settings like canvas dimension and DPI. User of document module need to
initialize CanvasContext with settings from the actual hardware screen before
calling renderPage/drawPage.
Note: CanvasContext is a singleton and it is not thread safe.
]]--
local Mupdf = require("ffi/mupdf")
local CanvasContext = {
is_color_rendering_enabled = false,
is_bgr = false,
}
--[[
Initialize CanvasContext with settings from device.
The following key is required for a device object:
* hasBGRFrameBuffer: function() -> boolean
* screen: object with following methods:
* getWidth() -> int
* getHeight() -> int
* getDPI() -> int
* getSize() -> Rect
* scaleBySize(int) -> int
* isColorEnabled() -> boolean
]]--
function CanvasContext:init(device)
self.device = device
self.screen = device.screen
-- NOTE: These work because they don't actually require accessing the Device object itself,
-- as opposed to more dynamic methods like the Screen ones we handle properly later...
-- By which I mean when one naively calls CanvasContext:isKindle(), it calls
-- device.isKindle(CanvasContext), whereas when one calls Device:isKindle(), it calls
-- Device.isKindle(Device).
-- In the latter case, self is sane, but *NOT* in the former.
-- TL;DR: The methods assigned below must *never* access self.
-- (Or programmers would have to be careful to call them through CanvasContext as functions,
-- and not methods, which is clunky, error-prone, and unexpected).
self.isAndroid = device.isAndroid
self.isDesktop = device.isDesktop
self.isEmulator = device.isEmulator
self.isKindle = device.isKindle
self.isPocketBook = device.isPocketBook
self.hasSystemFonts = device.hasSystemFonts
self:setColorRenderingEnabled(device.screen:isColorEnabled())
-- NOTE: At 32bpp, Kobo's fb is BGR, not RGB. Handle the conversion in MuPDF if needed.
if device:hasBGRFrameBuffer() then
self.is_bgr = true
Mupdf.bgr = true
end
-- This one may be called by a subprocess, and would crash on Android when
-- calling android.isEink() which is only allowed from the main thread.
local hasEinkScreen = device:hasEinkScreen()
self.hasEinkScreen = function() return hasEinkScreen end
self.canHWDither = device.canHWDither
self.fb_bpp = device.screen.fb_bpp
end
function CanvasContext:setColorRenderingEnabled(val)
self.is_color_rendering_enabled = val
end
function CanvasContext:getWidth()
return self.screen:getWidth()
end
function CanvasContext:getHeight()
return self.screen:getHeight()
end
function CanvasContext:getDPI()
return self.screen:getDPI()
end
function CanvasContext:getSize()
return self.screen:getSize()
end
function CanvasContext:scaleBySize(px)
return self.screen:scaleBySize(px)
end
function CanvasContext:enableCPUCores(amount)
return self.device:enableCPUCores(amount)
end
return CanvasContext
| agpl-3.0 |
nmabhi/Webface | training/util.lua | 8 | 2973 | -- Source: https://github.com/soumith/imagenet-multiGPU.torch/blob/master/util.lua
local ffi=require 'ffi'
------ Some FFI stuff used to pass storages between threads ------------------
ffi.cdef[[
void THFloatStorage_free(THFloatStorage *self);
void THLongStorage_free(THLongStorage *self);
]]
local function setFloatStorage(tensor, storage_p)
assert(storage_p and storage_p ~= 0, "FloatStorage is NULL pointer");
local cstorage = ffi.cast('THFloatStorage*', torch.pointer(tensor:storage()))
if cstorage ~= nil then
ffi.C['THFloatStorage_free'](cstorage)
end
local storage = ffi.cast('THFloatStorage*', storage_p)
tensor:cdata().storage = storage
end
local function setLongStorage(tensor, storage_p)
assert(storage_p and storage_p ~= 0, "LongStorage is NULL pointer");
local cstorage = ffi.cast('THLongStorage*', torch.pointer(tensor:storage()))
if cstorage ~= nil then
ffi.C['THLongStorage_free'](cstorage)
end
local storage = ffi.cast('THLongStorage*', storage_p)
tensor:cdata().storage = storage
end
function sendTensor(inputs)
local size = inputs:size()
local ttype = inputs:type()
local i_stg = tonumber(ffi.cast('intptr_t', torch.pointer(inputs:storage())))
inputs:cdata().storage = nil
return {i_stg, size, ttype}
end
function receiveTensor(obj, buffer)
local pointer = obj[1]
local size = obj[2]
local ttype = obj[3]
if buffer then
buffer:resize(size)
assert(buffer:type() == ttype, 'Buffer is wrong type')
else
buffer = torch[ttype].new():resize(size)
end
if ttype == 'torch.FloatTensor' then
setFloatStorage(buffer, pointer)
elseif ttype == 'torch.LongTensor' then
setLongStorage(buffer, pointer)
else
error('Unknown type')
end
return buffer
end
--Reduce the memory consumption by model by sharing the buffers
function optimizeNet( model, inputSize )
local optnet_loaded, optnet = pcall(require,'optnet')
if optnet_loaded then
local opts = {inplace=true, mode='training', removeGradParams=false}
local input = torch.rand(2,3,inputSize,inputSize)
if opt.cuda then
input = input:cuda()
end
optnet.optimizeMemory(model, input, opts)
else
print("'optnet' package not found, install it to reduce the memory consumption.")
print("Repo: https://github.com/fmassa/optimize-net")
end
end
function makeDataParallel(model, nGPU)
-- Wrap the model with DataParallelTable, if using more than one GPU
if nGPU > 1 then
local gpus = torch.range(1, nGPU):totable()
local fastest, benchmark = cudnn.fastest, cudnn.benchmark
local dpt = nn.DataParallelTable(1, true, true)
:add(model, gpus)
:threads(function()
require ("dpnn")
local cudnn = require 'cudnn'
cudnn.fastest, cudnn.benchmark = fastest, benchmark
end)
dpt.gradInput = nil
model = dpt:cuda()
end
return model
end
| apache-2.0 |
Lsty/ygopro-scripts | c60634565.lua | 3 | 1258 | --レプティレス・ラミア
function c60634565.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x3c),aux.NonTuner(nil),1)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(60634565,0))
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c60634565.descon)
e1:SetTarget(c60634565.destg)
e1:SetOperation(c60634565.desop)
c:RegisterEffect(e1)
end
function c60634565.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO
end
function c60634565.desfilter(c)
return c:IsFaceup() and c:GetAttack()==0 and c:IsDestructable()
end
function c60634565.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=Duel.GetMatchingGroup(c60634565.desfilter,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,g:GetCount())
end
function c60634565.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c60634565.desfilter,tp,0,LOCATION_MZONE,nil)
local ct=Duel.Destroy(g,REASON_EFFECT)
Duel.Draw(tp,ct,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c32646477.lua | 5 | 1420 | --ダーク・ダイブ・ボンバー
function c32646477.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(32646477,0))
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,32646477)
e1:SetCondition(c32646477.condition)
e1:SetCost(c32646477.cost)
e1:SetTarget(c32646477.target)
e1:SetOperation(c32646477.operation)
c:RegisterEffect(e1)
end
function c32646477.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_MAIN1
end
function c32646477.costfilter(c)
return c:GetLevel()>0
end
function c32646477.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c32646477.costfilter,1,nil) end
local g=Duel.SelectReleaseGroup(tp,c32646477.costfilter,1,1,nil)
e:SetLabel(g:GetFirst():GetLevel()*200)
Duel.Release(g,REASON_COST)
end
function c32646477.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(e:GetLabel())
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,e:GetLabel())
e:SetLabel(0)
end
function c32646477.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 |
Lsty/ygopro-scripts | c981540.lua | 3 | 1428 | --ハーフ・アンブレイク
function c981540.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c981540.target)
e1:SetOperation(c981540.activate)
c:RegisterEffect(e1)
end
function c981540.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) end
if chk==0 then return Duel.IsExistingTarget(nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c981540.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PRE_BATTLE_DAMAGE)
e2:SetCondition(c981540.rdcon)
e2:SetOperation(c981540.rdop)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e2)
end
end
function c981540.rdcon(e,tp,eg,ep,ev,re,r,rp)
return ep==e:GetOwnerPlayer()
end
function c981540.rdop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeBattleDamage(ep,ev/2)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Selbina/npcs/Melyon.lua | 9 | 2810 | -----------------------------------
-- Area: Selbina
-- NPC: Melyon
-- Starts and Finishes Quest: Only the Best (R)
-- Involved in Quest: Riding on the Clouds
-- !pos 25 -6 6 248
-----------------------------------
local ID = require("scripts/zones/Selbina/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
if
player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and
player:getCharVar("ridingOnTheClouds_3") == 3 and
npcUtil.tradeHas(trade, 1127)
then
player:setCharVar("ridingOnTheClouds_3", 0)
npcUtil.giveKeyItem(player, dsp.ki.SOMBER_STONE)
player:confirmTrade()
elseif player:getQuestStatus(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST) ~= QUEST_AVAILABLE then
if npcUtil.tradeHas(trade, {{4366, 5}}) then -- La Theine Cabbage x5
player:startEvent(62)
elseif npcUtil.tradeHas(trade, {{629, 3}}) then -- Millioncorn x3
player:startEvent(63)
elseif npcUtil.tradeHas(trade, 919) then -- Boyahda Moss x1
player:startEvent(64)
end
end
end
function onTrigger(player,npc)
if player:getQuestStatus(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST) == QUEST_AVAILABLE then
player:startEvent(60, 4366, 629, 919) -- Start quest "Only the Best"
else
player:startEvent(61, 4366, 629, 919) -- During & after completed quest "Only the Best"
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 60 and option == 10 then
player:addQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST)
elseif csid == 62 then
player:addGil(100)
player:messageSpecial(ID.text.GIL_OBTAINED, 100)
player:addFame(BASTOK, 10)
player:addFame(SANDORIA, 10)
player:addFame(JEUNO, 10)
player:completeQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST)
player:confirmTrade()
elseif (csid == 63) then
player:addGil(120)
player:messageSpecial(ID.text.GIL_OBTAINED, 120)
player:addFame(BASTOK, 20)
player:addFame(SANDORIA, 20)
player:addFame(JEUNO, 20)
player:completeQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST)
player:confirmTrade()
elseif (csid == 64) then
player:addGil(600)
player:messageSpecial(ID.text.GIL_OBTAINED, 600)
player:addFame(BASTOK, 30)
player:addFame(SANDORIA, 30)
player:addFame(JEUNO, 30)
player:completeQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.ONLY_THE_BEST)
player:confirmTrade()
end
end | gpl-3.0 |
Lsty/ygopro-scripts | c57827484.lua | 5 | 1431 | --シャドウ・ダイバー
function c57827484.initial_effect(c)
aux.EnableDualAttribute(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(57827484,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c57827484.condition)
e1:SetTarget(c57827484.target)
e1:SetOperation(c57827484.operation)
c:RegisterEffect(e1)
end
function c57827484.condition(e,tp,eg,ep,ev,re,r,rp)
return aux.IsDualState(e) and Duel.GetCurrentPhase()==PHASE_MAIN1
end
function c57827484.filter(c)
return c:IsFaceup() and c:IsLevelBelow(4) and c:IsAttribute(ATTRIBUTE_DARK) and not c:IsHasEffect(EFFECT_DIRECT_ATTACK)
end
function c57827484.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c57827484.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c57827484.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c57827484.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c57827484.operation(e,tp,eg,ep,ev,re,r,rp,chk)
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_DIRECT_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c34026662.lua | 3 | 1271 | --進化の奇跡
function c34026662.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c34026662.target)
e1:SetOperation(c34026662.activate)
c:RegisterEffect(e1)
end
function c34026662.filter(c)
local st=c:GetSummonType()
return c:IsFaceup() and st>=(SUMMON_TYPE_SPECIAL+150) and st<(SUMMON_TYPE_SPECIAL+180)
end
function c34026662.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c34026662.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c34026662.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c34026662.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c34026662.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
e1:SetValue(1)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Crawlers_Nest/mobs/Aqrabuamelu.lua | 11 | 1468 | -----------------------------------
-- Area: Crawlers' Nest
-- NM: Aqrabuamelu
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(dsp.mobMod.AUTO_SPIKES, 1)
mob:addStatusEffect(dsp.effect.ICE_SPIKES, 45, 0, 0)
mob:getStatusEffect(dsp.effect.ICE_SPIKES):setFlag(dsp.effectFlag.DEATH)
end
function onSpikesDamage(mob, target, damage)
local INT_diff = mob:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
if INT_diff > 20 then
INT_diff = 20 + (INT_diff - 20) * 0.5 -- INT above 20 is half as effective.
end
local dmg = (damage + INT_diff) * 0.5 -- INT adjustment and base damage averaged together.
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(mob, dsp.magic.ele.ICE, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(mob, target, dsp.magic.ele.ICE, 0)
dmg = adjustForTarget(target, dmg, dsp.magic.ele.ICE)
dmg = finalMagicNonSpellAdjustments(mob, target, dsp.magic.ele.ICE, dmg)
if dmg < 0 then
dmg = 0
end
return dsp.subEffect.ICE_SPIKES, dsp.msg.basic.SPIKES_EFFECT_DMG, dmg
end
function onMobDeath(mob, player, isKiller)
end
function onMobDespawn(mob)
UpdateNMSpawnPoint(mob:getID())
mob:setRespawnTime(math.random(7200, 7800)) -- 120 to 130 min
end | gpl-3.0 |
MalRD/darkstar | scripts/zones/Northern_San_dOria/npcs/Maloquedil.lua | 9 | 3283 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Maloquedil
-- Involved in Quest : Warding Vampires, Riding on the Clouds, Lure of the Wildcat (San d'Oria)
-- !pos 35 0.1 60 231
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
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
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.WARDING_VAMPIRES) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(1018,2) and trade:getItemCount() == 2) then -- Trade Shaman Garlic
player:startEvent(23);
end
end
if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getCharVar("ridingOnTheClouds_1") == 4) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setCharVar("ridingOnTheClouds_1",0);
player:tradeComplete();
player:addKeyItem(dsp.ki.SCOWLING_STONE);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SCOWLING_STONE);
end
end
end;
function onTrigger(player,npc)
local warding = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.WARDING_VAMPIRES);
local WildcatSandy = player:getCharVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,7) == false) then
player:startEvent(807);
elseif (warding == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then --Quest available for fame superior or equal to 3
player:startEvent(24);
elseif (warding == QUEST_ACCEPTED) then --Quest accepted, and he just tell me where to get item.
player:startEvent(22);
elseif (warding == QUEST_COMPLETED) then --Since the quest is repeatable, he tells me where to find (again) the items.
player:startEvent(22);
else
player:startEvent(21);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 24 and option == 1) then
player:addQuest(SANDORIA,dsp.quest.id.sandoria.WARDING_VAMPIRES);
elseif (csid == 23) then
player:tradeComplete();
player:addTitle(dsp.title.VAMPIRE_HUNTER_DMINUS);
player:addGil(GIL_RATE*900);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*900);
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.WARDING_VAMPIRES) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.WARDING_VAMPIRES);
else
player:addFame(SANDORIA,5);
end
elseif (csid == 807) then
player:setMaskBit(player:getCharVar("WildcatSandy"),"WildcatSandy",7,true);
end
end;
| gpl-3.0 |
patixx/bostg | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.