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 |
|---|---|---|---|---|---|
FFXIOrgins/FFXIOrgins | scripts/zones/Metalworks/npcs/Pius.lua | 23 | 1832 | -----------------------------------
-- Area: Metalworks
-- NPC: Pius
-- Involved In Mission: Journey Abroad
-- @pos 99 -21 -12 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Mission = player:getCurrentMission(player:getNation());
MissionStatus = player:getVar("MissionStatus");
if(Mission == JOURNEY_TO_BASTOK and MissionStatus == 3 or
Mission == JOURNEY_TO_BASTOK2 and MissionStatus == 8) then
player:startEvent(0x0163);
elseif(Mission == THE_THREE_KINGDOMS_BASTOK and MissionStatus == 3 or
Mission == THE_THREE_KINGDOMS_BASTOK2 and MissionStatus == 8) then
player:startEvent(0x0163,1);
elseif(Mission == JOURNEY_TO_BASTOK or
Mission == JOURNEY_TO_BASTOK2 or
Mission == THE_THREE_KINGDOMS_BASTOK2 and MissionStatus < 11) then
player:startEvent(0x0164);
else
player:startEvent(0x015e);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0163) then
if(player:getVar("MissionStatus") == 3) then
player:setVar("MissionStatus",4);
else
player:setVar("MissionStatus",9);
end
end
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/abilities/dark_shot.lua | 4 | 2320 | -----------------------------------
-- Ability: Dark Shot
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
--ranged weapon/ammo: You do not have an appropriate ranged weapon equipped.
--no card: <name> cannot perform that action.
if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then
return 216,0;
end
if (player:hasItem(2183, 0) or player:hasItem(2974, 0)) then
return 0,0;
else
return 71, 0;
end
end;
function OnUseAbility(player, target, ability)
local duration = 60;
local resist = applyResistanceAbility(player,target,ELE_DARK,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY));
if(resist < 0.25) then
ability:setMsg(324);--resist message
return 0;
end
duration = duration * resist;
local effects = {};
local counter = 1;
local bio = target:getStatusEffect(EFFECT_BIO);
if (bio ~= nil) then
effects[counter] = bio;
counter = counter + 1;
end
local threnody = target:getStatusEffect(EFFECT_THRENODY);
if (threnody ~= nil and threnody:getSubPower() == MOD_LIGHTRES) then
effects[counter] = threnody;
counter = counter + 1;
end
if counter > 1 then
local effect = effects[math.random(1, counter-1)];
local duration = effect:getDuration();
local startTime = effect:getStartTime();
local tick = effect:getTick();
local power = effect:getPower();
local subpower = effect:getSubPower();
local tier = effect:getTier();
local effectId = effect:getType();
local subId = effect:getSubType();
power = power * 1.5;
subpower = subpower * 1.5;
target:delStatusEffectSilent(effectId);
target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier);
local newEffect = target:getStatusEffect(effectId);
newEffect:setStartTime(startTime);
end
ability:setMsg(321);
local dispelledEffect = target:dispelStatusEffect();
if(dispelledEffect == EFFECT_NONE) then
-- no effect
ability:setMsg(323);
end
return dispelledEffect;
end; | gpl-3.0 |
Laendasill/waifu2x | cleanup_model.lua | 34 | 1775 | require './lib/portable'
require './lib/LeakyReLU'
torch.setdefaulttensortype("torch.FloatTensor")
-- ref: https://github.com/torch/nn/issues/112#issuecomment-64427049
local function zeroDataSize(data)
if type(data) == 'table' then
for i = 1, #data do
data[i] = zeroDataSize(data[i])
end
elseif type(data) == 'userdata' then
data = torch.Tensor():typeAs(data)
end
return data
end
-- Resize the output, gradInput, etc temporary tensors to zero (so that the
-- on disk size is smaller)
local function cleanupModel(node)
if node.output ~= nil then
node.output = zeroDataSize(node.output)
end
if node.gradInput ~= nil then
node.gradInput = zeroDataSize(node.gradInput)
end
if node.finput ~= nil then
node.finput = zeroDataSize(node.finput)
end
if tostring(node) == "nn.LeakyReLU" then
if node.negative ~= nil then
node.negative = zeroDataSize(node.negative)
end
end
if tostring(node) == "nn.Dropout" then
if node.noise ~= nil then
node.noise = zeroDataSize(node.noise)
end
end
-- Recurse on nodes with 'modules'
if (node.modules ~= nil) then
if (type(node.modules) == 'table') then
for i = 1, #node.modules do
local child = node.modules[i]
cleanupModel(child)
end
end
end
collectgarbage()
end
local cmd = torch.CmdLine()
cmd:text()
cmd:text("cleanup model")
cmd:text("Options:")
cmd:option("-model", "./model.t7", 'path of model file')
cmd:option("-iformat", "binary", 'input format')
cmd:option("-oformat", "binary", 'output format')
local opt = cmd:parse(arg)
local model = torch.load(opt.model, opt.iformat)
if model then
cleanupModel(model)
torch.save(opt.model, model, opt.oformat)
else
error("model not found")
end
| mit |
mahdikord/mahdibaryaji | bot/utils.lua | 239 | 13499 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
| gpl-2.0 |
KnightTeam/Knight | bot/utils.lua | 26 | 31633 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = (loadfile "./libs/serpent.lua")()
feedparser = (loadfile "./libs/feedparser.lua")()
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
if msg.to.type == 'channel' then
return 'channel#id'..msg.to.id
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "data/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
if not text or type(text) == 'boolean' then
return
end
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
function post_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
post_large_msg_callback(cb_extra, true)
end
function post_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
post_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
post_msg(destination, my_text, post_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
-- Workarrond to format the message as previously was received
function backward_msg_format (msg)
for k,name in pairs({'from', 'to'}) do
local longid = msg[name].id
msg[name].id = msg[name].peer_id
msg[name].peer_id = longid
msg[name].type = msg[name].peer_type
end
if msg.action and (msg.action.user or msg.action.link_issuer) then
local user = msg.action.user or msg.action.link_issuer
local longid = user.id
user.id = user.peer_id
user.peer_id = longid
user.type = user.peer_type
end
return msg
end
--Table Sort
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
--End Table Sort
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(chat)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local groups = 'groups'
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(chat)] then
if msg.to.type == 'chat' then
var = true
end
end
return var
end
end
function is_super_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local groups = 'groups'
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(chat)] then
if msg.to.type == 'channel' then
var = true
end
return var
end
end
end
function is_log_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local GBan_log = 'GBan_log'
if data[tostring(GBan_log)] then
if data[tostring(GBan_log)][tostring(msg.to.id)] then
if msg.to.type == 'channel' then
var = true
end
return var
end
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin1(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user_id)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user_any(user_id, chat_id)
local channel = 'channel#id'..chat_id
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
channel_kick(channel, user, ok_cb, false)
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
local channel = 'channel#id'..chat_id
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, false)
channel_kick(channel, user, ok_cb, false)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "Global bans!\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Support Team
function support_add(support_id)
-- Save to redis
local hash = 'support'
redis:sadd(hash, support_id)
end
function is_support(support_id)
--Save on redis
local hash = 'support'
local support = redis:sismember(hash, support_id)
return support or false
end
function support_remove(support_id)
--Save on redis
local hash = 'support'
redis:srem(hash, support_id)
end
-- Whitelist
function is_whitelisted(user_id)
--Save on redis
local hash = 'whitelist'
local is_whitelisted = redis:sismember(hash, user_id)
return is_whitelisted or false
end
--Begin Chat Mutes
function set_mutes(chat_id)
mutes = {[1]= "Audio: no",[2]= "Photo: no",[3]= "All: no",[4]="Documents: no",[5]="Text: no",[6]= "Video: no",[7]= "Gifs: no"}
local hash = 'mute:'..chat_id
for k,v in pairsByKeys(mutes) do
setting = v
redis:sadd(hash, setting)
end
end
function has_mutes(chat_id)
mutes = {[1]= "Audio: no",[2]= "Photo: no",[3]= "All: no",[4]="Documents: no",[5]="Text: no",[6]= "Video: no",[7]= "Gifs: no"}
local hash = 'mute:'..chat_id
for k,v in pairsByKeys(mutes) do
setting = v
local has_mutes = redis:sismember(hash, setting)
return has_mutes or false
end
end
function rem_mutes(chat_id)
local hash = 'mute:'..chat_id
redis:del(hash)
end
function mute(chat_id, msg_type)
local hash = 'mute:'..chat_id
local yes = "yes"
local no = 'no'
local old_setting = msg_type..': '..no
local setting = msg_type..': '..yes
redis:srem(hash, old_setting)
redis:sadd(hash, setting)
end
function is_muted(chat_id, msg_type)
local hash = 'mute:'..chat_id
local setting = msg_type
local muted = redis:sismember(hash, setting)
return muted or false
end
function unmute(chat_id, msg_type)
--Save on redis
local hash = 'mute:'..chat_id
local yes = 'yes'
local no = 'no'
local old_setting = msg_type..': '..yes
local setting = msg_type..': '..no
redis:srem(hash, old_setting)
redis:sadd(hash, setting)
end
function mute_user(chat_id, user_id)
local hash = 'mute_user:'..chat_id
redis:sadd(hash, user_id)
end
function is_muted_user(chat_id, user_id)
local hash = 'mute_user:'..chat_id
local muted = redis:sismember(hash, user_id)
return muted or false
end
function unmute_user(chat_id, user_id)
--Save on redis
local hash = 'mute_user:'..chat_id
redis:srem(hash, user_id)
end
-- Returns chat_id mute list
function mutes_list(chat_id)
local hash = 'mute:'..chat_id
local list = redis:smembers(hash)
local text = "Mutes for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairsByKeys(list) do
text = text.."Mute "..v.."\n"
end
return text
end
-- Returns chat_user mute list
function muted_user_list(chat_id)
local hash = 'mute_user:'..chat_id
local list = redis:smembers(hash)
local text = "Muted Users for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairsByKeys(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - [ "..v.." ]\n"
end
end
return text
end
--End Chat Mutes
-- /id by reply
function get_message_callback_id(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.peer_id
send_large_msg(chat, result.from.peer_id)
else
return
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_momod2(result.from.peer_id, result.to.peer_id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.peer_id, ok_cb, false)
channel_kick(channel, 'user#id'..result.from.peer_id, ok_cb, false)
else
return
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.peer_id, ok_cb, false)
channel_kick(channel, 'user#id'..result.from.peer_id, ok_cb, false)
else
return
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_momod2(result.from.peer_id, result.to.peer_id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.peer_id, result.to.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Banned")
else
return
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
ban_user(result.from.peer_id, result.to.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Banned")
send_large_msg(channel, "User "..result.from.peer_id.." Banned")
else
return
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
send_large_msg(chat, "User "..result.from.peer_id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.peer_id
redis:srem(hash, result.from.peer_id)
else
return
end
end
function banall_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('This is a old message!')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.peer_id)
chat_del_user(chat, 'user#id'..result.from.peer_id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.peer_id.."] globally banned")
else
return
end
end
| agpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Konschtat_Highlands/TextIDs.lua | 3 | 1253 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6378; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6381; -- Obtained: <item>.
GIL_OBTAINED = 6382; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6384; -- Obtained key item: <keyitem>.
ALREADY_OBTAINED_TELE = 7183; -- You already possess the gate crystal for this telepoint.
-- Other texts
SIGNPOST3 = 7351; -- North: Valkurm Dunes South: North Gustaberg East: Gusgen Mines, Pashhow Marshlands
SIGNPOST2 = 7352; -- North: Pashhow Marshlands West: Valkurm Dunes, North Gustaberg Southeast: Gusgen Mines
SIGNPOST_DIALOG_1 = 7353; -- North: Valkurm Dunes South: To Gustaberg
SIGNPOST_DIALOG_2 = 7354; -- You see something stuck behind the signpost.
SOMETHING_BURIED_HERE = 7355; -- Something has been buried here.
FIND_NOTHING = 7356; -- You thought you saw something, but find nothing.
NOTHING_HAPPENS = 119; -- Nothing happens...
NOTHING_OUT_OF_ORDINARY = 6395; -- There is nothing out of the ordinary here.
TELEPOINT_HAS_BEEN_SHATTERED = 7444; -- The telepoint has been shattered into a thousand pieces...
-- conquest Base
CONQUEST_BASE = 7024;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Teteroon.lua | 34 | 1033 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Teteroon
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x029F);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
krmarien/Proxmark | client/lualibs/html_dumplib.lua | 8 | 2995 | bin = require('bin')
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
local function dbg(args)
if DEBUG then
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print("ERROR: ",err)
return nil, err
end
local function save_HTML(javascript, filename)
-- Read the HTML-skel file
local skel = require("htmlskel")
html = skel.getHTML(javascript);
-- Open the output file
local outfile = io.open(filename, "w")
if outfile == nil then
return oops(string.format("Could not write to file %s",tostring(filename)))
end
-- Write the data into it
outfile:write(html)
io.close(outfile)
-- Done
return filename
end
local function convert_ascii_dump_to_JS(infile)
local t = infile:read("*all")
local output = "[";
for line in string.gmatch(t, "[^\n]+") do
output = output .. "'"..line.."',\n"
end
output = output .. "]"
return output
end
local function convert_binary_dump_to_JS(infile, blockLen)
local bindata = infile:read("*all")
len = string.len(bindata)
if len % blockLen ~= 0 then
return oops(("Bad data, length (%d) should be a multiple of blocklen (%d)"):format(len, blockLen))
end
local _,hex = bin.unpack(("H%d"):format(len),bindata)
-- Now that we've converted binary data into hex, we doubled the size.
-- One byte, like 0xDE is now
-- the characters 'D' and 'E' : one byte each.
-- Thus:
blockLen = blockLen * 2
local js,i = "[";
for i = 1, string.len(hex),blockLen do
js = js .."'" ..string.sub(hex,i,i+blockLen -1).."',\n"
end
js = js .. "]"
return js
end
---
-- Converts a .eml-file into a HTML/Javascript file.
-- @param input the file to convert
-- @param output the file to write to
-- @return the name of the new file.
local function convert_eml_to_html(input, output)
input = input or 'dumpdata.eml'
output = output or input .. 'html'
local infile = io.open(input, "r")
if infile == nil then
return oops(string.format("Could not read file %s",tostring(input)))
end
-- Read file, get JS
local javascript = convert_ascii_dump_to_JS(infile)
io.close(infile)
return save_HTML(javascript, output )
end
--- Converts a binary dump into HTML/Javascript file
-- @param input the file containing the dump (defaults to dumpdata.bin)
-- @param output the file to write to
-- @param blockLen, the length of each block. Defaults to 16 bytes
local function convert_bin_to_html(input, output, blockLen)
input = input or 'dumpdata.bin'
blockLen = blockLen or 16
output = output or input .. 'html'
local infile = io.open(input, "rb")
if infile == nil then
return oops(string.format("Could not read file %s",tostring(input)))
end
-- Read file, get JS
local javascript = convert_binary_dump_to_JS(infile, blockLen)
io.close(infile)
return save_HTML(javascript, output )
end
return {
convert_bin_to_html = convert_bin_to_html,
convert_eml_to_html = convert_eml_to_html,
}
| gpl-2.0 |
cwojtak/LoveUtils | utils/timer_helper.lua | 1 | 1540 | --timer_helper.lua
--v1.12.0
--Author: Connor Wojtak
--Purpose: A utility to allow for pausing of the application, while still rendering the application.
--Imports
local UTILS = require("utils/utils")
--Classes
Timer = {}
--Global Variables
GLOBAL_TIMER_LIST = {}
--Creates a new timer. Returns: Timer
function Timer:start(w, f)
local obj = {wait=w, func=f, enabled=true}
setmetatable(obj, self)
self.__index = self
table.insert(GLOBAL_TIMER_LIST, obj)
return obj
end
--Stops a timer, which can be restarted later. Returns: Nothing
function Timer:stop()
self:setEnabled(false)
end
--Destroys a Timer. Returns: Nothing
function Timer:destroy()
for i, b in ipairs(GLOBAL_TIMER_LIST) do
if b == self then
table.remove(GLOBAL_TIMER_LIST, i)
end
end
end
--Called by love.update() to update the timers. Returns: Nothing
function Timer.updateTimers(dt)
for i, t in ipairs(GLOBAL_TIMER_LIST) do
if t:getEnabled() == true then
t:setTime(t:getTime() - dt)
if t:getTime() <= 0 then
local func = t:getFunction()
func()
t:destroy()
end
end
end
end
--TIMER ATTRIBUTE GETTERS/SETTERS
--Gets or sets an attribute of a timer. Returns: Attribute or Nothing
function Timer:getTime()
return self["wait"]
end
function Timer:getFunction()
return self["func"]
end
function Timer:getEnabled()
return self["enabled"]
end
function Timer:setTime(attr)
self["wait"] = attr
end
function Timer:setFunction(attr)
self["func"] = attr
end
function Timer:setEnabled(attr)
self["enabled"] = attr
end
| mit |
FFXIOrgins/FFXIOrgins | scripts/globals/items/red_terrapin.lua | 17 | 1321 | -----------------------------------------
-- ID: 4402
-- Item: red_terrapin
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4402);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
m2mselect/owrt | feeds/luci/protocols/luci-proto-3g/luasrc/model/cbi/admin_network/proto_3g.lua | 2 | 5027 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, apn, service, pincode, username, password, dialnumber
local ipv6, maxwait, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/tty[A-Z]*")
or nixio.fs.glob("/dev/tts/*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
service = section:taboption("general", Value, "service", translate("Service Type"))
service:value("", translate("-- Please choose --"))
service:value("umts", "UMTS/GPRS")
service:value("umts_only", translate("UMTS only"))
service:value("gprs_only", translate("GPRS only"))
local simman = map.uci:get("simman", "core", "enabled") or "0"
if simman == "0" then
apn = section:taboption("general", Value, "apn", translate("APN"))
pincode = section:taboption("general", Value, "pincode", translate("PIN"))
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
else
apn = section:taboption("general", DummyValue, "apn", translate("APN"), translate("You can configure this value in the SIM manager, or after disabling it"))
pincode = section:taboption("general", DummyValue, "pincode", translate("PIN"), translate("You can configure this value in the SIM manager, or after disabling it"))
username = section:taboption("general", DummyValue, "username", translate("PAP/CHAP username"), translate("You can configure this value in the SIM manager, or after disabling it"))
password = section:taboption("general", DummyValue, "password", translate("PAP/CHAP password"), translate("You can configure this value in the SIM manager, or after disabling it"))
end
dialnumber = section:taboption("general", Value, "dialnumber", translate("Dial number"))
dialnumber.placeholder = "*99***1#"
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
maxwait = section:taboption("advanced", Value, "maxwait",
translate("Modem init timeout"),
translate("Maximum amount of seconds to wait for the modem to become ready"))
maxwait.placeholder = "20"
maxwait.datatype = "min(1)"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Windurst_Waters_[S]/npcs/Tohs_Jhannih.lua | 38 | 1050 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Tohs Jhannih
-- Type: Standard NPC
-- @zone: 94
-- @pos -46.492 -4.5 70.828
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01ae);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Cloister_of_Tides/npcs/Water_Protocrystal.lua | 4 | 1504 | -----------------------------------
-- Area: Cloister of Tides
-- NPC: Water Protocrystal
-- Involved in Quests: Trial by Water, Trial Size Trial by Water
-- @pos 560 36 560 211
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/bcnm");
require("scripts/zones/Cloister_of_Tides/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZone(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return;
else
player:messageSpecial(PROTOCRYSTAL);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option))then
return;
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/spells/knights_minne_v.lua | 4 | 1519 | -----------------------------------------
-- Spell: Knight's Minne V
-- Grants Defense bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 50 + math.floor((sLvl + iLvl)/10);
if(power >= 120) then
power = 120;
end
local iBoost = caster:getMod(MOD_MINNE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINNE_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINNE,power,0,duration,caster:getID(), 0, 5)) then
spell:setMsg(75);
end
return EFFECT_MINNE;
end; | gpl-3.0 |
peval/Atlas | lib/active-queries.lua | 40 | 3780 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
-- proxy.auto-config will pick them up
local commands = require("proxy.commands")
local auto_config = require("proxy.auto-config")
--- init the global scope
if not proxy.global.active_queries then
proxy.global.active_queries = {}
end
if not proxy.global.max_active_trx then
proxy.global.max_active_trx = 0
end
-- default config for this script
if not proxy.global.config.active_queries then
proxy.global.config.active_queries = {
show_idle_connections = false
}
end
---
-- track the active queries and dump all queries at each state-change
--
function collect_stats()
local num_conns = 0
local active_conns = 0
for k, v in pairs(proxy.global.active_queries) do
num_conns = num_conns + 1
if v.state ~= "idle" then
active_conns = active_conns + 1
end
end
if active_conns > proxy.global.max_active_trx then
proxy.global.max_active_trx = active_conns
end
return {
active_conns = active_conns,
num_conns = num_conns,
max_active_trx = proxy.global.max_active_trx
}
end
---
-- dump the state of the current queries
--
function print_stats(stats)
local o = ""
for k, v in pairs(proxy.global.active_queries) do
if v.state ~= "idle" or proxy.global.config.active_queries.show_idle_connections then
local cmd_query = ""
if v.cmd then
cmd_query = string.format("(%s) %q", v.cmd.type_name, v.cmd.query or "")
end
o = o .." ["..k.."] (".. v.username .."@".. v.db ..") " .. cmd_query .." (state=" .. v.state .. ")\n"
end
end
-- prepend the data and the stats about the number of connections and trx
o = os.date("%Y-%m-%d %H:%M:%S") .. "\n" ..
" #connections: " .. stats.num_conns ..
", #active trx: " .. stats.active_conns ..
", max(active trx): ".. stats.max_active_trx ..
"\n" .. o
print(o)
end
---
-- enable tracking the packets
function read_query(packet)
local cmd = commands.parse(packet)
local r = auto_config.handle(cmd)
if r then return r end
proxy.queries:append(1, packet)
-- add the query to the global scope
local connection_id = proxy.connection.server.thread_id
proxy.global.active_queries[connection_id] = {
state = "started",
cmd = cmd,
db = proxy.connection.client.default_db or "",
username = proxy.connection.client.username or ""
}
print_stats(collect_stats())
return proxy.PROXY_SEND_QUERY
end
---
-- statement is done, track the change
function read_query_result(inj)
local connection_id = proxy.connection.server.thread_id
proxy.global.active_queries[connection_id].state = "idle"
proxy.global.active_queries[connection_id].cmd = nil
if inj.resultset then
local res = inj.resultset
if res.flags.in_trans then
proxy.global.active_queries[connection_id].state = "in_trans"
end
end
print_stats(collect_stats())
end
---
-- remove the information about the connection
--
function disconnect_client()
local connection_id = proxy.connection.server.thread_id
if connection_id then
proxy.global.active_queries[connection_id] = nil
print_stats(collect_stats())
end
end
| gpl-2.0 |
navtej/papercrop | script/(portrait) vertical reflow.lua | 15 | 1275 | width=device_width
height=device_height
right_max_margin=0.1
figure_min_height=100
max_vspace_reflow=6 -- pixels
-- outdir: output directory
-- pageNo: current page
-- numRects: # of crop rectangles.
function processPage(outdir, pageNo, numRects)
-- create merged image imageM
local imageM=CImage()
processPageSubRoutine(imageM, pageNo, width*((1.0-right_max_margin)*2),numRects)
postprocessImage(imageM)
reflow(imageM, width, 2, max_vspace_reflow, 255, right_max_margin, figure_min_height)
splitImage(imageM, height, outdir, pageNo, false)
if numRects==0 then
win:setStatus("Error! no rects were specified.")
return 0
end
return 1
end
function processAllPages(outdir)
initializeOutput(outdir)
local imageM=CImage()
local pageNo=0
while pageNo<win:getNumPages() do
win:setCurPage(pageNo)
local imageS=CImage()
processPageSubRoutine(imageS, pageNo, width*((1.0-right_max_margin)*2),win:getNumRects())
reflow(imageS, width, 2, 2, 255, right_max_margin, figure_min_height) imageM:concatVertical(imageM, imageS)
splitImagePart(imageM, height, outdir, pageNo, false)
pageNo=pageNo+1
end
postprocessImage(imageM)
splitImage(imageM, height, outdir, pageNo, false)
finalizeOutput(outdir)
end
| gpl-2.0 |
hacker44-h44/1104 | vir/GroupManager.lua | 39 | 11325 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "This service is private for SUDO (@shayansoft)"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' created, check messages list...'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set this message for about=>\n\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'Group have not about'
end
local about = data[tostring(msg.to.id)][data_cat]
return about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set this message for rules=>\n\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'Group have not rules'
end
local rules = data[tostring(msg.to.id)][data_cat]
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Members are already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Send group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Photo is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Group photo save and set', ok_cb, false)
else
print('Error: '..msg.id)
send_large_msg(receiver, 'Failed, try again', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group Settings:\n_________________________\n> Lock Group Name : "..settings.lock_name.."\n> Lock Group Photo : "..settings.lock_photo.."\n> Lock Group Member : "..settings.lock_member.."\n> Anti Spam System : on\n> Anti Spam Mod : kick\n> Anti Spam Action : 10\n> Group Status : active\n> Group Model : free\n> Group Mod : 2\n> Supportion : yes\n> Bot Version : 1.6"
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'makegroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not group"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == '+' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == '-' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == '?' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Send new photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Group Manager System",
usage = {
"/makegroup (name) : create new group",
"/about : view group about",
"/rules : view group rules",
"/setname (name) : set group name",
"/setphoto : set group photo",
"/setabout (message) : set group about",
"/setrules (message) : set group rules",
"/group + name : lock group name",
"/group + photo : lock group photo",
"/group + member : lock group member",
"/group - name : unlock group name",
"/group - photo : unlock group photo",
"/group - member : unlock group member",
"/group ? : view group settings"
},
patterns = {
"^[!/](makegroup) (.*)$",
"^[!/](setabout) (.*)$",
"^[!/](about)$",
"^[!/](setrules) (.*)$",
"^[!/](rules)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](group) (+) (.*)$",
"^[!/](group) (-) (.*)$",
"^[!/](group) (?)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end
| gpl-2.0 |
ArchiveTeam/instacast-grab | table_show.lua | 58 | 3226 | --[[
Author: Julio Manuel Fernandez-Diaz
Date: January 12, 2007
(For Lua 5.1)
Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount()
Formats tables with cycles recursively to any depth.
The output is returned as a string.
References to other tables are shown as values.
Self references are indicated.
The string returned is "Lua code", which can be procesed
(in the case in which indent is composed by spaces or "--").
Userdata and function keys and values are shown as strings,
which logically are exactly not equivalent to the original code.
This routine can serve for pretty formating tables with
proper indentations, apart from printing them:
print(table.show(t, "t")) -- a typical use
Heavily based on "Saving tables with cycles", PIL2, p. 113.
Arguments:
t is the table.
name is the name of the table (optional)
indent is a first indentation (optional).
--]]
function table.show(t, name, indent)
local cart -- a container
local autoref -- for self references
--[[ counts the number of elements in a table
local function tablecount(t)
local n = 0
for _, _ in pairs(t) do n = n+1 end
return n
end
]]
-- (RiciLake) returns true if the table is empty
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
| unlicense |
moteus/ZipWriter | lua/ZipWriter/win/cp.lua | 3 | 10306 | local function prequire(m)
local ok, err = pcall(require, m)
if not ok then return nil, err end
if err == true then err = _G[m] or err end
return err
end
local DEFAULT_CP = 1251
local LOCAL_CP
if not LOCAL_CP then -- ffi
local ffi = prequire "ffi"
if ffi then
ffi.cdef"uint32_t __stdcall GetACP();"
LOCAL_CP = ffi.C.GetACP()
end
end
if not LOCAL_CP then -- alien
local alien = prequire "alien"
if alien then
local kernel32 = assert(alien.load("kernel32.dll"))
local GetACP = assert(kernel32.GetACP) -- win2k+
GetACP:types{abi="stdcall", ret = "int"}
LOCAL_CP = GetACP()
end
end
-- MSDN Code Page Identifiers
local WINDOWS_CODE_PAGES = {
[037] = "IBM037"; -- IBM EBCDIC US-Canada
[437] = "IBM437"; -- OEM United States
[500] = "IBM500"; -- IBM EBCDIC International
[708] = "ASMO-708"; -- Arabic (ASMO 708)
[709] = ""; -- Arabic (ASMO-449+, BCON V4)
[710] = ""; -- Arabic - Transparent Arabic
[720] = "DOS-720"; -- Arabic (Transparent ASMO); Arabic (DOS)
[737] = "ibm737"; -- OEM Greek (formerly 437G); Greek (DOS)
[775] = "ibm775"; -- OEM Baltic; Baltic (DOS)
[850] = "ibm850"; -- OEM Multilingual Latin 1; Western European (DOS)
[852] = "ibm852"; -- OEM Latin 2; Central European (DOS)
[855] = "IBM855"; -- OEM Cyrillic (primarily Russian)
[857] = "ibm857"; -- OEM Turkish; Turkish (DOS)
[858] = "IBM00858"; -- OEM Multilingual Latin 1 + Euro symbol
[860] = "IBM860"; -- OEM Portuguese; Portuguese (DOS)
[861] = "ibm861"; -- OEM Icelandic; Icelandic (DOS)
[862] = "DOS-862"; -- OEM Hebrew; Hebrew (DOS)
[863] = "IBM863"; -- OEM French Canadian; French Canadian (DOS)
[864] = "IBM864"; -- OEM Arabic; Arabic (864)
[865] = "IBM865"; -- OEM Nordic; Nordic (DOS)
[866] = "cp866"; -- OEM Russian; Cyrillic (DOS)
[869] = "ibm869"; -- OEM Modern Greek; Greek, Modern (DOS)
[870] = "IBM870"; -- IBM EBCDIC Multilingual/ROECE (Latin 2); IBM EBCDIC Multilingual Latin 2
[874] = "windows-874"; -- ANSI/OEM Thai (same as 28605, ISO 8859-15); Thai (Windows)
[875] = "cp875"; -- IBM EBCDIC Greek Modern
[932] = "shift_jis"; -- ANSI/OEM Japanese; Japanese (Shift-JIS)
[936] = "gb2312"; -- ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312)
[949] = "ks_c_5601-1987"; -- ANSI/OEM Korean (Unified Hangul Code)
[950] = "big5"; -- ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5)
[1026] = "IBM1026"; -- IBM EBCDIC Turkish (Latin 5)
[1047] = "IBM01047"; -- IBM EBCDIC Latin 1/Open System
[1140] = "IBM01140"; -- IBM EBCDIC US-Canada (037 + Euro symbol); IBM EBCDIC (US-Canada-Euro)
[1141] = "IBM01141"; -- IBM EBCDIC Germany (20273 + Euro symbol); IBM EBCDIC (Germany-Euro)
[1142] = "IBM01142"; -- IBM EBCDIC Denmark-Norway (20277 + Euro symbol); IBM EBCDIC (Denmark-Norway-Euro)
[1143] = "IBM01143"; -- IBM EBCDIC Finland-Sweden (20278 + Euro symbol); IBM EBCDIC (Finland-Sweden-Euro)
[1144] = "IBM01144"; -- IBM EBCDIC Italy (20280 + Euro symbol); IBM EBCDIC (Italy-Euro)
[1145] = "IBM01145"; -- IBM EBCDIC Latin America-Spain (20284 + Euro symbol); IBM EBCDIC (Spain-Euro)
[1146] = "IBM01146"; -- IBM EBCDIC United Kingdom (20285 + Euro symbol); IBM EBCDIC (UK-Euro)
[1147] = "IBM01147"; -- IBM EBCDIC France (20297 + Euro symbol); IBM EBCDIC (France-Euro)
[1148] = "IBM01148"; -- IBM EBCDIC International (500 + Euro symbol); IBM EBCDIC (International-Euro)
[1149] = "IBM01149"; -- IBM EBCDIC Icelandic (20871 + Euro symbol); IBM EBCDIC (Icelandic-Euro)
[1200] = "utf-16"; -- Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications
[1201] = "unicodeFFFE"; -- Unicode UTF-16, big endian byte order; available only to managed applications
[1250] = "windows-1250"; -- ANSI Central European; Central European (Windows)
[1251] = "windows-1251"; -- ANSI Cyrillic; Cyrillic (Windows)
[1252] = "windows-1252"; -- ANSI Latin 1; Western European (Windows)
[1253] = "windows-1253"; -- ANSI Greek; Greek (Windows)
[1254] = "windows-1254"; -- ANSI Turkish; Turkish (Windows)
[1255] = "windows-1255"; -- ANSI Hebrew; Hebrew (Windows)
[1256] = "windows-1256"; -- ANSI Arabic; Arabic (Windows)
[1257] = "windows-1257"; -- ANSI Baltic; Baltic (Windows)
[1258] = "windows-1258"; -- ANSI/OEM Vietnamese; Vietnamese (Windows)
[1361] = "Johab"; -- Korean (Johab)
[10000] = "macintosh"; -- MAC Roman; Western European (Mac)
[10001] = "x-mac-japanese"; -- Japanese (Mac)
[10002] = "x-mac-chinesetrad"; -- MAC Traditional Chinese (Big5); Chinese Traditional (Mac)
[10003] = "x-mac-korean"; -- Korean (Mac)
[10004] = "x-mac-arabic"; -- Arabic (Mac)
[10005] = "x-mac-hebrew"; -- Hebrew (Mac)
[10006] = "x-mac-greek"; -- Greek (Mac)
[10007] = "x-mac-cyrillic"; -- Cyrillic (Mac)
[10008] = "x-mac-chinesesimp"; -- MAC Simplified Chinese (GB 2312); Chinese Simplified (Mac)
[10010] = "x-mac-romanian"; -- Romanian (Mac)
[10017] = "x-mac-ukrainian"; -- Ukrainian (Mac)
[10021] = "x-mac-thai"; -- Thai (Mac)
[10029] = "x-mac-ce"; -- MAC Latin 2; Central European (Mac)
[10079] = "x-mac-icelandic"; -- Icelandic (Mac)
[10081] = "x-mac-turkish"; -- Turkish (Mac)
[10082] = "x-mac-croatian"; -- Croatian (Mac)
[12000] = "utf-32"; -- Unicode UTF-32, little endian byte order; available only to managed applications
[12001] = "utf-32BE"; -- Unicode UTF-32, big endian byte order; available only to managed applications
[20000] = "x-Chinese_CNS"; -- CNS Taiwan; Chinese Traditional (CNS)
[20001] = "x-cp20001"; -- TCA Taiwan
[20002] = "x_Chinese-Eten"; -- Eten Taiwan; Chinese Traditional (Eten)
[20003] = "x-cp20003"; -- IBM5550 Taiwan
[20004] = "x-cp20004"; -- TeleText Taiwan
[20005] = "x-cp20005"; -- Wang Taiwan
[20105] = "x-IA5"; -- IA5 (IRV International Alphabet No. 5, 7-bit); Western European (IA5)
[20106] = "x-IA5-German"; -- IA5 German (7-bit)
[20107] = "x-IA5-Swedish"; -- IA5 Swedish (7-bit)
[20108] = "x-IA5-Norwegian"; -- IA5 Norwegian (7-bit)
[20127] = "us-ascii"; -- US-ASCII (7-bit)
[20261] = "x-cp20261"; -- T.61
[20269] = "x-cp20269"; -- ISO 6937 Non-Spacing Accent
[20273] = "IBM273"; -- IBM EBCDIC Germany
[20277] = "IBM277"; -- IBM EBCDIC Denmark-Norway
[20278] = "IBM278"; -- IBM EBCDIC Finland-Sweden
[20280] = "IBM280"; -- IBM EBCDIC Italy
[20284] = "IBM284"; -- IBM EBCDIC Latin America-Spain
[20285] = "IBM285"; -- IBM EBCDIC United Kingdom
[20290] = "IBM290"; -- IBM EBCDIC Japanese Katakana Extended
[20297] = "IBM297"; -- IBM EBCDIC France
[20420] = "IBM420"; -- IBM EBCDIC Arabic
[20423] = "IBM423"; -- IBM EBCDIC Greek
[20424] = "IBM424"; -- IBM EBCDIC Hebrew
[20833] = "x-EBCDIC-KoreanExtended"; -- IBM EBCDIC Korean Extended
[20838] = "IBM-Thai"; -- IBM EBCDIC Thai
[20866] = "koi8-r"; -- Russian (KOI8-R); Cyrillic (KOI8-R)
[20871] = "IBM871"; -- IBM EBCDIC Icelandic
[20880] = "IBM880"; -- IBM EBCDIC Cyrillic Russian
[20905] = "IBM905"; -- IBM EBCDIC Turkish
[20924] = "IBM00924"; -- IBM EBCDIC Latin 1/Open System (1047 + Euro symbol)
[20932] = "EUC-JP"; -- Japanese (JIS 0208-1990 and 0121-1990)
[20936] = "x-cp20936"; -- Simplified Chinese (GB2312); Chinese Simplified (GB2312-80)
[20949] = "x-cp20949"; -- Korean Wansung
[21025] = "cp1025"; -- IBM EBCDIC Cyrillic Serbian-Bulgarian
[21027] = ""; -- (deprecated)
[21866] = "koi8-u"; -- Ukrainian (KOI8-U); Cyrillic (KOI8-U)
[28591] = "iso-8859-1"; -- ISO 8859-1 Latin 1; Western European (ISO)
[28592] = "iso-8859-2"; -- ISO 8859-2 Central European; Central European (ISO)
[28593] = "iso-8859-3"; -- ISO 8859-3 Latin 3
[28594] = "iso-8859-4"; -- ISO 8859-4 Baltic
[28595] = "iso-8859-5"; -- ISO 8859-5 Cyrillic
[28596] = "iso-8859-6"; -- ISO 8859-6 Arabic
[28597] = "iso-8859-7"; -- ISO 8859-7 Greek
[28598] = "iso-8859-8"; -- ISO 8859-8 Hebrew; Hebrew (ISO-Visual)
[28599] = "iso-8859-9"; -- ISO 8859-9 Turkish
[28603] = "iso-8859-13"; -- ISO 8859-13 Estonian
[28605] = "iso-8859-15"; -- ISO 8859-15 Latin 9
[29001] = "x-Europa"; -- Europa 3
[38598] = "iso-8859-8-i"; -- ISO 8859-8 Hebrew; Hebrew (ISO-Logical)
[50220] = "iso-2022-jp"; -- ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS)
[50221] = "csISO2022JP"; -- ISO 2022 Japanese with halfwidth Katakana; Japanese (JIS-Allow 1 byte Kana)
[50222] = "iso-2022-jp"; -- ISO 2022 Japanese JIS X 0201-1989; Japanese (JIS-Allow 1 byte Kana - SO/SI)
[50225] = "iso-2022-kr"; -- ISO 2022 Korean
[50227] = "x-cp50227"; -- ISO 2022 Simplified Chinese; Chinese Simplified (ISO 2022)
[50229] = ""; -- ISO 2022 Traditional Chinese
[50930] = ""; -- EBCDIC Japanese (Katakana) Extended
[50931] = ""; -- EBCDIC US-Canada and Japanese
[50933] = ""; -- EBCDIC Korean Extended and Korean
[50935] = ""; -- EBCDIC Simplified Chinese Extended and Simplified Chinese
[50936] = ""; -- EBCDIC Simplified Chinese
[50937] = ""; -- EBCDIC US-Canada and Traditional Chinese
[50939] = ""; -- EBCDIC Japanese (Latin) Extended and Japanese
[51932] = "euc-jp"; -- EUC Japanese
[51936] = "EUC-CN"; -- EUC Simplified Chinese; Chinese Simplified (EUC)
[51949] = "euc-kr"; -- EUC Korean
[51950] = ""; -- EUC Traditional Chinese
[52936] = "hz-gb-2312"; -- HZ-GB2312 Simplified Chinese; Chinese Simplified (HZ)
[54936] = "GB18030"; -- Windows XP and later: GB18030 Simplified Chinese (4 byte); Chinese Simplified (GB18030)
[57002] = "x-iscii-de"; -- ISCII Devanagari
[57003] = "x-iscii-be"; -- ISCII Bengali
[57004] = "x-iscii-ta"; -- ISCII Tamil
[57005] = "x-iscii-te"; -- ISCII Telugu
[57006] = "x-iscii-as"; -- ISCII Assamese
[57007] = "x-iscii-or"; -- ISCII Oriya
[57008] = "x-iscii-ka"; -- ISCII Kannada
[57009] = "x-iscii-ma"; -- ISCII Malayalam
[57010] = "x-iscii-gu"; -- ISCII Gujarati
[57011] = "x-iscii-pa"; -- ISCII Punjabi
[65000] = "utf-7"; -- Unicode (UTF-7)
[65001] = "utf-8"; -- Unicode (UTF-8)
}
local M = {}
function M.GetLocalCPCode()
return LOCAL_CP or DEFAULT_CP
end
function M.GetLocalCPName()
return WINDOWS_CODE_PAGES[ LOCAL_CP or DEFAULT_CP ]
end
return M | mit |
LoneWolfHT/lavastuff | items/nodecore.lua | 1 | 3277 | return function(cooldown, S)
local function finish(self)
local pos = self.object:get_pos()
if pos then
minetest.after(0.1, function()
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name = "nc_optics:glass_hot_source"})
end
end)
end
self.object:remove()
end
minetest.register_entity("lavastuff:shoveling_glass", {
is_visible = true,
visual = "wielditem",
textures = {"nc_optics:glass_hot_source"},
visual_size = vector.new(0.66, 0.66, 0.66), -- scale to just under regular node size
collisionbox = {-0.48, -0.48, -0.48, 0.48, 0.48, 0.48},
physical = true,
collide_with_objects = false,
makes_footstep_sound = false,
backface_culling = true,
static_save = true,
pointable = false,
glow = minetest.LIGHT_MAX,
on_punch = function() return true end,
on_step = function(self, dtime)
if not self.player then return finish(self) end
local player = minetest.get_player_by_name(self.player)
if not player then return finish(self) end
if player:get_player_control().dig or player:get_wielded_item():get_name() ~= "lavastuff:shovel" then
cooldown:set(player) -- remove cooldown that was set when the glass was picked up
return finish(self)
end
local phead = vector.add(player:get_pos(), {x=0,z=0, y = player:get_properties().eye_height or 0})
local targpos = vector.round(vector.add(phead, vector.multiply(player:get_look_dir(), 4)))
local objpos = self.object:get_pos()
local objtargpos = minetest.raycast(phead, targpos, false, true)
local next = objtargpos:next()
objtargpos = (next and next.type == "node" and next.above) or targpos
local dist = vector.distance(objpos, objtargpos)
if dist >= 0.4 then
self.object:set_velocity(vector.multiply(vector.direction(objpos, objtargpos), dist * 5))
elseif vector.length(self.object:get_velocity()) ~= 0 then
self.object:set_velocity(vector.new(0, 0, 0))
self.object:set_pos(objtargpos)
end
end,
})
minetest.override_item("lavastuff:sword", {
sound = {breaks = "nc_api_toolbreak"},
})
minetest.override_item("lavastuff:pick", {
tool_capabilities = minetest.registered_tools["nc_lux:tool_pick_tempered"].tool_capabilities,
sound = {breaks = "nc_api_toolbreak"},
})
minetest.override_item("lavastuff:shovel", {
tool_capabilities = minetest.registered_tools["nc_lux:tool_spade_tempered"].tool_capabilities,
on_place = function(itemstack, user, pointed_thing, ...)
if not pointed_thing or pointed_thing.type ~= "node" then return end
local node = minetest.get_node(pointed_thing.under)
local def = minetest.registered_nodes[node.name]
if not cooldown:get(user) and (def.groups.sand or (def.groups.silica_molten and def.liquidtype == "source")) then
cooldown:set(user, 0)
minetest.remove_node(pointed_thing.under)
local ent = minetest.add_entity(pointed_thing.under, "lavastuff:shoveling_glass")
ent:get_luaentity().player = user:get_player_name()
else
return lavastuff.tool_fire_func(itemstack, user, pointed_thing, ...)
end
end,
sound = {breaks = "nc_api_toolbreak"},
})
minetest.override_item("lavastuff:axe", {
tool_capabilities = minetest.registered_tools["nc_lux:tool_hatchet_tempered"].tool_capabilities,
on_place = lavastuff.tool_fire_func,
sound = {breaks = "nc_api_toolbreak"},
})
end | mit |
sjznxd/lc-20130127 | applications/luci-statistics/luasrc/statistics/rrdtool/definitions/interface.lua | 69 | 2769 | --[[
Luci statistics - interface plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.statistics.rrdtool.definitions.interface", package.seeall)
function rrdargs( graph, plugin, plugin_instance )
--
-- traffic diagram
--
local traffic = {
-- draw this diagram for each data instance
per_instance = true,
title = "%H: Transfer on %di",
vlabel = "Bytes/s",
-- diagram data description
data = {
-- defined sources for data types, if ommitted assume a single DS named "value" (optional)
sources = {
if_octets = { "tx", "rx" }
},
-- special options for single data lines
options = {
if_octets__tx = {
total = true, -- report total amount of bytes
color = "00ff00", -- tx is green
title = "Bytes (TX)"
},
if_octets__rx = {
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- rx is blue
title = "Bytes (RX)"
}
}
}
}
--
-- packet diagram
--
local packets = {
-- draw this diagram for each data instance
per_instance = true,
title = "%H: Packets on %di",
vlabel = "Packets/s",
-- diagram data description
data = {
-- data type order
types = { "if_packets", "if_errors" },
-- defined sources for data types
sources = {
if_packets = { "tx", "rx" },
if_errors = { "tx", "rx" }
},
-- special options for single data lines
options = {
-- processed packets (tx DS)
if_packets__tx = {
overlay = true, -- don't summarize
total = true, -- report total amount of bytes
color = "00ff00", -- processed tx is green
title = "Processed (tx)"
},
-- processed packets (rx DS)
if_packets__rx = {
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- processed rx is blue
title = "Processed (rx)"
},
-- packet errors (tx DS)
if_errors__tx = {
overlay = true, -- don't summarize
total = true, -- report total amount of packets
color = "ff5500", -- tx errors are orange
title = "Errors (tx)"
},
-- packet errors (rx DS)
if_errors__rx = {
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of packets
color = "ff0000", -- rx errors are red
title = "Errors (rx)"
}
}
}
}
return { traffic, packets }
end
| apache-2.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/vgui/bStorage_block_item.lua | 1 | 3132 |
local PANEL = {};
function PANEL:Init ( )
self:SetVisible(true)
self.ModelPanel = vgui.Create("DModelPanel", self);
function self.ModelPanel:LayoutEntity ( ) end
function self.ModelPanel.OnMousePressed ( _, mc ) self:OnMousePressed(mc) end
function self.ModelPanel.OnMouseReleased ( _, mc ) self:OnMouseReleased(mc) end
self.DownTime = 0;
end
function PANEL:PerformLayout ( )
self.ModelPanel:InvalidateLayout();
self.ModelPanel:SetPos(3, 3);
self.ModelPanel:SetSize(self:GetWide() - 6, self:GetTall() - 6);
end
function PANEL:SetItemTable ( itemTable )
if !itemTable then
return
end
self.itemTable = itemTable;
self.ModelPanel:SetModel(itemTable.InventoryModel);
self.ModelPanel:SetCamPos(itemTable.ModelCamPos)
self.ModelPanel:SetLookAt(itemTable.ModelLookAt)
self.ModelPanel:SetFOV(itemTable.ModelFOV)
local iSeq = self.ModelPanel.Entity:LookupSequence('ragdoll');
self.ModelPanel.Entity:ResetSequence(iSeq);
end
function PANEL:Think ( )
if (self.mouseDown) then
if (!input.IsMouseDown(self.mouseCode)) then
self:OnMouseReleased(MOUSE_LEFT)
return;
end
local mx, my = gui.MousePos();
self:SetPos(mx + self.InitialOffset_X, my + self.InitialOffset_Y);
end
end
local OnPress = Sound("UI/buttonclick.wav");
function PANEL:OnMousePressed ( MouseCode )
if (MouseCode == MOUSE_LEFT) then
surface.PlaySound(OnPress);
self.mouseCode = MouseCode;
self.mouseDown = true;
local mx, my = gui.MousePos();
local ox, oy = self:GetPos();
self.InitialOffset_X, self.InitialOffset_Y = ox - mx, oy - my;
self.InitialPos_X, self.InitialPos_Y = self:GetPos();
self.ModelPanel:MoveToFront();
self.trueParent:SetSuperGlow(true);
GAMEMODE.DraggingSomething = self;
if (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_MAIN) then
self:GetParent().MainWeaponEquip:SetSuperGlow(true);
elseif (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_SIDE) then
self:GetParent().SideWeaponEquip:SetSuperGlow(true);
end
self.DownTime = CurTime();
elseif (MouseCode == MOUSE_RIGHT) then
GAMEMODE.DropItem(self.trueParent.itemID);
end
end
function PANEL:OnMouseReleased( MouseCode )
if (MouseCode == MOUSE_LEFT) then
self.mouseDown = nil;
if (self.InitialPos_X) then self:SetPos(self.InitialPos_X, self.InitialPos_Y); end
self.trueParent:SetSuperGlow(false);
GAMEMODE.DraggingSomething = nil;
if (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_MAIN) then
self:GetParent().MainWeaponEquip:SetSuperGlow(false);
elseif (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_SIDE) then
self:GetParent().SideWeaponEquip:SetSuperGlow(false);
end
realSlot = self:GetParent():GetHoveredItemSlot();
if (CurTime() - self.DownTime < 1 && realSlot == self.trueParent) then
GAMEMODE.UseItem(self.trueParent.itemID);
else
if (realSlot && self.trueParent.itemID != realSlot.itemID) then
LocalPlayer():SwapItemPosition(self.trueParent.itemID, realSlot.itemID);
end
end
end
end
vgui.Register("perp_storage_block_item", PANEL); | mit |
FFXIOrgins/FFXIOrgins | scripts/globals/items/reishi_mushroom.lua | 35 | 1195 | -----------------------------------------
-- ID: 4449
-- Item: reishi_mushroom
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -6
-- Mind 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4449);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -6);
target:addMod(MOD_MND, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -6);
target:delMod(MOD_MND, 4);
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/shop.lua | 16 | 2301 | -----------------------------------
-- Author: Dia
--
-- Functions for Shop system
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/conquest");
-----------------------------------
-- Nations
-----------------------------------
SANDORIA = 0;
BASTOK = 1;
WINDURST = 2;
KAZHAM = 2;
JEUNO = 3;
SELBINA = 4;
RABAO = 4;
NORG = 5;
TAVNAZIA = 6;
STATIC = 7;
-----------------------------------
-- function showShop
--
-- Total stock cuts off after 16 items.
-- If you add more than that the extras won't display.
-----------------------------------
function showShop(player, nation, stock)
correction = 1;
if (nation ~= STATIC) then
correction = (1 + (0.20 * (9 - player:getFameLevel(nation)) / 8))*SHOP_PRICE;
end
player:createShop(#stock/2, nation);
for i = 1, #stock, 2 do
player:addShopItem(stock[i],stock[i+1]*correction);
end
player:sendMenu(2);
end;
-----------------------------------
-- function showNationShop
--
-- Total stock cuts off after 16 items.
-- If you add more than that the extras won't display.
-----------------------------------
function showNationShop(player, nation, stock)
conquest = getNationRank(nation);
playerNation = player:getNation();
correction = 1;
if (nation ~= STATIC) then
correction = (1 + (0.20 * (9 - player:getFameLevel(nation)) / 8))*SHOP_PRICE;
end
player:createShop(#stock/3, nation);
for i = 1, #stock, 3 do
if (stock[i+2] == 1) then
if (playerNation == nation and conquest == 1) then
player:addShopItem(stock[i],stock[i+1]*correction);
end
elseif (stock[i+2] == 2) then
if (conquest <= 2) then
player:addShopItem(stock[i],stock[i+1]*correction);
end
else
player:addShopItem(stock[i],stock[i+1]*correction);
end
end
player:sendMenu(2);
end;
-----------------------------------
-- function ShowOPVendorShop
-- creates the usual OP vendor store
-- {ItemID,Price}
-----------------------------------
function ShowOPVendorShop(player)
stock =
{
0x1034,316, --Antidote
0x1037,800, --Echo Drops
0x1020,4832, --Ether
0x1036,2595, --Eye Drops
0x1010,910 --Potion
};
showShop(player, STATIC, stock);
end; | gpl-3.0 |
Xinerki/Story | missions/marker_display.lua | 1 | 6686 |
missions = {}
function missions.renderMissionMarkers()
for i,v in ipairs(getElementsByType('marker')) do
if getElementData(v,"story.isMissionMarker") then
local x,y,z=getElementPosition(v)
local isUsed=getElementData(v,"story.isMissionMarkerUsed")
local usedBy=getElementData(v,"story.missionMarkerUsedBy")
if getDistanceBetweenPoints3D( x,y,z,getElementPosition(localPlayer) ) < 10 then
local x,y=getScreenFromWorldPosition( x,y,z+2 )
local outline=2
local scale=2
r,g,b=getMarkerColor(v)
if x and y and getElementDimension(v) == getElementDimension(localPlayer) then
x=x*2
if getElementData(v, "story.isMissionMarker1P") then
if isUsed then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
else
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
end
if getElementData(v, "story.isMissionMarker2P") and not getElementData(v, "story.isPlayer1inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
if getElementData(v, "story.isMissionMarker2P") and getElementData(v, "story.isPlayer1inMission") and not getElementData(v, "story.isPlayer2inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
if getElementData(v, "story.isMissionMarker2P") and getElementData(v, "story.isPlayer1inMission") and getElementData(v, "story.isPlayer2inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
end
--dxDrawText( string text, float left, float top [, float right=left, float bottom=top, int color=white, float scale=1, mixed font="default", string alignX="left", string alignY="top", bool clip=false, bool wordBreak=false, bool postGUI=false, bool colorCoded=false, bool subPixelPositioning=false, float fRotation=0, float fRotationCenterX=0, float fRotationCenterY=0 ] )
end
end
end
end | mit |
fartoverflow/naev | dat/factions/spawn/soromid.lua | 6 | 3017 | include("dat/factions/spawn/common.lua")
include("dat/factions/spawn/mercenary_helper.lua")
-- @brief Spawns a small patrol fleet.
function spawn_patrol ()
local pilots = {}
local r = rnd.rnd()
if r < pbm then
pilots = spawnLtMerc("Soromid")
elseif r < 0.5 then
scom.addPilot( pilots, "Soromid Reaver", 25 );
elseif r < 0.8 then
scom.addPilot( pilots, "Soromid Brigand", 20 );
scom.addPilot( pilots, "Soromid Marauder", 25 );
else
scom.addPilot( pilots, "Soromid Nyx", 75 );
end
return pilots
end
-- @brief Spawns a medium sized squadron.
function spawn_squad ()
local pilots = {}
local r = rnd.rnd()
if r < pbm then
pilots = spawnMdMerc("Soromid")
elseif r < 0.5 then
scom.addPilot( pilots, "Soromid Brigand", 20 );
scom.addPilot( pilots, "Soromid Marauder", 25 );
scom.addPilot( pilots, "Soromid Odium", 45 );
elseif r < 0.8 then
scom.addPilot( pilots, "Soromid Reaver", 25 );
scom.addPilot( pilots, "Soromid Odium", 45 );
else
scom.addPilot( pilots, "Soromid Brigand", 20 );
scom.addPilot( pilots, "Soromid Reaver", 25 );
scom.addPilot( pilots, "Soromid Nyx", 75 );
end
return pilots
end
-- @brief Spawns a capship with escorts.
function spawn_capship ()
local pilots = {}
if rnd.rnd() < pbm then
pilots = spawnBgMerc("Soromid")
else
local r = rnd.rnd()
-- Generate the capship
if r < 0.7 then
scom.addPilot( pilots, "Soromid Ira", 140 )
else
scom.addPilot( pilots, "Soromid Arx", 165 )
end
-- Generate the escorts
r = rnd.rnd()
if r < 0.5 then
scom.addPilot( pilots, "Soromid Brigand", 20 );
scom.addPilot( pilots, "Soromid Marauder", 25 );
scom.addPilot( pilots, "Soromid Reaver", 25 );
elseif r < 0.8 then
scom.addPilot( pilots, "Soromid Reaver", 25 );
scom.addPilot( pilots, "Soromid Odium", 45 );
else
scom.addPilot( pilots, "Soromid Reaver", 25 );
scom.addPilot( pilots, "Soromid Nyx", 75 );
end
end
return pilots
end
-- @brief Creation hook.
function create ( max )
local weights = {}
-- Create weights for spawn table
weights[ spawn_patrol ] = 100
weights[ spawn_squad ] = math.max(1, -80 + 0.80 * max)
weights[ spawn_capship ] = math.max(1, -500 + 1.70 * max)
-- Create spawn table base on weights
spawn_table = scom.createSpawnTable( weights )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( 0, scom.presence(spawn_data), max )
end
-- @brief Spawning hook
function spawn ( presence, max )
local pilots
-- Over limit
if presence > max then
return 5
end
-- Actually spawn the pilots
pilots = scom.spawn( spawn_data )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots
end
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Tavnazian_Safehold/npcs/Chemioue.lua | 38 | 1044 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Chemioue
-- Type: NPC Quest
-- @zone: 26
-- @pos 82.041 -34.964 67.636
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0118);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
OpenPrograms/samis-Programs | nidus/core.lua | 1 | 4291 | local class = require('oop-system').class
local NiDuS = class('NiDuS')
local serializer = require("serialization")
function NiDuS:init(file)
self.cfgfile = file
self.version = 1.0
self.protocol_string = "DNS 1 A"
self.hosts = {}
self.currentfeatures = {}
self:reloadConfig()
self:readHosts()
self:loadData()
end
function NiDuS:reloadConfig()
print("Configuration of NiDuS is not currently implemented.")
end
function NiDuS:sendError(code, description)
local error = "ERROR" .. code .. description
print("Sent:" .. error)
return error
end
function NiDuS:sendRecordError(rnumber, code, description)
local error = "ERROR" .. number .. code .. description
print("Sent:" .. error)
return error
end
function NiDuS:getRecord(domain, recordtype)
return self.hosts[domain][recordtype]
end
function NiDuS:negoiateFeatures(protocolstring)
print("Feature neogiation is not currently implemented.")
return protocol_string
end
function NiDuS:readHosts()
print("Reading from the hosts file is not currently implemented.")
end
local function contains(text, str)
return not string.find(text, str)
end
local function mysplit(inputstr, sep)
sep = sep or "%s"
local t={} ; local i=1 ;
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function NiDuS:handle(from, message)
if contains(message, "DNS") then
return self:negoiateFeatures(message)
end
if contains(message, "QUERY") then
return self:handleQuery(message)
end
if contains(message, "REGISTER") then
return self:handleRegistration(from, message)
end
if contains(message, "UNREGISTER") then
return self:handleUnregistration(from, message)
end
return self:sendError(400, "")
end
function NiDuS:handleQuery(message)
local queryparts = mysplit(message, " ")
if queryparts[1] ~= "QUERY" then
return self:sendError(400, "Word QUERY found but request is not a query")
end
local record = queryparts[2]
if record ~= "A" then
return self:sendError(501, "Server does not support this record type")
end
local domain = queryparts[3]
return self:resolve(record, domain)
end
function NiDuS:resolve(record, domain)
local error_string = "NXDOMAIN" .. domain
if not self:getRecord(domain, record) then
return error_string
else
result = self:getRecord(domain, record)
return "RESPONSE" .. domain .. record .. result
end
end
function NiDuS:handleRegistration(from, message)
local parts = mysplit(message, " ")
if parts[1] ~= "REGISTER" then
return self:sendError(400, "Word REGISTER found but is not a registration request")
end
local domain = parts[2]
local record = parts[3]
if record ~= "A" then
return self:sendError(501, "Server does not support this record type")
end
self.hosts[domain][record] = parts[4] or from
self:saveData()
return self:resolve(record, domain)
end
function NiDuS:handleUnregistration(from, message)
local parts = mysplit(message, " ")
if parts[1] ~= "UNREGISTER" then
return self:sendError(400, "Word UNREGISTER found but is not a unregistration request")
end
local domain = parts[2]
local assignedhost = self:getRecord(domain, "A")
if not assignedhost == from then
return self:sendError(400, "Only the address that registered a domain is allowed to unregister it.")
end
hosts[domain] = nil
self:saveData()
return self:sendError(200, "The domain has been unregistered.")
end
function NiDuS:saveData()
local hostsdb = io.open("/var/lib/nidus/hosts.db", wb)
local serialized_hosts = serializer.serialize(hosts)
hostsdb:write(serialized_hosts)
hostsdb:close()
end
function NiDuS:loadData()
local hostsdb, error = io.open("/var/lib/nidus/hosts.db", "rb")
if not hostsdb then
print("Unable to initially open hosts database. Reason:" .. error)
print("Attempting to create file...")
hostsdb = io.open("/var/lib/nidus/hosts.db", "w")
if not hostsdb then
hostsdb:close()
print("Unable to open hosts database. Exiting now")
os.exit()
end
end
local serialized_hosts = hostsdb:read("*a")
self.hosts = serializer.unserialize(serialized_hosts)
end
return {NiDuS = NiDuS} | mit |
shahabsaf1/DaLTon-bot-test2 | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/spells/bluemagic/magic_fruit.lua | 4 | 1405 | -----------------------------------------
-- Spell: Magic Fruit
-- Restores target's HP.
-- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local minCure = 250;
local divisor = 0.6666;
local constant = 130;
local power = getCurePowerOld(caster);
if(power > 559) then
divisor = 2.8333;
constant = 391.2
elseif(power > 319) then
divisor = 1;
constant = 210;
end
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true);
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
if(target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then
--Applying server mods....
final = final * CURE_POWER;
end
local diff = (target:getMaxHP() - target:getHP());
if(final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
spell:setMsg(7);
return final;
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Ugrihd.lua | 5 | 10497 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Ugrihd
-- Coin Exchange Vendor
-- @pos -63.079 -6 -28.571 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/besieged");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local badges = { 0, 780, 783, 784, 794, 795, 825, 826, 827, 894, 900, 909 };
local rank = 1;
while player:hasKeyItem(badges[rank + 1]) == true do
rank = rank + 1;
end;
player:startEvent(0x0096,rank-1,badges[rank],player:getImperialStanding(),0,39183,10577,4095,0,0); -- Unsure of what other params mean
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local Quantity = bit.rshift(option, 8);
local CoinType = bit.band(option, 255);
local Stacks = Quantity / 99;
local Remainder = Quantity % 99;
--printf("Quantity - %u CoinType - %u\n",Quantity, CoinType);
--printf("Stacks - %u Remainder - %u\n",Stacks, Remainder);
if (csid ==0x0096) then
if (CoinType == 1) then -- Bronze Pieces
if(Quantity == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184);
else
player:delImperialStanding(20*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINED,2184);
player:addItem(2184);
end
elseif(Quantity <= 99) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184);
else
player:delImperialStanding(20*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2184,Quantity);
player:addItem(2184,Quantity);
end
elseif(Quantity > 99 and Remainder == 0) then
if (player:getFreeSlotsCount() <= Stacks) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184);
else
player:delImperialStanding(20*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2184,Quantity);
for i = 1, Stacks do
player:addItem(2184,99);
end
end
elseif(Quantity > 99 and Remainder ~= 0) then
if (player:getFreeSlotsCount() <= Stacks+1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184);
else
player:delImperialStanding(20*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2184,Quantity);
for i = 1, Stacks do
player:addItem(2184,99);
end
player:addItem(2184,Remainder);
end
end
elseif (CoinType == 2) then -- Silver Pieces
if(Quantity == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2185);
else
player:delImperialStanding(100*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINED,2185);
player:addItem(2185);
end
elseif(Quantity <= 99) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2185);
else
player:delImperialStanding(100*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2185,Quantity);
player:addItem(2185,Quantity);
end
elseif(Quantity > 99 and Remainder == 0) then
if (player:getFreeSlotsCount() <= Stacks) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2185);
else
player:delImperialStanding(100*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2185,Quantity);
for i = 1, Stacks do
player:addItem(2185,99);
end
end
elseif(Quantity > 99 and Remainder ~= 0) then
if (player:getFreeSlotsCount() <= Stacks+1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2185);
else
player:delImperialStanding(100*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2185,Quantity);
for i = 1, Stacks do
player:addItem(2185,99);
end
player:addItem(2185,Remainder);
end
end
elseif (CoinType == 3) then -- Mythril Pieces
if(Quantity == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2186);
else
player:delImperialStanding(200*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINED,2186);
player:addItem(2186);
end
elseif(Quantity <= 99) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2186);
else
player:delImperialStanding(200*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2186,Quantity);
player:addItem(2186,Quantity);
end
elseif(Quantity > 99 and Remainder == 0) then
if (player:getFreeSlotsCount() <= Stacks) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2186);
else
player:delImperialStanding(200*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2186,Quantity);
for i = 1, Stacks do
player:addItem(2186,99);
end
end
elseif(Quantity > 99 and Remainder ~= 0) then
if (player:getFreeSlotsCount() <= Stacks+1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2186);
else
player:delImperialStanding(200*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2186,Quantity);
for i = 1, Stacks do
player:addItem(2186,99);
end
player:addItem(2186,Remainder);
end
end
elseif (CoinType == 4) then -- Gold Pieces
if(Quantity == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2187);
else
player:delImperialStanding(1000*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINED,2187);
player:addItem(2187);
end
elseif(Quantity <= 99) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2187);
else
player:delImperialStanding(1000*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2187,Quantity);
player:addItem(2187,Quantity);
end
elseif(Quantity > 99 and Remainder == 0) then
if (player:getFreeSlotsCount() <= Stacks) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2187);
else
player:delImperialStanding(1000*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2187,Quantity);
for i = 1, Stacks do
player:addItem(2187,99);
end
end
elseif(Quantity > 99 and Remainder ~= 0) then
if (player:getFreeSlotsCount() <= Stacks+1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2187);
else
player:delImperialStanding(1000*Quantity);
npc:showText(npc, UGRIHD_PURCHASE_DIALOGUE);
player:messageSpecial(ITEM_OBTAINEDX,2187,Quantity);
for i = 1, Stacks do
player:addItem(2187,99);
end
player:addItem(2187,Remainder);
end
end
end
end
end; | gpl-3.0 |
luzexi/slua-3rd-lib | build/luajit-2.0.4/src/jit/v.lua | 88 | 5614 | ----------------------------------------------------------------------------
-- Verbose mode of the LuaJIT compiler.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module shows verbose information about the progress of the
-- JIT compiler. It prints one line for each generated trace. This module
-- is useful to see which code has been compiled or where the compiler
-- punts and falls back to the interpreter.
--
-- Example usage:
--
-- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end"
-- luajit -jv=myapp.out myapp.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the
-- module is started.
--
-- The output from the first example should look like this:
--
-- [TRACE 1 (command line):1 loop]
-- [TRACE 2 (1/3) (command line):1 -> 1]
--
-- The first number in each line is the internal trace number. Next are
-- the file name ('(command line)') and the line number (':1') where the
-- trace has started. Side traces also show the parent trace number and
-- the exit number where they are attached to in parentheses ('(1/3)').
-- An arrow at the end shows where the trace links to ('-> 1'), unless
-- it loops to itself.
--
-- In this case the inner loop gets hot and is traced first, generating
-- a root trace. Then the last exit from the 1st trace gets hot, too,
-- and triggers generation of the 2nd trace. The side trace follows the
-- path along the outer loop and *around* the inner loop, back to its
-- start, and then links to the 1st trace. Yes, this may seem unusual,
-- if you know how traditional compilers work. Trace compilers are full
-- of surprises like this -- have fun! :-)
--
-- Aborted traces are shown like this:
--
-- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50]
--
-- Don't worry -- trace aborts are quite common, even in programs which
-- can be fully compiled. The compiler may retry several times until it
-- finds a suitable trace.
--
-- Of course this doesn't work with features that are not-yet-implemented
-- (NYI error messages). The VM simply falls back to the interpreter. This
-- may not matter at all if the particular trace is not very high up in
-- the CPU usage profile. Oh, and the interpreter is quite fast, too.
--
-- Also check out the -jdump module, which prints all the gory details.
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20004, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
local type, format = type, string.format
local stdout, stderr = io.stdout, io.stderr
-- Active flag and output file handle.
local active, out
------------------------------------------------------------------------------
local startloc, startex
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "start" then
startloc = fmtfunc(func, pc)
startex = otr and "("..otr.."/"..oex..") " or ""
else
if what == "abort" then
local loc = fmtfunc(func, pc)
if loc ~= startloc then
out:write(format("[TRACE --- %s%s -- %s at %s]\n",
startex, startloc, fmterr(otr, oex), loc))
else
out:write(format("[TRACE --- %s%s -- %s]\n",
startex, startloc, fmterr(otr, oex)))
end
elseif what == "stop" then
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if ltype == "interpreter" then
out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
tr, startex, startloc))
elseif link == tr or link == 0 then
out:write(format("[TRACE %3s %s%s %s]\n",
tr, startex, startloc, ltype))
elseif ltype == "root" then
out:write(format("[TRACE %3s %s%s -> %d]\n",
tr, startex, startloc, link))
else
out:write(format("[TRACE %3s %s%s -> %d %s]\n",
tr, startex, startloc, link, ltype))
end
else
out:write(format("[TRACE %s]\n", what))
end
out:flush()
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(outfile)
if active then dumpoff() end
if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(dump_trace, "trace")
active = true
end
-- Public module functions.
module(...)
on = dumpon
off = dumpoff
start = dumpon -- For -j command line option.
| mit |
gitfancode/skynet | examples/agent.lua | 65 | 2082 | local skynet = require "skynet"
local netpack = require "netpack"
local socket = require "socket"
local sproto = require "sproto"
local sprotoloader = require "sprotoloader"
local WATCHDOG
local host
local send_request
local CMD = {}
local REQUEST = {}
local client_fd
function REQUEST:get()
print("get", self.what)
local r = skynet.call("SIMPLEDB", "lua", "get", self.what)
return { result = r }
end
function REQUEST:set()
print("set", self.what, self.value)
local r = skynet.call("SIMPLEDB", "lua", "set", self.what, self.value)
end
function REQUEST:handshake()
return { msg = "Welcome to skynet, I will send heartbeat every 5 sec." }
end
function REQUEST:quit()
skynet.call(WATCHDOG, "lua", "close", client_fd)
end
local function request(name, args, response)
local f = assert(REQUEST[name])
local r = f(args)
if response then
return response(r)
end
end
local function send_package(pack)
local package = string.pack(">s2", pack)
socket.write(client_fd, package)
end
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
unpack = function (msg, sz)
return host:dispatch(msg, sz)
end,
dispatch = function (_, _, type, ...)
if type == "REQUEST" then
local ok, result = pcall(request, ...)
if ok then
if result then
send_package(result)
end
else
skynet.error(result)
end
else
assert(type == "RESPONSE")
error "This example doesn't support request client"
end
end
}
function CMD.start(conf)
local fd = conf.client
local gate = conf.gate
WATCHDOG = conf.watchdog
-- slot 1,2 set at main.lua
host = sprotoloader.load(1):host "package"
send_request = host:attach(sprotoloader.load(2))
skynet.fork(function()
while true do
send_package(send_request "heartbeat")
skynet.sleep(500)
end
end)
client_fd = fd
skynet.call(gate, "lua", "forward", fd)
end
function CMD.disconnect()
-- todo: do something before exit
skynet.exit()
end
skynet.start(function()
skynet.dispatch("lua", function(_,_, command, ...)
local f = CMD[command]
skynet.ret(skynet.pack(f(...)))
end)
end)
| mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Atelloune.lua | 17 | 2580 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Atelloune
-- Starts and Finishes Quest: Atelloune's Lament
-- @zone 230
-- @pos 122 0 82
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
-----lady bug
if(player:getQuestStatus(SANDORIA,ATELLOUNE_S_LAMENT) == QUEST_ACCEPTED) then
if(trade:hasItemQty(2506,1) and trade:getItemCount() == 1) then
player:startEvent(0x037b);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
atellounesLament = player:getQuestStatus(SANDORIA,ATELLOUNE_S_LAMENT)
sanFame = player:getFameLevel(SANDORIA);
if (atellounesLament == QUEST_AVAILABLE and sanFame >= 2) then
player:startEvent(0x037a);
elseif (atellounesLament == QUEST_ACCEPTED) then
player:startEvent(0x037c);
elseif (atellounesLament == QUEST_COMPLETED) then
player:startEvent(0x0374); -- im profesors research
elseif (sanFame < 2) then
player:startEvent(0x0374);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x037a) then
player:addQuest(SANDORIA,ATELLOUNE_S_LAMENT);
elseif(csid == 0x037b) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,15008); -- Trainee Gloves
else
player:addItem(15008);
player:messageSpecial(ITEM_OBTAINED,15008); -- Trainee Gloves
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,ATELLOUNE_S_LAMENT);
end
end
end; | gpl-3.0 |
daofeng2015/luci | protocols/luci-proto-relay/luasrc/model/cbi/admin_network/proto_relay.lua | 70 | 1945 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local ipaddr, network
local forward_bcast, forward_dhcp, gateway, expiry, retry, table
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Address to access local relay bridge"))
ipaddr.datatype = "ip4addr"
network = s:taboption("general", DynamicList, "network", translate("Relay between networks"))
network.widget = "checkbox"
network.exclude = arg[1]
network.template = "cbi/network_netlist"
network.nocreate = true
network.nobridges = true
network.novirtual = true
network:depends("proto", "relay")
forward_bcast = section:taboption("advanced", Flag, "forward_bcast",
translate("Forward broadcast traffic"))
forward_bcast.default = forward_bcast.enabled
forward_dhcp = section:taboption("advanced", Flag, "forward_dhcp",
translate("Forward DHCP traffic"))
forward_dhcp.default = forward_dhcp.enabled
gateway = section:taboption("advanced", Value, "gateway",
translate("Use DHCP gateway"),
translate("Override the gateway in DHCP responses"))
gateway.datatype = "ip4addr"
gateway:depends("forward_dhcp", forward_dhcp.enabled)
expiry = section:taboption("advanced", Value, "expiry",
translate("Host expiry timeout"),
translate("Specifies the maximum amount of seconds after which hosts are presumed to be dead"))
expiry.placeholder = "30"
expiry.datatype = "min(1)"
retry = section:taboption("advanced", Value, "retry",
translate("ARP retry threshold"),
translate("Specifies the maximum amount of failed ARP requests until hosts are presumed to be dead"))
retry.placeholder = "5"
retry.datatype = "min(1)"
table = section:taboption("advanced", Value, "table",
translate("Use routing table"),
translate("Override the table used for internal routes"))
table.placeholder = "16800"
table.datatype = "range(0,65535)"
| apache-2.0 |
tullamods/OmniCC | OmniCC/main.lua | 1 | 3249 | -- code to drive the addon
local ADDON, Addon = ...
local CONFIG_ADDON = ADDON .. '_Config'
local L = LibStub('AceLocale-3.0'):GetLocale(ADDON)
function Addon:OnLoad()
-- create and setup options frame and event loader
local frame = self:CreateHiddenFrame('Frame')
-- setup an event handler
frame:SetScript(
'OnEvent',
function(_, event, ...)
local func = self[event]
if type(func) == 'function' then
func(self, event, ...)
end
end
)
frame:RegisterEvent('ADDON_LOADED')
frame:RegisterEvent('PLAYER_ENTERING_WORLD')
frame:RegisterEvent('PLAYER_LOGIN')
frame:RegisterEvent('PLAYER_LOGOUT')
self.frame = frame
-- setup slash commands
_G[('SLASH_%s1'):format(ADDON)] = ('/%s'):format(ADDON:lower())
_G[('SLASH_%s2'):format(ADDON)] = '/occ'
SlashCmdList[ADDON] = function(cmd, ...)
if cmd == 'version' then
print(L.Version:format(self.db.global.addonVersion))
else
self:ShowOptionsFrame()
end
end
self.OnLoad= nil
end
-- events
function Addon:ADDON_LOADED(event, addonName)
if ADDON ~= addonName then
return
end
self.frame:UnregisterEvent(event)
self:InitializeDB()
self.Cooldown:SetupHooks()
end
function Addon:PLAYER_ENTERING_WORLD()
self.Timer:ForActive('Update')
end
function Addon:PLAYER_LOGIN()
if not self.db.global.disableBlizzardCooldownText then return end
-- disable and preserve the user's blizzard cooldown count setting
self.countdownForCooldowns = GetCVar('countdownForCooldowns')
if self.countdownForCooldowns ~= '0' then
SetCVar('countdownForCooldowns', '0')
end
end
function Addon:PLAYER_LOGOUT()
if not self.db.global.disableBlizzardCooldownText then return end
-- return the setting to whatever it was originally on logout
-- so that the user can uninstall omnicc and go back to what they had
local countdownForCooldowns = GetCVar('countdownForCooldowns')
if self.countdownForCooldowns ~= countdownForCooldowns then
SetCVar('countdownForCooldowns', self.countdownForCooldowns)
end
end
-- utility methods
function Addon:ShowOptionsFrame()
if self:IsConfigAddonEnabled() and LoadAddOn(CONFIG_ADDON) then
local dialog = LibStub('AceConfigDialog-3.0')
dialog:Open(ADDON)
dialog:SelectGroup(ADDON, "themes", DEFAULT)
return true
end
return false
end
function Addon:IsConfigAddonEnabled()
if GetAddOnEnableState(UnitName('player'), CONFIG_ADDON) >= 1 then
return true
end
return false
end
function Addon:CreateHiddenFrame(...)
local f = CreateFrame(...)
f:Hide()
return f
end
function Addon:GetButtonIcon(frame)
if frame then
local icon = frame.icon
if type(icon) == 'table' and icon.GetTexture then
return icon
end
local name = frame:GetName()
if name then
icon = _G[name .. 'Icon'] or _G[name .. 'IconTexture']
if type(icon) == 'table' and icon.GetTexture then
return icon
end
end
end
end
Addon:OnLoad()
-- exports
_G[ADDON] = Addon
| mit |
cyph84/mpv | TOOLS/lua/zones.lua | 11 | 2749 | -- zones.lua: mpv script for handling commands depending on where the mouse pointer is at,
-- mostly for mouse wheel handling, by configuring it via input.conf, e.g.:
--
-- Ported from avih's ( https://github.com/avih ) zones.js
--
-- Vertical positions can be top, middle, bottom or "*" to represent the whole column.
-- Horizontal positions can be left, middle, bottom or "*" to represent the whole row.
-- "default" will be the fallback command to be used if no command is assigned to that area.
--
-- input.conf example of use:
-- # wheel up/down with mouse
-- MOUSE_BTN3 script_message_to zones commands "middle-right: add brightness 1" "*-left: add volume 5" "default: seek 10"
-- MOUSE_BTN4 script_message_to zones commands "middle-right: add brightness -1" "*-left: add volume -5" "default: seek -10"
local ZONE_THRESH_PERCENTAGE = 20;
-- sides get 20% each, mid gets 60%, same vertically
local msg = mp.msg
function getMouseZone()
-- returns the mouse zone as two strings [top/middle/bottom], [left/middle/right], e.g. "middle", "right"
local screenW, screenH = mp.get_osd_resolution()
local mouseX, mouseY = mp.get_mouse_pos()
local threshY = screenH * ZONE_THRESH_PERCENTAGE / 100
local threshX = screenW * ZONE_THRESH_PERCENTAGE / 100
local yZone = (mouseY < threshY) and "top" or (mouseY < (screenH - threshY)) and "middle" or "bottom"
local xZone = (mouseX < threshX) and "left" or (mouseX < (screenW - threshX)) and "middle" or "right"
return yZone, xZone
end
function main (...)
local arg={...}
msg.debug('commands: \n\t'..table.concat(arg,'\n\t'))
local keyY, keyX = getMouseZone()
msg.debug("mouse at: " .. keyY .. '-' .. keyX)
local fallback = nil
for i, v in ipairs(arg) do
cmdY = v:match("^([%w%*]+)%-?[%w%*]*:")
cmdX = v:match("^[%w%*]*%-([%w%*]+)%s*:")
cmd = v:match("^[%S]-%s*:%s*(.+)")
msg.debug('cmdY: '..tostring(cmdY))
msg.debug('cmdX: '..tostring(cmdX))
msg.debug('cmd : '..tostring(cmd))
if (cmdY == keyY and cmdX == keyX) then
msg.verbose("running cmd: "..cmd)
mp.command(cmd)
return
elseif (cmdY == "*" and cmdX == keyX) or
(cmdY == keyY and cmdX == "*") then
msg.verbose("running cmd: "..cmd)
mp.command(cmd)
return
elseif cmdY == "default" then
fallback = cmd
end
end
if fallback ~= nil then
msg.verbose("running cmd: "..fallback)
mp.command(fallback)
return
else
msg.debug("no command assigned for "..keyY .. '-' .. keyX)
return
end
end
mp.register_script_message("commands", main)
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Dynamis-Buburimu/mobs/Apocalyptic_Beast.lua | 17 | 1492 | -----------------------------------
-- Area: Dynamis Buburimu
-- NPC: Apocalyptic_Beast
-----------------------------------
package.loaded["scripts/zones/Dynamis-Buburimu/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Buburimu/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(GetServerVariable("[DynaBuburimu]Boss_Trigger")==0)then
--spwan additional mob :
for additionalmob = 16941489, 16941665, 1 do
if(additionalmob ~= 16941666 or additionalmob ~= 16941576 or additionalmob ~= 16941552 or additionalmob ~= 16941520)then
SpawnMob(additionalmob);
end
end
SetServerVariable("[DynaBuburimu]Boss_Trigger",1);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if(killer:hasKeyItem(DYNAMIS_BUBURIMU_SLIVER ) == false)then
killer:addKeyItem(DYNAMIS_BUBURIMU_SLIVER);
killer:messageSpecial(KEYITEM_OBTAINED,DYNAMIS_BUBURIMU_SLIVER);
end
killer:addTitle(DYNAMISBUBURIMU_INTERLOPER);
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/West_Sarutabaruta/npcs/Slow_Axe_IM.lua | 8 | 2954 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Slow Axe, I.M.
-- Type: Border Conquest Guards
-- @pos 399.450 -25.858 727.545 115
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/West_Sarutabaruta/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = SARUTABARUTA;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if(supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if(arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if(option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif(option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if(hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif(option == 4) then
if(player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
JulianVolodia/awesome | lib/awful/layout/suit/spiral.lua | 14 | 2147 | ---------------------------------------------------------------------------
--- Dwindle and spiral layouts
--
-- @author Uli Schlachter <psychon@znc.in>
-- @copyright 2009 Uli Schlachter
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
--
-- @module awful.layout.suit.spiral
---------------------------------------------------------------------------
-- Grab environment we need
local ipairs = ipairs
local math = math
local spiral = {}
local function do_spiral(p, _spiral)
local wa = p.workarea
local cls = p.clients
local n = #cls
local old_width, old_height = wa.width, 2 * wa.height
for k, c in ipairs(cls) do
if k % 2 == 0 then
wa.width, old_width = math.ceil(old_width / 2), wa.width
if k ~= n then
wa.height, old_height = math.floor(wa.height / 2), wa.height
end
else
wa.height, old_height = math.ceil(old_height / 2), wa.height
if k ~= n then
wa.width, old_width = math.floor(wa.width / 2), wa.width
end
end
if k % 4 == 0 and _spiral then
wa.x = wa.x - wa.width
elseif k % 2 == 0 then
wa.x = wa.x + old_width
elseif k % 4 == 3 and k < n and _spiral then
wa.x = wa.x + math.ceil(old_width / 2)
end
if k % 4 == 1 and k ~= 1 and _spiral then
wa.y = wa.y - wa.height
elseif k % 2 == 1 and k ~= 1 then
wa.y = wa.y + old_height
elseif k % 4 == 0 and k < n and _spiral then
wa.y = wa.y + math.ceil(old_height / 2)
end
local g = {
x = wa.x,
y = wa.y,
width = wa.width,
height = wa.height
}
p.geometries[c] = g
end
end
--- Dwindle layout
spiral.dwindle = {}
spiral.dwindle.name = "dwindle"
function spiral.dwindle.arrange(p)
return do_spiral(p, false)
end
--- Spiral layout
spiral.name = "spiral"
function spiral.arrange(p)
return do_spiral(p, true)
end
return spiral
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Upper_Jeuno/npcs/Migliorozz.lua | 38 | 1033 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Migliorozz
-- Type: Standard NPC
-- @zone: 244
-- @pos -37.760 -2.499 12.924
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x272a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
subzrk/BadRotations | Rotations/Shaman/Restoration/RestorationSvs.lua | 1 | 39719 | local rotationName = "Svs"
---------------
--- Toggles ---
---------------
local function createToggles()
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range.", highlight = 1, icon = br.player.spell.riptide},
[2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used.", highlight = 0, icon = br.player.spell.chainHeal},
[3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.healingWave},
[4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.giftOfTheQueen}
};
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.healingTideTotem},
[2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.healingTideTotem},
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.healingTideTotem}
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.astralShift},
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.astralShift}
};
CreateButton("Defensive",3,0)
-- Interrupt Button
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.windShear},
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.windShear}
};
CreateButton("Interrupt",4,0)
-- Decurse Button
DecurseModes = {
[1] = { mode = "On", value = 1 , overlay = "Decurse Enabled", tip = "Decurse Enabled", highlight = 1, icon = br.player.spell.purifySpirit },
[2] = { mode = "Off", value = 2 , overlay = "Decurse Disabled", tip = "Decurse Disabled", highlight = 0, icon = br.player.spell.purifySpirit }
};
CreateButton("Decurse",5,0)
-- DPS Button
DPSModes = {
[1] = { mode = "On", value = 1 , overlay = "DPS Enabled", tip = "DPS Enabled", highlight = 1, icon = br.player.spell.lightningBolt },
[2] = { mode = "Off", value = 2 , overlay = "DPS Disabled", tip = "DPS Disabled", highlight = 0, icon = br.player.spell.healingSurge }
};
CreateButton("DPS",6,0)
end
--------------
--- COLORS ---
--------------
local colorBlue = "|cff00CCFF"
local colorGreen = "|cff00FF00"
local colorRed = "|cffFF0000"
local colorWhite = "|cffFFFFFF"
local colorGold = "|cffFFDD11"
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
local section
-- General Options
section = br.ui:createSection(br.ui.window.profile, "General")
br.ui:createCheckbox(section,"OOC Healing","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFout of combat healing|cffFFBB00.")
-- Dummy DPS Test
br.ui:createSpinner(section, "DPS Testing", 5, 5, 60, 5, "|cffFFFFFFSet to desired time for test in minuts. Min: 5 / Max: 60 / Interval: 5")
-- Pre-Pull Timer
br.ui:createSpinner(section, "Pre-Pull Timer", 5, 1, 10, 1, "|cffFFFFFFSet to desired time to start Pre-Pull (DBM Required). Min: 1 / Max: 10 / Interval: 1")
-- Ghost Wolf
br.ui:createCheckbox(section,"Ghost Wolf")
-- Water Walking
br.ui:createCheckbox(section,"Water Walking")
br.ui:checkSectionState(section)
-- Cooldown Options
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
-- Racial
br.ui:createCheckbox(section,"Racial")
-- Trinkets
br.ui:createCheckbox(section,"Trinkets")
-- Cloudburst Totem
br.ui:createSpinner(section, "Cloudburst Totem", 90, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Cloudburst Totem Targets", 3, 0, 40, 1, "Minimum Cloudburst Totem Targets")
-- Ancestral Guidance
br.ui:createSpinner(section, "Ancestral Guidance", 60, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Ancestral Guidance Targets", 3, 0, 40, 1, "Minimum Ancestral Guidance Targets")
-- Ascendance
br.ui:createSpinner(section,"Ascendance", 60, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Ascendance Targets", 3, 0, 40, 1, "Minimum Ascendance Targets")
-- Healing Tide Totem
br.ui:createSpinner(section, "Healing Tide Totem", 50, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Healing Tide Totem Targets", 3, 0, 40, 1, "Minimum Healing Tide Totem Targets")
br.ui:checkSectionState(section)
-- Defensive Options
section = br.ui:createSection(br.ui.window.profile, "Defensive")
-- Healthstone
br.ui:createSpinner(section, "Healthstone", 30, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Heirloom Neck
br.ui:createSpinner(section, "Heirloom Neck", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.");
-- Gift of The Naaru
if br.player.race == "Draenei" then
br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
end
-- Astral Shift
br.ui:createSpinner(section, "Astral Shift", 50, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Purge
br.ui:createCheckbox(section,"Purge")
-- Lightning Surge Totem
br.ui:createSpinner(section, "Lightning Surge Totem - HP", 50, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
br.ui:createSpinner(section, "Lightning Surge Totem - AoE", 5, 0, 10, 1, "|cffFFFFFFNumber of Units in 5 Yards to Cast At")
br.ui:checkSectionState(section)
-- Interrupt Options
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
-- Wind Shear
br.ui:createCheckbox(section,"Wind Shear")
-- Lightning Surge Totem
br.ui:createCheckbox(section,"Lightning Surge Totem")
-- Interrupt Percentage
br.ui:createSpinner(section, "Interrupt At", 0, 0, 95, 5, "|cffFFFFFFCast Percent to Cast At")
br.ui:checkSectionState(section)
-- Healing Options
section = br.ui:createSection(br.ui.window.profile, "Healing")
-- Healing Rain
br.ui:createSpinner(section, "Healing Rain", 80, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Healing Rain Targets", 2, 0, 40, 1, "Minimum Healing Rain Targets")
br.ui:createDropdown(section,"Healing Rain Key", br.dropOptions.Toggle, 6, colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.." Healing Rain manual usage.")
-- Spirit Link Totem
br.ui:createSpinner(section, "Spirit Link Totem", 50, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Spirit Link Totem Targets", 3, 0, 40, 1, "Minimum Spirit Link Totem Targets")
br.ui:createDropdown(section,"Spirit Link Totem Key", br.dropOptions.Toggle, 6, colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.." Spirit Link Totem manual usage.")
-- Riptide
br.ui:createSpinner(section, "Riptide", 90, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Healing Stream Totem
br.ui:createSpinner(section, "Healing Stream Totem", 80, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Unleash Life
br.ui:createSpinner(section, "Unleash Life", 80, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Healing Wave
br.ui:createSpinner(section, "Healing Wave", 70, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Healing Surge
br.ui:createSpinner(section, "Healing Surge", 60, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
-- Chain Heal
br.ui:createSpinner(section, "Chain Heal", 70, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At")
br.ui:createSpinnerWithout(section, "Chain Heal Targets", 3, 0, 40, 1, "Minimum Chain Heal Targets")
-- Gift of the Queen
br.ui:createSpinner(section, "Gift of the Queen", 80, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Gift of the Queen Targets", 3, 0, 40, 1, "Minimum Gift of the Queen Targets")
-- Wellspring
br.ui:createSpinner(section, "Wellspring", 80, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinnerWithout(section, "Wellspring Targets", 3, 0, 40, 1, "Minimum Wellspring Targets")
br.ui:checkSectionState(section)
-- Toggle Key Options
section = br.ui:createSection(br.ui.window.profile, "Toggle Keys")
-- Single/Multi Toggle
br.ui:createDropdown(section, "Rotation Mode", br.dropOptions.Toggle, 4)
-- Cooldown Key Toggle
br.ui:createDropdown(section, "Cooldown Mode", br.dropOptions.Toggle, 3)
-- Defensive Key Toggle
br.ui:createDropdown(section, "Defensive Mode", br.dropOptions.Toggle, 6)
-- Interrupts Key Toggle
br.ui:createDropdown(section, "Interrupt Mode", br.dropOptions.Toggle, 6)
-- Pause Toggle
br.ui:createDropdown(section, "Pause Mode", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
if br.timer:useTimer("debugRestoration", 0.1) then
--print("Running: "..rotationName)
---------------
--- Toggles --- -- List toggles here in order to update when pressed
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
UpdateToggle("Decurse",0.25)
UpdateToggle("DPS",0.25)
br.player.mode.decurse = br.data.settings[br.selectedSpec].toggles["Decurse"]
br.player.mode.dps = br.data.settings[br.selectedSpec].toggles["DPS"]
--------------
--- Locals ---
--------------
local artifact = br.player.artifact
local buff = br.player.buff
local cast = br.player.cast
local combatTime = getCombatTime()
local cd = br.player.cd
local charges = br.player.charges
local debuff = br.player.debuff
local drinking = UnitBuff("player",192002) ~= nil or UnitBuff("player",167152) ~= nil
local gcd = br.player.gcd
local healPot = getHealthPot()
local inCombat = br.player.inCombat
local inInstance = br.player.instance=="party"
local inRaid = br.player.instance=="raid"
local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player")>0
local lastSpell = lastSpellCast
local level = br.player.level
local lowest = br.friend[1].unit
local mode = br.player.mode
local perk = br.player.perk
local php = br.player.health
local power, powmax, powgen = br.player.power.amount.mana, br.player.power.mana.max, br.player.power.regen
local pullTimer = br.DBM:getPulltimer()
local race = br.player.race
local racial = br.player.getRacial()
local recharge = br.player.recharge
local spell = br.player.spell
local talent = br.player.talent
local wolf = br.player.buff.ghostWolf.exists()
local ttd = getTTD
local ttm = br.player.power.ttm
local units = units or {}
local lowestTank = {} --Tank
local enemies = enemies or {}
local friends = friends or {}
if CloudburstTotemTime == nil or cd.cloudburstTotem == 0 or not talent.cloudburstTotem then CloudburstTotemTime = 0 end
-- Cloudburst Totem
if isChecked("Cloudburst Totem") and talent.cloudburstTotem and not buff.cloudburstTotem.exists() then
if getLowAllies(getValue("Cloudburst Totem")) >= getValue("Cloudburst Totem Targets") then
if cast.cloudburstTotem() then
ChatOverlay(colorGreen.."Cloudburst Totem!")
CloudburstTotemTime = GetTime()
return
end
end
end
if inCombat and not IsMounted() then
if isChecked("Ancestral Guidance") and talent.ancestralGuidance and (not CloudburstTotemTime or GetTime() >= CloudburstTotemTime + 6) then
if getLowAllies(getValue("Ancestral Guidance")) >= getValue("Ancestral Guidance Targets") then
if cast.ancestralGuidance() then return end
end
end
end
units.dyn8 = br.player.units(8)
units.dyn40 = br.player.units(40)
enemies.yards5 = br.player.enemies(5)
enemies.yards8 = br.player.enemies(8)
enemies.yards8t = br.player.enemies(8,br.player.units(8,true))
enemies.yards10 = br.player.enemies(10)
enemies.yards20 = br.player.enemies(20)
enemies.yards30 = br.player.enemies(30)
enemies.yards40 = br.player.enemies(40)
friends.yards8 = getAllies("player",8)
friends.yards25 = getAllies("player",25)
friends.yards40 = getAllies("player",40)
--------------------
--- Action Lists ---
--------------------
-- Action List - Extras
local function actionList_Extras()
-- Dummy Test
if isChecked("DPS Testing") then
if GetObjectExists("target") then
if getCombatTime() >= (tonumber(getOptionValue("DPS Testing"))*60) and isDummy() then
StopAttack()
ClearTarget()
Print(tonumber(getOptionValue("DPS Testing")) .." Minute Dummy Test Concluded - Profile Stopped")
profileStop = true
end
end
end -- End Dummy Test
-- Ghost Wolf
if isChecked("Ghost Wolf") then
if ((#enemies.yards20 == 0 and not inCombat) or (#enemies.yards10 == 0 and inCombat)) and isMoving("player") and not buff.ghostWolf.exists() then
if cast.ghostWolf() then return end
end
end
-- Purge
if isChecked("Purge") and canDispel("target",spell.purge) and not isBoss() and GetObjectExists("target") then
if cast.purge() then return end
end
-- Water Walking
if falling > 1.5 and buff.waterWalking.exists() then
CancelUnitBuffID("player", spell.waterWalking)
end
if isChecked("Water Walking") and not inCombat and IsSwimming() then
if cast.waterWalking() then return end
end
end -- End Action List - Extras
-- Action List - Defensive
local function actionList_Defensive()
if useDefensive() then
-- Healthstone
if isChecked("Healthstone") and php <= getOptionValue("Healthstone")
and inCombat and hasItem(5512)
then
if canUse(5512) then
useItem(5512)
end
end
-- Heirloom Neck
if isChecked("Heirloom Neck") and php <= getOptionValue("Heirloom Neck") then
if hasEquiped(122668) then
if GetItemCooldown(122668)==0 then
useItem(122668)
end
end
end
-- Gift of the Naaru
if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and br.player.race == "Draenei" then
if castSpell("player",racial,false,false,false) then return end
end
-- Astral Shift
if isChecked("Astral Shift") and php <= getOptionValue("Astral Shift") and inCombat then
if cast.astralShift() then return end
end
end -- End Defensive Toggle
end -- End Action List - Defensive
-- Action List - Interrupts
local function actionList_Interrupts()
if useInterrupts() then
for i=1, #enemies.yards30 do
thisUnit = enemies.yards30[i]
if canInterrupt(thisUnit,getOptionValue("Interrupt At")) then
-- Wind Shear
if isChecked("Wind Shear") then
if cast.windShear(thisUnit) then return end
end
-- Lightning Surge Totem
if isChecked("Lightning Surge Totem") and cd.windShear > gcd then
if hasThreat(thisUnit) and not isMoving(thisUnit) and ttd(thisUnit) > 7 and lastSpell ~= spell.lightningSurgeTotem then
if cast.lightningSurgeTotem(thisUnit,"ground") then return end
end
end
end
end
end -- End useInterrupts check
end -- End Action List - Interrupts
-- Action List - Pre-Combat
function actionList_PreCombat()
-- Riptide
if isChecked("Riptide") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Riptide") and buff.riptide.remain(br.friend[i].unit) <= 1 then
if cast.riptide(br.friend[i].unit) then return end
end
end
end
-- Healing Stream Totem
if isChecked("Healing Stream Totem") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Stream Totem") then
if cast.healingStreamTotem(br.friend[i].unit) then return end
end
end
end
-- Healing Surge
if isChecked("Healing Surge") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Surge") and (buff.tidalWaves.exists() or level < 34) then
if cast.healingSurge(br.friend[i].unit) then return end
end
end
end
-- Healing Wave
if isChecked("Healing Wave") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Wave") and (buff.tidalWaves.exists() or level < 34) then
if cast.healingWave(br.friend[i].unit) then return end
end
end
end
-- Chain Heal
if isChecked("Chain Heal") and not moving and lastSpell ~= spell.chainHeal then
if getLowAllies(getValue("Chain Heal")) >= getValue("Chain Heal Targets") then
if hasEquiped(137051) and talent.unleashLife then
if cast.unleashLife(lowest) then return end
if buff.unleashLife.remain() > 2 then
if cast.chainHeal(lowest) then return end
end
else
if cast.chainHeal(lowest) then return end
end
end
end
-- Healing Rain
if isChecked("Healing Rain") and not moving then
if (SpecificToggle("Healing Rain Key") and not GetCurrentKeyBoardFocus()) then
if CastSpellByName(GetSpellInfo(spell.healingRain),"cursor") then return end
end
end
-- Spirit Link Totem
if isChecked("Spirit Link Totem") and not moving then
if (SpecificToggle("Spirit Link Totem Key") and not GetCurrentKeyBoardFocus()) then
if CastSpellByName(GetSpellInfo(spell.spiritLinkTotem),"cursor") then return end
end
end
end -- End Action List - Pre-Combat
function actionList_Cooldowns()
if useCDs() then
-- Ancestral Guidance
if isChecked("Ancestral Guidance") and talent.ancestralGuidance and not talent.cloudburstTotem then
if getLowAllies(getValue("Ancestral Guidance")) >= getValue("Ancestral Guidance Targets") then
if cast.ancestralGuidance() then return end
end
end
-- Ascendance
if isChecked("Ascendance") and talent.ascendance and not talent.cloudburstTotem then
if getLowAllies(getValue("Ascendance")) >= getValue("Ascendance Targets") then
if cast.ascendance() then return end
end
end
-- Healing Tide Totem
if isChecked("Healing Tide Totem") and not talent.cloudburstTotem then
if getLowAllies(getValue("Healing Tide Totem")) >= getValue("Healing Tide Totem Targets") then
if cast.healingTideTotem() then return end
end
end
-- Trinkets
if isChecked("Trinkets") then
if canUse(11) then
useItem(11)
end
if canUse(12) then
useItem(12)
end
if canUse(13) then
useItem(13)
end
if canUse(14) then
useItem(14)
end
end
-- Racial: Orc Blood Fury | Troll Berserking | Blood Elf Arcane Torrent
if isChecked("Racial") and (br.player.race == "Orc" or br.player.race == "Troll" or br.player.race == "BloodElf") then
if castSpell("player",racial,false,false,false) then return end
end
-- Chain Heal with Focuser of Jonat, the Elder legenadary ring
-- if hasEquiped(137051) and buff.jonatsFocus.stack() == 5 and not moving and lastSpell ~= spell.chainHeal then
-- if talent.unleashLife then
-- if cast.unleashLife(lowest) then return end
-- if buff.unleashLife.remain() > 2 then
-- if cast.chainHeal(lowest) then return end
-- end
-- else
-- if cast.chainHeal(lowest) then return end
-- end
-- end
end -- End useCooldowns check
end -- End Action List - Cooldowns
-- Cloudburst Totem
function actionList_CBT()
-- Ancestral Guidance
if isChecked("Ancestral Guidance") and talent.ancestralGuidance and (not CloudburstTotemTime or GetTime() >= CloudburstTotemTime + 6) then
if getLowAllies(getValue("Ancestral Guidance")) >= getValue("Ancestral Guidance Targets") then
if cast.ancestralGuidance() then return end
end
end
-- Ascendance
if isChecked("Ascendance") and talent.ascendance then
if getLowAllies(getValue("Ascendance")) >= getValue("Ascendance Targets") then
if cast.ascendance() then return end
end
end
-- Healing Tide Totem
if isChecked("Healing Tide Totem") then
if getLowAllies(getValue("Healing Tide Totem")) >= getValue("Healing Tide Totem Targets") then
if cast.healingTideTotem() then return end
end
end
-- Healing Rain
if not moving then
if (SpecificToggle("Healing Rain Key") and not GetCurrentKeyBoardFocus()) then
if CastSpellByName(GetSpellInfo(spell.healingRain),"cursor") then return end
end
if isChecked("Healing Rain") and not buff.healingRain.exists() and getLowAllies(getValue("Healing Rain")) >= getValue("Healing Rain Targets") then
if castGroundAtBestLocation(spell.healingRain, 20, 0, 40, 0, "heal") then return end
end
end
-- Riptide
if isChecked("Riptide") then
if not buff.tidalWaves.exists() and level >= 34 then
if cast.riptide(lowest) then return end
end
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Riptide") and buff.riptide.remain(br.friend[i].unit) <= 1 then
if cast.riptide(br.friend[i].unit) then return end
end
end
end
-- Gift of the Queen
if isChecked("Gift of the Queen") then
if getLowAllies(getValue("Gift of the Queen")) >= getValue("Gift of the Queen Targets") then
if cast.giftOfTheQueen(lowest.unit) then return end
end
end
-- Healing Stream Totem
if isChecked("Healing Stream Totem") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Stream Totem") then
if cast.healingStreamTotem(br.friend[i].unit) then return end
end
end
end
-- Unleash Life
if isChecked("Unleash Life") and talent.unleashLife and not hasEquiped(137051) then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Unleash Life") then
if cast.unleashLife() then return end
end
end
end
-- Healing Surge
if isChecked("Healing Surge") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Surge") and (buff.tidalWaves.exists() or level < 100) then
if cast.healingSurge(br.friend[i].unit) then return end
end
end
end
-- Healing Wave
if isChecked("Healing Wave") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Wave") and (buff.tidalWaves.exists() or level < 100) then
if cast.healingWave(br.friend[i].unit) then return end
end
end
end
end -- End Action List - Cloudburst Totem
-- AOE Healing
function actionList_AOEHealing()
-- Chain Heal
if isChecked("Chain Heal") and not moving and lastSpell ~= spell.chainHeal then
if getLowAllies(getValue("Chain Heal")) >= getValue("Chain Heal Targets") then
if talent.unleashLife and talent.highTide then
if cast.unleashLife(lowest) then return end
if buff.unleashLife.remain() > 2 then
if cast.chainHeal(lowest) then return end
end
else
if cast.chainHeal(lowest) then return end
end
end
end
-- Gift of the Queen
if isChecked("Gift of the Queen") and not talent.cloudburstTotem then
if getLowAllies(getValue("Gift of the Queen")) >= getValue("Gift of the Queen Targets") then
if cast.giftOfTheQueen(lowest.unit) then return end
end
end
-- Wellspring
if isChecked("Wellspring") then
if getLowAllies(getValue("Wellspring")) >= getValue("Wellspring Targets") then
if talent.cloudburstTotem and buff.cloudburstTotem.exists() then
if cast.wellspring() then return end
else
if cast.wellspring() then return end
end
end
end
end -- End Action List - AOEHealing
-- Single Target
function actionList_SingleTarget()
-- Purify Spirit
if br.player.mode.decurse == 1 then
for i = 1, #br.friend do
for n = 1,40 do
local buff,_,_,count,bufftype,duration = UnitDebuff(br.friend[i].unit, n)
if buff then
if bufftype == "Curse" or bufftype == "Magic" then
if cast.purifySpirit(br.friend[i].unit) then return end
end
end
end
end
end
-- Tidal Waves Proc Handling
if buff.tidalWaves.stack() == 2 or level < 100 then
if isChecked("Healing Surge") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Surge") then
if cast.healingSurge(br.friend[i].unit) then return end
end
end
end
if isChecked("Healing Wave") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Wave") then
if cast.healingWave(br.friend[i].unit) then return end
end
end
end
end
-- Riptide
if isChecked("Riptide") then
if not buff.tidalWaves.exists() and level >= 34 then
if cast.riptide(lowest) then return end
end
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Riptide") and buff.riptide.remain(br.friend[i].unit) <= 1 then
if cast.riptide(br.friend[i].unit) then return end
end
end
end
-- Earthen Shield Totem
if talent.earthenShieldTotem and not moving then
if cast.earthenShieldTotem() then return end
end
-- Healing Stream Totem
if isChecked("Healing Stream Totem") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Stream Totem") then
if not talent.echoOfTheElements then
if cast.healingStreamTotem(br.friend[i].unit) then return end
elseif talent.echoOfTheElements and (not HSTime or GetTime() - HSTime > 15) then
if cast.healingStreamTotem(br.friend[i].unit) then
HSTime = GetTime()
return true end
end
end
end
end
-- Unleash Life
if isChecked("Unleash Life") and talent.unleashLife and not hasEquiped(137051) then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Unleash Life") then
if cast.unleashLife() then return end
end
end
end
-- Healing Surge
if isChecked("Healing Surge") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Surge") and (buff.tidalWaves.exists() or level < 100) then
if cast.healingSurge(br.friend[i].unit) then return end
end
end
end
-- Healing Rain
if not moving then
if (SpecificToggle("Healing Rain Key") and not GetCurrentKeyBoardFocus()) then
if CastSpellByName(GetSpellInfo(spell.healingRain),"cursor") then return end
end
if isChecked("Healing Rain") and not buff.healingRain.exists() and getLowAllies(getValue("Healing Rain")) >= getValue("Healing Rain Targets") then
if castGroundAtBestLocation(spell.healingRain, 20, 0, 40, 0, "heal") then return end
end
end
-- Spirit Link Totem
if isChecked("Spirit Link Totem") and not moving then
if (SpecificToggle("Spirit Link Totem Key") and not GetCurrentKeyBoardFocus()) then
if CastSpellByName(GetSpellInfo(spell.spiritLinkTotem),"cursor") then return end
end
if not buff.healingRain.exists() and getLowAllies(getValue("Spirit Link Totem")) >= getValue("Spirit Link Totem Targets") then
if castGroundAtBestLocation(spell.spiritLinkTotem, 20, 3, 40, 0, "heal") then return end
end
end
-- Healing Wave
if isChecked("Healing Wave") then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue("Healing Wave") and (buff.tidalWaves.exists() or level < 100) then
if cast.healingWave(br.friend[i].unit) then return end
end
end
end
-- Oh Shit! Healing Surge
if isChecked("Healing Surge") then
for i = 1, #br.friend do
if br.friend[i].hp <= 40 then
if cast.healingSurge(br.friend[i].unit) then return end
end
end
end
-- Ephemeral Paradox trinket
if hasEquiped(140805) and getBuffRemain("player", 225771) > 2 then
if cast.healingWave(lowest.unit) then return end
end
end -- End Action List Single Target
-- Action List - DPS
local function actionList_DPS()
-- Lightning Surge Totem
if isChecked("Lightning Surge Totem - HP") and php <= getOptionValue("Lightning Surge Totem - HP") and inCombat and #enemies.yards5 > 0 and lastSpell ~= spell.lightningSurgeTotem then
if cast.lightningSurgeTotem("player","ground") then return end
end
if isChecked("Lightning Surge Totem - AoE") and #enemies.yards5 >= getOptionValue("Lightning Surge Totem - AoE") and inCombat and lastSpell ~= spell.lightningSurgeTotem then
if cast.lightningSurgeTotem("best",nil,getOptionValue("Lightning Surge Totem - AoE"),8) then return end
end
-- Lava Burst - Lava Surge
if buff.lavaSurge.exists() then
if cast.lavaBurst() then return end
end
-- Flameshock
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards5[i]
if not debuff.flameShock.exists(thisUnit) then
if cast.flameShock(thisUnit) then return end
end
end
-- Lava Burst
if debuff.flameShock.remain(units.dyn40) > getCastTime(spell.lavaBurst) or level < 20 then
if cast.lavaBurst() then return end
end
-- Lightning Bolt
if cast.lightningBolt() then return end
end -- End Action List - DPS
-----------------
--- Rotations ---
-----------------
-- Pause
if pause() or mode.rotation == 4 then
return true
else
---------------------------------
--- Out Of Combat - Rotations ---
---------------------------------
if not inCombat and not IsMounted() and not drinking then
actionList_Extras()
if isChecked("OOC Healing") then
actionList_PreCombat()
end
end -- End Out of Combat Rotation
-----------------------------
--- In Combat - Rotations ---
-----------------------------
if inCombat and not IsMounted() and not drinking then
actionList_Defensive()
actionList_Interrupts()
actionList_Cooldowns()
if talent.cloudburstTotem and buff.cloudburstTotem.exists() then
actionList_CBT()
end
actionList_AOEHealing()
actionList_SingleTarget()
if br.player.mode.dps == 1 then
actionList_DPS()
end
end -- End In Combat Rotation
end -- Pause
end -- End Timer
end -- End runRotation
local id = 264
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
}) | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/items/warm_egg.lua | 35 | 1186 | -----------------------------------------
-- ID: 4602
-- Item: warm_egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 18
-- Magic 18
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4602);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 18);
target:addMod(MOD_MP, 18);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 18);
target:delMod(MOD_MP, 18);
end;
| gpl-3.0 |
Gael-de-Sailly/minetest-minetestforfun-server | mods/homedecor_modpack/homedecor/kitchen_appliances.lua | 10 | 7100 | -- This file supplies refrigerators
local S = homedecor.gettext
-- steel-textured fridge
homedecor.register("refrigerator_steel", {
mesh = "homedecor_refrigerator.obj",
tiles = { "homedecor_refrigerator_steel.png" },
inventory_image = "homedecor_refrigerator_steel_inv.png",
description = S("Refrigerator (stainless steel)"),
groups = {snappy=3},
sounds = default.node_sound_stone_defaults(),
selection_box = homedecor.nodebox.slab_y(2),
collision_box = homedecor.nodebox.slab_y(2),
expand = { top="placeholder" },
infotext=S("Refrigerator"),
inventory = {
size=50,
lockable=true,
},
on_rotate = screwdriver.rotate_simple
})
-- white, enameled fridge
homedecor.register("refrigerator_white", {
mesh = "homedecor_refrigerator.obj",
tiles = { "homedecor_refrigerator_white.png" },
inventory_image = "homedecor_refrigerator_white_inv.png",
description = S("Refrigerator"),
groups = {snappy=3},
selection_box = homedecor.nodebox.slab_y(2),
collision_box = homedecor.nodebox.slab_y(2),
sounds = default.node_sound_stone_defaults(),
expand = { top="placeholder" },
infotext=S("Refrigerator"),
inventory = {
size=50,
lockable=true,
},
on_rotate = screwdriver.rotate_simple
})
minetest.register_alias("homedecor:refrigerator_white_bottom", "homedecor:refrigerator_white")
minetest.register_alias("homedecor:refrigerator_white_top", "air")
minetest.register_alias("homedecor:refrigerator_steel_bottom", "homedecor:refrigerator_steel")
minetest.register_alias("homedecor:refrigerator_steel_top", "air")
minetest.register_alias("homedecor:refrigerator_white_bottom_locked", "homedecor:refrigerator_white_locked")
minetest.register_alias("homedecor:refrigerator_white_top_locked", "air")
minetest.register_alias("homedecor:refrigerator_steel_bottom_locked", "homedecor:refrigerator_steel_locked")
minetest.register_alias("homedecor:refrigerator_steel_top_locked", "air")
-- kitchen "furnaces"
homedecor.register_furnace("oven", {
description = S("Oven"),
tile_format = "homedecor_oven_%s%s.png",
output_slots = 4,
output_width = 2,
cook_speed = 1.25,
})
homedecor.register_furnace("oven_steel", {
description = S("Oven (stainless steel)"),
tile_format = "homedecor_oven_steel_%s%s.png",
output_slots = 4,
output_width = 2,
cook_speed = 1.25,
})
homedecor.register_furnace("microwave_oven", {
description = S("Microwave Oven"),
tiles = {
"homedecor_microwave_top.png", "homedecor_microwave_top.png^[transformR180",
"homedecor_microwave_top.png^[transformR270", "homedecor_microwave_top.png^[transformR90",
"homedecor_microwave_top.png^[transformR180", "homedecor_microwave_front.png"
},
tiles_active = {
"homedecor_microwave_top.png", "homedecor_microwave_top.png^[transformR180",
"homedecor_microwave_top.png^[transformR270", "homedecor_microwave_top.png^[transformR90",
"homedecor_microwave_top.png^[transformR180", "homedecor_microwave_front_active.png"
},
output_slots = 2,
output_width = 2,
cook_speed = 1.5,
extra_nodedef_fields = {
node_box = {
type = "fixed",
fixed = { -0.5, -0.5, -0.125, 0.5, 0.125, 0.5 },
},
},
})
-- coffee!
-- coffee!
-- coffee!
local cm_cbox = {
type = "fixed",
fixed = {
{ 0, -8/16, 0, 7/16, 3/16, 8/16 },
{ -4/16, -8/16, -6/16, -1/16, -5/16, -3/16 }
}
}
homedecor.register("coffee_maker", {
mesh = "homedecor_coffeemaker.obj",
tiles = {
"homedecor_coffeemaker_decanter.png",
"homedecor_coffeemaker_cup.png",
"homedecor_coffeemaker_case.png",
},
description = "Coffee Maker",
inventory_image = "homedecor_coffeemaker_inv.png",
walkable = false,
groups = {snappy=3},
selection_box = cm_cbox,
node_box = cm_cbox,
on_rotate = screwdriver.disallow
})
local fdir_to_steampos = {
x = { 0.15, 0.275, -0.15, -0.275 },
z = { 0.275, -0.15, -0.275, 0.15 }
}
minetest.register_abm({
nodenames = "homedecor:coffee_maker",
label = "sfx",
interval = 2,
chance = 1,
action = function(pos, node)
local fdir = node.param2
if fdir and fdir < 4 then
local steamx = fdir_to_steampos.x[fdir + 1]
local steamz = fdir_to_steampos.z[fdir + 1]
minetest.add_particlespawner({
amount = 1,
time = 1,
minpos = {x=pos.x - steamx, y=pos.y - 0.35, z=pos.z - steamz},
maxpos = {x=pos.x - steamx, y=pos.y - 0.35, z=pos.z - steamz},
minvel = {x=-0.003, y=0.01, z=-0.003},
maxvel = {x=0.003, y=0.01, z=-0.003},
minacc = {x=0.0,y=-0.0,z=-0.0},
maxacc = {x=0.0,y=0.003,z=-0.0},
minexptime = 2,
maxexptime = 5,
minsize = 1,
maxsize = 1.2,
collisiondetection = false,
texture = "homedecor_steam.png",
})
end
end
})
homedecor.register("toaster", {
description = "Toaster",
tiles = { "homedecor_toaster_sides.png" },
inventory_image = "homedecor_toaster_inv.png",
walkable = false,
groups = { snappy=3 },
node_box = {
type = "fixed",
fixed = {
{-0.0625, -0.5, -0.125, 0.125, -0.3125, 0.125}, -- NodeBox1
},
},
on_rightclick = function(pos, node, clicker)
local fdir = node.param2
minetest.set_node(pos, { name = "homedecor:toaster_loaf", param2 = fdir })
minetest.sound_play("toaster", {
pos = pos,
gain = 1.0,
max_hear_distance = 5
})
end
})
homedecor.register("toaster_loaf", {
tiles = {
"homedecor_toaster_toploaf.png",
"homedecor_toaster_sides.png",
"homedecor_toaster_sides.png",
"homedecor_toaster_sides.png",
"homedecor_toaster_sides.png",
"homedecor_toaster_sides.png"
},
walkable = false,
groups = { snappy=3, not_in_creative_inventory=1 },
node_box = {
type = "fixed",
fixed = {
{-0.0625, -0.5, -0.125, 0.125, -0.3125, 0.125}, -- NodeBox1
{-0.03125, -0.3125, -0.0935, 0, -0.25, 0.0935}, -- NodeBox2
{0.0625, -0.3125, -0.0935, 0.0935, -0.25, 0.0935}, -- NodeBox3
},
},
on_rightclick = function(pos, node, clicker)
local fdir = node.param2
minetest.set_node(pos, { name = "homedecor:toaster", param2 = fdir })
end,
drop = "homedecor:toaster"
})
homedecor.register("dishwasher", {
description = "Dishwasher",
drawtype = "nodebox",
tiles = {
"homedecor_dishwasher_top.png",
"homedecor_dishwasher_bottom.png",
"homedecor_dishwasher_sides.png",
"homedecor_dishwasher_sides.png^[transformFX",
"homedecor_dishwasher_back.png",
"homedecor_dishwasher_front.png"
},
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.4375, 0.5},
{-0.5, -0.5, -0.5, 0.5, 0.5, -0.4375},
{-0.5, -0.5, -0.5, 0.5, 0.1875, 0.1875},
{-0.4375, -0.5, -0.5, 0.4375, 0.4375, 0.4375},
}
},
selection_box = { type = "regular" },
sounds = default.node_sound_stone_defaults(),
groups = { snappy = 3 },
})
local materials = {"granite", "marble", "steel", "wood"}
for _, m in ipairs(materials) do
homedecor.register("dishwasher_"..m, {
description = "Dishwasher ("..m..")",
tiles = {
"homedecor_kitchen_cabinet_top_"..m..".png",
"homedecor_dishwasher_bottom.png",
"homedecor_dishwasher_sides.png",
"homedecor_dishwasher_sides.png^[transformFX",
"homedecor_dishwasher_back.png",
"homedecor_dishwasher_front.png"
},
groups = { snappy = 3 },
sounds = default.node_sound_stone_defaults(),
})
end
| unlicense |
TRIEXTEAM/TaylortTG | plugins/plugins.lua | 1 | 6408 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local tmp = '\n\n@telemanager_ch'
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
local text = text..'\n\n'..nsum..' plugins installed\n\n'..nact..' plugins enabled\n\n'..nsum-nact..' plugins disabled'..tmp
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
-- text = text..v..' '..status..'\n'
end
end
local text = text..'\nPlugins Reloaded !\n\n'..nact..' plugins enabled\n'..nsum..' plugins installed\n\n@telemanager_ch'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return ''..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return ''..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return ' '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return ' '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return ' '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return ' '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == '+' and matches[3] == 'chat' then
if is_momod(msg) then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
end
-- Enable a plugin
if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if is_momod(msg) then
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
end
-- Disable a plugin on a chat
if matches[1] == '-' and matches[3] == 'chat' then
if is_momod(msg) then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
end
-- Disable a plugin
if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins + [plugin] : enable plugin.",
"!plugins - [plugin] : disable plugin.",
"!plugins * : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (+) ([%w_%.%-]+)$",
"^!plugins? (-) ([%w_%.%-]+)$",
"^!plugins? (+) ([%w_%.%-]+) (chat)",
"^!plugins? (-) ([%w_%.%-]+) (chat)",
"^!plugins? (*)$",
"^[!/](reload)$"
},
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
aosee1h1/AOSEE_2H2 | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
subzrk/BadRotations | System/Libs/LibRangeCheck-2.0/LibStub-1.0/tests/test.lua | 86 | 2013 | debugstack = debug.traceback
strmatch = string.match
loadfile("../LibStub.lua")()
local lib, oldMinor = LibStub:NewLibrary("Pants", 1) -- make a new thingy
assert(lib) -- should return the library table
assert(not oldMinor) -- should not return the old minor, since it didn't exist
-- the following is to create data and then be able to check if the same data exists after the fact
function lib:MyMethod()
end
local MyMethod = lib.MyMethod
lib.MyTable = {}
local MyTable = lib.MyTable
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 1) -- try to register a library with the same version, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 0) -- try to register a library with a previous, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 2) -- register a new version
assert(newLib) -- library table
assert(rawequal(newLib, lib)) -- should be the same reference as the previous
assert(newOldMinor == 1) -- should return the minor version of the previous version
assert(rawequal(lib.MyMethod, MyMethod)) -- verify that values were saved
assert(rawequal(lib.MyTable, MyTable)) -- verify that values were saved
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 3 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib) -- library table
assert(newOldMinor == 2) -- previous version was 2
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 4 and please ignore 15 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib)
assert(newOldMinor == 3) -- previous version was 3 (even though it gave a string)
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 5) -- register a new library, using a normal number instead of a string
assert(newLib)
assert(newOldMinor == 4) -- previous version was 4 (even though it gave a string) | gpl-3.0 |
sadegh1996/sword_antispam | plugins/save.lua | 13 | 2829 | local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return "ذخیره شد "..name
end
end
local function run(msg, matches)
if not is_momod(msg) then
return "فقط برای ادمین مجاز است"
end
local name = string.sub(matches[1], 1, 50)
local value = string.sub(matches[2], 1, 1000)
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
end
return {
patterns = {
"^[!/]save ([^%s]+) (.+)$",
},
run = run
}
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/mixtures/pot.lua | 1 | 1515 |
POT_GROW_TIME = 60 * 15;
MAX_POT = 5;
local MIXTURE = {}
MIXTURE.ID = 2;
MIXTURE.Results = "drug_pot";
MIXTURE.Ingredients = {"drug_pot_seeds", "item_pot"};
MIXTURE.Requires = {
{GENE_INTELLIGENCE, 1},
{GENE_DEXTERITY, 1},
};
MIXTURE.Free = true;
MIXTURE.RequiresHeatSource = false;
MIXTURE.RequiresWaterSource = false;
MIXTURE.RequiresSawHorse = false;
function MIXTURE.CanMix ( player, pos )
if (player:Team() != TEAM_CITIZEN) then
player:Notify("You cannot do this as a government official.");
return false;
end
local NumDrugs = 0;
//needs fix
for k, v in pairs(ents.FindByClass('ent_pot')) do
if v:GetTable().ItemSpawner == player then
NumDrugs = NumDrugs + 1;
end
end
local VipWeed = MAX_POT;
if(player:GetLevel() == 99) then
VipWeed = 6;
elseif(player:GetLevel() == 98) then
VipWeed = 8
elseif(player:GetLevel() <= 97) then
VipWeed = 10
end
if (NumDrugs >= VipWeed) then
if (player:GetLevel() == 100) then
player:Notify("Bronze VIP pot limit reached");
elseif(player:GetLevel() == 99) then
player:Notify("Silver VIP pot limit reached");
elseif(player:GetLevel() == 98) then
player:Notify("Gold VIP pot limit reached");
elseif(player:GetLevel() == 97) then
player:Notify("Diamond VIP pot limit reached");
elseif(player:GetLevel() < 97) then
player:Notify("Admin pot limit reached");
else
player:Notify("Guest pot limit reached");
end
return false;
end
return true;
end
GM:RegisterMixture(MIXTURE); | mit |
Arashbrsh/copyuz | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
sjznxd/lc-20130127 | applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua | 141 | 1054 | --[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, true)
return m
| apache-2.0 |
daofeng2015/luci | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua | 141 | 1054 | --[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, true)
return m
| apache-2.0 |
TW1STaL1CKY/pac3 | lua/pac3/core/client/parts.lua | 1 | 3727 | local pac = pac
local class = pac.class
local part_count = 0 -- unique id thing
local pairs = pairs
local function merge_storable(tbl, base)
if not base then return end
if base.StorableVars then
for k,v in pairs(base.StorableVars) do
tbl.StorableVars[k] = v
end
merge_storable(tbl, base.BaseClass)
end
end
local function initialize(part, owner)
if part.PreInitialize then
part:PreInitialize()
end
pac.AddPart(part)
if owner then
part:SetPlayerOwner(owner)
end
part:Initialize()
end
function pac.CreatePart(name, owner)
owner = owner or pac.LocalPlayer
if not name then
name = "base"
end
local part = class.Create("part", name)
if not part then
pac.Message("Tried to create unknown part: " .. name .. '!')
part = class.Create("part", "base")
end
part.Id = part_count
part_count = part_count + 1
part.IsEnabled = pac.CreateClientConVarFast("pac_enable_" .. name, "1", true,"boolean")
part:SetUniqueID(tostring(util.CRC(os.time() + pac.RealTime + part_count)))
merge_storable(part, part.BaseClass)
if part.RemovedStorableVars then
for k in pairs(part.RemovedStorableVars) do
part.StorableVars[k] = nil
end
end
if part.NonPhysical then
pac.RemoveProperty(part, "Bone")
pac.RemoveProperty(part, "Position")
pac.RemoveProperty(part, "Angles")
pac.RemoveProperty(part, "AngleVelocity")
pac.RemoveProperty(part, "EyeAngles")
pac.RemoveProperty(part, "AimName")
pac.RemoveProperty(part, "AimPartName")
pac.RemoveProperty(part, "PositionOffset")
pac.RemoveProperty(part, "AngleOffset")
pac.RemoveProperty(part, "Translucent")
pac.RemoveProperty(part, "IgnoreZ")
pac.RemoveProperty(part, "BlendMode")
pac.RemoveProperty(part, "NoTextureFiltering")
if part.ClassName ~= "group" then
pac.RemoveProperty(part, "DrawOrder")
end
end
part.DefaultVars = {}
for key in pairs(part.StorableVars) do
part.DefaultVars[key] = pac.class.Copy(part[key])
end
part.DefaultVars.UniqueID = "" -- uh
local ok, err = xpcall(initialize, ErrorNoHalt, part, owner)
if not ok then
part:Remove()
if part.ClassName ~= "base" then
return pac.CreatePart("base", owner)
end
end
pac.dprint("creating %s part owned by %s", part.ClassName, tostring(owner))
timer.Simple(0.1, function()
if part:IsValid() and part.show_in_editor ~= false and owner == pac.LocalPlayer then
pac.CallHook("OnPartCreated", part)
end
end)
return part
end
function pac.RegisterPart(META, name)
if META.Group == "experimental" then
-- something is up with the lua cache
-- file.Find("pac3/core/client/parts/*.lua", "LUA") will find the experimental parts as well
-- maybe because pac3 mounts the workshop version on server?
return
end
META.TypeBase = "base"
local _, name = class.Register(META, "part", name)
if pac.UpdatePartsWithMetatable then
pac.UpdatePartsWithMetatable(META, name)
end
end
function pac.GenerateNewUniqueID(part_data, base)
local part_data = table.Copy(part_data)
base = base or tostring(part_data)
local function fixpart(part)
for key, val in pairs(part.self) do
if val ~= "" and (key == "UniqueID" or key:sub(-3) == "UID") then
part.self[key] = util.CRC(base .. val)
end
end
for _, part in pairs(part.children) do
fixpart(part)
end
end
return part_data
end
function pac.LoadParts()
local files = file.Find("pac3/core/client/parts/*.lua", "LUA")
for _, name in pairs(files) do
include("pac3/core/client/parts/" .. name)
end
local files = file.Find("pac3/core/client/parts/legacy/*.lua", "LUA")
for _, name in pairs(files) do
include("pac3/core/client/parts/legacy/" .. name)
end
end
function pac.GetRegisteredParts()
return class.GetAll("part")
end
include("base_part.lua") | gpl-3.0 |
suchipi/pac3 | lua/pac3/editor/client/translations/japanese.lua | 1 | 3140 | return {
["sprite path"] = "sprite path",
["right upperarm"] = "右 上腕",
["neck"] = "首",
["size y"] = "Y軸のサイズ",
["draw shadow"] = "影を表示",
["copy"] = "コピー",
["start size"] = "開始 サイズ",
["clip"] = "クリップ",
["size"] = "サイズ",
["reset view"] = "カメラをリセット",
["right calf"] = "右 ふくらはぎ",
["effect"] = "エフェクト",
["max"] = "最大",
["angles"] = "角度",
["left foot"] = "左 足",
["font"] = "フォント",
["wear"] = "着用",
["load"] = "読み込み",
["bodygroup state"] = "ボディグループ ステータス",
["size x"] = "X軸のサイズ",
["relative bones"] = "relative bones",
["scale"] = "スケール",
["follow"] = "follow",
["outline color"] = "アウトラインの色",
["left thigh"] = "左 太もも",
["bone"] = "骨",
["invert"] = "反転",
["double face"] = "両面",
["clear"] = "全消去",
["right forearm"] = "右 前腕",
["left hand"] = "左 手",
["left upperarm"] = "左 上腕",
["false"] = "無効",
["alpha"] = "透過度",
["use lua"] = "Luaを使用",
["sprite"] = "sprite",
["my outfit"] = "自分の衣装",
["right hand"] = "右 手",
["angle velocity"] = "回転速度",
["right clavicle"] = "右 鎖骨",
["outline"] = "概要",
["string"] = "文字列",
["description"] = "説明",
["left clavicle"] = "左 鎖骨",
["color"] = "色",
["save"] = "保存",
["parent name"] = "親の名前",
["toggle t pose"] = "Tポーズのトグル",
["outline alpha"] = "アウトラインの透過度",
["remove"] = "削除",
["spine 4"] = "脊椎 4",
["skin"] = "スキン",
["command"] = "コマンド",
["material"] = "マテリアル",
["sound"] = "音",
["fullbright"] = "明るさの最大化",
["true"] = "有効",
["spine 2"] = "脊椎 2",
["bone merge"] = "骨 統合",
["animation"] = "アニメーション",
["spine 1"] = "脊椎 1",
["text"] = "テキスト",
["rate"] = "速度",
["operator"] = "operator",
["spine"] = "脊椎",
["loop"] = "繰り返し",
["clone"] = "複製",
["position"] = "位置",
["model"] = "モデル",
["sequence name"] = "シーケンス名",
["left toe"] = "左 つま先",
["pelvis"] = "骨盤",
["pitch"] = "ピッチ",
["right toe"] = "右 つま先",
["right finger 2"] = "右 指 2",
["add parts to me!"] = "add parts to me!",
["group"] = "グループ",
["right foot"] = "右 足",
["aim part name"] = "aim part name",
["left calf"] = "左 ふくらはぎ",
["rotate origin"] = "回転の原点",
["trail path"] = "trail path",
["reset eye angles"] = "目の角度をリセット",
["volume"] = "音量",
["entity"] = "エンティティ",
["modify"] = "編集",
["draw weapon"] = "武器を表示",
["hide"] = "隠す",
["length"] = "長さ",
["offset"] = "オフセット",
["owner name"] = "所有者名",
["head"] = "頭",
["bodygroup"] = "ボディグループ",
["brightness"] = "明るさ",
["eye angles"] = "目の角度",
["event"] = "イベント",
["trail"] = "trail",
["arguments"] = "引数",
["name"] = "名前",
["right thigh"] = "右 太もも",
["ping pong loop"] = "ping pong loop",
["min"] = "最小",
["left forearm"] = "左 腕",
["light"] = "ライト",
} | gpl-3.0 |
Gael-de-Sailly/minetest-minetestforfun-server | mods/_misc/sapling_crafts.lua | 7 | 2317 | -- Crafts for saplings
-- From Skyblock by Cornernote
--
-- sapling from leaves and sticks
minetest.register_craft({
output = 'default:sapling',
recipe = {
{'default:leaves', 'default:leaves', 'default:leaves'},
{'default:leaves', 'default:leaves', 'default:leaves'},
{'', 'default:stick', ''},
}
})
-- junglesapling from jungleleaves and sticks
minetest.register_craft({
output = 'default:junglesapling',
recipe = {
{'default:jungleleaves', 'default:jungleleaves', 'default:jungleleaves'},
{'default:jungleleaves', 'default:jungleleaves', 'default:jungleleaves'},
{'', 'default:stick', ''},
}
})
-- pine_sapling from pine_needles and sticks
minetest.register_craft({
output = 'default:pine_sapling',
recipe = {
{'default:pine_needles', 'default:pine_needles', 'default:pine_needles'},
{'default:pine_needles', 'default:pine_needles', 'default:pine_needles'},
{'', 'default:stick', ''},
}
})
-- Aspen tree
minetest.register_craft({
output = "default:aspen_sapling",
recipe = {
{"default:aspen_leaves", "default:aspen_leaves", "default:aspen_leaves"},
{"default:aspen_leaves", "default:aspen_leaves", "default:aspen_leaves"},
{"", "default:stick", ""},
}
})
-- Cherry trees
minetest.register_craft({
output = "default:cherry_sapling",
recipe = {
{"default:cherry_blossom_leaves", "default:cherry_blossom_leaves", "default:cherry_blossom_leaves"},
{"default:cherry_blossom_leaves", "default:cherry_blossom_leaves", "default:cherry_blossom_leaves"},
{"", "default:stick", ""},
}
})
-- With nether
if minetest.get_modpath("nether") then
minetest.register_craft({
output = "nether:tree_sapling",
recipe = {
{"nether:leaves", "nether:leaves", "nether:leaves"},
{"nether:leaves", "nether:leaves", "nether:leaves"},
{"", "default:stick", ""},
}
})
end
-- With moretrees
if minetest.get_modpath("moretrees") then
for _, tdef in pairs(moretrees.treelist) do
local treename = tdef[1]
if treename ~= "jungletree" then
local leaves = "moretrees:" .. treename .. "_leaves"
minetest.register_craft({
output = "moretrees:" .. treename .. "_sapling",
recipe = {
{leaves, leaves, leaves},
{leaves, leaves, leaves},
{"", "default:stick", ""},
}
})
end
end
end
| unlicense |
FFXIOrgins/FFXIOrgins | scripts/globals/items/black_curry_bun_+1.lua | 35 | 1350 | -----------------------------------------
-- ID: 5764
-- Item: black_curry_bun+1
-- Food Effect: 60 minutes, All Races
-----------------------------------------
-- Intelligence +1
-- Vitality +4
-- Dexterity +2
-- Defense +~16%
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,5764);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 1);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_FOOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_INT, 1);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_FOOD_DEFP, 16);
end; | gpl-3.0 |
Gael-de-Sailly/minetest-minetestforfun-server | mods/chesttools/init.lua | 8 | 17095 | -- 05.10.14 Fixed bug in protection/access
chesttools = {}
chesttools.chest_add = {};
chesttools.chest_add.tiles = {
"chesttools_blue_chest_top.png", "chesttools_blue_chest_top.png", "chesttools_blue_chest_side.png",
"chesttools_blue_chest_side.png", "chesttools_blue_chest_side.png", "chesttools_blue_chest_lock.png"};
chesttools.chest_add.groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2};
chesttools.chest_add.tube = {};
-- additional/changed definitions for pipeworks;
-- taken from pipeworks/compat.lua
if( minetest.get_modpath( 'pipeworks' )) then
chesttools.chest_add.tiles = {
"chesttools_blue_chest_top.png^pipeworks_tube_connection_wooden.png",
"chesttools_blue_chest_top.png^pipeworks_tube_connection_wooden.png",
"chesttools_blue_chest_side.png^pipeworks_tube_connection_wooden.png",
"chesttools_blue_chest_side.png^pipeworks_tube_connection_wooden.png",
"chesttools_blue_chest_side.png^pipeworks_tube_connection_wooden.png"};
chesttools.chest_add.groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2,
tubedevice = 1, tubedevice_receiver = 1 };
chesttools.chest_add.tube = {
insert_object = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:add_item("main", stack)
end,
can_insert = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:room_for_item("main", stack)
end,
input_inventory = "main",
connect_sides = {left=1, right=1, back=1, front=1, bottom=1, top=1}
};
end
chesttools.formspec = "size[9,10]"..
"list[current_name;main;0.5,0.3;8,4;]"..
"label[0.0,9.7;Title/Content:]"..
"field[1.8,10.0;6,0.5;chestname;;]"..
"button[7.5,9.7;1,0.5;set_chestname;Store]"..
"label[0.0,4.4;Main]"..
"button[1.0,4.5;1,0.5;craft;Craft]"..
"button[7.0,4.5;0.5,0.5;drop_all;DA]"..
"button[7.5,4.5;0.5,0.5;take_all;TA]"..
"button[8.0,4.5;0.5,0.5;swap_all;SA]"..
"button[8.5,4.5;0.5,0.5;filter_all;FA]";
if( minetest.get_modpath( 'unified_inventory')) then
chesttools.formspec = chesttools.formspec..
"button[2.0,4.5;1,0.5;bag1;Bag 1]"..
"button[3.0,4.5;1,0.5;bag2;Bag 2]"..
"button[4.0,4.5;1,0.5;bag3;Bag 3]"..
"button[5.0,4.5;1,0.5;bag4;Bag 4]";
end
chesttools.may_use = function( pos, player )
if( not( player )) then
return false;
end
local name = player:get_player_name();
local meta = minetest.get_meta( pos );
local owner = meta:get_string( 'owner' )
-- the owner can access the chest
if( owner == name or owner == "" ) then
return true;
end
-- the shared function only kicks in if the area is protected
if( not( minetest.is_protected(pos, name ))
and minetest.is_protected(pos, ' _DUMMY_PLAYER_ ')) then
return true;
end
return false;
end
chesttools.on_receive_fields = function(pos, formname, fields, player)
if( fields.quit ) then
return;
end
local meta = minetest.get_meta( pos );
local chestname = meta:get_string( 'chestname' );
if( fields.set_chestname and fields.chestname ) then
chestname = tostring( fields.chestname );
meta:set_string( 'chestname', chestname );
meta:set_string("infotext", "\""..chestname.."\" Chest (owned by "..meta:get_string("owner")..")")
-- update the normal formspec
meta:set_string("formspec", chesttools.formspec..
"field[1.8,10.0;6,0.5;chestname;;"..chestname.."]"..
"list[current_player;main;0.5,5.5;8,4;]");
end
local formspec = "size[9,10]"..
"label[0.0,9.7;Title/Content:]"..
"field[1.8,10.0;6,0.5;chestname;;"..tostring( chestname or "unconfigured").."]"..
"button[7.5,9.7;1,0.5;set_chestname;Store]"..
"list[current_name;main;0.5,0.3;8,4;]"..
"button[7.0,4.5;0.5,0.5;drop_all;DA]"..
"button[7.5,4.5;0.5,0.5;take_all;TA]"..
"button[8.0,4.5;0.5,0.5;swap_all;SA]"..
"button[8.5,4.5;0.5,0.5;filter_all;FA]";
local bm = "button[0.0,4.5;1,0.5;main;Main]";
local bc = "button[1.0,4.5;1,0.5;craft;Craft]";
local b1 = "button[2.0,4.5;1,0.5;bag1;Bag 1]";
local b2 = "button[3.0,4.5;1,0.5;bag2;Bag 2]";
local b3 = "button[4.0,4.5;1,0.5;bag3;Bag 3]";
local b4 = "button[5.0,4.5;1,0.5;bag4;Bag 4]";
local selected = '';
if( fields.drop_all or fields.take_all or fields.swap_all or fields.filter_all ) then
-- check if the player has sufficient access to the chest
local node = minetest.get_node( pos );
-- deny access for unsupported chests
if( not( node )
or (node.name == 'chesttools:shared_chest' and not( chesttools.may_use( pos, player )))
or (node.name == 'default:chest_locked'and player:get_player_name() ~= meta:get_string('owner' ))) then
if( node.name ~= 'default:chest' ) then
minetest.chat_send_player( player:get_player_name(), 'Sorry, you do not have access to the content of this chest.');
return;
end
end
selected = fields.selected;
if( not( selected ) or selected == '') then
selected = 'main';
end
local inv_list = 'main';
if( selected == 'main' ) then
inv_list = 'main';
elseif( selected == 'craft' ) then
inv_list = 'craft';
elseif( selected == 'bag1' or selected == 'bag2' or selected == 'bag3' or selected=='bag4') then
inv_list = selected.."contents";
end
local player_inv = player:get_inventory();
local chest_inv = meta:get_inventory();
if( fields.drop_all ) then
for i,v in ipairs( player_inv:get_list( inv_list ) or {}) do
if( chest_inv and chest_inv:room_for_item('main', v)) then
local leftover = chest_inv:add_item( 'main', v );
player_inv:remove_item( inv_list, v );
if( leftover and not( leftover:is_empty() )) then
player_inv:add_item( inv_list, v );
end
end
end
elseif( fields.take_all ) then
for i,v in ipairs( chest_inv:get_list( 'main' ) or {}) do
if( player_inv:room_for_item( inv_list, v)) then
local leftover = player_inv:add_item( inv_list, v );
chest_inv:remove_item( 'main', v );
if( leftover and not( leftover:is_empty() )) then
chest_inv:add_item( 'main', v );
end
end
end
elseif( fields.swap_all ) then
for i,v in ipairs( player_inv:get_list( inv_list ) or {}) do
if( chest_inv ) then
local tmp = player_inv:get_stack( inv_list, i );
player_inv:set_stack( inv_list, i, chest_inv:get_stack( 'main', i ));
chest_inv:set_stack( 'main', i, v );
end
end
elseif( fields.filter_all ) then
for i,v in ipairs( player_inv:get_list( inv_list ) or {}) do
if( chest_inv and chest_inv:room_for_item('main', v) and chest_inv:contains_item( 'main', v:get_name())) then
local leftover = chest_inv:add_item( 'main', v );
player_inv:remove_item( inv_list, v );
if( leftover and not( leftover:is_empty() )) then
player_inv:add_item( inv_list, v );
end
end
end
end
end
local bag_nr = 0;
if( fields[ 'main'] or selected=='main' or fields['set_chestname']) then
bag_nr = 0;
formspec = formspec..
"list[current_player;main;0.5,5.5;8,4;]";
bm = "label[0.0,4.4;Main]";
selected = 'main';
elseif( fields[ 'craft'] or selected=='craft') then
bag_nr = 0;
formspec = formspec..
"label[0,5.5;Crafting]"..
"list[current_player;craftpreview;6.5,6.5;1,1;]"..
"list[current_player;craft;2.5,6.5;3,3;]";
bc = "label[1.0,4.4;Craft]";
selected = 'craft';
elseif( fields[ 'bag1' ] or selected=='bag1') then
bag_nr = 1;
b1 = "label[2.0,4.4;Bag 1]";
selected = 'bag1';
elseif( fields[ 'bag2' ] or selected=='bag2') then
bag_nr = 2;
b2 = "label[3.0,4.4;Bag 2]";
selected = 'bag2';
elseif( fields[ 'bag3' ] or selected=='bag3') then
bag_nr = 3;
b3 = "label[4.0,4.4;Bag 3]";
selected = 'bag3';
elseif( fields[ 'bag4' ] or selected=='bag4') then
bag_nr = 4;
b4 = "label[5.0,4.4;Bag 4]";
selected = 'bag4';
end
if( bag_nr >= 1 and bag_nr <= 4 ) then
formspec = formspec..
"label[0.5,5.5;Bag "..bag_nr.."]";
local stack = player:get_inventory():get_stack( "bag"..bag_nr, 1)
if( stack and not( stack:is_empty())) then
local image = stack:get_definition().inventory_image
if( image ) then
formspec = formspec..
"image[7.5,5.5;1,1;"..image.."]";
end
local slots = stack:get_definition().groups.bagslots
if( slots and slots>0 ) then -- no bag present?
formspec = formspec..
"list[current_player;bag"..bag_nr.."contents;0.5,6.5;8,"..tostring(slots/8)..";]";
end
end
end
formspec = formspec..bm..bc..b1..b2..b3..b4..
-- provide the position of the chest
"field[20,20;0.1,0.1;pos2str;Pos;"..minetest.pos_to_string( pos ).."]"..
-- which inventory was selected?
"field[20,20;0.1,0.1;selected;selected;"..selected.."]";
-- instead of updating the formspec of the chest - which would be slow - we display
-- the new formspec directly to the player who asked for it;
-- this is also necessary because players may have bags with diffrent sizes
minetest.show_formspec( player:get_player_name(), "chesttools:shared_chest", formspec );
end
chesttools.update_chest = function(pos, formname, fields, player)
local pname = player:get_player_name();
if( not( pos ) or not( pos.x ) or not( pos.y ) or not( pos.z )) then
return;
end
local node = minetest.get_node( pos );
local price = 1;
if( node.name=='default:chest' ) then
if( fields.normal) then
return;
end
if( fields.locked ) then
price = 1;
elseif( fields.shared ) then
price = 2;
end
elseif( node.name=='default:chest_locked' ) then
if( fields.locked) then
return;
end
if( fields.normal ) then
price = -1;
elseif( fields.shared ) then
price = 1;
end
elseif( node.name=='chesttools:shared_chest') then
if( fields.shared) then
return;
end
if( fields.normal ) then
price = -2;
elseif( fields.locked ) then
price = -1;
end
else
return;
end
local player_inv = player:get_inventory();
if( price>0 and not( player_inv:contains_item( 'main', 'default:steel_ingot '..tostring( price )))) then
minetest.chat_send_player( pname, 'Sorry. You do not have '..tostring( price )..' steel ingots for the update.');
return;
end
-- only work on chests owned by the player (or unlocked ones)
local meta = minetest.get_meta( pos );
if( node.name ~= 'default:chest' and meta:get_string( 'owner' ) ~= pname ) then
minetest.chat_send_player( pname, 'You can only upgrade your own chests.');
return;
end
-- check if steel ingot is present
if( minetest.is_protected(pos, pname )) then
minetest.chat_send_player( pname, 'This chest is protected from digging.');
return;
end
if( price > 0 ) then
player_inv:remove_item( 'main', 'default:steel_ingot '..tostring( price ));
elseif( price < 0 ) then
price = price * -1;
player_inv:add_item( 'main', 'default:steel_ingot '..tostring( price ));
end
-- set the owner field
meta:set_string( 'owner', pname );
target = node.name;
if( fields.locked ) then
target = 'default:chest_locked';
meta:set_string("infotext", "Locked Chest (owned by "..meta:get_string("owner")..")")
elseif( fields.shared ) then
target = 'chesttools:shared_chest';
meta:set_string("infotext", "Shared Chest (owned by "..meta:get_string("owner")..")")
else
target = 'default:chest';
meta:set_string("infotext", "Chest")
end
if( not( fields.shared )) then
meta:set_string("formspec", "size[9,10]"..
"list[current_name;main;0.5,0.3;8,4;]"..
"list[current_player;main;0.5,5.5;8,4;]");
else
meta:set_string("formspec", chesttools.formspec..
"field[1.8,10.0;6,0.5;chestname;;"..tostring( meta:get_string("chestname") or "unconfigured").."]"..
"list[current_player;main;0.5,5.5;8,4;]");
end
minetest.swap_node( pos, { name = target, param2 = node.param2 });
minetest.chat_send_player( pname, 'Chest changed to '..tostring( minetest.registered_nodes[ target].description )..
' for '..tostring( price )..' steel ingots.');
end
-- translate general formspec calls back to specific chests/locations
chesttools.form_input_handler = function( player, formname, fields)
if( (formname == "chesttools:shared_chest" or formname == "chesttools:update") and fields.pos2str ) then
local pos = minetest.string_to_pos( fields.pos2str );
if( not( chesttools.may_use( pos, player ))) then
return;
end
if( formname == "chesttools:shared_chest") then
chesttools.on_receive_fields(pos, formname, fields, player);
elseif( formname == "chesttools:update") then
chesttools.update_chest( pos, formname, fields, player);
end
return;
end
end
-- establish a callback so that input from the player-specific formspec gets handled
minetest.register_on_player_receive_fields( chesttools.form_input_handler );
minetest.register_node( 'chesttools:shared_chest', {
description = 'Shared chest which can be used by all who can build at that spot',
name = 'shared chest',
tiles = chesttools.chest_add.tiles,
groups = chesttools.chest_add.groups,
tube = chesttools.chest_add.tube,
paramtype2 = "facedir",
legacy_facedir_simple = true,
is_ground_content = false,
sounds = default.node_sound_wood_defaults(),
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "Shared Chest (owned by "..meta:get_string("owner")..")")
end,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Shared Chest")
meta:set_string("owner", "")
local inv = meta:get_inventory()
inv:set_size("main", 8*4)
meta:set_string("formspec", chesttools.formspec..
"list[current_player;main;0.5,5.5;8,4;]");
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local inv = meta:get_inventory()
return inv:is_empty("main") and player:get_player_name() == meta:get_string('owner');
end,
allow_metadata_inventory_move = function(pos, from_list, from_index,
to_list, to_index, count, player)
-- the shared function only kicks in if the area is protected
if( not( chesttools.may_use( pos, player ))) then
return 0;
end
return count;
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if( not( chesttools.may_use( pos, player ))) then
return 0;
end
return stack:get_count();
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
if( not( chesttools.may_use( pos, player ))) then
return 0;
end
return stack:get_count();
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name()..
" puts "..tostring( stack:to_string() ).." to shared chest at "..minetest.pos_to_string(pos))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name()..
" takes "..tostring( stack:to_string() ).." from shared chest at "..minetest.pos_to_string(pos))
end,
on_receive_fields = function(pos, formname, fields, sender)
if( not( chesttools.may_use( pos, sender ))) then
return;
end
chesttools.on_receive_fields( pos, formname, fields, sender);
end,
on_use = function(itemstack, user, pointed_thing)
if( user == nil or pointed_thing == nil or pointed_thing.type ~= 'node') then
return nil;
end
local name = user:get_player_name();
local pos = minetest.get_pointed_thing_position( pointed_thing, mode );
local node = minetest.get_node_or_nil( pos );
if( node == nil or not( node.name )) then
return nil;
end
if( node.name=='default:chest'
or node.name=='default:chest_locked'
or node.name=='chesttools:shared_chest') then
local formspec = "size[8,4]"..
"label[2,0.4;Change chest type:]"..
"field[20,20;0.1,0.1;pos2str;Pos;"..minetest.pos_to_string( pos ).."]"..
"button_exit[2,3.5;1.5,0.5;abort;Abort]";
if( node.name ~= 'default:chest' ) then
formspec = formspec..'item_image_button[1,1;1.5,1.5;default:chest;normal;]'..
'button_exit[1,2.5;1.5,0.5;normal;normal]';
else
formspec = formspec..'item_image[1,1;1.5,1.5;default:chest]'..
'label[1,2.5;normal]';
end
if( node.name ~= 'default:chest_locked' ) then
formspec = formspec..'item_image_button[3,1;1.5,1.5;default:chest_locked;locked;]'..
'button_exit[3,2.5;1.5,0.5;locked;locked]';
else
formspec = formspec..'item_image[3,1;1.5,1.5;default:chest_locked]'..
'label[3,2.5;locked]';
end
if( node.name ~= 'chesttools:shared_chest' ) then
formspec = formspec..'item_image_button[5,1;1.5,1.5;chesttools:shared_chest;shared;]'..
'button_exit[5,2.5;1.5,0.5;shared;shared]';
else
formspec = formspec..'item_image[5,1;1.5,1.5;chesttools:shared_chest]'..
'label[5,2.5;shared]';
end
minetest.show_formspec( name, "chesttools:update", formspec );
end
return nil;
end,
})
minetest.register_craft({
output = 'chesttools:shared_chest',
type = 'shapeless',
recipe = { 'default:steel_ingot', 'default:chest_locked' },
})
| unlicense |
zaeem998/vtbot | 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-3.0 |
geektophe/blingbling | clock.lua | 6 | 4234 | --@author cedlemo
local os = os
local string = string
local awful = require("awful")
local textbox = require("wibox.widget.textbox")
local text_box = require("blingbling.text_box")
local days_of_week_in_kanji={
"日曜日", "月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"
}
local days_of_week_in_kana={
"にちようび","げつようび","かようび","すいようび","もくようび","きんようび",
"どようび"
}
local kanji_numbers={
"一","ニ","三","四","五","六","七","八","九","十"
}
local kanas_numbers={
"いち","に","さん","し","ご","ろく","しち","はち","く","じゅう"
}
local days_of_month_in_kanas={
"ついたち","ふつか","みっか","よっか","いつか","むいか","なのか","ようか",
"ここのか","とおか","ジュウイチニチ","ジュウニニチ","ジュウサンニチ",
"じゅうよっか", "ジュウゴニチ","ジュウロクニチ","ジュウシチニチ",
"ジュウハチニチ","ジュウクニチ","はつか","ニジュウイチニチ","ニジュウニニチ",
"ニジュウサンニチ","にじゅうよっか", "ニジュウゴニチ","ニジュウロクニチ",
"ニジュウシチニチ","ニジュウハチニチ","ニジュウクニチ","サンジュウニチ",
"サンジュウイチニチ"
}
---A clock module
--@module blingbling.clock
local function get_day_of_month_in_kanji(n)
if n<=10 then
return kanji_numbers[n] .. "日"
elseif n<20 then
return kanji_numbers[10]..(kanji_numbers[n-10] or "") .. "日"
elseif n<30 then
return kanji_numbers[2]..kanji_numbers[10]..(kanji_numbers[n-20] or "").. "日"
elseif n<=31 then
return kanji_numbers[3]..kanji_numbers[10]..(kanji_numbers[n-30] or "").. "日"
end
end
local function get_month_in_kanji(n)
if n<=10 then
return kanji_numbers[n].."月"
elseif n<=12 then
return kanji_numbers[10]..(kanji_numbers[n-10] or "").."月"
end
end
romajis_days_of_month={}
local function get_current_day_of_week_in_kanji()
return days_of_week_in_kanji[tonumber(os.date("%w") + 1)]
end
local function get_current_day_of_week_in_kanas()
return days_of_week_in_kana[tonumber(os.date("%w") + 1)]
end
local function get_current_day_of_month_in_kanji()
return get_day_of_month_in_kanji(tonumber(os.date("%d")))
end
local function get_current_day_of_month_in_kanas()
return days_of_month_in_kanas[tonumber(os.date("%d"))]
end
local function get_current_month_in_kanji()
return get_month_in_kanji(tonumber(os.date("%m")))
end
local function get_current_hour()
return os.date("%H")
end
local function get_current_minutes()
return os.date("%M")
end
local function get_current_time_in_japanese( str)
--if type(string) ~= "string" then
-- return nil
--end
local result = str or "%m、%d、%w、%H時%M分"
result = string.gsub(result,"%%w",get_current_day_of_week_in_kanji())
result = string.gsub(result,"%%d",get_current_day_of_month_in_kanji())
result = string.gsub(result,"%%m",get_current_month_in_kanji())
result = os.date(result)
return result
end
local function japanese_clock(str, args)
local clock = text_box(args)
clock:set_text(get_current_time_in_japanese( str ))
clocktimer = timer({ timeout = 1 })
clocktimer:connect_signal("timeout", function() clock:set_text(get_current_time_in_japanese( str )) end)
clocktimer:start()
--clock_tooltip= awful.tooltip({
-- objects = { clock },
-- timer_function= function()
-- return os.date("%B, %d, %A, %H:%M")
-- end,
-- })
return clock
end
---A clock that displays the date and the time in kanjis. This clock have a popup that shows the current date in your langage.
--@usage myclock = blingbling.japanese_clock() --then just add it in your wibox like a classical widget
--@name japanese_clock
--@class function
--@return a clock widget
return {
japanese = japanese_clock,
get_current_time_in_japanese = get_current_time_in_japanese,
get_current_day_of_week_in_kanji = get_current_day_of_week_in_kanji,
get_current_day_of_month_in_kanji = get_current_day_of_month_in_kanji,
get_current_month_in_kanji = get_current_month_in_kanji,
get_current_day_of_month_in_kanas = get_current_day_of_month_in_kanas,
get_current_day_of_week_in_kanas = get_current_day_of_week_in_kanas
}
| gpl-2.0 |
punisherbot/test | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
peval/Atlas | lib/admin-sql.lua | 40 | 8858 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- map SQL commands to the hidden MySQL Protocol commands
--
-- some protocol commands are only available through the mysqladmin tool like
-- * ping
-- * shutdown
-- * debug
-- * statistics
--
-- ... while others are avaible
-- * process info (SHOW PROCESS LIST)
-- * process kill (KILL <id>)
--
-- ... and others are ignored
-- * time
--
-- that way we can test MySQL Servers more easily with "mysqltest"
--
---
-- recognize special SQL commands and turn them into COM_* sequences
--
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then return end
if packet:sub(2) == "COMMIT SUICIDE" then
proxy.queries:append(proxy.COM_SHUTDOWN, string.char(proxy.COM_SHUTDOWN), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PING" then
proxy.queries:append(proxy.COM_PING, string.char(proxy.COM_PING), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "STATISTICS" then
proxy.queries:append(proxy.COM_STATISTICS, string.char(proxy.COM_STATISTICS), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PROCINFO" then
proxy.queries:append(proxy.COM_PROCESS_INFO, string.char(proxy.COM_PROCESS_INFO), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TIME" then
proxy.queries:append(proxy.COM_TIME, string.char(proxy.COM_TIME), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEBUG" then
proxy.queries:append(proxy.COM_DEBUG, string.char(proxy.COM_DEBUG), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PROCKILL" then
proxy.queries:append(proxy.COM_PROCESS_KILL, string.char(proxy.COM_PROCESS_KILL), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "SETOPT" then
proxy.queries:append(proxy.COM_SET_OPTION, string.char(proxy.COM_SET_OPTION), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "BINLOGDUMP" then
proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "BINLOGDUMP1" then
proxy.queries:append(proxy.COM_BINLOG_DUMP,
string.char(proxy.COM_BINLOG_DUMP) ..
"\004\000\000\000" ..
"\000\000" ..
"\002\000\000\000" ..
"\000" ..
""
, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "REGSLAVE" then
proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "REGSLAVE1" then
proxy.queries:append(proxy.COM_REGISTER_SLAVE,
string.char(proxy.COM_REGISTER_SLAVE) ..
"\001\000\000\000" .. -- server-id
"\000" .. -- report-host
"\000" .. -- report-user
"\000" .. -- report-password ?
"\001\000" .. -- our port
"\000\000\000\000" .. -- recovery rank
"\001\000\000\000" .. -- master id ... what ever that is
""
, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PREP" then
proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PREP1" then
proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE) .. "SELECT ?", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "EXEC" then
proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "EXEC1" then
proxy.queries:append(proxy.COM_STMT_EXECUTE,
string.char(proxy.COM_STMT_EXECUTE) ..
"\001\000\000\000" .. -- stmt-id
"\000" .. -- flags
"\001\000\000\000" .. -- iteration count
"\000" .. -- null-bits
"\001" .. -- new-parameters
"\000\254" ..
"\004" .. "1234" ..
"", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEAL" then
proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEAL1" then
proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE) .. "\001\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "RESET" then
proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "RESET1" then
proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET) .. "\001\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FETCH" then
proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FETCH1" then
proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH) .. "\001\000\000\000" .. "\128\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FLIST" then
proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FLIST1" then
proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST) .. "t1\000id\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP1" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t1", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP2" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t2", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
end
end
---
-- adjust the response to match the needs of COM_QUERY
-- where neccesary
--
-- * some commands return EOF (COM_SHUTDOWN),
-- * some are plain-text (COM_STATISTICS)
--
-- in the end the client sent us a COM_QUERY and we have to hide
-- all those specifics
function read_query_result(inj)
if inj.id == proxy.COM_SHUTDOWN or
inj.id == proxy.COM_SET_OPTION or
inj.id == proxy.COM_BINLOG_DUMP or
inj.id == proxy.COM_STMT_PREPARE or
inj.id == proxy.COM_STMT_FETCH or
inj.id == proxy.COM_FIELD_LIST or
inj.id == proxy.COM_TABLE_DUMP or
inj.id == proxy.COM_DEBUG then
-- translate the EOF packet from the COM_SHUTDOWN into a OK packet
-- to match the needs of the COM_QUERY we got
if inj.resultset.raw:byte() ~= 255 then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
return proxy.PROXY_SEND_RESULT
end
elseif inj.id == proxy.COM_PING or
inj.id == proxy.COM_TIME or
inj.id == proxy.COM_PROCESS_KILL or
inj.id == proxy.COM_REGISTER_SLAVE or
inj.id == proxy.COM_STMT_EXECUTE or
inj.id == proxy.COM_STMT_RESET or
inj.id == proxy.COM_PROCESS_INFO then
-- no change needed
elseif inj.id == proxy.COM_STATISTICS then
-- the response a human readable plain-text
--
-- just turn it into a proper result-set
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = {
{ name = "statisitics" }
},
rows = {
{ inj.resultset.raw }
}
}
}
return proxy.PROXY_SEND_RESULT
else
-- we don't know them yet, just return ERR to the client to
-- match the needs of COM_QUERY
print(("got: %q"):format(inj.resultset.raw))
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
}
return proxy.PROXY_SEND_RESULT
end
end
| gpl-2.0 |
hacker44-h44/1104 | plugins/groupmanager.lua | 136 | 11323 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin!"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategroup <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategroup) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end | gpl-2.0 |
nehz/busted | spec/execution_order_sync_spec.lua | 12 | 1154 | local egg = ''
describe('before_each after_each egg test', function()
setup(function()
egg = egg..'S'
end)
teardown(function()
egg = egg..'T'
end)
before_each(function()
egg = egg..'b'
end)
after_each(function()
egg = egg..'a'
end)
describe('asd', function()
before_each(function()
egg = egg..'B'
end)
after_each(function()
egg = egg..'A'
end)
it('1', function()
assert.equal(egg,'SbB')
egg = egg..'1'
end)
it('2', function()
assert.equal(egg,'SbB1AabB')
egg = egg..'2'
end)
describe('jkl', function()
setup(function()
egg = egg..'s'
end)
teardown(function()
egg = egg..'t'
end)
before_each(function()
egg = egg..'E'
end)
after_each(function()
egg = egg..'F'
end)
it('3', function()
assert.equal(egg,'SbB1AabB2AasbBE')
egg = egg..'3'
end)
end)
end)
it('4', function()
assert.equal(egg,'SbB1AabB2AasbBE3FAatb')
egg = egg..'4'
end)
end)
it('5', function()
assert.equal(egg,'SbB1AabB2AasbBE3FAatb4aT')
end)
| mit |
sjznxd/lc-20130127 | applications/luci-pbx/luasrc/model/cbi/pbx-users.lua | 146 | 5623 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-users"
modulenamecalls = "pbx-calls"
modulenameadvanced = "pbx-advanced"
m = Map (modulename, translate("User Accounts"),
translate("Here you must configure at least one SIP account, that you \
will use to register with this service. Use this account either in an Analog Telephony \
Adapter (ATA), or in a SIP software like CSipSimple, Linphone, or Sipdroid on your \
smartphone, or Ekiga, Linphone, or X-Lite on your computer. By default, all SIP accounts \
will ring simultaneously if a call is made to one of your VoIP provider accounts or GV \
numbers."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null")
end
externhost = m.uci:get(modulenameadvanced, "advanced", "externhost")
bindport = m.uci:get(modulenameadvanced, "advanced", "bindport")
ipaddr = m.uci:get("network", "lan", "ipaddr")
-----------------------------------------------------------------------------
s = m:section(NamedSection, "server", "user", translate("Server Setting"))
s.anonymous = true
if ipaddr == nil or ipaddr == "" then
ipaddr = "(IP address not static)"
end
if bindport ~= nil then
just_ipaddr = ipaddr
ipaddr = ipaddr .. ":" .. bindport
end
s:option(DummyValue, "ipaddr", translate("Server Setting for Local SIP Devices"),
translate("Enter this IP (or IP:port) in the Server/Registrar setting of SIP devices you will \
use ONLY locally and never from a remote location.")).default = ipaddr
if externhost ~= nil then
if bindport ~= nil then
just_externhost = externhost
externhost = externhost .. ":" .. bindport
end
s:option(DummyValue, "externhost", translate("Server Setting for Remote SIP Devices"),
translate("Enter this hostname (or hostname:port) in the Server/Registrar setting of SIP \
devices you will use from a remote location (they will work locally too).")
).default = externhost
end
if bindport ~= nil then
s:option(DummyValue, "bindport", translate("Port Setting for SIP Devices"),
translatef("If setting Server/Registrar to %s or %s does not work for you, try setting \
it to %s or %s and entering this port number in a separate field that specifies the \
Server/Registrar port number. Beware that some devices have a confusing \
setting that sets the port where SIP requests originate from on the SIP \
device itself (the bind port). The port specified on this page is NOT this bind port \
but the port this service listens on.",
ipaddr, externhost, just_ipaddr, just_externhost)).default = bindport
end
-----------------------------------------------------------------------------
s = m:section(TypedSection, "local_user", translate("SIP Device/Softphone Accounts"))
s.anonymous = true
s.addremove = true
s:option(Value, "fullname", translate("Full Name"),
translate("You can specify a real name to show up in the Caller ID here."))
du = s:option(Value, "defaultuser", translate("User Name"),
translate("Use (four to five digit) numeric user name if you are connecting normal telephones \
with ATAs to this system (so they can dial user names)."))
du.datatype = "uciname"
pwd = s:option(Value, "secret", translate("Password"),
translate("Your password disappears when saved for your protection. It will be changed \
only when you enter a value different from the saved one."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
p = s:option(ListValue, "ring", translate("Receives Incoming Calls"))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
p = s:option(ListValue, "can_call", translate("Makes Outgoing Calls"))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
return m
| apache-2.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/items/bowl_of_adoulin_soup.lua | 36 | 1504 | -----------------------------------------
-- ID: 5998
-- Item: Bowl of Adoulin Soup
-- Food Effect: 180 Min, All Races
-----------------------------------------
-- HP % 3 Cap 40
-- Vitality 3
-- Defense % 15 Cap 70
-- HP Healing 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5998);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 3);
target:addMod(MOD_FOOD_HP_CAP, 40);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_FOOD_DEFP, 15);
target:addMod(MOD_FOOD_DEF_CAP, 70);
target:addMod(MOD_HPHEAL, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 3);
target:delMod(MOD_FOOD_HP_CAP, 40);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_FOOD_DEFP, 15);
target:delMod(MOD_FOOD_DEF_CAP, 70);
target:delMod(MOD_HPHEAL, 6);
end;
| gpl-3.0 |
sjznxd/luci-0.11-aa | modules/rpc/luasrc/jsonrpc.lua | 12 | 2238 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: jsonrpc.lua 3000 2008-08-29 12:27:54Z Cyrus $
]]--
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 |
FFXIOrgins/FFXIOrgins | scripts/zones/Bastok_Mines/npcs/Home_Point.lua | 8 | 1190 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Home Point
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
player:startEvent(0x0050);
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 (option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Dynamis-Xarcabard/mobs/King_Zagan.lua | 19 | 1251 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: King Zagan
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if(mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 2048;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if(Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if(Animate_Trigger == 32767) then
killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Bastok_Markets/npcs/HomePoint#3.lua | 3 | 1712 | -----------------------------------
-- Area: Bastok Markets
-- NPC: HomePoint#3
-- @pos -189 -8 26 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
if(HOMEPOINT_TELEPORT == 1)then
-- ?/1-Ru'lude5 /Lude-Ru'Aun/Tav-end/ ?/Gil /Expantion level/Registered
player:startEvent(0x21fe,0,player:getVar("hpmask1"),player:getVar("hpmask2"),player:getVar("hpmask3"),player:getVar("hpmask4"),player:getGil(),4095,13 + addtohps(player,1,13));
else
player:startEvent(0x21fe)
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x21fe) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpteleport(player,option);
end
end
end;
| gpl-3.0 |
sjznxd/lc-20130127 | libs/px5g/lua/px5g/util.lua | 170 | 1148 | --[[
* px5g - Embedded x509 key and certificate generator based on PolarSSL
*
* Copyright (C) 2009 Steven Barth <steven@midlink.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1 as published by the Free Software Foundation.
]]--
local nixio = require "nixio"
local table = require "table"
module "px5g.util"
local preamble = {
key = "-----BEGIN RSA PRIVATE KEY-----",
cert = "-----BEGIN CERTIFICATE-----",
request = "-----BEGIN CERTIFICATE REQUEST-----"
}
local postamble = {
key = "-----END RSA PRIVATE KEY-----",
cert = "-----END CERTIFICATE-----",
request = "-----END CERTIFICATE REQUEST-----"
}
function der2pem(data, type)
local b64 = nixio.bin.b64encode(data)
local outdata = {preamble[type]}
for i = 1, #b64, 64 do
outdata[#outdata + 1] = b64:sub(i, i + 63)
end
outdata[#outdata + 1] = postamble[type]
outdata[#outdata + 1] = ""
return table.concat(outdata, "\n")
end
function pem2der(data)
local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
return nixio.bin.b64decode(b64)
end | apache-2.0 |
daofeng2015/luci | modules/luci-base/luasrc/http/protocol.lua | 16 | 16196 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
-- This class contains several functions useful for http message- and content
-- decoding and to retrive form data from raw http messages.
module("luci.http.protocol", package.seeall)
local ltn12 = require("luci.ltn12")
HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size
-- the "+" sign to " " - and return the decoded string.
function urldecode( str, no_plus )
local function __chrdec( hex )
return string.char( tonumber( hex, 16 ) )
end
if type(str) == "string" then
if not no_plus then
str = str:gsub( "+", " " )
end
str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec )
end
return str
end
-- from given url or string. Returns a table with urldecoded values.
-- Simple parameters are stored as string values associated with the parameter
-- name within the table. Parameters with multiple values are stored as array
-- containing the corresponding values.
function urldecode_params( url, tbl )
local params = tbl or { }
if url:find("?") then
url = url:gsub( "^.+%?([^?]+)", "%1" )
end
for pair in url:gmatch( "[^&;]+" ) do
-- find key and value
local key = urldecode( pair:match("^([^=]+)") )
local val = urldecode( pair:match("^[^=]+=(.+)$") )
-- store
if type(key) == "string" and key:len() > 0 then
if type(val) ~= "string" then val = "" end
if not params[key] then
params[key] = val
elseif type(params[key]) ~= "table" then
params[key] = { params[key], val }
else
table.insert( params[key], val )
end
end
end
return params
end
function urlencode( str )
local function __chrenc( chr )
return string.format(
"%%%02x", string.byte( chr )
)
end
if type(str) == "string" then
str = str:gsub(
"([^a-zA-Z0-9$_%-%.%~])",
__chrenc
)
end
return str
end
-- separated by "&". Tables are encoded as parameters with multiple values by
-- repeating the parameter name with each value.
function urlencode_params( tbl )
local enc = ""
for k, v in pairs(tbl) do
if type(v) == "table" then
for i, v2 in ipairs(v) do
enc = enc .. ( #enc > 0 and "&" or "" ) ..
urlencode(k) .. "=" .. urlencode(v2)
end
else
enc = enc .. ( #enc > 0 and "&" or "" ) ..
urlencode(k) .. "=" .. urlencode(v)
end
end
return enc
end
-- (Internal function)
-- Initialize given parameter and coerce string into table when the parameter
-- already exists.
local function __initval( tbl, key )
if tbl[key] == nil then
tbl[key] = ""
elseif type(tbl[key]) == "string" then
tbl[key] = { tbl[key], "" }
else
table.insert( tbl[key], "" )
end
end
-- (Internal function)
-- Initialize given file parameter.
local function __initfileval( tbl, key, filename, fd )
if tbl[key] == nil then
tbl[key] = { file=filename, fd=fd, name=key, "" }
else
table.insert( tbl[key], "" )
end
end
-- (Internal function)
-- Append given data to given parameter, either by extending the string value
-- or by appending it to the last string in the parameter's value table.
local function __appendval( tbl, key, chunk )
if type(tbl[key]) == "table" then
tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk
else
tbl[key] = tbl[key] .. chunk
end
end
-- (Internal function)
-- Finish the value of given parameter, either by transforming the string value
-- or - in the case of multi value parameters - the last element in the
-- associated values table.
local function __finishval( tbl, key, handler )
if handler then
if type(tbl[key]) == "table" then
tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] )
else
tbl[key] = handler( tbl[key] )
end
end
end
-- Table of our process states
local process_states = { }
-- Extract "magic", the first line of a http message.
-- Extracts the message type ("get", "post" or "response"), the requested uri
-- or the status code if the line descripes a http response.
process_states['magic'] = function( msg, chunk, err )
if chunk ~= nil then
-- ignore empty lines before request
if #chunk == 0 then
return true, nil
end
-- Is it a request?
local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$")
-- Yup, it is
if method then
msg.type = "request"
msg.request_method = method:lower()
msg.request_uri = uri
msg.http_version = tonumber( http_ver )
msg.headers = { }
-- We're done, next state is header parsing
return true, function( chunk )
return process_states['headers']( msg, chunk )
end
-- Is it a response?
else
local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$")
-- Is a response
if code then
msg.type = "response"
msg.status_code = code
msg.status_message = message
msg.http_version = tonumber( http_ver )
msg.headers = { }
-- We're done, next state is header parsing
return true, function( chunk )
return process_states['headers']( msg, chunk )
end
end
end
end
-- Can't handle it
return nil, "Invalid HTTP message magic"
end
-- Extract headers from given string.
process_states['headers'] = function( msg, chunk )
if chunk ~= nil then
-- Look for a valid header format
local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" )
if type(hdr) == "string" and hdr:len() > 0 and
type(val) == "string" and val:len() > 0
then
msg.headers[hdr] = val
-- Valid header line, proceed
return true, nil
elseif #chunk == 0 then
-- Empty line, we won't accept data anymore
return false, nil
else
-- Junk data
return nil, "Invalid HTTP header received"
end
else
return nil, "Unexpected EOF"
end
end
-- data line by line with the trailing \r\n stripped of.
function header_source( sock )
return ltn12.source.simplify( function()
local chunk, err, part = sock:receive("*l")
-- Line too long
if chunk == nil then
if err ~= "timeout" then
return nil, part
and "Line exceeds maximum allowed length"
or "Unexpected EOF"
else
return nil, err
end
-- Line ok
elseif chunk ~= nil then
-- Strip trailing CR
chunk = chunk:gsub("\r$","")
return chunk, nil
end
end )
end
-- Content-Type. Stores all extracted data associated with its parameter name
-- in the params table withing the given message object. Multiple parameter
-- values are stored as tables, ordinary ones as strings.
-- If an optional file callback function is given then it is feeded with the
-- file contents chunk by chunk and only the extracted file name is stored
-- within the params table. The callback function will be called subsequently
-- with three arguments:
-- o Table containing decoded (name, file) and raw (headers) mime header data
-- o String value containing a chunk of the file data
-- o Boolean which indicates wheather the current chunk is the last one (eof)
function mimedecode_message_body( src, msg, filecb )
if msg and msg.env.CONTENT_TYPE then
msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$")
end
if not msg.mime_boundary then
return nil, "Invalid Content-Type found"
end
local tlen = 0
local inhdr = false
local field = nil
local store = nil
local lchunk = nil
local function parse_headers( chunk, field )
local stat
repeat
chunk, stat = chunk:gsub(
"^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n",
function(k,v)
field.headers[k] = v
return ""
end
)
until stat == 0
chunk, stat = chunk:gsub("^\r\n","")
-- End of headers
if stat > 0 then
if field.headers["Content-Disposition"] then
if field.headers["Content-Disposition"]:match("^form%-data; ") then
field.name = field.headers["Content-Disposition"]:match('name="(.-)"')
field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$')
end
end
if not field.headers["Content-Type"] then
field.headers["Content-Type"] = "text/plain"
end
if field.name and field.file and filecb then
__initval( msg.params, field.name )
__appendval( msg.params, field.name, field.file )
store = filecb
elseif field.name and field.file then
local nxf = require "nixio"
local fd = nxf.mkstemp(field.name)
__initfileval ( msg.params, field.name, field.file, fd )
if fd then
store = function(hdr, buf, eof)
fd:write(buf)
if (eof) then
fd:seek(0, "set")
end
end
else
store = function( hdr, buf, eof )
__appendval( msg.params, field.name, buf )
end
end
elseif field.name then
__initval( msg.params, field.name )
store = function( hdr, buf, eof )
__appendval( msg.params, field.name, buf )
end
else
store = nil
end
return chunk, true
end
return chunk, false
end
local function snk( chunk )
tlen = tlen + ( chunk and #chunk or 0 )
if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then
return nil, "Message body size exceeds Content-Length"
end
if chunk and not lchunk then
lchunk = "\r\n" .. chunk
elseif lchunk then
local data = lchunk .. ( chunk or "" )
local spos, epos, found
repeat
spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true )
if not spos then
spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true )
end
if spos then
local predata = data:sub( 1, spos - 1 )
if inhdr then
predata, eof = parse_headers( predata, field )
if not eof then
return nil, "Invalid MIME section header"
elseif not field.name then
return nil, "Invalid Content-Disposition header"
end
end
if store then
store( field, predata, true )
end
field = { headers = { } }
found = found or true
data, eof = parse_headers( data:sub( epos + 1, #data ), field )
inhdr = not eof
end
until not spos
if found then
-- We found at least some boundary. Save
-- the unparsed remaining data for the
-- next chunk.
lchunk, data = data, nil
else
-- There was a complete chunk without a boundary. Parse it as headers or
-- append it as data, depending on our current state.
if inhdr then
lchunk, eof = parse_headers( data, field )
inhdr = not eof
else
-- We're inside data, so append the data. Note that we only append
-- lchunk, not all of data, since there is a chance that chunk
-- contains half a boundary. Assuming that each chunk is at least the
-- boundary in size, this should prevent problems
store( field, lchunk, false )
lchunk, chunk = chunk, nil
end
end
end
return true
end
return ltn12.pump.all( src, snk )
end
-- Content-Type. Stores all extracted data associated with its parameter name
-- in the params table withing the given message object. Multiple parameter
-- values are stored as tables, ordinary ones as strings.
function urldecode_message_body( src, msg )
local tlen = 0
local lchunk = nil
local function snk( chunk )
tlen = tlen + ( chunk and #chunk or 0 )
if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then
return nil, "Message body size exceeds Content-Length"
elseif tlen > HTTP_MAX_CONTENT then
return nil, "Message body size exceeds maximum allowed length"
end
if not lchunk and chunk then
lchunk = chunk
elseif lchunk then
local data = lchunk .. ( chunk or "&" )
local spos, epos
repeat
spos, epos = data:find("^.-[;&]")
if spos then
local pair = data:sub( spos, epos - 1 )
local key = pair:match("^(.-)=")
local val = pair:match("=([^%s]*)%s*$")
if key and #key > 0 then
__initval( msg.params, key )
__appendval( msg.params, key, val )
__finishval( msg.params, key, urldecode )
end
data = data:sub( epos + 1, #data )
end
until not spos
lchunk = data
end
return true
end
return ltn12.pump.all( src, snk )
end
-- version, message headers and resulting CGI environment variables from the
-- given ltn12 source.
function parse_message_header( src )
local ok = true
local msg = { }
local sink = ltn12.sink.simplify(
function( chunk )
return process_states['magic']( msg, chunk )
end
)
-- Pump input data...
while ok do
-- get data
ok, err = ltn12.pump.step( src, sink )
-- error
if not ok and err then
return nil, err
-- eof
elseif not ok then
-- Process get parameters
if ( msg.request_method == "get" or msg.request_method == "post" ) and
msg.request_uri:match("?")
then
msg.params = urldecode_params( msg.request_uri )
else
msg.params = { }
end
-- Populate common environment variables
msg.env = {
CONTENT_LENGTH = msg.headers['Content-Length'];
CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type'];
REQUEST_METHOD = msg.request_method:upper();
REQUEST_URI = msg.request_uri;
SCRIPT_NAME = msg.request_uri:gsub("?.+$","");
SCRIPT_FILENAME = ""; -- XXX implement me
SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version);
QUERY_STRING = msg.request_uri:match("?")
and msg.request_uri:gsub("^.+?","") or ""
}
-- Populate HTTP_* environment variables
for i, hdr in ipairs( {
'Accept',
'Accept-Charset',
'Accept-Encoding',
'Accept-Language',
'Connection',
'Cookie',
'Host',
'Referer',
'User-Agent',
} ) do
local var = 'HTTP_' .. hdr:upper():gsub("%-","_")
local val = msg.headers[hdr]
msg.env[var] = val
end
end
end
return msg
end
-- This function will examine the Content-Type within the given message object
-- to select the appropriate content decoder.
-- Currently the application/x-www-urlencoded and application/form-data
-- mime types are supported. If the encountered content encoding can't be
-- handled then the whole message body will be stored unaltered as "content"
-- property within the given message object.
function parse_message_body( src, msg, filecb )
-- Is it multipart/mime ?
if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and
msg.env.CONTENT_TYPE:match("^multipart/form%-data")
then
return mimedecode_message_body( src, msg, filecb )
-- Is it application/x-www-form-urlencoded ?
elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and
msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded")
then
return urldecode_message_body( src, msg, filecb )
-- Unhandled encoding
-- If a file callback is given then feed it chunk by chunk, else
-- store whole buffer in message.content
else
local sink
-- If we have a file callback then feed it
if type(filecb) == "function" then
local meta = {
name = "raw",
encoding = msg.env.CONTENT_TYPE
}
sink = function( chunk )
if chunk then
return filecb(meta, chunk, false)
else
return filecb(meta, nil, true)
end
end
-- ... else append to .content
else
msg.content = ""
msg.content_length = 0
sink = function( chunk )
if chunk then
if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then
msg.content = msg.content .. chunk
msg.content_length = msg.content_length + #chunk
return true
else
return nil, "POST data exceeds maximum allowed length"
end
end
return true
end
end
-- Pump data...
while true do
local ok, err = ltn12.pump.step( src, sink )
if not ok and err then
return nil, err
elseif not ok then -- eof
return true
end
end
return true
end
end
statusmsg = {
[200] = "OK",
[206] = "Partial Content",
[301] = "Moved Permanently",
[302] = "Found",
[304] = "Not Modified",
[400] = "Bad Request",
[403] = "Forbidden",
[404] = "Not Found",
[405] = "Method Not Allowed",
[408] = "Request Time-out",
[411] = "Length Required",
[412] = "Precondition Failed",
[416] = "Requested range not satisfiable",
[500] = "Internal Server Error",
[503] = "Server Unavailable",
}
| apache-2.0 |
sjznxd/luci-0.11-aa | applications/luci-tinyproxy/luasrc/model/cbi/tinyproxy.lua | 80 | 7364 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("tinyproxy", translate("Tinyproxy"),
translate("Tinyproxy is a small and fast non-caching HTTP(S)-Proxy"))
s = m:section(TypedSection, "tinyproxy", translate("Server Settings"))
s.anonymous = true
s:tab("general", translate("General settings"))
s:tab("privacy", translate("Privacy settings"))
s:tab("filter", translate("Filtering and ACLs"))
s:tab("limits", translate("Server limits"))
o = s:taboption("general", Flag, "enabled", translate("Enable Tinyproxy server"))
o.rmempty = false
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("tinyproxy")
else
luci.sys.init.disable("tinyproxy")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "Port", translate("Listen port"),
translate("Specifies the HTTP port Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "port"
o.placeholder = 8888
o = s:taboption("general", Value, "Listen", translate("Listen address"),
translate("Specifies the addresses Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "Bind", translate("Bind address"),
translate("Specifies the address Tinyproxy binds to for outbound forwarded requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "DefaultErrorFile", translate("Error page"),
translate("HTML template file to serve when HTTP errors occur"))
o.optional = true
o.default = "/usr/share/tinyproxy/default.html"
o = s:taboption("general", Value, "StatFile", translate("Statistics page"),
translate("HTML template file to serve for stat host requests"))
o.optional = true
o.default = "/usr/share/tinyproxy/stats.html"
o = s:taboption("general", Flag, "Syslog", translate("Use syslog"),
translate("Writes log messages to syslog instead of a log file"))
o = s:taboption("general", Value, "LogFile", translate("Log file"),
translate("Log file to use for dumping messages"))
o.default = "/var/log/tinyproxy.log"
o:depends("Syslog", "")
o = s:taboption("general", ListValue, "LogLevel", translate("Log level"),
translate("Logging verbosity of the Tinyproxy process"))
o:value("Critical")
o:value("Error")
o:value("Warning")
o:value("Notice")
o:value("Connect")
o:value("Info")
o = s:taboption("general", Value, "User", translate("User"),
translate("Specifies the user name the Tinyproxy process is running as"))
o.default = "nobody"
o = s:taboption("general", Value, "Group", translate("Group"),
translate("Specifies the group name the Tinyproxy process is running as"))
o.default = "nogroup"
--
-- Privacy
--
o = s:taboption("privacy", Flag, "XTinyproxy", translate("X-Tinyproxy header"),
translate("Adds an \"X-Tinyproxy\" HTTP header with the client IP address to forwarded requests"))
o = s:taboption("privacy", Value, "ViaProxyName", translate("Via hostname"),
translate("Specifies the Tinyproxy hostname to use in the Via HTTP header"))
o.placeholder = "tinyproxy"
o.datatype = "hostname"
s:taboption("privacy", DynamicList, "Anonymous", translate("Header whitelist"),
translate("Specifies HTTP header names which are allowed to pass-through, all others are discarded. Leave empty to disable header filtering"))
--
-- Filter
--
o = s:taboption("filter", DynamicList, "Allow", translate("Allowed clients"),
translate("List of IP addresses or ranges which are allowed to use the proxy server"))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("filter", DynamicList, "ConnectPort", translate("Allowed connect ports"),
translate("List of allowed ports for the CONNECT method. A single value \"0\" allows all ports"))
o.placeholder = 0
o.datatype = "port"
s:taboption("filter", FileUpload, "Filter", translate("Filter file"),
translate("Plaintext file with URLs or domains to filter. One entry per line"))
s:taboption("filter", Flag, "FilterURLs", translate("Filter by URLs"),
translate("By default, filtering is done based on domain names. Enable this to match against URLs instead"))
s:taboption("filter", Flag, "FilterExtended", translate("Filter by RegExp"),
translate("By default, basic POSIX expressions are used for filtering. Enable this to activate extended regular expressions"))
s:taboption("filter", Flag, "FilterCaseSensitive", translate("Filter case-sensitive"),
translate("By default, filter strings are treated as case-insensitive. Enable this to make the matching case-sensitive"))
s:taboption("filter", Flag, "FilterDefaultDeny", translate("Default deny"),
translate("By default, the filter rules act as blacklist. Enable this option to only allow matched URLs or domain names"))
--
-- Limits
--
o = s:taboption("limits", Value, "Timeout", translate("Connection timeout"),
translate("Maximum number of seconds an inactive connection is held open"))
o.optional = true
o.datatype = "uinteger"
o.default = 600
o = s:taboption("limits", Value, "MaxClients", translate("Max. clients"),
translate("Maximum allowed number of concurrently connected clients"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "MinSpareServers", translate("Min. spare servers"),
translate("Minimum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxSpareServers", translate("Max. spare servers"),
translate("Maximum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "StartServers", translate("Start spare servers"),
translate("Number of idle processes to start when launching Tinyproxy"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxRequestsPerChild", translate("Max. requests per server"),
translate("Maximum allowed number of requests per process. If it is exeeded, the process is restarted. Zero means unlimited."))
o.datatype = "uinteger"
o.default = 0
--
-- Upstream
--
s = m:section(TypedSection, "upstream", translate("Upstream Proxies"),
translate("Upstream proxy rules define proxy servers to use when accessing certain IP addresses or domains."))
s.anonymous = true
s.addremove = true
t = s:option(ListValue, "type", translate("Policy"),
translate("<em>Via proxy</em> routes requests to the given target via the specifed upstream proxy, <em>Reject access</em> disables any upstream proxy for the target"))
t:value("proxy", translate("Via proxy"))
t:value("reject", translate("Reject access"))
ta = s:option(Value, "target", translate("Target host"),
translate("Can be either an IP address or range, a domain name or \".\" for any host without domain"))
ta.rmempty = true
ta.placeholder = "0.0.0.0/0"
ta.datatype = "host"
v = s:option(Value, "via", translate("Via proxy"),
translate("Specifies the upstream proxy to use for accessing the target host. Format is <code>address:port</code>"))
v:depends({type="proxy"})
v.placeholder = "10.0.0.1:8080"
return m
| apache-2.0 |
Igalia/snabb | src/lib/lpm/lpm4_dxr.lua | 9 | 5195 | module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lpm4_trie = require("lib.lpm.lpm4_trie").LPM4_trie
local lpm4 = require("lib.lpm.lpm4")
local ip4 = require("lib.lpm.ip4")
LPM4_dxr = setmetatable({ alloc_storable = { "dxr_smints", "dxr_keys", "dxr_bottoms", "dxr_tops" } }, { __index = lpm4_trie })
ffi.cdef([[
uint16_t lpm4_dxr_search(uint32_t ip, uint16_t *ints, uint16_t *keys, uint32_t *bottoms, uint32_t *tops);
]])
function LPM4_dxr:new ()
self = lpm4_trie.new(self)
self:alloc("dxr_intervals", ffi.typeof("uint32_t"), 2000000)
self:alloc("dxr_keys", ffi.typeof("uint16_t"), 2000000)
self:alloc("dxr_smints", ffi.typeof("uint16_t"), 2000000)
self:alloc("dxr_tops", ffi.typeof("uint32_t"), 2^16)
self:alloc("dxr_bottoms", ffi.typeof("uint32_t"), 2^16)
self.dxr_ioff = 0
return self
end
function LPM4_dxr:print_intervals (first, last)
local first = first or 0
local last = last or self.dxr_ioff - 1
for i = first, last do
print(string.format("INTERVAL%d %s %s %d",
i,
ip4.tostring(self.dxr_intervals[i]),
ip4.tostring(self.dxr_smints[i]),
self.dxr_keys[i]
))
end
return self
end
function LPM4_dxr:build ()
self.built = false
self.dxr_ioff = 0
self:build_intervals()
self:build_compressed()
self:build_direct()
self.built = true
return self
end
function LPM4_dxr:build_intervals ()
local stk = ffi.new(ffi.typeof("$[33]", lpm4.entry))
local soff = -1
local previous = -1
function bcast (e)
return e.ip + 2^(32-e.length) - 1
end
function pop ()
soff = soff - 1
end
function head ()
return stk[soff]
end
function push (e)
soff = soff + 1
stk[soff].ip, stk[soff].length, stk[soff].key = e.ip, e.length, e.key
end
function empty ()
return soff < 0
end
function add_interval (finish)
previous = finish
self.dxr_intervals[self.dxr_ioff] = finish
self.dxr_keys[self.dxr_ioff] = head().key
self.dxr_ioff = self.dxr_ioff + 1
end
for e in self:entries() do
if e.ip == 0 and e.length == 0 then
push(e)
elseif bcast(head()) < e.ip then
-- while there is something the stack that finishes before e.ip
while(bcast(head()) < e.ip) do
if bcast(head()) > previous then
add_interval(bcast(head()))
end
pop()
end
end
-- if there is a gap between the end of what we popped and this fill
-- it with what's on the stack
if previous + 1 < e.ip - 1 then
add_interval(e.ip - 1)
end
push(e)
end
while not empty() do
add_interval(bcast(head()))
pop()
end
return self
end
function LPM4_dxr:build_compressed ()
local ints = self.dxr_intervals
local keys = self.dxr_keys
local smints = self.dxr_smints
local i,j = self.dxr_ioff, 0
local function tbits(ip) return ffi.cast("uint32_t", bit.rshift(ip, 16)) end
local function bbits(ip) return ffi.cast("uint16_t", bit.band(ip, 0xffff)) end
for k = 0,i do
if keys[k] == keys[k+1] and tbits(ints[k]) == tbits(ints[k+1]) then
else
keys[j] = keys[k]
ints[j] = ints[k]
smints[j] = bbits(ints[k])
j = j + 1
end
end
self.dxr_ioff = j
end
function LPM4_dxr:build_direct ()
for i=0, 2^16 -1 do
local base = i * 2^16
self.dxr_bottoms[i] = self:search_interval(base)
self.dxr_tops[i] = self:search_interval(base + 2^16-1)
end
end
function LPM4_dxr:search_interval (ip)
local ints = self.dxr_intervals
local top = self.dxr_ioff - 1
local bottom = 0
local mid
if self.built then
local base = bit.rshift(ip, 16)
top = self.dxr_tops[base]
bottom = self.dxr_bottoms[base]
ip = tonumber(ffi.cast("uint16_t", bit.band(ip, 0xffff)))
ints = self.dxr_smints
end
while bottom < top do
mid = math.floor( bottom + (top - bottom) / 2 )
if ints[mid] < ip then
bottom = mid + 1
else
top = mid
end
end
return top
end
function LPM4_dxr:search (ip)
return C.lpm4_dxr_search(ip, self.dxr_smints, self.dxr_keys, self.dxr_bottoms, self.dxr_tops)
--return self.dxr_keys[self:search_interval(ip)]
end
function selftest ()
local f = LPM4_dxr:new()
f:add_string("0.0.0.0/0",700)
f:add_string("128.0.0.0/8",701)
f:add_string("192.0.0.0/8",702)
f:add_string("192.0.0.0/16",703)
f:add_string("224.0.0.0/8",704)
f:build()
function lsearch(f, ip)
return f.dxr_keys[f:search_interval(ip4.parse(ip))]
end
assert(700 == lsearch(f, "1.1.1.1"))
assert(701 == lsearch(f, "128.1.1.1"))
assert(702 == lsearch(f, "192.1.1.1"))
assert(703 == lsearch(f, "192.0.1.1"))
assert(704 == lsearch(f, "224.1.1.1"))
assert(700 == lsearch(f, "225.1.1.1"))
assert(700 == f:search_string("1.1.1.1"))
assert(701 == f:search_string("128.1.1.1"))
assert(702 == f:search_string("192.1.1.1"))
assert(703 == f:search_string("192.0.1.1"))
assert(704 == f:search_string("224.1.1.1"))
assert(700 == f:search_string("225.1.1.1"))
LPM4_dxr:selftest()
end
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Xarcabard/npcs/Tememe_WW.lua | 13 | 3314 | -----------------------------------
-- Area: Xarcabard
-- NPC: Tememe, W.W.
-- Type: Border Conquest Guards
-- @pos -133.678 -22.517 112.224 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VALDEAUNIA;
local csid = 0x7ff6;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Cape_Teriggan/mobs/Tegmine.lua | 7 | 1875 | ----------------------------------
-- Area: Cape Teriggan
-- NM: Tegmine
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
end;
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(mob,target,damage)
-- Wiki says nothing about proc rate, going with 80% for now.
-- I remember it going off every hit when I fought him.
local chance = 80;
local LV_diff = target:getMainLvl() - mob:getMainLvl();
if (target:getMainLvl() > mob:getMainLvl()) then
chance = chance - 5 * LV_diff;
chance = utils.clamp(chance, 5, 95);
end
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT);
if (INT_diff > 20) then
INT_diff = 20 + (INT_diff - 20) / 2;
end
local dmg = INT_diff+LV_diff+damage/2;
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(mob, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(mob,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
dmg = finalMagicNonSpellAdjustments(mob,target,ELE_WATER,dmg);
return SUBEFFECT_WATER_DAMAGE, MSGBASIC_ADD_EFFECT_DMG, dmg;
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
-- UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random((7200),(7800))); -- 120 to 130 min
end; | gpl-3.0 |
tinymins/MY | MY_Toolbox/src/MY_InfoTip.lua | 1 | 18745 | --------------------------------------------------------
-- This file is part of the JX3 Mingyi Plugin.
-- @link : https://jx3.derzh.com/
-- @desc : ÐÅÏ¢ÌõÏÔʾ
-- @author : ÜøÒÁ @Ë«ÃÎÕò @×··çõæÓ°
-- @modifier : Emil Zhai (root@derzh.com)
-- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = 'MY_Toolbox'
local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = 'MY_InfoTip'
local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then
return
end
--------------------------------------------------------------------------
local CONFIG_FILE_PATH = {'config/infotip.jx3dat', X.PATH_TYPE.ROLE}
local INFO_TIP_LIST = {
-- ÍøÂçÑÓ³Ù
{
id = 'Ping',
i18n = {
name = _L['Ping monitor'], prefix = _L['Ping: '], content = '%d',
},
config = X.CreateUserSettingsModule('MY_InfoTip__Ping', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 95, 255, 95 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 48,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = -133, y = -111, s = 'BOTTOMCENTER', r = 'BOTTOMCENTER' },
},
}),
options = {
bPlaceholder = false,
},
cache = {},
GetFormatString = function(data)
return string.format(data.cache.formatString, GetPingValue() / 2)
end,
},
-- ±¶ËÙÏÔʾ£¨ÏÔʾ·þÎñÆ÷Óж࿨¡¡£©
{
id = 'TimeMachine',
i18n = {
name = _L['Time machine'], prefix = _L['Rate: '], content = 'x%.2f',
},
config = X.CreateUserSettingsModule('MY_InfoTip__TimeMachine', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 31, 255, 31 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 0,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = -276, y = -111, s = 'BOTTOMCENTER', r = 'BOTTOMCENTER' },
},
}),
options = {
bPlaceholder = false,
},
cache = {
tTimeMachineRec = {},
nTimeMachineLFC = GetLogicFrameCount(),
},
GetFormatString = function(data)
local s = 1
if data.cache.nTimeMachineLFC ~= GetLogicFrameCount() then
local tm = data.cache.tTimeMachineRec[GLOBAL.GAME_FPS] or {}
tm.frame = GetLogicFrameCount()
tm.tick = GetTickCount()
for i = GLOBAL.GAME_FPS, 1, -1 do
data.cache.tTimeMachineRec[i] = data.cache.tTimeMachineRec[i - 1]
end
data.cache.tTimeMachineRec[1] = tm
data.cache.nTimeMachineLFC = GetLogicFrameCount()
end
local tm = data.cache.tTimeMachineRec[GLOBAL.GAME_FPS]
if tm then
s = 1000 * (GetLogicFrameCount() - tm.frame) / GLOBAL.GAME_FPS / (GetTickCount() - tm.tick)
end
return string.format(data.cache.formatString, s)
end,
},
-- Ä¿±ê¾àÀë
{
id = 'Distance',
i18n = {
name = _L['Target distance'], prefix = _L['Distance: '], content = _L['%.1f Foot'],
},
config = X.CreateUserSettingsModule('MY_InfoTip__Distance', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bPlaceholder = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 255, 0 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 209,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = 203, y = -106, s = 'CENTER', r = 'CENTER' },
},
}),
options = {
bPlaceholder = true,
},
cache = {},
GetFormatString = function(data)
local p, s = X.GetObject(X.GetTarget()), data.config.bPlaceholder and _L['No Target'] or ''
if p then
s = string.format(data.cache.formatString, X.GetDistance(p))
end
return s
end,
},
-- ϵͳʱ¼ä
{
id = 'SysTime',
i18n = {
name = _L['System time'], prefix = _L['Time: '], content = '%02d:%02d:%02d',
},
config = X.CreateUserSettingsModule('MY_InfoTip__SysTime', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 255, 255 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 0,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = 285, y = -18, s = 'BOTTOMLEFT', r = 'BOTTOMLEFT' },
},
}),
options = {
bPlaceholder = false,
},
cache = {},
GetFormatString = function(data)
local tDateTime = TimeToDate(GetCurrentTime())
return string.format(data.cache.formatString, tDateTime.hour, tDateTime.minute, tDateTime.second)
end,
},
-- Õ½¶·¼ÆÊ±
{
id = 'FightTime',
i18n = {
name = _L['Fight clock'], prefix = _L['Fight Clock: '], content = '',
},
config = X.CreateUserSettingsModule('MY_InfoTip__FightTime', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bPlaceholder = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 0, 128 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 199,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = 353, y = -117, s = 'BOTTOMCENTER', r = 'BOTTOMCENTER' },
},
}),
options = {
bPlaceholder = true,
},
cache = {},
GetFormatString = function(data)
if X.GetFightUUID() or X.GetLastFightUUID() then
return data.cache.formatString .. X.GetFightTime('H:mm:ss')
end
return data.config.bPlaceholder and _L['Never Fight'] or ''
end,
},
-- Á«»¨ºÍźµ¹¼ÆÊ±
{
id = 'LotusTime',
i18n = {
name = _L['Lotus clock'], prefix = _L['Lotus Clock: '], content = '%d:%d:%d',
},
config = X.CreateUserSettingsModule('MY_InfoTip__LotusTime', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 255, 255 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 0,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = -290, y = -38, s = 'BOTTOMRIGHT', r = 'BOTTOMRIGHT' },
},
}),
options = {
bPlaceholder = false,
},
cache = {},
GetFormatString = function(data)
local nTotal = 6 * 60 * 60 - GetLogicFrameCount() / 16 % (6 * 60 * 60)
return string.format(data.cache.formatString, math.floor(nTotal / (60 * 60)), math.floor(nTotal / 60 % 60), math.floor(nTotal % 60))
end,
},
-- ½Çɫ׸±ê
{
id = 'GPS',
i18n = {
name = _L['GPS'], prefix = _L['Location: '], content = '[%d]%d,%d,%d',
},
config = X.CreateUserSettingsModule('MY_InfoTip__GPS', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 255, 255 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 0,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = -21, y = 250, s = 'TOPRIGHT', r = 'TOPRIGHT' },
},
}),
options = {
bPlaceholder = false,
},
cache = {},
GetFormatString = function(data)
local player, text = GetClientPlayer(), ''
if player then
text = string.format(data.cache.formatString, player.GetMapID(), player.nX, player.nY, player.nZ)
end
return text
end,
},
-- ½ÇÉ«ËÙ¶È
{
id = 'Speedometer',
i18n = {
name = _L['Speedometer'], prefix = _L['Speed: '], content = _L['%.2f f/s'],
},
config = X.CreateUserSettingsModule('MY_InfoTip__Speedometer', _L['System'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowBg = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bShowTitle = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
rgb = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Tuple(X.Schema.Number, X.Schema.Number, X.Schema.Number),
xDefaultValue = { 255, 255, 255 },
},
nFont = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.Number,
xDefaultValue = 0,
},
anchor = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_InfoTip'],
xSchema = X.Schema.FrameAnchor,
xDefaultValue = { x = -10, y = 210, s = 'TOPRIGHT', r = 'TOPRIGHT' },
},
}),
options = {
bPlaceholder = false,
},
cache = {
tSpeedometerRec = {},
nSpeedometerLFC = GetLogicFrameCount(),
},
GetFormatString = function(data)
local s = 0
local me = GetClientPlayer()
if me and data.cache.nSpeedometerLFC ~= GetLogicFrameCount() then
local sm = data.cache.tSpeedometerRec[GLOBAL.GAME_FPS] or {}
sm.framecount = GetLogicFrameCount()
sm.x, sm.y, sm.z = me.nX, me.nY, me.nZ
for i = GLOBAL.GAME_FPS, 1, -1 do
data.cache.tSpeedometerRec[i] = data.cache.tSpeedometerRec[i - 1]
end
data.cache.tSpeedometerRec[1] = sm
data.cache.nSpeedometerLFC = GetLogicFrameCount()
end
local sm = data.cache.tSpeedometerRec[GLOBAL.GAME_FPS]
if sm and me then
s = math.sqrt(math.pow(me.nX - sm.x, 2) + math.pow(me.nY - sm.y, 2) + math.pow((me.nZ - sm.z) / 8, 2)) / 64
/ (GetLogicFrameCount() - sm.framecount) * GLOBAL.GAME_FPS
end
return string.format(data.cache.formatString, s)
end
},
}
local D = {}
X.RegisterEvent('CUSTOM_UI_MODE_SET_DEFAULT', function()
for _, v in ipairs(INFO_TIP_LIST) do
v.config('reset', {'anchor'})
end
D.ReinitUI()
end)
-- ÏÔʾÐÅÏ¢Ìõ
function D.ReinitUI()
for _, data in ipairs(INFO_TIP_LIST) do
local ui = UI('Normal/MY_InfoTip_' .. data.id)
if data.config.bEnable then
if ui:Count() == 0 then
ui = UI.CreateFrame('MY_InfoTip_' .. data.id, { empty = true })
:Size(220,30)
:Event(
'UI_SCALED',
function()
UI(this):Anchor(data.config.anchor)
end)
:CustomLayout(data.i18n.name)
:CustomLayout(function(bEnter, anchor)
if bEnter then
UI(this):BringToTop()
else
data.config.anchor = anchor
end
end)
:Drag(0, 0, 0, 0)
:Drag(false)
:Penetrable(true)
ui:Append('Image', {
name = 'Image_Default',
w = 220, h = 30,
alpha = 180,
image = 'UI/Image/UICommon/Commonpanel.UITex', imageframe = 86,
})
local txt = ui:Append('Text', {
name = 'Text_Default',
w = 220, h = 30,
text = data.i18n.name,
font = 2, valign = 1, halign = 1,
})
ui:Breathe(function() txt:Text(data.GetFormatString(data)) end)
end
data.cache.formatString = data.config.bShowTitle
and data.i18n.prefix .. data.i18n.content
or data.i18n.content
ui:Fetch('Image_Default'):Visible(data.config.bShowBg)
ui:Fetch('Text_Default')
:Font(data.config.nFont or 0)
:Color(data.config.rgb or { 255, 255, 255 })
ui:Anchor(data.config.anchor)
else
ui:Remove()
end
end
end
-- ×¢²áINITʼþ
X.RegisterUserSettingsUpdate('@@INIT@@', 'MY_INFOTIP', function()
D.ReinitUI()
end)
local PS = {}
function PS.OnPanelActive(wnd)
local ui = UI(wnd)
local w, h = ui:Size()
local x, y = 45, 40
ui:Append('Text', {
name = 'Text_InfoTip',
x = x, y = y, w = 350,
text = _L['Infomation tips'],
color = {255, 255, 0},
})
y = y + 5
for _, data in ipairs(INFO_TIP_LIST) do
x, y = 60, y + 30
ui:Append('WndCheckBox', {
name = 'WndCheckBox_InfoTip_' .. data.id,
x = x, y = y, w = 250,
text = data.i18n.name,
checked = data.config.bEnable or false,
oncheck = function(bChecked)
data.config.bEnable = bChecked
D.ReinitUI()
end,
})
x = x + 220
if data.options.bPlaceholder then
ui:Append('WndCheckBox', {
name = 'WndCheckBox_InfoTipPlaceholder_' .. data.id,
x = x, y = y, w = 100,
text = _L['Placeholder'],
checked = data.config.bPlaceholder or false,
oncheck = function(bChecked)
data.config.bPlaceholder = bChecked
D.ReinitUI()
end,
})
end
x = x + 100
ui:Append('WndCheckBox', {
name = 'WndCheckBox_InfoTipTitle_' .. data.id,
x = x, y = y, w = 60,
text = _L['Title'],
checked = data.config.bShowTitle or false,
oncheck = function(bChecked)
data.config.bShowTitle = bChecked
D.ReinitUI()
end,
})
x = x + 70
ui:Append('WndCheckBox', {
name = 'WndCheckBox_InfoTipBg_' .. data.id,
x = x, y = y, w = 60,
text = _L['Background'],
checked = data.config.bShowBg or false,
oncheck = function(bChecked)
data.config.bShowBg = bChecked
D.ReinitUI()
end,
})
x = x + 70
ui:Append('WndButton', {
name = 'WndButton_InfoTipFont_' .. data.id,
x = x, y = y, w = 50,
text = _L['Font'],
onclick = function()
UI.OpenFontPicker(function(f)
data.config.nFont = f
D.ReinitUI()
end)
end,
})
x = x + 60
ui:Append('Shadow', {
name = 'Shadow_InfoTipColor_' .. data.id,
x = x, y = y, w = 20, h = 20,
color = data.config.rgb or {255, 255, 255},
onclick = function()
local el = this
UI.OpenColorPicker(function(r, g, b)
UI(el):Color(r, g, b)
data.config.rgb = { r, g, b }
D.ReinitUI()
end)
end,
})
end
end
X.RegisterPanel(_L['System'], 'MY_InfoTip', _L['MY_InfoTip'], 'ui/Image/UICommon/ActivePopularize2.UITex|22', PS)
| bsd-3-clause |
Kosmos82/kosmosdarkstar | scripts/globals/items/mercanbaligi.lua | 18 | 1313 | -----------------------------------------
-- ID: 5454
-- Item: Mercanbaligi
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 4
-- Mind -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5454);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -6);
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Yuhtunga_Jungle/npcs/Robino-Mobino.lua | 13 | 1885 | -----------------------------------
-- Area: Yuhtunga Jungle
-- NPC: Robino-Mobino
-- @pos -244 0 -401 123
-----------------------------------
package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Yuhtunga_Jungle/TextIDs");
local region = ELSHIMOLOWLANDS;
local csid = 0x7ff4;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local owner = GetRegionOwner(region);
local arg1 = getArg1(owner,player);
if (owner == player:getNation()) then
nation = 1;
elseif (arg1 < 1792) then
nation = 2;
else
nation = 0;
end
player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP());
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if (option == 1) then
ShowOPVendorShop(player);
elseif (option == 2) then
if (player:delGil(OP_TeleFee(player,region))) then
toHomeNation(player);
end
elseif (option == 6) then
player:delCP(OP_TeleFee(player,region));
toHomeNation(player);
end
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Kazham/npcs/Roropp.lua | 13 | 8473 | -----------------------------------
-- Area: Kazham
-- NPC: Roropp
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/pathfind");
local path = {
16.031977, -8.000000, -106.132980,
16.257568, -8.000000, -105.056381,
16.488544, -8.000000, -103.993233,
16.736769, -8.000000, -102.925789,
16.683693, -8.000000, -103.979767,
16.548674, -8.000000, -105.063362,
16.395681, -8.000000, -106.140511,
16.232897, -8.000000, -107.264717,
15.467215, -8.000000, -111.498398,
14.589552, -8.000000, -110.994324,
15.159187, -8.000000, -111.843941,
14.467873, -8.000000, -110.962730,
15.174071, -8.000000, -111.862633,
14.541949, -8.000000, -111.057007,
14.902087, -8.000000, -110.084839,
16.047390, -8.000000, -109.979256,
15.778022, -8.000000, -111.043304,
14.890110, -8.000000, -111.671753,
14.021555, -8.000000, -112.251015,
14.686207, -8.000000, -111.499725,
14.093862, -8.000000, -110.499420,
13.680259, -8.000000, -109.391823,
13.557489, -8.000000, -108.379669,
13.505498, -8.000000, -107.381012,
13.459559, -8.000000, -106.253922,
13.316416, -8.000000, -103.526192,
13.187886, -8.000000, -104.739197,
13.107801, -8.000000, -105.800117,
12.796517, -8.000000, -112.526253,
13.832601, -8.000000, -112.296143,
14.750398, -8.000000, -111.783379,
15.670343, -8.000000, -111.165863,
16.603874, -8.000000, -110.633209,
16.092684, -8.000000, -111.518547,
14.989306, -8.000000, -111.488846,
14.200422, -8.000000, -110.700859,
13.893030, -8.000000, -109.573753,
14.125311, -8.000000, -108.444000,
14.459513, -8.000000, -107.450630,
14.801712, -8.000000, -106.489639,
17.003086, -8.000000, -99.881256,
16.131863, -8.000000, -100.382454,
15.278582, -8.000000, -101.082420,
14.444073, -8.000000, -101.823395,
13.716499, -8.000000, -102.551468,
13.602413, -8.000000, -103.671387,
13.773719, -8.000000, -104.753410,
14.019071, -8.000000, -105.842079,
14.275101, -8.000000, -106.944748,
15.256051, -8.000000, -111.604820,
14.447664, -8.000000, -110.851128,
15.032362, -8.000000, -111.679832,
14.342421, -8.000000, -110.802597,
13.347830, -8.000000, -111.075569,
12.911378, -8.000000, -112.149437,
13.853123, -8.000000, -112.719269,
14.862821, -8.000000, -112.491272,
14.661202, -8.000000, -111.423317,
14.026034, -8.000000, -110.421486,
13.683197, -8.000000, -109.474442,
13.565609, -8.000000, -108.425598,
13.508922, -8.000000, -107.411247,
13.463074, -8.000000, -106.340248,
13.314778, -8.000000, -103.679779,
13.196125, -8.000000, -104.712784,
13.107168, -8.000000, -105.817261,
12.642462, -8.000000, -112.284569,
12.722448, -8.000000, -111.167519,
12.800394, -8.000000, -110.082321,
13.358773, -8.000000, -103.535522,
13.700077, -8.000000, -104.534401,
13.968060, -8.000000, -105.588699,
14.196942, -8.000000, -106.594994,
14.446990, -8.000000, -107.686691,
14.850841, -8.000000, -109.436707,
15.239276, -8.000000, -111.548279,
14.406080, -8.000000, -110.805321,
15.076430, -8.000000, -111.739746,
14.353576, -8.000000, -110.817177,
13.903994, -8.000000, -109.854828,
14.002557, -8.000000, -108.838097,
14.350549, -8.000000, -107.686317,
14.707720, -8.000000, -106.730751,
15.101375, -8.000000, -105.648056,
16.961918, -8.000000, -99.919090,
15.985752, -8.000000, -100.501892,
15.192271, -8.000000, -101.161407,
14.369474, -8.000000, -101.891479,
13.749530, -8.000000, -102.797821,
13.968772, -8.000000, -103.829323,
14.469959, -8.000000, -104.888268,
14.964800, -8.000000, -105.802879,
16.955986, -8.000000, -109.414169,
16.776617, -8.000000, -110.478836,
16.263479, -8.000000, -111.339577,
15.200941, -8.000000, -111.526329,
14.352178, -8.000000, -110.754326,
15.190737, -8.000000, -110.001801,
16.302240, -8.000000, -110.005722,
15.815475, -8.000000, -111.014900,
14.911292, -8.000000, -111.661888,
14.005045, -8.000000, -112.263855,
14.883535, -8.000000, -111.781982,
14.404255, -8.000000, -110.876640,
15.071056, -8.000000, -111.731522,
14.335340, -8.000000, -110.793587,
13.342915, -8.000000, -111.184967,
12.869198, -8.000000, -112.210732,
13.971279, -8.000000, -112.223083,
14.902745, -8.000000, -111.661880,
15.813969, -8.000000, -111.060051,
16.728361, -8.000000, -110.402679,
16.754343, -8.000000, -109.357780,
16.393435, -8.000000, -108.410202,
15.880263, -8.000000, -107.455299,
15.362660, -8.000000, -106.521095,
13.593607, -8.000000, -103.312202,
14.028812, -8.000000, -102.335686,
14.836555, -8.000000, -101.487602,
15.656289, -8.000000, -100.748199,
16.544455, -8.000000, -99.965248,
15.712431, -8.000000, -100.702980,
14.859239, -8.000000, -101.459091,
13.961225, -8.000000, -102.255051,
14.754376, -8.000000, -101.551842,
15.574628, -8.000000, -100.824944,
16.913191, -8.000000, -99.639374,
16.158613, -8.000000, -100.307716,
15.371163, -8.000000, -101.005310,
13.802610, -8.000000, -102.395645,
13.852294, -8.000000, -103.601982,
14.296268, -8.000000, -104.610878,
14.826925, -8.000000, -105.560638,
15.320851, -8.000000, -106.448463,
15.858366, -8.000000, -107.421883,
17.018456, -8.000000, -109.527451,
16.734596, -8.000000, -110.580498,
16.095715, -8.000000, -111.542282
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
function onTrade(player,npc,trade)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(1157,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(905,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 3 or failed == 4 then
if goodtrade then
player:startEvent(0x00DE);
elseif badtrade then
player:startEvent(0x00E8);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local retry = player:getVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(0x00C8);
npc:wait(-1);
elseif (progress == 3 or failed == 4) then
player:startEvent(0x00D2); -- asking for sands of silence
elseif (progress >= 4 or failed >= 5) then
player:startEvent(0x00F5); -- happy with sands of silence
end
else
player:startEvent(0x00C8);
npc:wait(-1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00DE) then -- correct trade, onto next opo
if player:getVar("OPO_OPO_PROGRESS") == 3 then
player:tradeComplete();
player:setVar("OPO_OPO_PROGRESS",4);
player:setVar("OPO_OPO_FAILED",0);
else
player:setVar("OPO_OPO_FAILED",5);
end
elseif (csid == 0x00E8) then -- wrong trade, restart at first opo
player:setVar("OPO_OPO_FAILED",1);
player:setVar("OPO_OPO_RETRY",4);
else
npc:wait(0);
end
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Windurst_Waters/npcs/Fuepepe.lua | 12 | 3846 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Fuepepe
-- Starts and Finishes Quest: Teacher's Pet
-- Involved in Quest: Making the grade, Class Reunion
-- @zone = 238
-- @pos = 161 -2 161
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED and player:getVar("QuestMakingTheGrade_prog") == 0) then
if (trade:hasItemQty(544,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then
player:startEvent(0x01c7); -- Quest Progress: Test Papers Shown and told to deliver them to principal
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gradestatus = player:getQuestStatus(WINDURST,MAKING_THE_GRADE);
local prog = player:getVar("QuestMakingTheGrade_prog");
-- 1 = answers found
-- 2 = gave test answers to principle
-- 3 = spoke to chomoro
if (player:getQuestStatus(WINDURST,TEACHER_S_PET) == QUEST_COMPLETED and gradestatus == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >=3 and player:getQuestStatus(WINDURST,LET_SLEEPING_DOGS_LIE) ~= QUEST_ACCEPTED) then
player:startEvent(0x01ba); -- Quest Start
elseif (gradestatus == QUEST_ACCEPTED) then
if (prog == 0) then
player:startEvent(0x01bb); -- Get Test Sheets Reminder
elseif (prog == 1) then
player:startEvent(0x01c8); -- Deliver Test Sheets Reminder
elseif (prog == 2 or prog == 3) then
player:startEvent(0x01ca); -- Quest Finish
end
elseif (gradestatus == QUEST_COMPLETED and player:needToZone() == true) then
player:startEvent(0x01cb); -- After Quest
-------------------------------------------------------
-- Class Reunion
elseif (player:getQuestStatus(WINDURST,CLASS_REUNION) == QUEST_ACCEPTED and player:getVar("ClassReunionProgress") >= 3 and player:getVar("ClassReunion_TalkedToFupepe") ~= 1) then
player:startEvent(0x0331); -- he tells you about Uran-Mafran
-------------------------------------------------------
else
player:startEvent(0x1a7); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x01ba and option == 1) then -- Quest Start
player:addQuest(WINDURST,MAKING_THE_GRADE);
elseif (csid == 0x01c7) then -- Quest Progress: Test Papers Shown and told to deliver them to principal
player:setVar("QuestMakingTheGrade_prog",1);
elseif (csid == 0x01ca) then -- Quest Finish
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4855);
else
player:completeQuest(WINDURST,MAKING_THE_GRADE);
player:addFame(WINDURST,75);
player:addItem(4855);
player:messageSpecial(ITEM_OBTAINED,4855);
player:setVar("QuestMakingTheGrade_prog",0);
player:needToZone(true);
end
elseif (csid == 0x0331) then
player:setVar("ClassReunion_TalkedToFupepe",1);
end
end;
| gpl-3.0 |
aStonedPenguin/fprp | entities/entities/microwave/init.lua | 1 | 4104 | AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");
include("shared.lua");
function ENT:Initialize()
self:SetModel("models/props/cs_office/microwave.mdl");
self:PhysicsInit(SOLID_VPHYSICS);
self:SetMoveType(MOVETYPE_VPHYSICS);
self:SetSolid(SOLID_VPHYSICS);
self:SetUseType(SIMPLE_USE);
local phys = self:GetPhysicsObject();
phys:Wake();
self.sparking = false
self.damage = 100
self:Setprice(math.Clamp((GAMEMODE.Config.pricemin ~= 0 and GAMEMODE.Config.pricemin) or 30, (GAMEMODE.Config.pricecap ~= 0 and GAMEMODE.Config.pricecap) or 30));
end
function ENT:OnTakeDamage(dmg)
self.damage = self.damage - dmg:GetDamage();
if (self.damage <= 0) then
self:Destruct();
self:Remove();
end
end
function ENT:Destruct()
local vPoint = self:GetPos();
local effectdata = EffectData();
effectdata:SetStart(vPoint);
effectdata:SetOrigin(vPoint);
effectdata:SetScale(1);
util.Effect("Explosion", effectdata);
end
function ENT:SalePrice(activator)
local owner = self:Getowning_ent();
local discounted = math.ceil(GAMEMODE.Config.microwavefoodcost * 0.82);
if activator == owner then
-- If they are still a cook, sell them the food at the discounted rate
if self.allowed and type(self.allowed) == "table" and table.HasValue(self.allowed, activator:Team()) then
return discounted
else -- Otherwise, sell it to them at full price
return math.ceil(GAMEMODE.Config.microwavefoodcost);
end
else
return self:Getprice();
end
end
ENT.Once = false
function ENT:Use(activator, caller)
local owner = self:Getowning_ent();
self.user = activator
if not activator:canAfford(self:SalePrice(activator)) then
fprp.notify(activator, 1, 3, fprp.getPhrase("cant_afford", string.lower(fprp.getPhrase("food"))));
return ""
end
local diff = (self:SalePrice(activator) - self:SalePrice(owner));
if diff < 0 and not owner:canAfford(math.abs(diff)) then
fprp.notify(activator, 2, 3, fprp.getPhrase("owner_poor", fprp.getPhrase("microwave")));
return ""
end
if activator.maxFoods and activator.maxFoods >= GAMEMODE.Config.maxfoods then
fprp.notify(activator, 1, 3, fprp.getPhrase("limit", string.lower(fprp.getPhrase("food"))));
elseif not self.Once then
self.Once = true
self.sparking = true
local discounted = math.ceil(GAMEMODE.Config.microwavefoodcost * 0.82);
local cash = self:SalePrice(activator);
activator:addshekel(cash * -1);
fprp.notify(activator, 0, 3, fprp.getPhrase("you_bought", string.lower(fprp.getPhrase("food")), fprp.formatshekel(cash)));
if activator ~= owner then
local gain = 0
if self.allowed and type(self.allowed) == "table" and table.HasValue(self.allowed, owner:Team()) then
gain = math.floor(self:Getprice() - discounted);
else
gain = math.floor(self:Getprice() - GAMEMODE.Config.microwavefoodcost);
end
if gain == 0 then
fprp.notify(owner, 3, 3, fprp.getPhrase("you_received_x", fprp.formatshekel(0) .. fprp.getPhrase("profit"), string.lower(fprp.getPhrase("food"))));
else
owner:addshekel(gain);
local word = fprp.getPhrase("profit");
if gain < 0 then word = fprp.getPhrase("loss") end
fprp.notify(owner, 0, 3, fprp.getPhrase("you_received_x", fprp.formatshekel(math.abs(gain)) .. word, string.lower(fprp.getPhrase("food"))));
end
end
timer.Create(self:EntIndex() .. "food", 1, 1, function() self:createFood() end)
end
end
function ENT:createFood()
local activator = self.user
self.Once = false
local foodPos = self:GetPos();
local food = ents.Create("food");
food:SetPos(Vector(foodPos.x,foodPos.y,foodPos.z + 23));
food:Setowning_ent(activator);
food.ShareGravgun = true
food.nodupe = true
food:Spawn();
if not activator.maxFoods then
activator.maxFoods = 0
end
activator.maxFoods = activator.maxFoods + 1
self.sparking = false
end
function ENT:Think()
if self.sparking then
local effectdata = EffectData();
effectdata:SetOrigin(self:GetPos());
effectdata:SetMagnitude(1);
effectdata:SetScale(1);
effectdata:SetRadius(2);
util.Effect("Sparks", effectdata);
end
end
function ENT:OnRemove()
timer.Destroy(self:EntIndex().."food");
end
| mit |
Kosmos82/kosmosdarkstar | scripts/globals/items/slice_of_hare_meat.lua | 18 | 1334 | -----------------------------------------
-- ID: 4358
-- Hare Meat
-- 5 Minutes, food effect, Galka Only
-----------------------------------------
-- Strength +1
-- Intelligence -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4358);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 1);
target:addMod(MOD_INT,-3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 1);
target:delMod(MOD_INT,-3);
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Bastok_Markets/npcs/Arawn.lua | 25 | 2553 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Arawn
-- Starts & Finishes Quest: Stamp Hunt
-- @pos -121.492 -4.000 -123.923 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT);
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,11) == false) then
player:startEvent(0x01ad);
elseif (StampHunt == QUEST_AVAILABLE) then
player:startEvent(0x00e1);
elseif (StampHunt == QUEST_ACCEPTED and player:isMaskFull(player:getVar("StampHunt_Mask"),7) == true) then
player:startEvent(0x00e2);
else
player:startEvent(0x0072);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00e1 and option == 0) then
player:addQuest(BASTOK,STAMP_HUNT);
player:addKeyItem(STAMP_SHEET);
player:messageSpecial(KEYITEM_OBTAINED,STAMP_SHEET);
elseif (csid == 0x00e2) then
if (player:getFreeSlotsCount(0) >= 1) then
player:addTitle(STAMPEDER);
player:addItem(13081);
player:messageSpecial(ITEM_OBTAINED,13081); -- Leather Gorget
player:delKeyItem(STAMP_SHEET);
player:setVar("StampHunt_Mask",0);
player:addFame(BASTOK,50);
player:completeQuest(BASTOK,STAMP_HUNT);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13081);
end
elseif (csid == 0x01ad) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",11,true);
end
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/items/bowl_of_puls.lua | 18 | 1290 | -----------------------------------------
-- ID: 4492
-- Item: bowl_of_puls
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- Vitality 2
-- Dexterity -1
-- HP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4492);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 2);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 2);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
wingo/snabbswitch | lib/ljsyscall/include/luaunit/luaunit.lua | 24 | 19044 | --[[
luaunit.lua
Description: A unit testing framework
Homepage: http://phil.freehackers.org/luaunit/
Initial author: Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit)
Lot of improvements by Philippe Fremy <phil@freehackers.org>
More improvements by Ryan P. <rjpcomputing@gmail.com>
Version: 2.0
License: X11 License, see LICENSE.txt
- Justin Cormack added slightly hacky method for marking tests as skipped, not really suitable for upstream yet.
Changes between 2.0 and 1.3:
- This is a major update that has some breaking changes to make it much more easy to use and code in many different styles
- Made the module only touch the global table for the asserts. You now use the module much more like Lua 5.2 when you require it.
You need to store the LuaUnit table after you require it to allow you access to the LuaUnit methods and variables.
(ex. local LuaUnit = require( "luaunit" ))
- Made changes to the style of which LuaUnit forced users to code there test classes. It now is more layed back and give the ability to code in a few styles.
- Made "testable" classes able to start with 'test' or 'Test' for their name.
- Made "testable" methods able to start with 'test' or 'Test' for their name.
- Made testClass:setUp() methods able to be named with 'setUp' or 'Setup' or 'setup'.
- Made testClass:tearDown() methods able to be named with 'tearDown' or 'TearDown' or 'teardown'.
- Made LuaUnit.wrapFunctions() function able to be called with 'wrapFunctions' or 'WrapFunctions' or 'wrap_functions'.
- Made LuaUnit:run() method able to be called with 'run' or 'Run'.
- Added the ability to tell if tables are equal using assertEquals. This uses a deep compare, not just the equality that they are the same memory address.
- Added LuaUnit.is<Type> and LuaUnit.is_<type> helper functions. (e.g. assert( LuaUnit.isString( getString() ) )
- Added assert<Type> and assert_<type>
- Added assertNot<Type> and assert_not_<type>
- Added _VERSION variable to hold the LuaUnit version
- Added LuaUnit:setVerbosity(lvl) method to the LuaUnit table to allow you to control the verbosity now. If lvl is greater than 1 it will give verbose output.
This can be called from alias of LuaUnit.SetVerbosity() and LuaUnit:set_verbosity().
- Moved wrapFunctions to the LuaUnit module table (e.g. local LuaUnit = require( "luaunit" ); LuaUnit.wrapFunctions( ... ) )
- Fixed the verbosity to actually format in a way that is closer to other unit testing frameworks I have used.
NOTE: This is not the only way, I just thought the old output was way to verbose and duplicated the errors.
- Made the errors only show in the "test report" section (at the end of the run)
Changes between 1.3 and 1.2a:
- port to lua 5.1
- use orderedPairs() to iterate over a table in the right order
- change the order of expected, actual in assertEquals() and the default value of
USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS. This can be adjusted with
USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS.
Changes between 1.2a and 1.2:
- fix: test classes were not run in the right order
Changes between 1.2 and 1.1:
- tests are now run in alphabetical order
- fix a bug that would prevent all tests from being run
Changes between 1.1 and 1.0:
- internal variables are not global anymore
- you can choose between assertEquals( actual, expected) or assertEquals(
expected, actual )
- you can assert for an error: assertError( f, a, b ) will assert that calling
the function f(a,b) generates an error
- display the calling stack when an error is spotted
- a dedicated class collects and displays the result, to provide easy
customisation
- two verbosity level, like in python unittest
]]--
-- SETUP -----------------------------------------------------------------------
--
local argv = arg
local typenames = { "Nil", "Boolean", "Number", "String", "Table", "Function", "Thread", "Userdata" }
--[[ Some people like assertEquals( actual, expected ) and some people prefer
assertEquals( expected, actual ).
]]--
USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS = USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS or true
-- HELPER FUNCTIONS ------------------------------------------------------------
--
local function tablePrint(tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then
local sb = {}
for key, value in pairs(tt) do
table.insert(sb, string.rep(" ", indent)) -- indent it
if type(value) == "table" and not done[value] then
done[value] = true
table.insert(sb, "[\""..key.."\"] = {\n");
table.insert(sb, tablePrint(value, indent + 2, done))
table.insert(sb, string.rep(" ", indent)) -- indent it
table.insert(sb, "}\n");
elseif "number" == type(key) then
table.insert(sb, string.format("\"%s\"\n", tostring(value)))
else
table.insert(sb, string.format(
"%s = \"%s\"\n", tostring(key), tostring(value)))
end
end
return table.concat(sb)
else
return tt .. "\n"
end
end
local function toString( tbl )
if "nil" == type( tbl ) then
return tostring(nil)
elseif "table" == type( tbl ) then
return tablePrint(tbl)
elseif "string" == type( tbl ) then
return tbl
else
return tostring(tbl)
end
end
local function deepCompare(t1, t2, ignore_mt)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(t1)
if not ignore_mt and mt and mt.__eq then return t1 == t2 end
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or not deepCompare(v1,v2) then return false end
end
for k2,v2 in pairs(t2) do
local v1 = t1[k2]
if v1 == nil or not deepCompare(v1,v2) then return false end
end
return true
end
-- Order of testing
local function __genOrderedIndex( t )
local orderedIndex = {}
for key,_ in pairs(t) do
table.insert( orderedIndex, key )
end
table.sort( orderedIndex )
return orderedIndex
end
local function orderedNext(t, state)
-- Equivalent of the next() function of table iteration, but returns the
-- keys in the alphabetic order. We use a temporary ordered key table that
-- is stored in the table being iterated.
--print("orderedNext: state = "..tostring(state) )
if state == nil then
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex( t )
local key = t.__orderedIndex[1]
return key, t[key]
end
-- fetch the next value
local key = nil
for i = 1,#t.__orderedIndex do
if t.__orderedIndex[i] == state then
key = t.__orderedIndex[i+1]
end
end
if key then
return key, t[key]
end
-- no more value to return, cleanup
t.__orderedIndex = nil
return
end
local function orderedPairs(t)
-- Equivalent of the pairs() function on tables. Allows to iterate
-- in order
return orderedNext, t, nil
end
-- ASSERT FUNCTIONS ------------------------------------------------------------
--
function assertError(f, ...)
-- assert that calling f with the arguments will raise an error
-- example: assertError( f, 1, 2 ) => f(1,2) should generate an error
local has_error, error_msg = not pcall( f, ... )
if has_error then return end
error( "No error generated", 2 )
end
assert_error = assertError
function assertEquals(actual, expected)
-- assert that two values are equal and calls error else
if not USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS then
expected, actual = actual, expected
end
if "table" == type(actual) then
if not deepCompare(actual, expected, true) then
error("table expected: \n"..toString(expected)..", actual: \n"..toString(actual))
end
else
if actual ~= expected then
local function wrapValue( v )
if type(v) == 'string' then return "'"..v.."'" end
return tostring(v)
end
local errorMsg
--if type(expected) == 'string' then
-- errorMsg = "\nexpected: "..wrapValue(expected).."\n"..
-- "actual : "..wrapValue(actual).."\n"
--else
errorMsg = "expected: "..wrapValue(expected)..", actual: "..wrapValue(actual)
--end
--print(errorMsg)
error(errorMsg, 2)
end
end
end
assert_equals = assertEquals
-- assert_<type> functions
for _, typename in ipairs(typenames) do
local tName = typename:lower()
local assert_typename = "assert"..typename
_G[assert_typename] = function(actual, msg)
local actualtype = type(actual)
if actualtype ~= tName then
local errorMsg = tName.." expected but was a "..actualtype
if msg then
errorMsg = msg.."\n"..errorMsg
end
error(errorMsg, 2)
end
return actual
end
-- Alias to lower underscore naming
_G["assert_"..tName] = _G[assert_typename]
end
-- assert_not_<type> functions
for _, typename in ipairs(typenames) do
local tName = typename:lower()
local assert_not_typename = "assertNot"..typename
_G[assert_not_typename] = function(actual, msg)
if type(actual) == tName then
local errorMsg = tName.." not expected but was one"
if msg then
errorMsg = msg.."\n"..errorMsg
end
error(errorMsg, 2)
end
end
-- Alias to lower underscore naming
_G["assert_not_"..tName] = _G[assert_not_typename]
end
-- UNITRESULT CLASS ------------------------------------------------------------
--
local UnitResult = { -- class
failureCount = 0,
skipCount = 0,
testCount = 0,
errorList = {},
currentClassName = "",
currentTestName = "",
testHasFailure = false,
testSkipped = false,
verbosity = 1
}
function UnitResult:displayClassName()
--if self.verbosity == 0 then print("") end
print(self.currentClassName)
end
function UnitResult:displayTestName()
if self.verbosity == 0 then
io.stdout:write(".")
else
io.stdout:write((" [%s] "):format(self.currentTestName))
end
end
function UnitResult:displayFailure(errorMsg)
if self.verbosity == 0 then
io.stdout:write("F")
else
--print(errorMsg)
print("", "Failed")
end
end
function UnitResult:displaySuccess()
if self.verbosity == 0 then
io.stdout:write(".")
else
print("", "Ok")
end
end
function UnitResult:displaySkip()
if self.verbosity == 0 then
io.stdout:write(".")
else
print("", "Skipped")
end
end
function UnitResult:displayOneFailedTest(failure)
local testName, errorMsg = unpack(failure)
print(">>> "..testName.." failed")
print(errorMsg)
end
function UnitResult:displayFailedTests()
if #self.errorList == 0 then return end
print("Failed tests:")
print("-------------")
for i,v in ipairs(self.errorList) do self.displayOneFailedTest(i, v) end
end
function UnitResult:displayFinalResult()
if self.verbosity == 0 then print("") end
print("=========================================================")
self:displayFailedTests()
local failurePercent, successCount
local totalTested = self.testCount - self.skipCount
if totalTested == 0 then
failurePercent = 0
else
failurePercent = 100 * self.failureCount / totalTested
end
local successCount = totalTested - self.failureCount
print( string.format("Success : %d%% - %d / %d (total of %d tests, %d skipped)",
100-math.ceil(failurePercent), successCount, totalTested, self.testCount, self.skipCount ) )
return self.failureCount
end
function UnitResult:startClass(className)
self.currentClassName = className
self:displayClassName()
-- indent status messages
if self.verbosity == 0 then io.stdout:write("\t") end
end
function UnitResult:startTest(testName)
self.currentTestName = testName
self:displayTestName()
self.testCount = self.testCount + 1
self.testHasFailure = false
self.testSkipped = false
end
function UnitResult:addFailure( errorMsg )
self.failureCount = self.failureCount + 1
self.testHasFailure = true
table.insert( self.errorList, { self.currentTestName, errorMsg } )
self:displayFailure( errorMsg )
end
function UnitResult:addSkip()
self.testSkipped = true
self.skipCount = self.skipCount + 1
end
function UnitResult:endTest()
if not self.testHasFailure then
if self.testSkipped then
self:displaySkip()
else
self:displaySuccess()
end
end
end
-- class UnitResult end
-- LUAUNIT CLASS ---------------------------------------------------------------
--
local LuaUnit = {
result = UnitResult,
_VERSION = "2.0"
}
-- Sets the verbosity level
-- @param lvl {number} If greater than 0 there will be verbose output. Defaults to 0
function LuaUnit:setVerbosity(lvl)
self.result.verbosity = lvl or 0
assert("number" == type(self.result.verbosity), ("bad argument #1 to 'setVerbosity' (number expected, got %s)"):format(type(self.result.verbosity)))
end
-- Other alias's
LuaUnit.set_verbosity = LuaUnit.setVerbosity
LuaUnit.SetVerbosity = LuaUnit.setVerbosity
-- Split text into a list consisting of the strings in text,
-- separated by strings matching delimiter (which may be a pattern).
-- example: strsplit(",%s*", "Anna, Bob, Charlie,Dolores")
function LuaUnit.strsplit(delimiter, text)
local list = {}
local pos = 1
if string.find("", delimiter, 1) then -- this would result in endless loops
error("delimiter matches empty string!")
end
while 1 do
local first, last = string.find(text, delimiter, pos)
if first then -- found?
table.insert(list, string.sub(text, pos, first-1))
pos = last+1
else
table.insert(list, string.sub(text, pos))
break
end
end
return list
end
-- Type check functions
for _, typename in ipairs(typenames) do
local tName = typename:lower()
LuaUnit["is"..typename] = function(x)
return type(x) == tName
end
-- Alias to lower underscore naming
LuaUnit["is_"..tName] = LuaUnit["is"..typename]
end
-- Use me to wrap a set of functions into a Runnable test class:
-- TestToto = wrapFunctions( f1, f2, f3, f3, f5 )
-- Now, TestToto will be picked up by LuaUnit:run()
function LuaUnit.wrapFunctions(...)
local testClass, testFunction
testClass = {}
local function storeAsMethod(idx, testName)
testFunction = _G[testName]
testClass[testName] = testFunction
end
for i, v in ipairs {...} do storeAsMethod(i, v) end
return testClass
end
-- Other alias's
LuaUnit.wrap_functions = LuaUnit.wrapFunctions
LuaUnit.WrapFunctions = LuaUnit.wrapFunctions
function LuaUnit.strip_luaunit_stack(stack_trace)
local stack_list = LuaUnit.strsplit( "\n", stack_trace )
local strip_end = nil
for i = #stack_list,1,-1 do
-- a bit rude but it works !
if string.find(stack_list[i],"[C]: in function `xpcall'",0,true)
then
strip_end = i - 2
end
end
if strip_end then
table.setn( stack_list, strip_end )
end
local stack_trace = table.concat( stack_list, "\n" )
return stack_trace
end
function LuaUnit:runTestMethod(aName, aClassInstance, aMethod)
local ok, errorMsg
-- example: runTestMethod( 'TestToto:test1', TestToto, TestToto.testToto(self) )
LuaUnit.result:startTest(aName)
-- run setUp first(if any)
if self.isFunction( aClassInstance.setUp) then
aClassInstance:setUp()
elseif self.isFunction( aClassInstance.Setup) then
aClassInstance:Setup()
elseif self.isFunction( aClassInstance.setup) then
aClassInstance:setup()
end
-- run testMethod()
local tracemsg
local function trace(err)
tracemsg = debug.traceback()
return err
end
local ok, errorMsg, ret = xpcall( aMethod, trace )
if not ok then
errorMsg = self.strip_luaunit_stack(errorMsg)
if type(errorMsg) == "string" and errorMsg:sub(-9):lower() == ": skipped" then
LuaUnit.result:addSkip()
else
LuaUnit.result:addFailure( errorMsg ..'\n'.. tracemsg)
end
end
-- lastly, run tearDown(if any)
if self.isFunction(aClassInstance.tearDown) then
aClassInstance:tearDown()
elseif self.isFunction(aClassInstance.TearDown) then
aClassInstance:TearDown()
elseif self.isFunction(aClassInstance.teardown) then
aClassInstance:teardown()
end
self.result:endTest()
end
function LuaUnit:runTestMethodName(methodName, classInstance)
-- example: runTestMethodName( 'TestToto:testToto', TestToto )
local methodInstance = loadstring(methodName .. '()')
LuaUnit:runTestMethod(methodName, classInstance, methodInstance)
end
function LuaUnit:runTestClassByName(aClassName)
--assert("table" == type(aClassName), ("bad argument #1 to 'runTestClassByName' (string expected, got %s). Make sure you are not trying to just pass functions not part of a class."):format(type(aClassName)))
-- example: runTestMethodName( 'TestToto' )
local hasMethod, methodName, classInstance
hasMethod = string.find(aClassName, ':' )
if hasMethod then
methodName = string.sub(aClassName, hasMethod+1)
aClassName = string.sub(aClassName,1,hasMethod-1)
end
classInstance = _G[aClassName]
if "table" ~= type(classInstance) then
error("No such class: "..aClassName)
end
LuaUnit.result:startClass( aClassName )
if hasMethod then
if not classInstance[ methodName ] then
error( "No such method: "..methodName )
end
LuaUnit:runTestMethodName( aClassName..':'.. methodName, classInstance )
else
-- run all test methods of the class
for methodName, method in orderedPairs(classInstance) do
--for methodName, method in classInstance do
if LuaUnit.isFunction(method) and (string.sub(methodName, 1, 4) == "test" or string.sub(methodName, 1, 4) == "Test") then
LuaUnit:runTestMethodName( aClassName..':'.. methodName, classInstance )
end
end
end
end
function LuaUnit:run(...)
-- Run some specific test classes.
-- If no arguments are passed, run the class names specified on the
-- command line. If no class name is specified on the command line
-- run all classes whose name starts with 'Test'
--
-- If arguments are passed, they must be strings of the class names
-- that you want to run
local args = {...}
if #args > 0 then
for i, v in ipairs(args) do LuaUnit.runTestClassByName(i, v) end
else
if argv and #argv > 1 then
-- Run files passed on the command line
for i, v in ipairs(argv) do LuaUnit.runTestClassByName(i, v) end
else
-- create the list before. If you do not do it now, you
-- get undefined result because you modify _G while iterating
-- over it.
local testClassList = {}
for key, val in pairs(_G) do
if type(key) == "string" and "table" == type(val) then
if string.sub(key, 1, 4) == "Test" or string.sub(key, 1, 4) == "test" then
table.insert( testClassList, key )
end
end
end
for i, val in orderedPairs(testClassList) do
LuaUnit:runTestClassByName(val)
end
end
end
return LuaUnit.result:displayFinalResult()
end
-- Other alias
LuaUnit.Run = LuaUnit.run
-- end class LuaUnit
return LuaUnit
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Altar_Room/npcs/Magicite.lua | 13 | 1666 | -----------------------------------
-- Area: Altar Room
-- NPC: Magicite
-- Involved in Mission: Magicite
-- @zone 152
-- @pos -344 25 43
-----------------------------------
package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Altar_Room/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_ORASTONE) == false) then
if (player:getVar("MissionStatus") < 4) then
player:startEvent(0x002c,1); -- play Lion part of the CS (this is first magicite)
else
player:startEvent(0x002c); -- don't play Lion part of the CS
end
else
player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x002c) then
player:setVar("MissionStatus",4);
player:addKeyItem(MAGICITE_ORASTONE);
player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_ORASTONE);
end
end; | gpl-3.0 |
Kazuki-Nakamae/Lua_DLfromScratch | 14.二層ニューラルネット/common/init.lua | 1 | 4188 | --Copyright (C) 2017 Kazuki Nakamae
--Released under MIT License
--license available in LICENSE file
require './function.lua'
require './gradient.lua'
require './exTorch.lua'
local common = {}
local help = {
softmax = [[softmax(x) -- Normalize input Tencor]],
sigmoid = [[sigmoid(x) -- the sigmoid of input Tencor]],
relu = [[relu(x) -- the ReLU of input Tencor]],
cross_entropy_error = [[cross_entropy_error(y, t) -- Calculate the cross entropy between y and t]],
numerical_gradient = [[numerical_gradient(f, X) -- Calculate gradient of a given function f(X)]],
mulTensor = [[mulTensor(A, B) -- Calculate multiple of tensor A and tensor B]],
tensor2scalar = [[tensor2scalar(tensor) -- Convert tensor to scalar]],
makeIterTensor = [[makeIterTensor(vector,iter) -- Generate tensor whose rows are repeated]],
getRandIndex = [[getRandIndex(datasize,getsize,seed) -- Get random index of tensor which have elements of datasize]],
getElement = [[getElement(readTensor,...) -- Get value of readTensor[...]. When #{...}>=2, Access value of readTensor according to each value of elements in {...}]],
thresMaxTensor = [[thresMaxTensor(t) -- threshold Tensor by maximum value]]
}
common.softmax = function(x)
if not x then
xlua.error('x must be supplied',
'common.softmax',
help.softmax)
end
return softmax(x)
end
common.sigmoid = function(x)
if not x then
xlua.error('x must be supplied',
'common.sigmoid',
help.sigmoid)
end
return sigmoid(x)
end
common.relu = function(x)
if not x then
xlua.error('x must be supplied',
'common.relu',
help.relu)
end
return relu(x)
end
common.cross_entropy_error = function(y, t)
if not y then
xlua.error('y must be supplied',
'common.cross_entropy_error',
help.cross_entropy_error)
elseif not t then
xlua.error('t must be supplied',
'common.cross_entropy_error',
help.cross_entropy_error)
end
return cross_entropy_error(y, t)
end
common.numerical_gradient = function(f, X)
if not f then
xlua.error('f must be supplied',
'common.numerical_gradient',
help.numerical_gradient)
elseif not X then
xlua.error('X must be supplied',
'common.numerical_gradient',
help.numerical_gradient)
end
return numerical_gradient(f, X)
end
common.mulTensor = function(A, B)
if not A then
xlua.error('A must be supplied',
'common.mulTensor',
help.mulTensor)
elseif not B then
xlua.error('B must be supplied',
'common.mulTensor',
help.mulTensor)
end
return mulTensor(A, B)
end
common.tensor2scalar = function(tensor)
if not A then
xlua.error('tensor must be supplied',
'common.tensor2scalar',
help.tensor2scalar)
end
return tensor2scalar(tensor)
end
common.makeIterTensor = function(vector,iter)
if not vector then
xlua.error('vector must be supplied',
'common.makeIterTensor',
help.makeIterTensor)
elseif not iter then
xlua.error('iter must be supplied',
'common.makeIterTensor',
help.makeIterTensor)
end
return makeIterTensor(vector,iter)
end
common.getRandIndex = function(datasize,getsize,seed)
if not datasize then
xlua.error('datasize must be supplied',
'common.getRandIndex',
help.getRandIndex)
elseif not getsize then
xlua.error('getsize must be supplied',
'common.getRandIndex',
help.getRandIndex)
elseif not seed then
xlua.error('seed must be supplied',
'common.getRandIndex',
help.getRandIndex)
end
return getRandIndex(datasize,getsize,seed)
end
common.getElement = function(readTensor,...)
if not readTensor then
xlua.error('readTensor must be supplied',
'common.getElement',
help.getElement)
end
return getElement(readTensor,...)
end
common.thresMaxTensor = function(t)
if not t then
xlua.error('t must be supplied',
'common.thresMaxTensort',
help.thresMaxTensor)
end
return thresMaxTensor(t)
end
return common
| mit |
satanevil/hellbot | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
RobberPhex/thrift | lib/lua/Thrift.lua | 4 | 6744 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
---- namespace thrift
--thrift = {}
--setmetatable(thrift, {__index = _G}) --> perf hit for accessing global methods
--setfenv(1, thrift)
package.cpath = package.cpath .. ';bin/?.so' -- TODO FIX
function ttype(obj)
if type(obj) == 'table' and
obj.__type and
type(obj.__type) == 'string' then
return obj.__type
end
return type(obj)
end
function terror(e)
if e and e.__tostring then
error(e:__tostring())
return
end
error(e)
end
function ttable_size(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
version = '0.14.0'
TType = {
STOP = 0,
VOID = 1,
BOOL = 2,
BYTE = 3,
I08 = 3,
DOUBLE = 4,
I16 = 6,
I32 = 8,
I64 = 10,
STRING = 11,
UTF7 = 11,
STRUCT = 12,
MAP = 13,
SET = 14,
LIST = 15,
UTF8 = 16,
UTF16 = 17
}
TMessageType = {
CALL = 1,
REPLY = 2,
EXCEPTION = 3,
ONEWAY = 4
}
-- Recursive __index function to achieve inheritance
function __tobj_index(self, key)
local v = rawget(self, key)
if v ~= nil then
return v
end
local p = rawget(self, '__parent')
if p then
return __tobj_index(p, key)
end
return nil
end
-- Basic Thrift-Lua Object
__TObject = {
__type = '__TObject',
__mt = {
__index = __tobj_index
}
}
function __TObject:new(init_obj)
local obj = {}
if ttype(obj) == 'table' then
obj = init_obj
end
-- Use the __parent key and the __index function to achieve inheritance
obj.__parent = self
setmetatable(obj, __TObject.__mt)
return obj
end
-- Return a string representation of any lua variable
function thrift_print_r(t)
local ret = ''
local ltype = type(t)
if (ltype == 'table') then
ret = ret .. '{ '
for key,value in pairs(t) do
ret = ret .. tostring(key) .. '=' .. thrift_print_r(value) .. ' '
end
ret = ret .. '}'
elseif ltype == 'string' then
ret = ret .. "'" .. tostring(t) .. "'"
else
ret = ret .. tostring(t)
end
return ret
end
-- Basic Exception
TException = __TObject:new{
message,
errorCode,
__type = 'TException'
}
function TException:__tostring()
if self.message then
return string.format('%s: %s', self.__type, self.message)
else
local message
if self.errorCode and self.__errorCodeToString then
message = string.format('%d: %s', self.errorCode, self:__errorCodeToString())
else
message = thrift_print_r(self)
end
return string.format('%s:%s', self.__type, message)
end
end
TApplicationException = TException:new{
UNKNOWN = 0,
UNKNOWN_METHOD = 1,
INVALID_MESSAGE_TYPE = 2,
WRONG_METHOD_NAME = 3,
BAD_SEQUENCE_ID = 4,
MISSING_RESULT = 5,
INTERNAL_ERROR = 6,
PROTOCOL_ERROR = 7,
INVALID_TRANSFORM = 8,
INVALID_PROTOCOL = 9,
UNSUPPORTED_CLIENT_TYPE = 10,
errorCode = 0,
__type = 'TApplicationException'
}
function TApplicationException:__errorCodeToString()
if self.errorCode == self.UNKNOWN_METHOD then
return 'Unknown method'
elseif self.errorCode == self.INVALID_MESSAGE_TYPE then
return 'Invalid message type'
elseif self.errorCode == self.WRONG_METHOD_NAME then
return 'Wrong method name'
elseif self.errorCode == self.BAD_SEQUENCE_ID then
return 'Bad sequence ID'
elseif self.errorCode == self.MISSING_RESULT then
return 'Missing result'
elseif self.errorCode == self.INTERNAL_ERROR then
return 'Internal error'
elseif self.errorCode == self.PROTOCOL_ERROR then
return 'Protocol error'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_PROTOCOL then
return 'Invalid protocol'
elseif self.errorCode == self.UNSUPPORTED_CLIENT_TYPE then
return 'Unsupported client type'
else
return 'Default (unknown)'
end
end
function TException:read(iprot)
iprot:readStructBegin()
while true do
local fname, ftype, fid = iprot:readFieldBegin()
if ftype == TType.STOP then
break
elseif fid == 1 then
if ftype == TType.STRING then
self.message = iprot:readString()
else
iprot:skip(ftype)
end
elseif fid == 2 then
if ftype == TType.I32 then
self.errorCode = iprot:readI32()
else
iprot:skip(ftype)
end
else
iprot:skip(ftype)
end
iprot:readFieldEnd()
end
iprot:readStructEnd()
end
function TException:write(oprot)
oprot:writeStructBegin('TApplicationException')
if self.message then
oprot:writeFieldBegin('message', TType.STRING, 1)
oprot:writeString(self.message)
oprot:writeFieldEnd()
end
if self.errorCode then
oprot:writeFieldBegin('type', TType.I32, 2)
oprot:writeI32(self.errorCode)
oprot:writeFieldEnd()
end
oprot:writeFieldStop()
oprot:writeStructEnd()
end
-- Basic Client (used in generated lua code)
__TClient = __TObject:new{
__type = '__TClient',
_seqid = 0
}
function __TClient:new(obj)
if ttype(obj) ~= 'table' then
error('TClient must be initialized with a table')
end
-- Set iprot & oprot
if obj.protocol then
obj.iprot = obj.protocol
obj.oprot = obj.protocol
obj.protocol = nil
elseif not obj.iprot then
error('You must provide ' .. ttype(self) .. ' with an iprot')
end
if not obj.oprot then
obj.oprot = obj.iprot
end
return __TObject.new(self, obj)
end
function __TClient:close()
self.iprot.trans:close()
self.oprot.trans:close()
end
-- Basic Processor (used in generated lua code)
__TProcessor = __TObject:new{
__type = '__TProcessor'
}
function __TProcessor:new(obj)
if ttype(obj) ~= 'table' then
error('TProcessor must be initialized with a table')
end
-- Ensure a handler is provided
if not obj.handler then
error('You must provide ' .. ttype(self) .. ' with a handler')
end
return __TObject.new(self, obj)
end
| apache-2.0 |
TannerRogalsky/haex | enemies/free_chase.lua | 1 | 2028 | local FreeChase = class('FreeChase', Enemy):include(Stateful)
local MAX_ROT_PER_SECOND = math.pi / 3
local SPEED = 35
local function setCollider(collider, x, y, w, h)
collider:moveTo(x, y)
end
local function getViewport(quad, texture)
local w, h = texture:getDimensions()
local qx, qy, qw, qh = quad:getViewport()
return qx / w, qy / h, qw / w, qh / h
end
function FreeChase:initialize(map, x, y, w, h)
Enemy.initialize(self)
self.x, self.y = x, y
self.w, self.h = w, h
self.rotation = 0
self.map = map
self.collider = map.collider:rectangle(self.x, self.y, self.w * 0.75, self.h * 0.75)
self.collider.parent = self
local sprites = require('images.sprites')
local texture = sprites.texture
local quad = sprites.quads['enemy3_body.png']
local qx, qy, qw, qh = getViewport(quad, texture)
self.mesh = g.newMesh({
{-w / 2, -h / 2, qx, qy},
{-w / 2, h / 2, qx, qy + qh},
{w / 2, h / 2, qx + qw, qy + qh},
{w / 2, -h / 2, qx + qw, qy},
}, 'fan', 'static')
self.mesh:setTexture(texture)
self.t = 0
end
function FreeChase:move(time_to_move)
end
function FreeChase:update(dt)
self.t = self.t + dt
local tau = math.pi * 2
local px, py = game.player.x - self.w / 2, game.player.y - self.h / 2
local max_rot = MAX_ROT_PER_SECOND * dt
local rotation = math.atan2(py - self.y, px - self.x)
local delta_phi = ((((rotation - self.rotation) % tau) + math.pi * 3) % tau) - math.pi
delta_phi = math.clamp(-max_rot / 2, delta_phi, max_rot)
self.rotation = self.rotation + delta_phi
self.collider:setRotation(self.rotation)
local dx, dy = math.cos(self.rotation), math.sin(self.rotation)
self.x = self.x + SPEED * dt * dx
self.y = self.y + SPEED * dt * dy
setCollider(self.collider, self.x, self.y, self.w, self.h)
end
function FreeChase:draw()
g.setColor(255, 255, 255)
g.draw(self.mesh, self.x, self.y, self.rotation + math.pi / 2, 2, 2)
if game.debug then
g.setColor(0, 0, 255, 150)
self.collider:draw('fill')
end
end
return FreeChase
| mit |
april-org/april-ann | packages/bayesian/lua_src/bayesian.lua | 3 | 1977 | get_table_from_dotted_string("bayesian", true)
-- modifies model weights to be the MAP model for a given eval function
function bayesian.get_MAP_weights(eval, samples)
assert(samples, "Needs a table with samples as 2nd argument")
assert(#samples > 0, "samples table is empty")
local best,argbest = table.pack(eval(samples[1], 1)),samples[1]
for i=2,#samples do
local current = table.pack(eval(samples[i], i))
if current[1] < best[1] then
best,argbest = current,samples[i]
end
end
return argbest,table.unpack(best)
end
-- returns a model which forwards computation is a combination of N sampled
-- parameters
function bayesian.build_bayes_comb(t)
local params = get_table_fields(
{
forward = { mandatory = true, type_match = "function" },
shuffle = { isa_match = random, mandatory = false, default=nil },
samples = { type_match = "table", mandatory = true },
N = { type_match = "number", mandatory = true, default=100 },
}, t, true)
assert(#params.samples > 0, "samples table is empty")
return ann.components.wrapper{
state = {
N = params.N,
samples = params.samples,
rnd = params.shuffle,
forward = params.forward,
},
weights = params.samples[#params.samples],
forward = function(self,input)
local forward = self.state.forward
local N = self.state.N
local rnd = self.state.rnd
local samples = self.state.samples
local invN = 1/N
local which = rnd:choose(samples)
local out = forward(which, input)
assert(class.is_a(out, matrix), "The forward function must return a matrix")
local output = out:clone():scal(invN)
for i=2,N do
local which = rnd:choose(samples)
local out = forward(which, input)
output:axpy(invN, out)
end
return output
end,
}
end
------------------------------------------------------------------------------
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/mobskills/Glacier_Splitter.lua | 33 | 1074 | ---------------------------------------------
-- Glacier Splitter
--
-- Description: Cleaves into targets in a fan-shaped area. Additional effect: Paralyze
-- Type: Physical
-- Utsusemi/Blink absorb: 1-3 shadows
-- Range: Unknown cone
-- Notes: Only used the Aern wielding a sword (RDM, DRK, and PLD).
---------------------------------------------
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 = math.random(1,3);
local accmod = 1;
local dmgmod = 1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local typeEffect = EFFECT_PARALYSIS;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 15, 0, 120);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Apollyon/npcs/Armoury_Crate.lua | 14 | 4349 | -----------------------------------
-- Area: Apollyon
-- NPC: Armoury Crate
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Apollyon/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CofferID = npc:getID();
local CofferType=0;
local lootID=0;
local InstanceRegion=0;
local addtime=0;
local DespawnOtherCoffer=false;
local MimicID=0;
for coffer = 1,table.getn (ARMOURY_CRATES_LIST_APPOLLYON),2 do
if (ARMOURY_CRATES_LIST_APPOLLYON[coffer]== CofferID-16932864) then
CofferType=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][1];
InstanceRegion=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][2];
addtime=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][3];
DespawnOtherCoffer=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][4];
MimicID=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][5];
lootID=ARMOURY_CRATES_LIST_APPOLLYON[coffer+1][6];
end
end
-- printf("CofferID : %u",CofferID-16932864);
-- printf("Coffertype %u",CofferType);
-- printf("InstanceRegion: %u",InstanceRegion);
-- printf("addtime: %u",addtime);
-- printf("MimicID: %u",MimicID);
-- printf("lootID: %u",lootID);
if (CofferType == cTIME) then
player:addTimeToSpecialBattlefield(InstanceRegion,addtime);
elseif (CofferType == cITEM) then
player:BCNMSetLoot(lootID,InstanceRegion,CofferID);
player:getBCNMloot();
elseif (CofferType == cRESTORE) then
player:RestoreAndHealOnBattlefield(InstanceRegion);
elseif (CofferType == cMIMIC) then
if (CofferID==16932864+210) then
GetNPCByID(16932864+195):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetNPCByID(16932864+195):setStatus(STATUS_NORMAL);
elseif (CofferID==16932864+211) then
GetMobByID(16932896):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932896):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932896):updateClaim(player);
elseif (CofferID==16932864+212) then
GetNPCByID(16932864+196):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetNPCByID(16932864+196):setStatus(STATUS_NORMAL);
elseif (CofferID==16932864+213) then
GetMobByID(16932897):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932897):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932897):updateClaim(player);
elseif (CofferID==16932864+214) then
GetNPCByID(16932864+197):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetNPCByID(16932864+197):setStatus(STATUS_NORMAL);
elseif (CofferID==16932864+215) then
GetMobByID(16932898):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932898):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932898):updateClaim(player);
elseif (CofferID==16932864+216) then
GetMobByID(16932899):setPos(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932899):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos());
GetMobByID(16932899):updateClaim(player);
end
end
if (DespawnOtherCoffer==true) then
HideArmouryCrates(InstanceRegion,APPOLLYON_SE_NE);
end
npc:setStatus(STATUS_DISAPPEAR);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
april-org/april-ann | packages/basics/ee5_base64/package.lua | 2 | 1309 | package{ name = "ee5_base64",
version = "1.0",
depends = { "aprilio" },
keywords = { "base64" },
description = "base64 encoder/decoder",
-- targets como en ant
target{
name = "init",
mkdir{ dir = "build" },
mkdir{ dir = "include" },
},
target{ name = "clean",
delete{ dir = "build" },
delete{ dir = "include" },
},
-- target{
-- name = "test",
-- lua_unit_test{
-- file={
-- "test/test_april_io.lua",
-- },
-- },
-- c_unit_test{
-- file = { "test/test_april_io.cc" },
-- },
-- },
target{
name = "provide",
depends = "init",
-- copy{ file= "c_src/*.h", dest_dir = "include" },
-- provide_bind{ file = "binding/bind_april_io.lua.cc", dest_dir = "include" }
},
target{
name = "build",
depends = "provide",
use_timestamp = true,
-- object{
-- file = "c_src/*.cc",
-- include_dirs = "${include_dirs}",
-- dest_dir = "build",
-- },
luac{
orig_dir = "lua_src",
dest_dir = "build",
},
-- build_bind{
-- file = "binding/bind_april_io.lua.cc",
-- dest_dir = "build",
-- }
},
target{
name = "document",
document_src{
},
document_bind{
},
},
}
| gpl-3.0 |
gulafaran/awesome | src/lib/vicious/widgets/uptime.lua | 15 | 1191 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
-- * (c) 2009, Lucas de Vries <lucas@glacicle.com>
---------------------------------------------------
-- {{{ Grab environment
local setmetatable = setmetatable
local math = { floor = math.floor }
local string = { match = string.match }
local helpers = require("vicious.helpers")
-- }}}
-- Uptime: provides system uptime and load information
-- vicious.widgets.uptime
local uptime = {}
-- {{{ Uptime widget type
local function worker(format)
local proc = helpers.pathtotable("/proc")
-- Get system uptime
local up_t = math.floor(string.match(proc.uptime, "[%d]+"))
local up_d = math.floor(up_t / (3600 * 24))
local up_h = math.floor((up_t % (3600 * 24)) / 3600)
local up_m = math.floor(((up_t % (3600 * 24)) % 3600) / 60)
local l1, l5, l15 = -- Get load averages for past 1, 5 and 15 minutes
string.match(proc.loadavg, "([%d%.]+)[%s]([%d%.]+)[%s]([%d%.]+)")
return {up_d, up_h, up_m, l1, l5, l15}
end
-- }}}
return setmetatable(uptime, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
AmirPGA/AmirPGA | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
justincormack/snabbswitch | src/lib/protocol/ipv4.lua | 7 | 5967 | module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
local header = require("lib.protocol.header")
local ipsum = require("lib.checksum").ipsum
local htons, ntohs, htonl, ntohl =
lib.htons, lib.ntohs, lib.htonl, lib.ntohl
-- TODO: generalize
local AF_INET = 2
local INET_ADDRSTRLEN = 16
local ipv4hdr_pseudo_t = ffi.typeof[[
struct {
uint8_t src_ip[4];
uint8_t dst_ip[4];
uint8_t ulp_zero;
uint8_t ulp_protocol;
uint16_t ulp_length;
} __attribute__((packed))
]]
local ipv4_addr_t = ffi.typeof("uint8_t[4]")
local ipv4_addr_t_size = ffi.sizeof(ipv4_addr_t)
local ipv4 = subClass(header)
-- Class variables
ipv4._name = "ipv4"
ipv4._ulp = {
class_map = {
[6] = "lib.protocol.tcp",
[17] = "lib.protocol.udp",
[47] = "lib.protocol.gre",
[58] = "lib.protocol.icmp.header",
},
method = 'protocol' }
ipv4:init(
{
[1] = ffi.typeof[[
struct {
uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2)
uint16_t total_length;
uint16_t id;
uint16_t frag_off; // flags:3, fragmen_offset:13
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint8_t src_ip[4];
uint8_t dst_ip[4];
} __attribute__((packed))
]],
})
-- Class methods
function ipv4:new (config)
local o = ipv4:superClass().new(self)
o:header().ihl_v_tos = htons(0x4000) -- v4
o:ihl(o:sizeof() / 4)
o:dscp(config.dscp or 0)
o:ecn(config.ecn or 0)
o:total_length(o:sizeof()) -- default to header only
o:id(config.id or 0)
o:flags(config.flags or 0)
o:frag_off(config.frag_off or 0)
o:ttl(config.ttl or 0)
o:protocol(config.protocol or 0xff)
o:src(config.src)
o:dst(config.dst)
o:checksum()
return o
end
function ipv4:pton (p)
local in_addr = ffi.new("uint8_t[4]")
local result = C.inet_pton(AF_INET, p, in_addr)
if result ~= 1 then
return false, "malformed IPv4 address: " .. address
end
return in_addr
end
function ipv4:ntop (n)
local p = ffi.new("char[?]", INET_ADDRSTRLEN)
local c_str = C.inet_ntop(AF_INET, n, p, INET_ADDRSTRLEN)
return ffi.string(c_str)
end
-- Instance methods
function ipv4:version (v)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 0, 4, v)
end
function ipv4:ihl (ihl)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 4, 4, ihl)
end
function ipv4:dscp (dscp)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 8, 6, dscp)
end
function ipv4:ecn (ecn)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 14, 2, ecn)
end
function ipv4:total_length (length)
if length ~= nil then
self:header().total_length = htons(length)
else
return(ntohs(self:header().total_length))
end
end
function ipv4:id (id)
if id ~= nil then
self:header().id = htons(id)
else
return(ntohs(self:header().id))
end
end
function ipv4:flags (flags)
return lib.bitfield(16, self:header(), 'frag_off', 0, 3, flags)
end
function ipv4:frag_off (frag_off)
return lib.bitfield(16, self:header(), 'frag_off', 3, 13, frag_off)
end
function ipv4:ttl (ttl)
if ttl ~= nil then
self:header().ttl = ttl
else
return self:header().ttl
end
end
function ipv4:protocol (protocol)
if protocol ~= nil then
self:header().protocol = protocol
else
return self:header().protocol
end
end
function ipv4:checksum ()
self:header().checksum = htons(ipsum(ffi.cast("uint8_t *", self:header()),
self:sizeof(), 0))
return ntohs(self:header().checksum)
end
function ipv4:src (ip)
if ip ~= nil then
ffi.copy(self:header().src_ip, ip, ipv4_addr_t_size)
else
return self:header().src_ip
end
end
function ipv4:src_eq (ip)
return C.memcmp(ip, self:header().src_ip, ipv4_addr_t_size) == 0
end
function ipv4:dst (ip)
if ip ~= nil then
ffi.copy(self:header().dst_ip, ip, ipv4_addr_t_size)
else
return self:header().dst_ip
end
end
function ipv4:dst_eq (ip)
return C.memcmp(ip, self:header().dst_ip, ipv4_addr_t_size) == 0
end
-- override the default equality method
function ipv4:eq (other)
--compare significant fields
return (self:ihl() == other:ihl()) and
(self:id() == other:id()) and
(self:protocol() == other:protocol()) and
self:src_eq(other:src()) and self:dst_eq(other:dst())
end
-- Return a pseudo header for checksum calculation in a upper-layer
-- protocol (e.g. icmp). Note that the payload length and next-header
-- values in the pseudo-header refer to the effective upper-layer
-- protocol. They differ from the respective values of the ipv6
-- header if extension headers are present.
function ipv4:pseudo_header (ulplen, proto)
local ph = ipv4hdr_pseudo_t()
local h = self:header()
ffi.copy(ph, h.src_ip, 2*ipv4_addr_t_size) -- Copy source and destination
ph.ulp_length = htons(ulplen)
ph.ulp_protocol = proto
return(ph)
end
local function test_ipv4_checksum ()
local IP_BASE = 14
local IP_HDR_SIZE = 20
local p = packet.from_string(lib.hexundump([[
52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00
00 34 59 1a 40 00 40 06 00 00 c0 a8 14 a9 6b 15
f0 b4 de 0b 01 bb e7 db 57 bc 91 cd 18 32 80 10
05 9f 00 00 00 00 01 01 08 0a 06 0c 5c bd fa 4a
e1 65
]], 66))
local ip_hdr = ipv4:new_from_mem(p.data + IP_BASE, IP_HDR_SIZE)
local csum = ip_hdr:checksum()
assert(csum == 0xb08e, "Wrong IPv4 checksum")
end
function selftest()
local ipv4_address = "192.168.1.1"
assert(ipv4_address == ipv4:ntop(ipv4:pton(ipv4_address)),
'ipv4 text to binary conversion failed.')
test_ipv4_checksum()
local ipv4hdr = ipv4:new({})
assert(C.ntohs(ipv4hdr:header().ihl_v_tos) == 0x4500,
'ipv4 header field ihl_v_tos not initialized correctly.')
end
ipv4.selftest = selftest
return ipv4
| apache-2.0 |
mrTag/GreatGreenArkleseizure | gga.lua | 1 | 3886 | solution "gga"
configurations {"Release", "Debug" }
location (_OPTIONS["to"])
-------------------------------------
-- glfw static lib
-------------------------------------
project "glfw_proj"
language "C"
kind "StaticLib"
defines {
"_CRT_SECURE_NO_WARNINGS"
}
includedirs {
"./3rdParty/glfw/include"
}
files {
"./3rdParty/glfw/src/internal.h",
"./3rdParty/glfw/src/glfw_config.h",
"./3rdParty/glfw/include/GLFW/glfw3.h",
"./3rdParty/glfw/include/GLFW/glfw3native.h",
"./3rdParty/glfw/src/context.c",
"./3rdParty/glfw/src/init.c",
"./3rdParty/glfw/src/input.c",
"./3rdParty/glfw/src/monitor.c",
"./3rdParty/glfw/src/window.c"
}
configuration "windows"
defines {
"_GLFW_WIN32"
}
files {
"./3rdParty/glfw/src/vulkan.c",
"./3rdParty/glfw/src/win32_platform.h",
"./3rdParty/glfw/src/win32_joystick.h",
"./3rdParty/glfw/src/wgl_context.h",
"./3rdParty/glfw/src/egl_context.c",
"./3rdParty/glfw/src/win32_init.c",
"./3rdParty/glfw/src/win32_joystick.c",
"./3rdParty/glfw/src/win32_monitor.c",
"./3rdParty/glfw/src/win32_time.c",
"./3rdParty/glfw/src/win32_tls.c",
"./3rdParty/glfw/src/win32_window.c",
"./3rdParty/glfw/src/wgl_context.c",
"./3rdParty/glfw/src/egl_context.c"
}
targetdir "./lib"
configuration { "windows", "gmake" }
includedirs {
"./3rdParty/glfw/deps/mingw"
}
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
targetdir "./lib/debug"
targetname "glfwd"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
targetdir "./lib/release"
targetname "glfw"
-------------------------------------
-- glew static lib
-------------------------------------
project "glew_proj"
language "C"
kind "StaticLib"
includedirs {
"./3rdParty/glew/include"
}
files {
"./3rdParty/glew/src/**.h",
"./3rdParty/glew/src/**.c",
"./3rdParty/glew/include/GL/**.h"
}
configuration "windows"
defines {
"WIN32",
"_LIB",
"WIN32_LEAN_AND_MEAN",
"GLEW_STATIC",
"GLEW_BUILD",
"_CRT_SECURE_NO_WARNINGS"
}
targetdir "./lib"
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
targetdir "./lib/debug"
targetname "glewd"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
targetdir "./lib/release"
targetname "glew"
-------------------------------------
-- top level gga project
-------------------------------------
project "gga"
targetname "gga"
language "C++"
kind "ConsoleApp"
flags {
"No64BitChecks",
"StaticRuntime"
}
includedirs {
"./lib",
"./3rdParty/glew/include",
"./3rdParty/glfw/include/"
}
libdirs {
"./lib"
}
links {
"glfw_proj",
"glew_proj"
}
files {
"./src/**.h",
"./src/**.cpp"
}
defines {
"GLEW_STATIC"
}
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
libdirs { "./lib/debug" }
links { "msvcrtd", "gdi32", "opengl32", "glewd", "glfwd" }
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
libdirs { "./lib/release" }
links { "msvcrt", "gdi32", "opengl32", "glew", "glfw" }
configuration "windows"
defines { "_WIN32" }
targetdir "./bin/windows"
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
| mit |
Kosmos82/kosmosdarkstar | scripts/zones/Beaucedine_Glacier/npcs/Rattling_Rain_IM.lua | 13 | 3344 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Rattling Rain, I.M.
-- Type: Border Conquest Guards
-- @pos -227.956 -81.475 260.442 111
-----------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Beaucedine_Glacier/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = FAUREGANDI;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
streetturtle/AwesomeWM | cpu-widget/cpu-widget.lua | 1 | 2180 | -------------------------------------------------
-- CPU Widget for Awesome Window Manager
-- Shows the current CPU utilization
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/cpu-widget
-- @author Pavel Makhov
-- @copyright 2019 Pavel Makhov
-------------------------------------------------
local watch = require("awful.widget.watch")
local wibox = require("wibox")
local beautiful = require("beautiful")
local widget = {}
local function worker(args)
local args = args or {}
local width = args.width or 50
local step_width = args.step_width or 2
local step_spacing = args.step_spacing or 1
local color= args.color or beautiful.fg_normal
local cpugraph_widget = wibox.widget {
max_value = 100,
background_color = "#00000000",
forced_width = width,
step_width = step_width,
step_spacing = step_spacing,
widget = wibox.widget.graph,
color = "linear:0,0:0,20:0,#FF0000:0.3,#FFFF00:0.6," .. color
}
--- By default graph widget goes from left to right, so we mirror it and push up a bit
local cpu_widget = wibox.container.margin(wibox.container.mirror(cpugraph_widget, { horizontal = true }), 0, 0, 0, 2)
local total_prev = 0
local idle_prev = 0
watch([[bash -c "cat /proc/stat | grep '^cpu '"]], 1,
function(widget, stdout)
local user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice =
stdout:match('(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s')
local total = user + nice + system + idle + iowait + irq + softirq + steal
local diff_idle = idle - idle_prev
local diff_total = total - total_prev
local diff_usage = (1000 * (diff_total - diff_idle) / diff_total + 5) / 10
widget:add_value(diff_usage)
total_prev = total
idle_prev = idle
end,
cpugraph_widget
)
return cpu_widget
end
return setmetatable(widget, { __call = function(_, ...)
return worker(...)
end })
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.