commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
---|---|---|---|---|---|---|---|---|---|
909ae73147b9caf3027e217d3f98184ea6cc9de9
|
otouto/plugins/service_leave_group.lua
|
otouto/plugins/service_leave_group.lua
|
local leave_group = {}
leave_group.triggers = {
'^//tgservice group_chat_created$',
'^//tgservice supergroup_chat_created$'
}
local report_to_admin = true -- set to false to not be notified, when Bot leaves groups without you
function leave_group:check_for_admin(msg, config)
local result = bindings.request('getChatMember', {
chat_id = msg.chat.id,
user_id = config.admin
} )
if not result.ok then
print('Konnte nicht prüfen, ob Admin in Gruppe ist! Verlasse sie sicherheitshalber...')
return false
end
if result.result.status ~= "member" and result.result.status ~= "administrator" and result.result.status ~= "creator" then
return false
else
return true
end
end
function leave_group:action(msg, config)
if not is_service_msg(msg) then return end -- Bad attempt at trolling!
local admin_in_group = leave_group:check_for_admin(msg, config)
if not admin_in_group then
print('Admin ist nicht in der Gruppe, verlasse sie deshalb...')
utilities.send_reply(msg, 'Dieser Bot wurde in eine fremde Gruppe hinzugefügt. Dies wird gemeldet!\nThis bot was added to foreign group. This incident will be reported!')
local result = bindings.request('leaveChat', {
chat_id = msg.chat.id
} )
local chat_name = msg.chat.title
local chat_id = msg.chat.id
local from = msg.from.name
local from_id = msg.from.id
if report_to_admin then
utilities.send_message(config.admin, '#WARNUNG: Bot wurde in fremde Gruppe hinzugefügt:\nGruppenname: '..chat_name..' ('..chat_id..')\nHinzugefügt von: '..from..' ('..from_id..')')
end
end
end
return leave_group
|
local leave_group = {}
leave_group.triggers = {
'^//tgservice group_chat_created$',
'^//tgservice supergroup_chat_created$',
'^//tgservice new_chat_member$',
'^//tgservice (left_chat_member)$'
}
local report_to_admin = true -- set to false to not be notified, when Bot leaves groups without you
function leave_group:check_for_admin(msg, config)
local result = bindings.request('getChatMember', {
chat_id = msg.chat.id,
user_id = config.admin
} )
if not result.ok then
print('Konnte nicht prüfen, ob Admin in Gruppe ist! Verlasse sie sicherheitshalber...')
return false
end
if result.result.status ~= "member" and result.result.status ~= "administrator" and result.result.status ~= "creator" then
return false
else
return true
end
end
function leave_group:action(msg, config, matches)
if not is_service_msg(msg) then return end -- Bad attempt at trolling!
if matches[1] == 'left_chat_member' then
if msg.left_chat_member.id == config.admin then
admin_in_group = false
else
admin_in_group = leave_group:check_for_admin(msg, config)
end
else
admin_in_group = leave_group:check_for_admin(msg, config)
end
if not admin_in_group then
print('Admin ist nicht in der Gruppe, verlasse sie deshalb...')
utilities.send_reply(msg, 'Dieser Bot wurde in eine fremde Gruppe hinzugefügt. Dies wird gemeldet!\nThis bot was added to foreign group. This incident will be reported!')
local result = bindings.request('leaveChat', {
chat_id = msg.chat.id
} )
local chat_name = msg.chat.title
local chat_id = msg.chat.id
local from = msg.from.name
local from_id = msg.from.id
if report_to_admin then
utilities.send_message(config.admin, '#WARNUNG: Bot wurde in fremde Gruppe hinzugefügt:\nGruppenname: '..chat_name..' ('..chat_id..')\nHinzugefügt von: '..from..' ('..from_id..')')
end
end
end
return leave_group
|
Fixe service_leave_group
|
Fixe service_leave_group
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
1d39403cd0ea5debb605e9f48c7092e64a28b483
|
Quadtastic/Dialog.lua
|
Quadtastic/Dialog.lua
|
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local State = require(current_folder .. ".State")
local InputField = require(current_folder .. ".Inputfield")
local Layout = require(current_folder .. ".Layout")
local Button = require(current_folder .. ".Button")
local Label = require(current_folder .. ".Label")
local Window = require(current_folder .. ".Window")
local imgui = require(current_folder .. ".imgui")
local Dialog = {}
local function show_buttons(state, gui_state, buttons)
do Layout.start(gui_state)
for key,button in pairs(buttons) do
local button_pressed = Button.draw(gui_state, nil, nil, nil, nil, string.upper(button))
local key_pressed = type(key) == "string" and
(imgui.was_key_pressed(gui_state, key) or
-- Special case since "return" is a reserved keyword
key == "enter" and imgui.was_key_pressed(gui_state, "return"))
if button_pressed or key_pressed then
state.respond(button)
end
Layout.next(gui_state, "-")
end
end Layout.finish(gui_state, "-")
end
function Dialog.show_dialog(message, buttons)
-- Draw the dialog
local function draw(app, data, gui_state, w, h)
local min_w = data.min_w or 0
local min_h = data.min_h or 0
local x = data.win_x or (w - min_w) / 2
local y = data.win_y or (h - min_h) / 2
local dx, dy
do Window.start(gui_state, x, y, min_w, min_h)
do Layout.start(gui_state)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
Label.draw(gui_state, nil, nil,
w/2, nil,
data.message)
Layout.next(gui_state, "|")
imgui.pop_style(gui_state, "font")
show_buttons(app.dialog, gui_state, data.buttons)
Layout.next(gui_state, "|")
end Layout.finish(gui_state, "|")
end data.min_w, data.min_h, dx, dy, data.dragging = Window.finish(
gui_state, x, y, data.dragging)
if dx then data.win_x = (data.win_x or x) + dx end
if dy then data.win_y = (data.win_y or y) + dy end
end
assert(coroutine.running(), "This function must be run in a coroutine.")
local transitions = {
-- luacheck: no unused args
respond = function(app, data, response)
return response
end,
}
local dialog_state = State("dialog", transitions,
{message = message, buttons = buttons or {enter = "OK"}})
-- Store the draw function in the state
dialog_state.draw = draw
return coroutine.yield(dialog_state)
end
function Dialog.query(message, input, buttons)
-- Draw the dialog
local function draw(app, data, gui_state, w, h)
local min_w = data.min_w or 0
local min_h = data.min_h or 0
local x = data.win_x or (w - min_w) / 2
local y = data.win_y or (h - min_h) / 2
local dx, dy
do Window.start(gui_state, x, y, min_w, min_h)
do Layout.start(gui_state)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
Label.draw(gui_state, nil, nil,
w/2, nil,
data.message)
Layout.next(gui_state, "|")
imgui.pop_style(gui_state, "font")
data.input = InputField.draw(gui_state, nil, nil,
w/2, nil, data.input,
{forced_keyboard_focus = true,
select_all = not data.was_drawn})
Layout.next(gui_state, "|")
show_buttons(app.query, gui_state, data.buttons)
Layout.next(gui_state, "|")
end Layout.finish(gui_state, "|")
end data.min_w, data.min_h, dx, dy, data.dragging = Window.finish(
gui_state, x, y, data.dragging)
if dx then data.win_x = (data.win_x or x) + dx end
if dy then data.win_y = (data.win_y or y) + dy end
data.was_drawn = true
end
assert(coroutine.running(), "This function must be run in a coroutine.")
local transitions = {
-- luacheck: no unused args
respond = function(app, data, response)
return response, data.input
end,
}
local query_state = State("query", transitions,
{input = input or "", message = message,
buttons = buttons or {escape = "Cancel", enter = "OK"},
was_drawn = false,
})
-- Store the draw function in the state
query_state.draw = draw
return coroutine.yield(query_state)
end
return Dialog
|
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local State = require(current_folder .. ".State")
local InputField = require(current_folder .. ".Inputfield")
local Layout = require(current_folder .. ".Layout")
local Button = require(current_folder .. ".Button")
local Label = require(current_folder .. ".Label")
local Window = require(current_folder .. ".Window")
local imgui = require(current_folder .. ".imgui")
local Dialog = {}
local function show_buttons(state, gui_state, buttons)
do Layout.start(gui_state)
for key,button in pairs(buttons) do
local button_pressed = Button.draw(gui_state, nil, nil, nil, nil, string.upper(button))
local key_pressed = type(key) == "string" and
(imgui.was_key_pressed(gui_state, key) or
-- Special case since "return" is a reserved keyword
key == "enter" and imgui.was_key_pressed(gui_state, "return"))
if button_pressed or key_pressed then
state.respond(button)
end
Layout.next(gui_state, "-")
end
end Layout.finish(gui_state, "-")
end
function Dialog.show_dialog(message, buttons)
-- Draw the dialog
local function draw(app, data, gui_state, w, h)
local min_w = data.min_w or 0
local min_h = data.min_h or 0
local x = data.win_x or (w - min_w) / 2
local y = data.win_y or (h - min_h) / 2
local dx, dy
do Window.start(gui_state, x, y, min_w, min_h)
do Layout.start(gui_state)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
Label.draw(gui_state, nil, nil,
w/2, nil,
data.message)
Layout.next(gui_state, "|")
imgui.pop_style(gui_state, "font")
show_buttons(app.dialog, gui_state, data.buttons)
Layout.next(gui_state, "|")
end Layout.finish(gui_state, "|")
end data.min_w, data.min_h, dx, dy, data.dragging = Window.finish(
gui_state, x, y, data.dragging)
if dx then data.win_x = (data.win_x or x) + dx end
if dy then data.win_y = (data.win_y or y) + dy end
end
assert(coroutine.running(), "This function must be run in a coroutine.")
local transitions = {
-- luacheck: no unused args
respond = function(app, data, response)
return response
end,
}
local dialog_state = State("dialog", transitions,
{message = message, buttons = buttons or {enter = "OK"}})
-- Store the draw function in the state
dialog_state.draw = draw
return coroutine.yield(dialog_state)
end
function Dialog.query(message, input, buttons)
-- Draw the dialog
local function draw(app, data, gui_state, w, h)
local min_w = data.min_w or 0
local min_h = data.min_h or 0
local x = data.win_x or (w - min_w) / 2
local y = data.win_y or (h - min_h) / 2
local dx, dy
do Window.start(gui_state, x, y, min_w, min_h)
do Layout.start(gui_state)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
Label.draw(gui_state, nil, nil,
w/2, nil,
data.message)
Layout.next(gui_state, "|")
imgui.pop_style(gui_state, "font")
local committed
data.input, committed = InputField.draw(gui_state, nil, nil,
w/2, nil, data.input,
{forced_keyboard_focus = true,
select_all = not data.was_drawn})
Layout.next(gui_state, "|")
show_buttons(app.query, gui_state, data.buttons)
Layout.next(gui_state, "|")
if committed then
app.query.respond("OK")
end
end Layout.finish(gui_state, "|")
end data.min_w, data.min_h, dx, dy, data.dragging = Window.finish(
gui_state, x, y, data.dragging)
if dx then data.win_x = (data.win_x or x) + dx end
if dy then data.win_y = (data.win_y or y) + dy end
data.was_drawn = true
end
assert(coroutine.running(), "This function must be run in a coroutine.")
local transitions = {
-- luacheck: no unused args
respond = function(app, data, response)
return response, data.input
end,
}
local query_state = State("query", transitions,
{input = input or "", message = message,
buttons = buttons or {escape = "Cancel", enter = "OK"},
was_drawn = false,
})
-- Store the draw function in the state
query_state.draw = draw
return coroutine.yield(query_state)
end
return Dialog
|
Fix query dialog not accepting input on Enter
|
Fix query dialog not accepting input on Enter
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
930f37b188420a1eb1ce3e3fc2215eaa914c464f
|
views/pull.lua
|
views/pull.lua
|
-- TODO: race conditions are possible
local WANTED_CHATS = {"CHANNEL", "CHANNEL_ACTIVE", "GROUP", "GUILD",
"PRIVATE", "PRINT", "SECTOR"}
local json = dofile("lib/json.lua")
local change = {}
-- Target change
local function target(event, data)
change["target"] = GetTargetInfo()
end
RegisterEvent(target, "TARGET_CHANGED")
-- Chat Messages
local function chat(event, data)
change["chat"] = change["chat"] or {}
local add = {
color="#"..chatinfo[event][1]:sub(2),
formatstring=chatinfo[event]["formatstring"],
}
for k, v in pairs(data) do
add[k] = v
end
if data["faction"] then
add["faction_color"] = "#"..rgbtohex(FactionColor_RGB[data["faction"]]):sub(2)
end
if data["location"] then
add["location"] = ShortLocationStr(data["location"])
end
table.insert(change["chat"], add)
end
for _, m in ipairs(WANTED_CHATS) do
RegisterEvent(chat, "CHAT_MSG_"..m)
end
local function serve(req)
local r = vohttp.response.Response:new()
r.headers["Content-Type"] = "application/json"
change["sector"] = {}
ForEachPlayer(function(pid)
table.insert(change["sector"],
{pid, GetPlayerName(pid), math.floor(GetPlayerDistance(pid) or 0),
math.floor(GetPlayerHealth(pid) or 100),
GetPlayerFaction(pid), GetPlayerFactionStanding(pid)}) end)
change["sector"] = {}
r.body = json.encode(change)
change = {}
return r
end
return serve
|
-- TODO: race conditions are possible
local WANTED_CHATS = {"CHANNEL", "CHANNEL_ACTIVE", "GROUP", "GUILD",
"PRIVATE", "PRINT", "SECTOR"}
local json = dofile("lib/json.lua")
local change = {}
-- Target change
local function target(event, data)
change["target"] = GetTargetInfo()
end
RegisterEvent(target, "TARGET_CHANGED")
-- Chat Messages
local function chat(event, data)
change["chat"] = change["chat"] or {}
local add = {
color="#"..chatinfo[event][1]:sub(2),
formatstring=chatinfo[event]["formatstring"],
}
for k, v in pairs(data) do
add[k] = v
end
if data["faction"] then
add["faction_color"] = "#"..rgbtohex(FactionColor_RGB[data["faction"]]):sub(2)
end
if data["location"] then
add["location"] = ShortLocationStr(data["location"])
end
if data["color"] then
add["color"] = data["color"]:sub(2)
end
table.insert(change["chat"], add)
end
for _, m in ipairs(WANTED_CHATS) do
RegisterEvent(chat, "CHAT_MSG_"..m)
end
local function serve(req)
local r = vohttp.response.Response:new()
r.headers["Content-Type"] = "application/json"
change["sector"] = {}
ForEachPlayer(function(pid)
table.insert(change["sector"],
{pid, GetPlayerName(pid), math.floor(GetPlayerDistance(pid) or 0),
math.floor(GetPlayerHealth(pid) or 100),
GetPlayerFaction(pid), GetPlayerFactionStanding(pid)}) end)
change["sector"] = {}
r.body = json.encode(change)
change = {}
return r
end
return serve
|
pull: fixed return color
|
pull: fixed return color
|
Lua
|
mit
|
fhirschmann/vocontrol
|
bde4cfa36b5f9e0c1e3a9891c96e4ee21ee7eace
|
mod_pastebin/mod_pastebin.lua
|
mod_pastebin/mod_pastebin.lua
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.load()
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
efb763c6c578c06538a86b9a6383b8679db56d31
|
third_party/vulkan/loader/premake5.lua
|
third_party/vulkan/loader/premake5.lua
|
group("third_party")
project("vulkan-loader")
uuid("07d77359-1618-43e6-8a4a-0ee9ddc5fa6a")
kind("StaticLib")
language("C++")
defines({
"_LIB",
"API_NAME=\"vulkan\"",
})
removedefines({
"_UNICODE",
"UNICODE",
})
includedirs({
".",
})
recursive_platform_files()
filter("platforms:Windows")
warnings("Off") -- Too many warnings.
characterset("MBCS")
defines({
"VK_USE_PLATFORM_WIN32_KHR",
})
|
group("third_party")
project("vulkan-loader")
uuid("07d77359-1618-43e6-8a4a-0ee9ddc5fa6a")
kind("StaticLib")
language("C")
defines({
"_LIB",
"API_NAME=\"vulkan\"",
})
removedefines({
"_UNICODE",
"UNICODE",
})
includedirs({
".",
})
recursive_platform_files()
filter("platforms:Windows")
warnings("Off") -- Too many warnings.
characterset("MBCS")
defines({
"VK_USE_PLATFORM_WIN32_KHR",
})
filter("platforms:not Windows")
removefiles("dirent_on_windows.c")
filter("platforms:Linux")
defines({
[[SYSCONFDIR="\"/etc\""]],
[[DATADIR="\"/usr/share\""]],
})
|
third_party: vulkan: loader: fix Linux build
|
third_party: vulkan: loader: fix Linux build
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,maxton/xenia,maxton/xenia,maxton/xenia,sephiroth99/xenia,sephiroth99/xenia
|
3600b6826c2884f2f482a1aa21bec2d30405cbc8
|
nyagos.d/open.lua
|
nyagos.d/open.lua
|
nyagos.alias("open",function(args)
local count=0
for i=1,#args do
local list=nyagos.glob(args[i])
if list and #list >= 1 then
for i=1,#list do
assert(nyagos.shellexecute("open",list[i]))
end
else
if nyagos.access(args[i],0) then
assert(nyagos.shellexecute("open",args[i]))
else
print(args[i] .. ": can not get status")
end
end
count = count +1
end
if count <= 0 then
if nyagos.access(".\\open.cmd",0) then
nyagos.exec("open.cmd")
else
assert(nyagos.shellexecute("open","."))
end
end
end)
|
nyagos.alias("open",function(args)
local count=0
for i=1,#args do
local list=nyagos.glob(args[i])
if list and #list >= 1 then
for j=1,#list do
if nyagos.access(list[j],0) then
assert(nyagos.shellexecute("open",list[j]))
else
print(args[i] .. ": can not get status")
end
end
else
if nyagos.access(args[i],0) then
assert(nyagos.shellexecute("open",args[i]))
else
print(args[i] .. ": can not get status")
end
end
count = count +1
end
if count <= 0 then
if nyagos.access(".\\open.cmd",0) then
nyagos.exec("open.cmd")
else
assert(nyagos.shellexecute("open","."))
end
end
end)
|
Fixed(again) open.lua did not print error when wildcard did not match anyfiles."
|
Fixed(again) open.lua did not print error when wildcard did not match anyfiles."
|
Lua
|
bsd-3-clause
|
hattya/nyagos,hattya/nyagos,tsuyoshicho/nyagos,tyochiai/nyagos,zetamatta/nyagos,kissthink/nyagos,hattya/nyagos,kissthink/nyagos,kissthink/nyagos,nocd5/nyagos
|
0f8095f7a270d57ea2f6f0f3a811e6ff6afe1dfa
|
water.lua
|
water.lua
|
--[[
This file is part of ClearTables
@author Paul Norman <[email protected]>
@copyright 2015 Paul Norman, MIT license
]]--
require "common"
function accept_water_area (tags)
return tags["natural"] == "water" or tags["waterway"] == "riverbank" or tags["landuse"] == "reservoir"
end
function transform_water_area (tags)
local cols = {}
cols.water = tags["water"] or (tags["waterway"] == "riverbank" and "river") or (tags["landuse"] == "reservoir" and "reservoir") or nil
cols.name = tags["name"]
return cols
end
function accept_waterway (tags)
return tags["waterway"] == "stream" or tags["waterway"] == "river" or tags["waterway"] == "ditch"
or tags["waterway"] == "canal" or tags["waterway"] == "drain"
end
function transform_waterway (tags)
local cols = {}
cols.name = tags["name"]
cols.waterway = tags["waterway"]
cols.bridge = yesno(tags["bridge"])
cols.tunnel = yesno(tags["tunnel"])
return cols
end
function water_area_ways (tags, num_keys)
return generic_polygon_way(tags, accept_water_area, transform_water_area)
end
function water_area_rels (tags, num_keys)
if (tags["type"] == "multipolygon" and accept_water_area(tags)) then
return 0, tags
end
return 1, {}
end
function water_area_rel_members (tags, member_tags, member_roles, membercount)
return generic_multipolygon_members(tags, member_tags, membercount, accept_water_area, transform_water_area)
end
function waterway_ways (tags, num_keys)
return generic_line_way(tags, accept_waterway, transform_waterway)
end
|
--[[
This file is part of ClearTables
@author Paul Norman <[email protected]>
@copyright 2015 Paul Norman, MIT license
]]--
require "common"
function accept_water_area (tags)
return tags["natural"] == "water" or tags["waterway"] == "riverbank" or tags["landuse"] == "reservoir"
end
function transform_water_area (tags)
local cols = {}
cols.water = tags["water"] or (tags["waterway"] == "riverbank" and "river") or (tags["landuse"] == "reservoir" and "reservoir") or nil
cols.name = tags["name"]
return cols
end
function accept_waterway (tags)
return tags["waterway"] == "stream" or tags["waterway"] == "river" or tags["waterway"] == "ditch"
or tags["waterway"] == "canal" or tags["waterway"] == "drain"
end
function transform_waterway (tags)
local cols = {}
cols.name = tags["name"]
cols.waterway = tags["waterway"]
cols.bridge = yesno(tags["bridge"])
cols.tunnel = yesno(tags["tunnel"])
cols.layer = layer(tags["layer"])
return cols
end
function water_area_ways (tags, num_keys)
return generic_polygon_way(tags, accept_water_area, transform_water_area)
end
function water_area_rels (tags, num_keys)
if (tags["type"] == "multipolygon" and accept_water_area(tags)) then
return 0, tags
end
return 1, {}
end
function water_area_rel_members (tags, member_tags, member_roles, membercount)
return generic_multipolygon_members(tags, member_tags, membercount, accept_water_area, transform_water_area)
end
function waterway_ways (tags, num_keys)
return generic_line_way(tags, accept_waterway, transform_waterway)
end
|
Handle waterway layer
|
Handle waterway layer
Fixes #3
|
Lua
|
mit
|
pnorman/ClearTables,ClearTables/ClearTables
|
3410887d02d7e947ddfc0debc05caae19504100a
|
spec/unit/pic_spec.lua
|
spec/unit/pic_spec.lua
|
local DrawContext = require("ffi/drawcontext")
local BB = require("ffi/blitbuffer")
local Pic = require("ffi/pic")
local SAMPLE_JPG = "spec/base/unit/data/sample.jpg"
describe("Pic module", function()
describe("basic API", function()
it("should return error on unkonw format", function()
assert.has_error(function()
Pic.openDocument("/mnt/yolo.jpgwtffmt")
end, "Unsupported image format")
end)
end)
describe("JPG support", function()
local d
setup(function()
d = Pic.openDocument(SAMPLE_JPG)
end)
it("should load jpg file", function()
assert.are_not.equal(d, nil)
end)
it("should be able to get image size", function()
local page = d:openPage()
local dc_null = DrawContext.new()
assert.are.same({d:getOriginalPageSize()}, {313, 234, 3})
assert.are_not.equal(page, nil)
assert.are.same({page:getSize(dc_null)}, {313, 234})
page:close()
end)
it("should return emtpy table of content", function()
assert.are.same(d:getToc(), {})
end)
it("should return 1 as number of pages", function()
assert.are.same(d:getPages(), 1)
end)
it("should return 0 as cache size", function()
assert.are.same(d:getCacheSize(), 0)
end)
it("should render JPG as inverted BB properly", function()
local page = d:openPage()
local dc_null = DrawContext.new()
local tmp_bb = BB.new(d.width, d.height, BB.TYPE_BBRGB24)
--@TODO check against digest 15.06 2014 (houqp)
page:draw(dc_null, tmp_bb)
tmp_bb:invert()
local c = tmp_bb:getPixel(0, 0)
assert.are.same(c.r, 78)
assert.are.same(c.g, 91)
assert.are.same(c.b, 61)
c = tmp_bb:getPixel(1, 0)
assert.are.same(c.r, 76)
assert.are.same(c.g, 89)
assert.are.same(c.b, 59)
c = tmp_bb:getPixel(2, 0)
assert.are.same(c.r, 72)
assert.are.same(c.g, 85)
assert.are.same(c.b, 55)
page:close()
end)
teardown(function()
d:close()
end)
end)
end)
|
local DrawContext = require("ffi/drawcontext")
local BB = require("ffi/blitbuffer")
local Pic = require("ffi/pic")
Pic.color = true
local SAMPLE_JPG = "spec/base/unit/data/sample.jpg"
describe("Pic module", function()
describe("basic API", function()
it("should return error on unkonw format", function()
assert.has_error(function()
Pic.openDocument("/mnt/yolo.jpgwtffmt")
end, "Unsupported image format")
end)
end)
describe("JPG support", function()
local d
setup(function()
d = Pic.openDocument(SAMPLE_JPG)
end)
it("should load jpg file", function()
assert.are_not.equal(d, nil)
end)
it("should be able to get image size", function()
local page = d:openPage()
local dc_null = DrawContext.new()
assert.are.same({d:getOriginalPageSize()}, {313, 234, 3})
assert.are_not.equal(page, nil)
assert.are.same({page:getSize(dc_null)}, {313, 234})
page:close()
end)
it("should return emtpy table of content", function()
assert.are.same(d:getToc(), {})
end)
it("should return 1 as number of pages", function()
assert.are.same(d:getPages(), 1)
end)
it("should return 0 as cache size", function()
assert.are.same(d:getCacheSize(), 0)
end)
it("should render JPG as inverted BB properly", function()
local page = d:openPage()
local dc_null = DrawContext.new()
local tmp_bb = BB.new(d.width, d.height, BB.TYPE_BBRGB24)
--@TODO check against digest 15.06 2014 (houqp)
page:draw(dc_null, tmp_bb)
tmp_bb:invert()
tmp_bb:writePAM("/home/vagrant/koreader/out.pam")
local c = tmp_bb:getPixel(0, 0)
assert.are.same(c.r, 0xB1)
assert.are.same(c.g, 0xA4)
assert.are.same(c.b, 0xC2)
c = tmp_bb:getPixel(1, 0)
assert.are.same(c.r, 0xB3)
assert.are.same(c.g, 0xA6)
assert.are.same(c.b, 0xC4)
c = tmp_bb:getPixel(2, 0)
assert.are.same(c.r, 0xB7)
assert.are.same(c.g, 0xAA)
assert.are.same(c.b, 0xC8)
page:close()
end)
teardown(function()
d:close()
end)
end)
end)
|
fix pic.lua test spec
|
fix pic.lua test spec
Since working on pic.lua, tests were broken.
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader-base,frankyifei/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,koreader/koreader-base,frankyifei/koreader-base,houqp/koreader-base,Frenzie/koreader-base
|
d0c3740395b38aa85f7a3483362fcae016e6a4b4
|
tests/test-leaks.lua
|
tests/test-leaks.lua
|
return require('lib/tap')(function (test)
local function bench(uv, p, count, fn)
collectgarbage()
local before
local notify = count / 8
for i = 1, count do
fn()
if i % notify == 0 then
uv.run()
collectgarbage()
local now = uv.resident_set_memory()
if not before then before = now end
p(i, now)
end
end
uv.run()
collectgarbage()
local after = uv.resident_set_memory()
p{
before = before,
after = after,
}
assert(after < before * 1.5)
end
test("lots-o-timers", function (print, p, expect, uv)
bench(uv, p, 0x10000, function ()
local timer = uv.new_timer()
uv.close(timer)
end)
end)
test("lots-o-timers with canceled callbacks", function (print, p, expect, uv)
bench(uv, p, 0x10000, function ()
local timer = uv.new_timer()
uv.timer_start(timer, 100, 100, function ()
end)
uv.timer_stop(timer)
uv.close(timer, function ()
end)
uv.run()
end)
end)
test("lots-o-timers with real timeouts", function (print, p, expect, uv)
bench(uv, p, 0x500, function ()
local timer = uv.new_timer()
uv.timer_start(timer, 10, 0, expect(function ()
uv.timer_stop(timer)
uv.close(timer, function ()
end)
end))
end)
end)
test("reading file async", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x500, function ()
local onOpen, onStat, onRead, onClose
local fd, stat
onOpen = expect(function (err, result)
assert(not err, err)
fd = result
uv.fs_fstat(fd, onStat)
end)
onStat = expect(function (err, result)
assert(not err, err)
stat = result
uv.fs_read(fd, stat.size, 0, onRead)
end)
onRead = expect(function (err, data)
assert(not err, err)
assert(#data == stat.size)
uv.fs_close(fd, onClose)
end)
onClose = expect(function (err)
assert(not err, err)
end)
assert(uv.fs_open("README.md", "r", mode, onOpen))
end)
end)
test("reading file sync", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x2000, function ()
local fd = assert(uv.fs_open("README.md", "r", mode))
local stat = assert(uv.fs_fstat(fd))
local data = assert(uv.fs_read(fd, stat.size, 0))
assert(#data == stat.size)
assert(uv.fs_close(fd))
end)
end)
test("invalid file", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x1500, function ()
local req = uv.fs_open("BAD_FILE", "r", mode, expect(function (err, fd)
assert(not fd)
assert(err)
end))
end)
end)
test("invalid file sync", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x20000, function ()
local fd, err = uv.fs_open("BAD_FILE", "r", mode)
assert(not fd)
assert(err)
end)
end)
test("invalid spawn args", function (print, p, expect, uv)
-- Regression test for #73
bench(uv, p, 0x10000, function ()
local ret, err = pcall(function ()
return uv.spawn("ls", {
args = {"-l", "-h"},
stdio = {0, 1, 2},
env = {"EXTRA=true"},
gid = false, -- Should be integer
})
end)
assert(not ret)
assert(err)
end)
end)
test("pipe writing with vectors", function (print, p, expect, uv)
local port = 0
bench(uv, p, 0x800, function ()
local data = {}
for i = 0, 100 do
data[i + 1] = string.rep(string.char(i), 100)
end
local server = uv.new_tcp()
server:bind("::1", port)
server:listen(1, expect(function (err)
assert(not err, err)
local client = uv.new_pipe(false)
server:accept(client)
client:write(data)
client:close()
server:close()
end))
local address = server:getsockname()
port = address.port
local socket = uv.new_tcp()
socket:connect(address.ip, port, expect(function (err)
assert(not err, err)
socket:read_start(expect(function (err, chunk)
assert(not err, err)
assert(chunk)
socket:close()
end))
end))
uv.run()
end)
end)
end)
|
return require('lib/tap')(function (test)
local function bench(uv, p, count, fn)
collectgarbage()
local before
local notify = count / 8
for i = 1, count do
fn()
if i % notify == 0 then
uv.run()
collectgarbage()
local now = uv.resident_set_memory()
if not before then before = now end
p(i, now)
end
end
uv.run()
collectgarbage()
local after = uv.resident_set_memory()
p{
before = before,
after = after,
}
assert(after < before * 1.5)
end
test("lots-o-timers", function (print, p, expect, uv)
bench(uv, p, 0x10000, function ()
local timer = uv.new_timer()
uv.close(timer)
end)
end)
test("lots-o-timers with canceled callbacks", function (print, p, expect, uv)
bench(uv, p, 0x10000, function ()
local timer = uv.new_timer()
uv.timer_start(timer, 100, 100, function ()
end)
uv.timer_stop(timer)
uv.close(timer, function ()
end)
uv.run()
end)
end)
test("lots-o-timers with real timeouts", function (print, p, expect, uv)
bench(uv, p, 0x500, function ()
local timer = uv.new_timer()
uv.timer_start(timer, 10, 0, expect(function ()
uv.timer_stop(timer)
uv.close(timer, function ()
end)
end))
end)
end)
test("reading file async", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x500, function ()
local onOpen, onStat, onRead, onClose
local fd, stat
onOpen = expect(function (err, result)
assert(not err, err)
fd = result
uv.fs_fstat(fd, onStat)
end)
onStat = expect(function (err, result)
assert(not err, err)
stat = result
uv.fs_read(fd, stat.size, 0, onRead)
end)
onRead = expect(function (err, data)
assert(not err, err)
assert(#data == stat.size)
uv.fs_close(fd, onClose)
end)
onClose = expect(function (err)
assert(not err, err)
end)
assert(uv.fs_open("README.md", "r", mode, onOpen))
end)
end)
test("reading file sync", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x2000, function ()
local fd = assert(uv.fs_open("README.md", "r", mode))
local stat = assert(uv.fs_fstat(fd))
local data = assert(uv.fs_read(fd, stat.size, 0))
assert(#data == stat.size)
assert(uv.fs_close(fd))
end)
end)
test("invalid file", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x1500, function ()
local req = uv.fs_open("BAD_FILE", "r", mode, expect(function (err, fd)
assert(not fd)
assert(err)
end))
end)
end)
test("invalid file sync", function (print, p, expect, uv)
local mode = tonumber("644", 8)
bench(uv, p, 0x20000, function ()
local fd, err = uv.fs_open("BAD_FILE", "r", mode)
assert(not fd)
assert(err)
end)
end)
test("invalid spawn args", function (print, p, expect, uv)
-- Regression test for #73
bench(uv, p, 0x10000, function ()
local ret, err = pcall(function ()
return uv.spawn("ls", {
args = {"-l", "-h"},
stdio = {0, 1, 2},
env = {"EXTRA=true"},
gid = false, -- Should be integer
})
end)
assert(not ret)
assert(err)
end)
end)
test("stream writing with string and array", function (print, p, expect, uv)
local port = 0
local server = uv.new_tcp()
local data
local count = 0x800
server:unref()
server:bind("127.0.0.1", port)
server:listen(128, expect(function (err)
assert(not err, err)
local client = uv.new_tcp()
server:accept(client)
client:write(data)
client:read_start(expect(function (err, data)
assert(not err, err)
assert(data)
client:close()
end))
end, count))
local address = server:getsockname()
bench(uv, p, count, function ()
data = string.rep("Hello", 500)
local socket = uv.new_tcp()
socket:connect(address.ip, address.port, expect(function (err)
assert(not err, err)
socket:read_start(expect(function (err, chunk)
assert(not err, err)
assert(chunk)
local data = {}
for i = 0, 100 do
data[i + 1] = string.rep(string.char(i), 100)
end
socket:write(data)
socket:close()
end))
end))
uv.run()
end)
server:close()
end)
end)
|
Fix write test
|
Fix write test
|
Lua
|
apache-2.0
|
brimworks/luv,NanXiao/luv,daurnimator/luv,RomeroMalaquias/luv,kidaa/luv,NanXiao/luv,mkschreder/luv,daurnimator/luv,zhaozg/luv,xpol/luv,brimworks/luv,mkschreder/luv,RomeroMalaquias/luv,luvit/luv,luvit/luv,RomeroMalaquias/luv,joerg-krause/luv,joerg-krause/luv,xpol/luv,leecrest/luv,zhaozg/luv,kidaa/luv,DBarney/luv,DBarney/luv,leecrest/luv,daurnimator/luv
|
8be1c73eb3d54be42b50792be0b5d05221089b02
|
Modules/Utility/os.lua
|
Modules/Utility/os.lua
|
-- to use: local os = require(this_script)
-- Adds an os.date() function back to the Roblox os table!
-- @author Narrev
-- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3)
-- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600)
-- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour
local firstRequired = os.time()
return {
help = function(...) return
[[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding
os.date("*t") returns a table with the following indices:
hour 14
min 36
wday 1
year 2003
yday 124
month 5
sec 33
day 4
String reference:
%a abbreviated weekday name (e.g., Wed)
%A full weekday name (e.g., Wednesday)
%b abbreviated month name (e.g., Sep)
%B full month name (e.g., September)
%c date and time (e.g., 09/16/98 23:48:10)
%d day of the month (16) [01-31]
%H hour, using a 24-hour clock (23) [00-23]
%I hour, using a 12-hour clock (11) [01-12]
%j day of year [01-365]
%M minute (48) [00-59]
%m month (09) [01-12]
%n New-line character ('\n')
%p either "am" or "pm" ('_' makes it uppercase)
%r 12-hour clock time * 02:55:02 pm
%R 24-hour HH:MM time, equivalent to %H:%M 14:55
%S second (10) [00-61]
%t Horizontal-tab character ('\t')
%T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm
%u ISO 8601 weekday as number with Monday as 1 (1-7) 4
%w weekday (3) [0-6 = Sunday-Saturday]
%x date (e.g., 09/16/98)
%X time (e.g., 23:48:10)
%Y full year (1998)
%y two-digit year (98) [00-99]
%% the character `%´]]
end;
date = function(optString, unix)
local stringPassed = false
if not (optString == nil and unix == nil) then
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
-- if they didn't pass a non unix time
unix, optString = optString
elseif type(optString) == "string" then
assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date")
unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString
stringPassed = true
end
if type(unix) == "string" then
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
end
local unix = type(unix) == "number" and unix or tick()
local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end
local year = 1970
local days = math.ceil(unix / 86400)
local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
local hours = math.floor(unix / 3600 % 24)
local minutes = math.floor(unix / 60 % 60)
local seconds = math.floor(unix % 60)
-- Calculate year and days into that year
while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end
local yDay = days
-- Subtract amount of days from each month until we find what month we are in and what day in that month
for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do
if days - daysInMonth <= 0 then
month = monthIndex
break
end
days = days - daysInMonth
end
-- string.format("%d/%d/%04d", month, days, year) same as "%x"
-- string.format("%02d:%02d:%02d %s", hours, minutes, seconds, period) same as "%r"
padded = function(num)
return string.format("%02d", num)
end
if stringPassed then
local returner = optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", monthsAbbr[month])
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end;
time = function(...) return os.time(...) end;
difftime = function(...) return os.difftime(...) end;
clock = function(...) return os.difftime(os.time(), firstRequired) end;
}
|
-- to use: local os = require(this_script)
-- Adds an os.date() function back to the Roblox os table!
-- @author Narrev
-- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3)
-- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600)
-- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour
local firstRequired = os.time()
return {
help = function(...) return
[[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding
os.date("*t") returns a table with the following indices:
hour 14
min 36
wday 1
year 2003
yday 124
month 5
sec 33
day 4
String reference:
%a abbreviated weekday name (e.g., Wed)
%A full weekday name (e.g., Wednesday)
%b abbreviated month name (e.g., Sep)
%B full month name (e.g., September)
%c date and time (e.g., 09/16/98 23:48:10)
%d day of the month (16) [01-31]
%H hour, using a 24-hour clock (23) [00-23]
%I hour, using a 12-hour clock (11) [01-12]
%j day of year [01-365]
%M minute (48) [00-59]
%m month (09) [01-12]
%n New-line character ('\n')
%p either "am" or "pm" ('_' makes it uppercase)
%r 12-hour clock time * 02:55:02 pm
%R 24-hour HH:MM time, equivalent to %H:%M 14:55
%S second (10) [00-61]
%t Horizontal-tab character ('\t')
%T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm
%u ISO 8601 weekday as number with Monday as 1 (1-7) 4
%w weekday (3) [0-6 = Sunday-Saturday]
%x date (e.g., 09/16/98)
%X time (e.g., 23:48:10)
%Y full year (1998)
%y two-digit year (98) [00-99]
%% the character `%´]]
end;
date = function(optString, unix)
-- Precise!
local stringPassed = false
if not (optString == nil and unix == nil) then
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
-- if they didn't pass a non unix time
unix, optString = optString
elseif type(optString) == "string" then
assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date")
unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString
stringPassed = true
end
if type(unix) == "string" then
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
end
local dayAlign = unix == 0 and 1 or 0
local unix = type(unix) == "number" and unix + dayAlign or tick()
local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end
local year = 1970
local days = math.ceil(unix / 86400)
local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
local hours = math.floor(unix / 3600 % 24)
local minutes = math.floor(unix / 60 % 60)
local seconds = math.floor(unix % 60) - dayAlign
-- Calculate year and days into that year
while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end
local yDay = days
-- Subtract amount of days from each month until we find what month we are in and what day in that month
for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do
if days - daysInMonth <= 0 then
month = monthIndex
break
end
days = days - daysInMonth
end
padded = function(num)
return string.format("%02d", num)
end
if stringPassed then
local returner = optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", monthsAbbr[month])
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end;
time = function(...) return os.time(...) end;
difftime = function(...) return os.difftime(...) end;
clock = function(...) return os.difftime(os.time(), firstRequired) end;
}
|
Fixed for unixTime = 0
|
Fixed for unixTime = 0
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
cc531e04a90dd8ff1312caa65965eb72c22084d5
|
project.lua
|
project.lua
|
local utils = require("textadept-nim.utils")
local check_type = utils.check_type
local file_exists = utils.file_exists
local _M = {}
local sep = WIN32 and "\\" or "/"
local function parse_nimble(filename)
check_type("string", filename)
local project = {}
project.backend = "c" -- nimble builds project in C by default
-- parse nimble file
for line in io.lines(filename)
do
local key, val = line:match("^%s*(%S+)%s*=%s*(%S+)")
if key == "bin"
then
project.bin = val
elseif key == "srcDir"
then
project.srcdir = val
elseif key == "backend"
then
project.backend = val
elseif line:match("setCommand") ~= nil
then
project.backend = line:match("setCommand%s+\"(%a+)\"")
end
end
return project
end
function _M.detect_project(filename)
-- Trying to obtain project root file
-- If not succeed returns passed filename
check_type("string", filename)
local root_dir = io.get_project_root(buffer.filename) or
filename:match("^([%p%w]-)[^/\\]+$") or
"."
local nimble_file = ""
lfs.dir_foreach(root_dir, function(n)
if n:match("%.nimble") or n:match("%.babel") then
nimble_file = n
return false
end
end,
"!.*","", 0, false)
if #nimble_file > 0
then
local project = parse_nimble(nimble_file)
if project.bin == nil
then -- if project builds no binaries
-- trying to consider as root a file with name similar to nimble file
project.root = tostring(nimble_file:match("(.*%.)[^/\\]+")).."nim"
if not file_exists(project.root)
then
-- if it does not exists checking it in srcdir(if exists)
project.root = root_dir..sep..(project.srcdir or "")..
project.root:match(".*([/\\][^/\\]+)$")
if not file_exists(project.root)
then -- finally give up, project root will be a given file
project.root = filename
end
end
else -- otherwise root file is a file that transforms to a binary
project.root = root_dir..sep..(project.srcdir or "")..
sep..project.bin..".nim"
end
return project
end
local dummy_project =
{
backend = "c",
srcdir = root_dir,
root = filename
} -- When no nimble file detected - just return dummy project for one file
return dummy_project
end
return _M
|
local utils = require("textadept-nim.utils")
local check_type = utils.check_type
local file_exists = utils.file_exists
local _M = {}
local sep = WIN32 and "\\" or "/"
local function parse_nimble(filename)
check_type("string", filename)
local project = {}
project.backend = "c" -- nimble builds project in C by default
-- parse nimble file
for line in io.lines(filename)
do
local key, val = line:match("^%s*(%S+)%s*=%s*(%S+)")
if key == "bin"
then
project.bin = val
elseif key == "srcDir"
then
project.srcdir = val
elseif key == "backend"
then
project.backend = val
elseif line:match("setCommand") ~= nil
then
project.backend = line:match("setCommand%s+\"(%a+)\"")
end
end
return project
end
function _M.detect_project(filename)
-- Trying to obtain project root file
-- If not succeed returns passed filename
check_type("string", filename)
local root_dir = io.get_project_root(buffer.filename) or
filename:match("^([%p%w]-)[^/\\]+$") or
"."
local nimble_file = ""
lfs.dir_foreach(root_dir, function(n)
if n:match("%.nimble") or n:match("%.babel") then
nimble_file = n
return false
end
end,
"!.*","", 0, false)
if #nimble_file > 0
then
local project = parse_nimble(nimble_file)
if project.bin ~= nil
then -- root file is a file that transforms to a binary
project.root = root_dir..sep..(project.srcdir or "")..
sep..project.bin..".nim"
if file_exists(project.root)
then
return project
end
end
-- if project builds no binaries
-- trying to consider as root a file with name similar to nimble file
project.root = tostring(nimble_file:match("(.*%.)[^/\\]+")).."nim"
if not file_exists(project.root)
then
-- if it does not exists checking it in srcdir(if exists)
project.root = root_dir..sep..(project.srcdir or "")..
project.root:match(".*([/\\][^/\\]+)$")
if not file_exists(project.root)
then -- finally give up, project root will be a given file
project.root = filename
end
end
return project
end
local dummy_project =
{
backend = "c",
srcdir = root_dir,
root = filename
} -- When no nimble file detected - just return dummy project for one file
return dummy_project
end
return _M
|
Fixed nimsuggest crash then bin file not exists
|
Fixed nimsuggest crash then bin file not exists
|
Lua
|
mit
|
xomachine/textadept-nim
|
9dab7e4739cb4e1d9b51117fbf1932a4b83635cc
|
xmake/core/project/config.lua
|
xmake/core/project/config.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file config.lua
--
-- define module
local config = config or {}
-- load modules
local io = require("base/io")
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local option = require("base/option")
-- get the configure file
function config._file()
return path.join(config.directory(), "xmake.conf")
end
-- load the project configure
function config._load(targetname)
-- check
targetname = targetname or "all"
-- load configure from the file first
local filepath = config._file()
if os.isfile(filepath) then
-- load it
local results, errors = io.load(filepath)
if not results then
return nil, errors
end
-- load the target configure
if results._TARGETS then
return table.wrap(results._TARGETS[targetname])
end
end
-- empty
return {}
end
-- get the current given configure
function config.get(name)
-- get it
local value = nil
if config._CONFIGS then
value = config._CONFIGS[name]
if type(value) == "string" and value == "auto" then
value = nil
end
end
-- get it
return value
end
-- this config name is readonly?
function config.readonly(name)
return config._MODES and config._MODES["__readonly_" .. name]
end
-- set the given configure to the current
--
-- @param name the name
-- @param value the value
-- @param opt the argument options, e.g. {readonly = false, force = false}
--
function config.set(name, value, opt)
-- check
assert(name)
-- init options
opt = opt or {}
-- check readonly
assert(opt.force or not config.readonly(name), "cannot set readonly config: " .. name)
-- set it
config._CONFIGS = config._CONFIGS or {}
config._CONFIGS[name] = value
-- mark as readonly
if opt.readonly then
config._MODES = config._MODES or {}
config._MODES["__readonly_" .. name] = true
end
end
-- get all options
function config.options()
-- check
assert(config._CONFIGS)
-- remove values with "auto" and private item
local configs = {}
for name, value in pairs(config._CONFIGS) do
if not name:find("^_%u+") and (type(value) ~= "string" or value ~= "auto") then
configs[name] = value
end
end
-- get it
return configs
end
-- get the buildir
function config.buildir()
-- get it
local buildir = config.get("buildir")
if buildir then
-- get the absolute path first
if not path.is_absolute(buildir) then
buildir = path.absolute(buildir, os.projectdir())
end
-- adjust path for the current directory
buildir = path.relative(buildir, os.curdir())
end
return buildir
end
-- get the configure directory on the current host/arch platform
function config.directory()
if config._DIRECTORY == nil then
local rootdir = os.getenv("XMAKE_CONFIGDIR") or path.join(os.projectdir(), ".xmake")
config._DIRECTORY = path.join(rootdir, os.host(), os.arch())
end
return config._DIRECTORY
end
-- load the project configure
function config.load(targetname)
-- load configure
local results, errors = config._load(targetname)
if not results then
utils.error(errors)
return false
end
-- merge the target configure first
local ok = false
for name, value in pairs(results) do
if config.get(name) == nil then
config.set(name, value)
ok = true
end
end
-- ok?
return ok
end
-- save the project configure
function config.save(targetname)
-- check
targetname = targetname or "all"
-- load the previous results from configure
local results = {}
local filepath = config._file()
if os.isfile(filepath) then
results = io.load(filepath) or {}
end
-- the targets
local targets = results._TARGETS or {}
results._TARGETS = targets
-- clear target first
targets[targetname] = {}
-- update target
local target = targets[targetname]
for name, value in pairs(config.options()) do
target[name] = value
end
-- add version
results.__version = xmake._VERSION_SHORT
-- save it
return io.save(config._file(), results)
end
-- read value from the configure file directly
function config.read(name, targetname)
-- load configs
local configs = config._load(targetname)
-- get it
local value = nil
if configs then
value = configs[name]
if type(value) == "string" and value == "auto" then
value = nil
end
end
-- ok?
return value
end
-- clear config
function config.clear()
config._MODES = nil
config._CONFIGS = nil
end
-- the current mode is belong to the given modes?
function config.is_mode(...)
return config.is_value("mode", ...)
end
-- the current platform is belong to the given platforms?
function config.is_plat(...)
return config.is_value("plat", ...)
end
-- the current architecture is belong to the given architectures?
function config.is_arch(...)
return config.is_value("arch", ...)
end
-- the current config is belong to the given config values?
function config.is_value(name, ...)
-- get the current config value
local value = config.get(name)
if not value then return false end
-- exists this value? and escape '-'
for _, v in ipairs(table.join(...)) do
if v and type(v) == "string" and value:find("^" .. v:gsub("%-", "%%-") .. "$") then
return true
end
end
end
-- has the given configs?
function config.has(...)
for _, name in ipairs(table.join(...)) do
if name and type(name) == "string" and config.get(name) then
return true
end
end
end
-- dump the configure
function config.dump()
if not option.get("quiet") then
utils.print("configure")
utils.print("{")
for name, value in pairs(config.options()) do
if not name:startswith("__") then
utils.print(" %s = %s", name, value)
end
end
utils.print("}")
end
end
-- return module
return config
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file config.lua
--
-- define module
local config = config or {}
-- load modules
local io = require("base/io")
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local option = require("base/option")
-- get the configure file
function config._file()
return path.join(config.directory(), "xmake.conf")
end
-- load the project configure
function config._load(targetname)
-- check
targetname = targetname or "all"
-- load configure from the file first
local filepath = config._file()
if os.isfile(filepath) then
-- load it
local results, errors = io.load(filepath)
if not results then
return nil, errors
end
-- load the target configure
if results._TARGETS then
return table.wrap(results._TARGETS[targetname])
end
end
-- empty
return {}
end
-- get the current given configure
function config.get(name)
-- get it
local value = nil
if config._CONFIGS then
value = config._CONFIGS[name]
if type(value) == "string" and value == "auto" then
value = nil
end
end
-- get it
return value
end
-- this config name is readonly?
function config.readonly(name)
return config._MODES and config._MODES["__readonly_" .. name]
end
-- set the given configure to the current
--
-- @param name the name
-- @param value the value
-- @param opt the argument options, e.g. {readonly = false, force = false}
--
function config.set(name, value, opt)
-- check
assert(name)
-- init options
opt = opt or {}
-- check readonly
assert(opt.force or not config.readonly(name), "cannot set readonly config: " .. name)
-- set it
config._CONFIGS = config._CONFIGS or {}
config._CONFIGS[name] = value
-- mark as readonly
if opt.readonly then
config._MODES = config._MODES or {}
config._MODES["__readonly_" .. name] = true
end
end
-- get all options
function config.options()
-- check
assert(config._CONFIGS)
-- remove values with "auto" and private item
local configs = {}
for name, value in pairs(config._CONFIGS) do
if not name:find("^_%u+") and (type(value) ~= "string" or value ~= "auto") then
configs[name] = value
end
end
-- get it
return configs
end
-- get the buildir
function config.buildir()
-- get it
local buildir = config.get("buildir")
if buildir then
-- get the absolute path first
if not path.is_absolute(buildir) then
buildir = path.absolute(buildir, os.projectdir())
end
-- adjust path for the current directory
buildir = path.relative(buildir, os.curdir())
end
return buildir
end
-- get the configure directory on the current host/arch platform
function config.directory()
if config._DIRECTORY == nil then
local rootdir = os.getenv("XMAKE_CONFIGDIR") or os.projectdir()
config._DIRECTORY = path.join(rootdir, ".xmake", os.host(), os.arch())
end
return config._DIRECTORY
end
-- load the project configure
function config.load(targetname)
-- load configure
local results, errors = config._load(targetname)
if not results then
utils.error(errors)
return false
end
-- merge the target configure first
local ok = false
for name, value in pairs(results) do
if config.get(name) == nil then
config.set(name, value)
ok = true
end
end
-- ok?
return ok
end
-- save the project configure
function config.save(targetname)
-- check
targetname = targetname or "all"
-- load the previous results from configure
local results = {}
local filepath = config._file()
if os.isfile(filepath) then
results = io.load(filepath) or {}
end
-- the targets
local targets = results._TARGETS or {}
results._TARGETS = targets
-- clear target first
targets[targetname] = {}
-- update target
local target = targets[targetname]
for name, value in pairs(config.options()) do
target[name] = value
end
-- add version
results.__version = xmake._VERSION_SHORT
-- save it
return io.save(config._file(), results)
end
-- read value from the configure file directly
function config.read(name, targetname)
-- load configs
local configs = config._load(targetname)
-- get it
local value = nil
if configs then
value = configs[name]
if type(value) == "string" and value == "auto" then
value = nil
end
end
-- ok?
return value
end
-- clear config
function config.clear()
config._MODES = nil
config._CONFIGS = nil
end
-- the current mode is belong to the given modes?
function config.is_mode(...)
return config.is_value("mode", ...)
end
-- the current platform is belong to the given platforms?
function config.is_plat(...)
return config.is_value("plat", ...)
end
-- the current architecture is belong to the given architectures?
function config.is_arch(...)
return config.is_value("arch", ...)
end
-- the current config is belong to the given config values?
function config.is_value(name, ...)
-- get the current config value
local value = config.get(name)
if not value then return false end
-- exists this value? and escape '-'
for _, v in ipairs(table.join(...)) do
if v and type(v) == "string" and value:find("^" .. v:gsub("%-", "%%-") .. "$") then
return true
end
end
end
-- has the given configs?
function config.has(...)
for _, name in ipairs(table.join(...)) do
if name and type(name) == "string" and config.get(name) then
return true
end
end
end
-- dump the configure
function config.dump()
if not option.get("quiet") then
utils.print("configure")
utils.print("{")
for name, value in pairs(config.options()) do
if not name:startswith("__") then
utils.print(" %s = %s", name, value)
end
end
utils.print("}")
end
end
-- return module
return config
|
fix configdir
|
fix configdir
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
0564a11b151a7f3561b5cb8fe09805b8f0d0d7a6
|
extensions/hints/init.lua
|
extensions/hints/init.lua
|
--- === hs.hints ===
---
--- Switch focus with a transient per-application keyboard shortcut
local hints = require "hs.hints.internal"
local screen = require "hs.screen"
local window = require "hs.window"
local hotkey = require "hs.hotkey"
local modal_hotkey = hotkey.modal
--- hs.hints.hintChars
--- Variable
--- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map
--- The default is the letters A-Z.
hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
--- hs.hints.style
--- Variable
--- If this is set to "vimperator", every window hint starts with the first character
--- of the parent application's title
hints.style = "default"
--- hs.hints.fontName
--- Variable
--- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.)
--- The default value is the system font
hints.fontName = nil
--- hs.hints.fontSize
--- Variable
--- The size of font that should be used. A value of 0.0 will use the default size.
hints.fontSize = 0.0
local openHints = {}
local takenPositions = {}
local hintDict = {}
local modalKey = nil
local bumpThresh = 40^2
local bumpMove = 80
function hints.bumpPos(x,y)
for i, pos in ipairs(takenPositions) do
if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then
return hints.bumpPos(x,y+bumpMove)
end
end
return {x = x,y = y}
end
function hints.addWindow(dict, win)
local n = dict['count']
if n == nil then
dict['count'] = 0
n = 0
end
local m = (n % #hints.hintChars) + 1
local char = hints.hintChars[m]
if n < #hints.hintChars then
dict[char] = win
else
if type(dict[char]) == "userdata" then
-- dict[m] is already occupied by another window
-- which me must convert into a new dictionary
local otherWindow = dict[char]
dict[char] = {}
hints.addWindow(dict, otherWindow)
end
hints.addWindow(dict[char], win)
end
dict['count'] = dict['count'] + 1
end
function hints.displayHintsForDict(dict, prefixstring)
for key, val in pairs(dict) do
if type(val) == "userdata" then -- this is a window
local win = val
local app = win:application()
local fr = win:frame()
local sfr = win:screen():frame()
if app and win:isStandard() then
local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y}
c = hints.bumpPos(c.x, c.y)
if c.y < 0 then
print("hs.hints: Skipping offscreen window: "..win:title())
else
-- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging
local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize)
table.insert(takenPositions, c)
table.insert(openHints, hint)
end
end
elseif type(val) == "table" then -- this is another window dict
hints.displayHintsForDict(val, prefixstring .. key)
end
end
end
function hints.processChar(char)
if hintDict[char] ~= nil then
hints.closeHints()
if type(hintDict[char]) == "userdata" then
if hintDict[char] then hintDict[char]:focus() end
modalKey:exit()
elseif type(hintDict[char]) == "table" then
hintDict = hintDict[char]
local hintDictLength = 0
for _ in pairs(hintDict) do hintDictLength = hintDictLength + 1 end
if hintDictLength == 1 then
for key, val in ipairs(hintDict) do
v:focus()
modalKey:exit()
end
else
takenPositions = {}
hints.displayHintsForDict(hintDict, "")
end
end
end
end
function hints.setupModal()
k = modal_hotkey.new(nil, nil)
k:bind({}, 'escape', function() hints.closeHints(); k:exit() end)
for _, c in ipairs(hints.hintChars) do
k:bind({}, c, function() hints.processChar(c) end)
end
return k
end
--- hs.hints.windowHints()
--- Function
--- Displays a keyboard hint for switching focus to each window
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * If there are more windows open than there are characters available in hs.hints.hintChars,
--- we resort to multi-character hints
--- * If hints.style is set to "vimperator", every window hint is prefixed with the first
--- character of the parent application's name
function hints.windowHints()
if (modalKey == nil) then
modalKey = hints.setupModal()
end
hints.closeHints()
hintDict = {}
for i, win in ipairs(window.allWindows()) do
local app = win:application()
if app and win:isStandard() then
if hints.style == "vimperator" then
if app and win:isStandard() then
local appchar = string.upper(string.sub(app:title(), 1, 1))
modalKey:bind({}, appchar, function() hints.processChar(appchar) end)
if hintDict[appchar] == nil then
hintDict[appchar] = {}
end
hints.addWindow(hintDict[appchar], win)
end
else
hints.addWindow(hintDict, win)
end
end
end
takenPositions = {}
if next(hintDict) ~= nil then
hints.displayHintsForDict(hintDict, "")
modalKey:enter()
end
end
function hints.closeHints()
for _, hint in ipairs(openHints) do
hint:close()
end
openHints = {}
takenPositions = {}
end
return hints
|
--- === hs.hints ===
---
--- Switch focus with a transient per-application keyboard shortcut
local hints = require "hs.hints.internal"
local screen = require "hs.screen"
local window = require "hs.window"
local hotkey = require "hs.hotkey"
local modal_hotkey = hotkey.modal
--- hs.hints.hintChars
--- Variable
--- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map
--- The default is the letters A-Z.
hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
--- hs.hints.style
--- Variable
--- If this is set to "vimperator", every window hint starts with the first character
--- of the parent application's title
hints.style = "default"
--- hs.hints.fontName
--- Variable
--- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.)
--- The default value is the system font
hints.fontName = nil
--- hs.hints.fontSize
--- Variable
--- The size of font that should be used. A value of 0.0 will use the default size.
hints.fontSize = 0.0
local openHints = {}
local takenPositions = {}
local hintDict = {}
local modalKey = nil
local bumpThresh = 40^2
local bumpMove = 80
function hints.bumpPos(x,y)
for i, pos in ipairs(takenPositions) do
if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then
return hints.bumpPos(x,y+bumpMove)
end
end
return {x = x,y = y}
end
function hints.addWindow(dict, win)
local n = dict['count']
if n == nil then
dict['count'] = 0
n = 0
end
local m = (n % #hints.hintChars) + 1
local char = hints.hintChars[m]
if n < #hints.hintChars then
dict[char] = win
else
if type(dict[char]) == "userdata" then
-- dict[m] is already occupied by another window
-- which me must convert into a new dictionary
local otherWindow = dict[char]
dict[char] = {}
hints.addWindow(dict, otherWindow)
end
hints.addWindow(dict[char], win)
end
dict['count'] = dict['count'] + 1
end
function hints.displayHintsForDict(dict, prefixstring)
for key, val in pairs(dict) do
if type(val) == "userdata" then -- this is a window
local win = val
local app = win:application()
local fr = win:frame()
local sfr = win:screen():frame()
if app and win:isStandard() then
local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y}
c = hints.bumpPos(c.x, c.y)
if c.y < 0 then
print("hs.hints: Skipping offscreen window: "..win:title())
else
-- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging
local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize)
table.insert(takenPositions, c)
table.insert(openHints, hint)
end
end
elseif type(val) == "table" then -- this is another window dict
hints.displayHintsForDict(val, prefixstring .. key)
end
end
end
function hints.processChar(char)
if hintDict[char] ~= nil then
hints.closeHints()
if type(hintDict[char]) == "userdata" then
if hintDict[char] then hintDict[char]:focus() end
modalKey:exit()
elseif type(hintDict[char]) == "table" then
hintDict = hintDict[char]
if hintDict.count == 1 then
hintDict.A:focus()
modalKey:exit()
else
takenPositions = {}
hints.displayHintsForDict(hintDict, "")
end
end
end
end
function hints.setupModal()
k = modal_hotkey.new(nil, nil)
k:bind({}, 'escape', function() hints.closeHints(); k:exit() end)
for _, c in ipairs(hints.hintChars) do
k:bind({}, c, function() hints.processChar(c) end)
end
return k
end
--- hs.hints.windowHints()
--- Function
--- Displays a keyboard hint for switching focus to each window
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * If there are more windows open than there are characters available in hs.hints.hintChars,
--- we resort to multi-character hints
--- * If hints.style is set to "vimperator", every window hint is prefixed with the first
--- character of the parent application's name
function hints.windowHints()
if (modalKey == nil) then
modalKey = hints.setupModal()
end
hints.closeHints()
hintDict = {}
for i, win in ipairs(window.allWindows()) do
local app = win:application()
if app and win:isStandard() then
if hints.style == "vimperator" then
if app and win:isStandard() then
local appchar = string.upper(string.sub(app:title(), 1, 1))
modalKey:bind({}, appchar, function() hints.processChar(appchar) end)
if hintDict[appchar] == nil then
hintDict[appchar] = {}
end
hints.addWindow(hintDict[appchar], win)
end
else
hints.addWindow(hintDict, win)
end
end
end
takenPositions = {}
if next(hintDict) ~= nil then
hints.displayHintsForDict(hintDict, "")
modalKey:enter()
end
end
function hints.closeHints()
for _, hint in ipairs(openHints) do
hint:close()
end
openHints = {}
takenPositions = {}
end
return hints
|
Fixing broken code.
|
Fixing broken code.
|
Lua
|
mit
|
wvierber/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,peterhajas/hammerspoon,zzamboni/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,trishume/hammerspoon,hypebeast/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,hypebeast/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,junkblocker/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,junkblocker/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,Stimim/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,knl/hammerspoon,wsmith323/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,knl/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,hypebeast/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,peterhajas/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,knl/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,tmandry/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,knu/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,wvierber/hammerspoon,Habbie/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,trishume/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,nkgm/hammerspoon,nkgm/hammerspoon
|
0a0ffafd4370440541d935ff778674193e4a453f
|
mod_mam/rsm.lib.lua
|
mod_mam/rsm.lib.lua
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
else
module:log("debug", "RSM parse failed, %s", tostring(st));
end
end
return { parse = parse, generate = generate, get = get };
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
6af6d6b3887ba4d93318a145500f317510e7ed1b
|
ffi/mupdfimg.lua
|
ffi/mupdfimg.lua
|
--[[
rendering image with mupdf library
--]]
local ffi = require("ffi")
local Blitbuffer = require("ffi/blitbuffer")
local mupdf = ffi.load("libs/libmupdf.so")
require("ffi/mupdf_h")
local Image = {}
function Image:initContext(cache_size)
-- Remember to change library version when upgrading MuPDF!
self.context = mupdf.fz_new_context_imp(nil, nil, cache_size or bit.lshift(8, 20), "1.5")
end
function Image:loadImage(filename, width, height)
local file = io.open(filename)
if file then
local data = file:read("*a")
file:close()
self.image = mupdf.fz_new_image_from_data(self.context,
ffi.cast("unsigned char*", data), #data)
if self.image ~= nil then
self.pixmap = mupdf.fz_new_pixmap_from_image(self.context,
self.image, width or -1, height or -1)
end
end
end
function Image:toBlitBuffer()
local pixmap = ffi.new("fz_pixmap[1]")
pixmap = self.pixmap
if self.pixmap.n ~= 2 then
self.pixmap = mupdf.fz_new_pixmap(self.context, mupdf.fz_device_gray(self.context),
pixmap.w, pixmap.h);
mupdf.fz_convert_pixmap(self.context, self.pixmap, pixmap);
mupdf.fz_drop_pixmap(self.context, pixmap);
end
self.bb = Blitbuffer.new(self.pixmap.w, self.pixmap.h, Blitbuffer.TYPE_BB8A, self.pixmap.samples)
self.bb:invert() -- our blitbuffers have reversed b->w scale
self.bb = self.bb:copy() -- we make a copy so mupdf can drop the memory
end
function Image:freeContext()
if self.pixmap ~= nil then
mupdf.fz_drop_pixmap(self.context, self.pixmap)
self.pixmap = nil
end
if self.image ~= nil then
mupdf.fz_drop_image(self.context, self.image)
self.image = nil
end
--[[ FIXME: segmentation fault when calling fz_free_context if we called
-- fz_drop_image first. Although valgrind shows that commenting out
-- fz_free_context does not leading to memory leak, it's still a dirty hack
-- and need to be fixed by those who knows mupdf better.
if self.context ~= nil then
mupdf.fz_free_context(self.context)
self.context = nil
end
--]]
end
function Image:fromFile(filename, width, height)
self:initContext()
self:loadImage(filename, width, height)
self:toBlitBuffer()
self:freeContext()
return self.bb
end
return Image
|
--[[
rendering image with mupdf library
--]]
local ffi = require("ffi")
local Blitbuffer = require("ffi/blitbuffer")
local mupdf = ffi.load("libs/libmupdf.so")
require("ffi/mupdf_h")
local Image = {}
function Image:initContext(cache_size)
-- Remember to change library version when upgrading MuPDF!
self.context = mupdf.fz_new_context_imp(nil, nil, cache_size or bit.lshift(8, 20), "1.5")
end
function Image:loadImage(filename, width, height)
local file = io.open(filename)
if file then
local data = file:read("*a")
file:close()
local image = mupdf.fz_new_image_from_data(self.context,
ffi.cast("unsigned char*", data), #data)
if image ~= nil then
self.pixmap = mupdf.fz_new_pixmap_from_image(self.context,
image, width or -1, height or -1)
self.image = mupdf.fz_keep_image(self.context, image)
end
end
end
function Image:toBlitBuffer()
local pixmap = ffi.new("fz_pixmap[1]")
pixmap = self.pixmap
if self.pixmap.n ~= 2 then
self.pixmap = mupdf.fz_new_pixmap(self.context, mupdf.fz_device_gray(self.context),
pixmap.w, pixmap.h);
mupdf.fz_convert_pixmap(self.context, self.pixmap, pixmap);
mupdf.fz_drop_pixmap(self.context, pixmap);
end
self.bb = Blitbuffer.new(self.pixmap.w, self.pixmap.h, Blitbuffer.TYPE_BB8A, self.pixmap.samples)
self.bb:invert() -- our blitbuffers have reversed b->w scale
self.bb = self.bb:copy() -- we make a copy so mupdf can drop the memory
end
function Image:freeContext()
if self.image ~= nil then
mupdf.fz_drop_image(self.context, self.image)
self.image = nil
end
if self.pixmap ~= nil then
mupdf.fz_drop_pixmap(self.context, self.pixmap)
self.pixmap = nil
end
if self.context ~= nil then
mupdf.fz_free_context(self.context)
self.context = nil
end
end
function Image:fromFile(filename, width, height)
self:initContext(0)
self:loadImage(filename, width, height)
self:toBlitBuffer()
self:freeContext()
return self.bb
end
return Image
|
fix memory leak in freeContext
|
fix memory leak in freeContext
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,koreader/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,houqp/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,apletnev/koreader-base
|
5b0bb640c1e512d5d40c1082b46150ccb1961ce0
|
tools/bundler.lua
|
tools/bundler.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local FS = require('fs')
local Path = require('path')
local Table = require('table')
local ChildProcess = require('childprocess')
local function map(array, fn)
local new_array = {}
for i,v in ipairs(array) do
new_array[i] = fn(v, i, array)
end
return new_array
end
local function mapcat(array, fn, join)
return Table.concat(map(array, fn), join or "")
end
local libdir = Path.join(Path.dirname(process.execPath), "../lib/luvit")
local files = FS.readdirSync(libdir)
local names = map(files, function (file)
return file:match("^([^.]*)")
end)
Table.sort(names)
local exports_c = [[
/* This file is generated by bundler.lua */
#include <string.h>
#include "luvit.h"
const void *luvit_ugly_hack = NULL;
]] .. mapcat(names, function (name) return "extern const char *luaJIT_BC_" .. name .. "[];\n" end) .. [[
const void *luvit__suck_in_symbols(void)
{
luvit_ugly_hack = (const char*)
]] .. mapcat(names, function (name) return " (size_t)(const char *)luaJIT_BC_" .. name end, " +\n") .. [[;
return luvit_ugly_hack;
}
]]
local exports_h = [[
/* This file is generated by bundler.lua */
#ifndef LUV_EXPORTS
#define LUV_EXPORTS
const void *luvit__suck_in_symbols(void);
#endif
]]
FS.mkdir("bundle", "0755", function (err)
if err then
if not (err.code == "EEXIST") then error(err) end
end
local left = 0
local function pend()
left = left + 1
return function (err)
if err then error(err) end
left = left - 1
if left == 0 then
-- print("Done!")
end
end
end
FS.writeFile("src/luvit_exports.c", exports_c, pend())
FS.writeFile("src/luvit_exports.h", exports_h, pend())
for i, file in ipairs(files) do
ChildProcess.execFile("deps/luajit/src/luajit", {"-bg", "lib/luvit/" .. file, "bundle/" .. names[i] .. ".c"}, {}, pend())
end
end);
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local FS = require('fs')
local Path = require('path')
local Table = require('table')
local ChildProcess = require('childprocess')
local function map(array, fn)
local new_array = {}
for i,v in ipairs(array) do
new_array[i] = fn(v, i, array)
end
return new_array
end
local function mapcat(array, fn, join)
return Table.concat(map(array, fn), join or "")
end
local libdir = Path.join(Path.dirname(process.execPath), Path.join("..", "lib", "luvit"))
local files = FS.readdirSync(libdir)
local names = map(files, function (file)
return file:match("^([^.]*)")
end)
Table.sort(names)
local exports_c = [[
/* This file is generated by bundler.lua */
#include <string.h>
#include "luvit.h"
const void *luvit_ugly_hack = NULL;
]] .. mapcat(names, function (name) return "extern const char *luaJIT_BC_" .. name .. "[];\n" end) .. [[
const void *luvit__suck_in_symbols(void)
{
luvit_ugly_hack = (const char*)
]] .. mapcat(names, function (name) return " (size_t)(const char *)luaJIT_BC_" .. name end, " +\n") .. [[;
return luvit_ugly_hack;
}
]]
local exports_h = [[
/* This file is generated by bundler.lua */
#ifndef LUV_EXPORTS
#define LUV_EXPORTS
const void *luvit__suck_in_symbols(void);
#endif
]]
FS.mkdir("bundle", "0755", function (err)
if err then
if not (err.code == "EEXIST") then error(err) end
end
local left = 0
local function pend()
left = left + 1
return function (err)
if err then error(err) end
left = left - 1
if left == 0 then
-- print("Done!")
end
end
end
FS.writeFile(Path.join("src", "luvit_exports.c"), exports_c, pend())
FS.writeFile(Path.join("src", "luvit_exports.h"), exports_h, pend())
for i, file in ipairs(files) do
ChildProcess.execFile(Path.join("deps", "luajit", "src", "luajit"), {"-bg", Path.join("lib", "luvit", file), Path.join("bundle", names[i] .. ".c")}, {}, pend())
end
end);
|
Fix mixed path separators on Windows platform in tools/bundler.lua
|
Fix mixed path separators on Windows platform in tools/bundler.lua
path.join() is the good replacement of hardcoded paths and it provides correct strings for both windows and
posix types of paths.
|
Lua
|
apache-2.0
|
DBarney/luvit,bsn069/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,boundary/luvit,sousoux/luvit,boundary/luvit,sousoux/luvit,DBarney/luvit,boundary/luvit,rjeli/luvit,kaustavha/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,DBarney/luvit,rjeli/luvit,kaustavha/luvit,rjeli/luvit,sousoux/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,sousoux/luvit,sousoux/luvit,sousoux/luvit,bsn069/luvit
|
327c5319e1c3e53c78648f6d95c0ee91b075ba68
|
motionLights.lua
|
motionLights.lua
|
--[[
%% properties
59 value
63 value
66 value
69 value
72 value
75 value
78 value
%% globals
--]]
-- Script to turn ON/OFF lights when motion is detected. One script handles them all :-)
-- Remi Bergsma [email protected]
-- Please note:
-- This script requires global variable 'Sun' to be defined in the Variables Panel.
-- Configuration:
-- Add motion devices in header, and create a line in the config array for each of them.
-- In this array, define motion and light devices to switch
-- Data structure: lightArray['motion id'] = { identifier, light id, isDimmer, dimLevel, timeout }
local lightArray = { }
lightArray['59'] = { 'Corridor', 62, 1, 10, 180 }
lightArray['63'] = { 'Living room', 18, 0, 0, 300 }
lightArray['69'] = { 'Kitchen', 56, 1, 50, 300 }
-- whether or not to display debug messages
local debug = 1
-- check how we are invoked
-- type=other => manual
local trigger = fibaro:getSourceTrigger()
if trigger["type"] == "other" then
fibaro:debug("Invoked manually, cannot use dynamic configuration. Halting.")
fibaro:abort()
end
-- how many instances are running
local nrOfScenes = fibaro:countScenes()
if debug ==1 then fibaro:debug("New session: total number of concurrent running scenes is now " .. nrOfScenes) end
-- who triggered us
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Triggered by device of type " .. trigger["type"] .. ".") end
-- do we have config for triggering device?
local configFound = 0
for k, v in pairs(lightArray) do
if k == trigger['deviceID'] then
configFound = 1
end
end
if configFound == 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "No config found for triggering device " .. trigger['deviceID'] .. ". Halting.") end
fibaro:abort()
end
-- getting config
local configArray = lightArray[trigger['deviceID']]
-- which config are we running
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Running config for " .. configArray[1] .. ".") end
-- vars needed in the code below
-- id of the light to switch
local light = configArray[2]
-- is the light a dimmer
local isDimmer = configArray[3]
-- dimmer percentage (ignored of not a dimmer)
local dimLevel = configArray[4]
-- number of seconds after which to turn off lights when motion stopped
local offTimeout = configArray[5]
-- motion reported
if tonumber(fibaro:getValue(trigger['deviceID'], "value")) > 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Motion detected." ) end
-- Only if the sun is set (does not make sense to switch lights during daytime)
if fibaro:getGlobalValue("Sun") == "Set" then
-- already on?
if tonumber(fibaro:getValue(light, "value")) == 0 then
-- switch on the light
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Switching ON light due to motion") end
if isDimmer == 1 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Set dim level to " .. dimLevel .. "%") end
fibaro:call(light, "setValue", dimLevel);
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Turned on the light") end
fibaro:call(light, "turnOn");
end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Not turning ON lights: already on") end
end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Not turning ON lights during day time.") end
end
-- no motion reported
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Device " .. trigger['deviceID'] .. " reports no more motion." ) end
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Sleeping " .. offTimeout .. "s before turning OFF.." ) end
fibaro:sleep(offTimeout*1000)
-- first check for ongoing motion
currentStatus = tonumber(fibaro:getValue(trigger['deviceID'], "value"))
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Testing for ongoing motion..") end
if currentStatus == 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "No ongoing motion.") end
-- how long ago was last motion?
time = os.time()
last = tonumber(fibaro:getValue(trigger['deviceID'], "lastBreached"))
diff = tonumber(time-last)
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Last motion was at " .. last .. ", that is " .. diff .. " sec ago. Current motion status is: " .. currentStatus) end
-- if lights are on and no motion, then switch them off
local lightStatus = tonumber(fibaro:getValue(light, "value"))
-- relay switch will report 1 if on, dimmer will report dimlevel (1-99)
if diff > offTimeout then
if lightStatus >= 1 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Current status of light: " .. lightStatus) end
fibaro:call(light, "turnOff");
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Turned OFF due to no activity") end
fibaro:sleep(1000)
lightStatus = tonumber(fibaro:getValue(light, "value"))
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "New status of light: " .. lightStatus) end
elseif debug ==1 then
fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Nothing to do, lamp is already off.")
end
elseif debug ==1 then
fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Nothing to do, timeout is not over yet.") end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Ongoing motion, skipping turning OFF.") end
end
end
|
--[[
%% properties
59 value
63 value
66 value
69 value
72 value
75 value
78 value
%% globals
--]]
-- Script to turn ON/OFF lights when motion is detected. One script handles them all :-)
-- Remi Bergsma [email protected]
-- Please note:
-- This script requires global variable 'Sun' to be defined in the Variables Panel.
-- Configuration:
-- Add motion devices in header, and create a line in the config array for each of them.
-- In this array, define motion and light devices to switch
-- Data structure: lightArray['motion id'] = { identifier, light id, isDimmer, dimLevel, timeout }
local lightArray = { }
lightArray['59'] = { 'Corridor', 62, 1, 10, 180 }
lightArray['63'] = { 'Living room', 18, 0, 0, 300 }
lightArray['69'] = { 'Kitchen', 56, 1, 50, 300 }
-- whether or not to display debug messages
local debug = 1
-- check how we are invoked
-- type=other => manual
local trigger = fibaro:getSourceTrigger()
if trigger["type"] == "other" then
fibaro:debug("Invoked manually, cannot use dynamic configuration. Halting.")
fibaro:abort()
end
-- how many instances are running
local nrOfScenes = fibaro:countScenes()
if debug ==1 then fibaro:debug("New session: total number of concurrent running scenes is now " .. nrOfScenes) end
-- who triggered us
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Triggered by device of type " .. trigger["type"] .. ".") end
-- do we have config for triggering device?
local configFound = 0
for k, v in pairs(lightArray) do
if k == trigger['deviceID'] then
configFound = 1
end
end
if configFound == 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "No config found for triggering device " .. trigger['deviceID'] .. ". Halting.") end
fibaro:abort()
end
-- getting config
local configArray = lightArray[trigger['deviceID']]
-- which config are we running
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Running config for " .. configArray[1] .. ".") end
-- vars needed in the code below
-- id of the light to switch
local light = configArray[2]
-- is the light a dimmer
local isDimmer = configArray[3]
-- dimmer percentage (ignored of not a dimmer)
local dimLevel = configArray[4]
-- number of seconds after which to turn off lights when motion stopped
local offTimeout = configArray[5]
-- motion reported
if tonumber(fibaro:getValue(trigger['deviceID'], "value")) > 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Motion detected." ) end
-- Only if the sun is set (does not make sense to switch lights during daytime)
if fibaro:getGlobalValue("Sun") == "Set" then
-- already on?
if tonumber(fibaro:getValue(light, "value")) == 0 then
-- switch on the light
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Switching ON light due to motion") end
if isDimmer == 1 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Set dim level to " .. dimLevel .. "%") end
fibaro:call(light, "setValue", dimLevel);
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Turned on the light") end
fibaro:call(light, "turnOn");
end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Not turning ON lights: already on") end
end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Not turning ON lights during day time.") end
end
-- no motion reported
-- only makes sense to check this when the sun is set
elseif fibaro:getGlobalValue("Sun") == "Set" then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Device " .. trigger['deviceID'] .. " reports no more motion." ) end
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Sleeping " .. offTimeout .. "s before turning OFF.." ) end
fibaro:sleep(offTimeout*1000)
-- first check for ongoing motion
currentStatus = tonumber(fibaro:getValue(trigger['deviceID'], "value"))
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Testing for ongoing motion..") end
if currentStatus == 0 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "No ongoing motion.") end
-- how long ago was last motion?
time = os.time()
last = tonumber(fibaro:getValue(trigger['deviceID'], "lastBreached"))
diff = tonumber(time-last)
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Last motion was at " .. last .. ", that is " .. diff .. " sec ago. Current motion status is: " .. currentStatus) end
-- if lights are on and no motion, then switch them off
local lightStatus = tonumber(fibaro:getValue(light, "value"))
-- relay switch will report 1 if on, dimmer will report dimlevel (1-99)
if diff > offTimeout then
if lightStatus >= 1 then
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Current status of light: " .. lightStatus) end
fibaro:call(light, "turnOff");
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Turned OFF due to no activity") end
fibaro:sleep(1000)
lightStatus = tonumber(fibaro:getValue(light, "value"))
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "New status of light: " .. lightStatus) end
elseif debug ==1 then
fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Nothing to do, lamp is already off.")
end
elseif debug ==1 then
fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Nothing to do, timeout is not over yet.") end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Ongoing motion, skipping turning OFF.") end
end
else
if debug ==1 then fibaro:debug("Device " .. trigger['deviceID'] .. ": " .. "Device " .. trigger['deviceID'] .. " reports no more motion. Nothing to do during day time." ) end
end
|
fixed unneeded sleeping during day time
|
fixed unneeded sleeping during day time
|
Lua
|
apache-2.0
|
remibergsma/fibaro-hc2-scenes
|
99ddaad672fd74245ba79b292e428230460beddc
|
BIOS/setup.lua
|
BIOS/setup.lua
|
--BIOS Setup Screen
local Handled, Devkits = ... --It has been passed by the BIOS POST Screen :)
local BIOS = Handled.BIOS
local GPU = Handled.GPU
local CPU = Handled.CPU
local fs = Handled.HDD
GPU.clear(0)
GPU.color(7)
GPU.printCursor(0,0,0)
GPU.print("Setup")
GPU.print("Press F1 to reflash DiskOS")
GPU.print("Press R to reboot")
while true do
for event, a, b, c, d, e, f in CPU.pullEvent do
if event == "keypressed" and a == "f1" and c == false then
GPU.print("Flashing in 5 seconds...")
CPU.sleep(5)
love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false)
CPU.reboot()
end
if event == "keypressed" and a == "r" and c == false then
CPU.reboot()
end
end
end
CPU.reboot()
|
--BIOS Setup Screen
local Handled, Devkits = ... --It has been passed by the BIOS POST Screen :)
local BIOS = Handled.BIOS
local GPU = Handled.GPU
local CPU = Handled.CPU
local fs = Handled.HDD
local KB = Handled.Keyboard
local coreg = require("Engine.coreg")
local stopWhile = false
GPU.clear(0)
GPU.color(7)
KB.textinput(true)
local function drawInfo()
GPU.clear(0)
GPU.printCursor(0,0,0)
GPU.print("LIKO-12 Setup ------ Press R to reboot")
GPU.print("Press O to reflash DiskOS")
GPU.print("Press B to boot from D:")
GPU.print("Press W then C or D to wipe a disk")
end
local function attemptBootFromD()
fs.drive("D")
if not fs.exists("/boot.lua") then
GPU.print("Could not find boot.lua")
CPU.sleep(1)
drawInfo()
return
end
local bootchunk, err = fs.load("/boot.lua")
if not bootchunk then error(err or "") end
local coglob = coreg:sandbox(bootchunk)
local co = coroutine.create(bootchunk)
local HandledAPIS = BIOS.HandledAPIS()
coroutine.yield("echo",HandledAPIS)
coreg:setCoroutine(co,coglob) --Switch to boot.lua coroutine
end
drawInfo()
while not stopWhile do
for event, a, b, c, d, e, f in CPU.pullEvent do
if event == "keypressed" and c == false then
if a == "o" then
GPU.print("Flashing in 5 seconds...")
CPU.sleep(5)
love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false)
CPU.reboot()
end
if a == "r" then
CPU.reboot()
end
if a == "w" then
wipingMode = true
GPU.print("Wiping mode enabled")
GPU.flip()
end
if a == "b" then
stopWhile = true
break
end
if wipingMode then
if a == "c" then
GPU.print("Wiping C: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("C")
fs.delete("/")
GPU.print("Wipe done.")
GPU.flip()
CPU.sleep(1)
drawInfo()
end
if a == "d" and c == false then
GPU.print("Wiping D: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("D")
fs.delete("/")
GPU.print("Wipe done.")
CPU.sleep(1)
drawInfo()
end
end
end
if event == "touchpressed" then
KB.textinput(true)
end
end
end
attemptBootFromD()
|
Add more options to BIOS Setup
|
Add more options to BIOS Setup
Adding options such as booting from D: and wiping HDDs.
Also fixes keyboard state on mobile.
Former-commit-id: 29093de6f7930fcbdb214242eaeec1fc3d8cd536
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
81b93e510445d182e1c936a38e0e9b9ebbc7f667
|
spec/spec_utils.lua
|
spec/spec_utils.lua
|
local say = require "say"
local types = require "cassandra.types"
local assert = require "luassert.assert"
local string_utils = require "cassandra.utils.string"
local unpack
if _VERSION == "Lua 5.3" then
unpack = table.unpack
else
unpack = _G.unpack
end
local _M = {}
function _M.create_keyspace(session, keyspace)
local res, err = session:execute([[
CREATE KEYSPACE IF NOT EXISTS ]]..keyspace..[[
WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1}
]])
if err then
error(err)
end
return res
end
function _M.drop_keyspace(session, keyspace)
local res, err = session:execute("DROP KEYSPACE "..keyspace)
if err then
error(err)
end
return res
end
local delta = 0.0000001
local function validFixture(state, arguments)
local fixture_type, fixture, decoded = unpack(arguments)
local result
if fixture_type == "float" then
result = math.abs(decoded - fixture) < delta
elseif type(fixture) == "table" then
result = pcall(assert.same, fixture, decoded)
else
result = pcall(assert.equal, fixture, decoded)
end
return result
end
local function sameSet(state, arguments)
local fixture, decoded = unpack(arguments)
for _, x in ipairs(fixture) do
local has = false
for _, y in ipairs(decoded) do
if y == x then
has = true
break
end
end
if not has then
return false
end
end
return true
end
say:set("assertion.sameSet.positive", "Fixture and decoded value do not match")
say:set("assertion.sameSet.negative", "Fixture and decoded value do not match")
assert:register("assertion", "sameSet", sameSet, "assertion.sameSet.positive", "assertion.sameSet.negative")
say:set("assertion.validFixture.positive", "Fixture and decoded value do not match")
say:set("assertion.validFixture.negative", "Fixture and decoded value do not match")
assert:register("assertion", "validFixture", validFixture, "assertion.validFixture.positive", "assertion.validFixture.negative")
_M.cql_fixtures = {
-- custom
ascii = {"Hello world", ""},
bigint = {0, 42, -42, 42000000000, -42000000000},
boolean = {true, false},
-- counter
double = {0, 1.0000000000000004, -1.0000000000000004},
float = {0, 3.14151, -3.14151},
inet = {
"127.0.0.1", "0.0.0.1", "8.8.8.8",
"2001:0db8:85a3:0042:1000:8a2e:0370:7334",
"2001:0db8:0000:0000:0000:0000:0000:0001"
},
int = {0, 4200, -42},
text = {"Hello world", ""},
-- list
-- map
-- set
-- uuid
timestamp = {1405356926},
varchar = {"Hello world", ""},
varint = {0, 4200, -42},
timeuuid = {"1144bada-852c-11e3-89fb-e0b9a54a6d11"}
-- udt
-- tuple
}
_M.cql_list_fixtures = {
{value_type = types.cql_types.text, type_name = "text", value = {"abc", "def"}},
{value_type = types.cql_types.int, type_name = "int", value = {1, 2 , 0, -42, 42}}
}
_M.cql_map_fixtures = {
{
key_type = types.cql_types.text,
key_type_name = "text",
value_type = types.cql_types.text,
value_type_name = "text",
value = {k1 = "v1", k2 = "v2"}
},
{
key_type = types.cql_types.text,
key_type_name = "text",
value_type = types.cql_types.int,
value_type_name = "int",
value = {k1 = 1, k2 = 2}
}
}
_M.cql_set_fixtures = _M.cql_list_fixtures
_M.cql_tuple_fixtures = {
{type = {"text", "text"}, value = {"hello", "world"}},
{type = {"text", "text"}, value = {"world", "hello"}}
}
local HOSTS = os.getenv("HOSTS")
HOSTS = HOSTS and string_utils.split(HOSTS, ",") or {"127.0.0.1"}
local SMALL_LOAD = os.getenv("SMALL_LOAD") ~= nil
_M.hosts = HOSTS
_M.n_inserts = SMALL_LOAD and 1000 or 10000
return _M
|
local say = require "say"
local types = require "cassandra.types"
local assert = require "luassert.assert"
local string_utils = require "cassandra.utils.string"
local unpack
if _VERSION == "Lua 5.3" then
unpack = table.unpack
else
unpack = _G.unpack
end
local _M = {}
function _M.create_keyspace(session, keyspace)
local res, err = session:execute([[
CREATE KEYSPACE IF NOT EXISTS ]]..keyspace..[[
WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1}
]])
if err then
error(err)
end
return res
end
function _M.drop_keyspace(session, keyspace)
local res, err = session:execute("DROP KEYSPACE "..keyspace)
if err then
error(err)
end
return res
end
local delta = 0.0000001
local function validFixture(state, arguments)
local fixture_type, fixture, decoded = unpack(arguments)
local result
if fixture_type == "float" then
result = math.abs(decoded - fixture) < delta
elseif type(fixture) == "table" then
result = pcall(assert.same, fixture, decoded)
else
result = pcall(assert.equal, fixture, decoded)
end
-- pop first argument, for proper output message (like assert.same)
table.remove(arguments, 1)
table.insert(arguments, 1, table.remove(arguments, 2))
return result
end
local function sameSet(state, arguments)
local fixture, decoded = unpack(arguments)
for _, x in ipairs(fixture) do
local has = false
for _, y in ipairs(decoded) do
if y == x then
has = true
break
end
end
if not has then
return false
end
end
return true
end
say:set("assertion.sameSet.positive", "Fixture and decoded value do not match")
say:set("assertion.sameSet.negative", "Fixture and decoded value do not match")
assert:register("assertion", "sameSet", sameSet, "assertion.sameSet.positive", "assertion.sameSet.negative")
say:set("assertion.validFixture.positive", "Expected fixture and decoded value to match.\nPassed in:\n%s\nExpected:\n%s")
say:set("assertion.validFixture.negative", "Expected fixture and decoded value to not match.\nPassed in:\n%s\nExpected:\n%s")
assert:register("assertion", "validFixture", validFixture, "assertion.validFixture.positive", "assertion.validFixture.negative")
_M.cql_fixtures = {
-- custom
ascii = {"Hello world", ""},
bigint = {0, 42, -42, 42000000000, -42000000000},
boolean = {true, false},
-- counter
double = {0, 1.0000000000000004, -1.0000000000000004},
float = {0, 3.14151, -3.14151},
inet = {
"127.0.0.1", "0.0.0.1", "8.8.8.8",
"2001:0db8:85a3:0042:1000:8a2e:0370:7334",
"2001:0db8:0000:0000:0000:0000:0000:0001"
},
int = {0, 4200, -42},
text = {"Hello world", ""},
-- list
-- map
-- set
-- uuid
timestamp = {1405356926},
varchar = {"Hello world", ""},
varint = {0, 4200, -42},
timeuuid = {"1144bada-852c-11e3-89fb-e0b9a54a6d11"}
-- udt
-- tuple
}
_M.cql_list_fixtures = {
{value_type = types.cql_types.text, type_name = "text", value = {"abc", "def"}},
{value_type = types.cql_types.int, type_name = "int", value = {1, 2 , 0, -42, 42}}
}
_M.cql_map_fixtures = {
{
key_type = types.cql_types.text,
key_type_name = "text",
value_type = types.cql_types.text,
value_type_name = "text",
value = {k1 = "v1", k2 = "v2"}
},
{
key_type = types.cql_types.text,
key_type_name = "text",
value_type = types.cql_types.int,
value_type_name = "int",
value = {k1 = 1, k2 = 2}
}
}
_M.cql_set_fixtures = _M.cql_list_fixtures
_M.cql_tuple_fixtures = {
{type = {"text", "text"}, value = {"hello", "world"}},
{type = {"text", "text"}, value = {"world", "hello"}}
}
local HOSTS = os.getenv("HOSTS")
HOSTS = HOSTS and string_utils.split(HOSTS, ",") or {"127.0.0.1"}
local SMALL_LOAD = os.getenv("SMALL_LOAD") ~= nil
_M.hosts = HOSTS
_M.n_inserts = SMALL_LOAD and 1000 or 10000
return _M
|
chore(spec) output of invalid fixture assertions
|
chore(spec) output of invalid fixture assertions
|
Lua
|
mit
|
thibaultCha/lua-cassandra,thibaultCha/lua-cassandra
|
a05a7137d938437cdbcf4f30821eb200acc08ffd
|
premake4.lua
|
premake4.lua
|
-- Gorgon Engine Solution
PROJ_NAME = "Gorgon"
-- Premake OS Constants
WINDOWS = "windows"
LINUX = "linux"
OSX = "macosx"
DEBUG_DEFINES = { "DEBUG" }
DEBUG_FLAGS = { "Symbols" }
RELEASE_DEFINES = { "NDEBUG" }
RELEASE_FLAGS = { "Optimize" }
DEBUG_LIB_DIRS = {}
RELEASE_LIB_DIRS = {}
WINDOWS_X86_DEBUG = "lib/debug/nt/x86"
WINDOWS_X86_RELEASE = "lib/release/nt/x86"
if os.is(WINDOWS) then
DEBUG_LIB_DIRS.insert(WINDOWS_X86_DEBUG)
RELEASE_LIB_DIRS.insert(WINDOWS_X86_RELEASE)
end
elseif os.is(OSX) then
end
elseif os.is(LINUX) then
end
solution(PROJ_NAME)
configurations { "Debug", "Release" }
project(PROJ_NAME)
kind("ConsoleApp")
language("C++")
files { "**.h", "**.cpp" }
links { "logog", "SDL" }
configuration "Debug"
libdirs { DEBUG_LIB_DIRS }
defines { DEBUG_DEFINES }
flags { DEBUG_FLAGS }
configuration "Release"
libdirs { RELEASE_LIB_DIRS }
defines { RELEASE_DEFINES }
flags { RELEASE_FLAGS }
|
-- Gorgon Engine Solution
PROJ_NAME = "Gorgon"
-- Premake OS Constants
WINDOWS = "windows"
LINUX = "linux"
OSX = "macosx"
DEBUG_DEFINES = { "DEBUG" }
DEBUG_FLAGS = { "Symbols" }
RELEASE_DEFINES = { "NDEBUG" }
RELEASE_FLAGS = { "Optimize" }
DEBUG_LIB_DIRS = {}
RELEASE_LIB_DIRS = {}
WINDOWS_X86_DEBUG = "lib/debug/nt/x86"
WINDOWS_X86_RELEASE = "lib/release/nt/x86"
if os.is(WINDOWS) then
table.insert(DEBUG_LIB_DIRS, WINDOWS_X86_DEBUG)
table.insert(RELEASE_LIB_DIRS, WINDOWS_X86_RELEASE)
elseif os.is(OSX) then
elseif os.is(LINUX) then
end
solution(PROJ_NAME)
configurations { "Debug", "Release" }
project(PROJ_NAME)
kind("ConsoleApp")
language("C++")
files { "**.h", "**.cpp" }
links { "logog", "SDL" }
configuration "Debug"
libdirs { DEBUG_LIB_DIRS }
defines { DEBUG_DEFINES }
flags { DEBUG_FLAGS }
configuration "Release"
libdirs { RELEASE_LIB_DIRS }
defines { RELEASE_DEFINES }
flags { RELEASE_FLAGS }
|
Library discovery fix
|
Library discovery fix
The insert method has been fixed to its proper usage when including directories
for library lookups.
|
Lua
|
mit
|
dwsarber/flock,dwsarber/flock
|
b22cce0cc38f359ee65f323eb769181e235b4ae6
|
src/roslua/utils.lua
|
src/roslua/utils.lua
|
----------------------------------------------------------------------------
-- utils.lua - Utilities used in the code
--
-- Created: Thu Jul 29 10:59:22 2010 (at Intel Research, Pittsburgh)
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
--
----------------------------------------------------------------------------
-- Licensed under BSD license
--- General roslua utilities.
-- This module contains useful functions used in roslua.
-- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh
-- @release Released under BSD license
module("roslua.utils", package.seeall)
local asserted_rospack = false
--- Assert availability of rospack.
-- Throws an error if rospack cannot be executed, for example because ROS is
-- not installed or the binary is not in the PATH.
function assert_rospack()
if not asserted_rospack then
local rv = os.execute("rospack 2>/dev/null")
assert(rv == 0, "Cannot find rospack command, must be in PATH")
asserted_rospack = true
end
end
local rospack_path_cache = {}
--- Get path for a package.
-- Uses rospack to find the path to a certain package. The path is cached so
-- that consecutive calls will not trigger another rospack execution, but are
-- rather handled directly from the cache. An error is thrown if the package
-- cannot be found.
-- @return path to give package
function find_rospack(package)
if not rospack_path_cache[package] then
local p = io.popen("rospack find " .. package)
local path = p:read("*a")
-- strip trailing newline
rospack_path_cache[package] = string.gsub(path, "^(.+)\n$", "%1")
p:close()
end
assert(rospack_path_cache[package], "Package path could not be found")
assert(rospack_path_cache[package] ~= "", "Package path could not be found")
return rospack_path_cache[package]
end
--- Split string.
-- Splits a string at a given separator and returns the parts in a table.
-- @param s string to split
-- @param sep separator to split at
-- @return table with splitted parts
function split(s, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
string.gsub(s, pattern, function(c) fields[#fields+1] = c end)
return fields
end
--- Package loader to find Lua modules in ROS packages.
-- This will use the first part of the module name and assume it to
-- be the name of a ROS package. It will then try to determine the path using
-- rospack and if found try to load the module in the package directory.
-- @param module module name as given to require()
-- @return function of loaded code if module was found, nil otherwise
function package_loader(module)
local package = string.match(module, "^[^%.]+")
if not package then return end
local try_paths = { "%s/src/%s.lua", "%s/src/%s/init.lua" }
local errmsg = ""
local ok, packpath = pcall(find_rospack, package)
if ok then
errmsg = errmsg .. string.format("\n\tFound matching ROS package %s (%s)",
package, packpath)
for _, tp in ipairs(try_paths) do
local modulepath = string.gsub(module, "%.", "/")
local filename = string.format(tp, packpath, modulepath)
local file = io.open(filename, "rb")
if file then
-- Compile and return the module
return assert(loadstring(assert(file:read("*a")), filename))
end
errmsg = errmsg .. string.format("\n\tno file %s (ROS loader)", filename)
end
end
return errmsg
end
|
----------------------------------------------------------------------------
-- utils.lua - Utilities used in the code
--
-- Created: Thu Jul 29 10:59:22 2010 (at Intel Research, Pittsburgh)
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
--
----------------------------------------------------------------------------
-- Licensed under BSD license
--- General roslua utilities.
-- This module contains useful functions used in roslua.
-- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh
-- @release Released under BSD license
module("roslua.utils", package.seeall)
local asserted_rospack = false
--- Assert availability of rospack.
-- Throws an error if rospack cannot be executed, for example because ROS is
-- not installed or the binary is not in the PATH.
function assert_rospack()
if not asserted_rospack then
local rv = os.execute("rospack 2>/dev/null")
assert(rv == 0, "Cannot find rospack command, must be in PATH")
asserted_rospack = true
end
end
local rospack_path_cache = {}
--- Get path for a package.
-- Uses rospack to find the path to a certain package. The path is cached so
-- that consecutive calls will not trigger another rospack execution, but are
-- rather handled directly from the cache. An error is thrown if the package
-- cannot be found.
-- @return path to give package
function find_rospack(package)
if not rospack_path_cache[package] then
local p = io.popen("rospack find " .. package)
local path = p:read("*a")
-- strip trailing newline
rospack_path_cache[package] = string.gsub(path, "^(.+)\n$", "%1")
p:close()
end
assert(rospack_path_cache[package], "Package path could not be found")
assert(rospack_path_cache[package] ~= "", "Package path could not be found")
return rospack_path_cache[package]
end
--- Split string.
-- Splits a string at a given separator and returns the parts in a table.
-- @param s string to split
-- @param sep separator to split at
-- @return table with splitted parts
function split(s, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
string.gsub(s, pattern, function(c) fields[#fields+1] = c end)
return fields
end
--- Package loader to find Lua modules in ROS packages.
-- This will use the first part of the module name and assume it to
-- be the name of a ROS package. It will then try to determine the path using
-- rospack and if found try to load the module in the package directory.
-- Additionally it appends the string "_lua" to the package name, thus
-- allowing a module named my_module in the ROS package my_module_lua. This
-- is done to allow to mark Lua ROS packages, but avoid having to have
-- the _lua suffix in module names. The suffixed version takes precedence.
-- @param module module name as given to require()
-- @return function of loaded code if module was found, nil otherwise
function package_loader(module)
local package = string.match(module, "^[^%.]+")
if not package then return end
local try_paths = { "%s/src/%s.lua", "%s/src/%s/init.lua" }
local try_packages = { package .. "_lua", package }
local errmsg = ""
for _, package in ipairs(try_packages) do
local ok, packpath = pcall(find_rospack, package)
if ok then
errmsg = errmsg .. string.format("\n\tFound matching ROS package %s (%s)",
package, packpath)
for _, tp in ipairs(try_paths) do
local modulepath = string.gsub(module, "%.", "/")
local filename = string.format(tp, packpath, modulepath)
local file = io.open(filename, "rb")
if file then
-- Compile and return the module
return assert(loadstring(assert(file:read("*a")), filename))
end
errmsg = errmsg .. string.format("\n\tno file %s (ROS loader)", filename)
end
end
end
return errmsg
end
|
Extend Lua ROS package loader
|
Extend Lua ROS package loader
The ROS Lua package loader now also looks for packages with a _lua suffix
in their name. It is convenient to name ROS packages this way, but usually
not so much to name the Lua package like this.
|
Lua
|
bsd-3-clause
|
timn/roslua
|
fec50ceefea9d5ca16ab60872fa9eb972a445e9b
|
core/debug-output.lua
|
core/debug-output.lua
|
if (not SILE.outputters) then SILE.outputters = {} end
local f
local cx
local cy
SILE.outputters.debug = {
init = function()
print("Set paper size ", SILE.documentState.paperSize[1],SILE.documentState.paperSize[2])
print("Begin page")
end,
newPage = function()
print("New page")
end,
finish = function()
print("End page")
print("Finish")
end,
setColor = function(self, color)
print("Set color", color.r, color.g, color.b)
end,
pushColor = function (self, color)
print("Push color", ("%.4g"):format(color.r), ("%.4g"):format(color.g),("%.4g"):format(color.b))
end,
popColor = function (self)
print("Pop color")
end,
outputHbox = function (value,w)
buf = {}
for i=1,#(value.glyphString) do
buf[#buf+1] = value.glyphString[i]
end
buf = table.concat(buf, " ")
print("T", buf, "("..value.text..")")
end,
setFont = function (options)
if f ~= SILE.font._key(options) then
print("Set font ", SILE.font._key(options))
f = SILE.font._key(options)
end
end,
drawImage = function (src, x,y,w,h)
print("Draw image", src, string.format("%.4f %.4f %.4f %.4f",x, y, w, h))
end,
imageSize = function (src)
local pdf = require("justenoughlibtexpdf");
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
moveTo = function (x,y)
if string.format("%.4f",x) ~= string.format("%.4f",cx) then print("Mx ",string.format("%.4f",x)); cx = x end
if string.format("%.4f",y) ~= string.format("%.4f",cy) then print("My ",string.format("%.4f",y)); cy = y end
end,
rule = function (x,y,w,d)
print("Draw line", x, y, w, d)
end,
debugFrame = function (self,f)
end,
debugHbox = function(typesetter, hbox, scaledWidth)
end
}
SILE.outputter = SILE.outputters.debug
|
if (not SILE.outputters) then SILE.outputters = {} end
local f
local cx
local cy
SILE.outputters.debug = {
init = function()
print("Set paper size ", SILE.documentState.paperSize[1],SILE.documentState.paperSize[2])
print("Begin page")
end,
newPage = function()
print("New page")
end,
finish = function()
print("End page")
print("Finish")
end,
setColor = function(self, color)
print("Set color", color.r, color.g, color.b)
end,
pushColor = function (self, color)
print("Push color", ("%.4g"):format(color.r), ("%.4g"):format(color.g),("%.4g"):format(color.b))
end,
popColor = function (self)
print("Pop color")
end,
outputHbox = function (value,w)
buf = {}
for i=1,#(value.glyphString) do
buf[#buf+1] = value.glyphString[i]
end
buf = table.concat(buf, " ")
print("T", buf, "("..value.text..")")
end,
setFont = function (options)
if f ~= SILE.font._key(options) then
print("Set font ", SILE.font._key(options))
f = SILE.font._key(options)
end
end,
drawImage = function (src, x,y,w,h)
print("Draw image", src, string.format("%.4f %.4f %.4f %.4f",x, y, w, h))
end,
imageSize = function (src)
local pdf = require("justenoughlibtexpdf");
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
moveTo = function (x,y)
if string.format("%.4f",x) ~= string.format("%.4f",cx) then print("Mx ",string.format("%.4f",x)); cx = x end
if string.format("%.4f",y) ~= string.format("%.4f",cy) then print("My ",string.format("%.4f",y)); cy = y end
end,
rule = function (x,y,w,d)
print("Draw line", string.format("%.4f %.4f %.4f %.4f",x, y, w, d))
end,
debugFrame = function (self,f)
end,
debugHbox = function(typesetter, hbox, scaledWidth)
end
}
SILE.outputter = SILE.outputters.debug
|
Fix drawLine debug output for lua 5.3
|
Fix drawLine debug output for lua 5.3
|
Lua
|
mit
|
neofob/sile,neofob/sile,neofob/sile,simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile
|
4a4cce6af80cfa4b19f8319ea6185a32952e924b
|
core/ext/key_commands_std.lua
|
core/ext/key_commands_std.lua
|
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- Defines the key commands used by the Textadept key command manager.
-- For non-ascii keys, see textadept.keys for string aliases.
-- This set of key commands is pretty standard among other text editors.
module('textadept.key_commands_std', package.seeall)
--[[
C: B D H J K L R U
A: A B C D E F G H J K L M N P Q R S T U V W X Y Z
CS: A B C D F G H J K L M N O Q R T U V X Y Z
SA: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CA: A B C D E F G H J K L M N O Q R S T U V W X Y Z
CSA: A B C D E F G H J K L M N O P Q R S T U V W X Y Z
]]--
---
-- Global container that holds all key commands.
-- @class table
-- @name keys
_G.keys = {}
local keys = keys
keys.clear_sequence = 'esc'
local b, v = 'buffer', 'view'
local t = textadept
keys.ct = {} -- Textadept command chain
keys.ct.e = {} -- Enclose in... chain
keys.ct.s = {} -- Select in... chain
keys.ct.v = {} -- Buffer view chain
-- File
keys.cn = { t.new_buffer }
keys.co = { t.io.open }
-- TODO: { 'reload', b }
keys.cs = { 'save', b }
keys.css = { 'save_as', b }
keys.cw = { 'close', b }
keys.csw = { t.io.close_all }
-- TODO: { t.io.load_session } after prompting with open dialog
-- TODO: { t.io.save_session } after prompting with save dialog
-- TODO: quit
-- Edit
local m_editing = _m.textadept.editing
-- Undo is cz.
-- Redo is cy.
-- Cut is cx.
-- Copy is cc.
-- Paste is cv.
-- Delete is delete.
-- Select All is ca.
keys.ce = { m_editing.match_brace }
keys.cse = { m_editing.match_brace, 'select' }
keys['c\n'] = { m_editing.autocomplete_word, '%w_' }
keys.cq = { m_editing.block_comment }
-- TODO: { m_editing.current_word, 'delete' }
-- TODO: { m_editing.transpose_chars }
-- TODO: { m_editing.squeeze }
-- TODO: { m_editing.move_line, 'up' }
-- TODO: { m_editing.move_line, 'down' }
-- TODO: { m_editing.convert_indentation }
-- TODO: { m_editing.smart_cutcopy }
-- TODO: { m_editing.smart_cutcopy, 'copy' }
-- TODO: { m_editing.smart_paste }
-- TODO: { m_editing.smart_paste, 'cycle' }
-- TODO: { m_editing.smart_paste, 'reverse' }
-- TODO: { m_editing.ruby_exec }
-- TODO: { m_editing.lua_exec }
keys.ct.e.t = { m_editing.enclose, 'tag' }
keys.ct.e.st = { m_editing.enclose, 'single_tag' }
keys.ct.e['"'] = { m_editing.enclose, 'dbl_quotes' }
keys.ct.e["'"] = { m_editing.enclose, 'sng_quotes' }
keys.ct.e['('] = { m_editing.enclose, 'parens' }
keys.ct.e['['] = { m_editing.enclose, 'brackets' }
keys.ct.e['{'] = { m_editing.enclose, 'braces' }
keys.ct.e.c = { m_editing.enclose, 'chars' }
keys.ct.e.g = { m_editing.grow_selection, 1 }
keys.ct.s.e = { m_editing.select_enclosed }
keys.ct.s.t = { m_editing.select_enclosed, 'tags' }
keys.ct.s['"'] = { m_editing.select_enclosed, 'dbl_quotes' }
keys.ct.s["'"] = { m_editing.select_enclosed, 'sng_quotes' }
keys.ct.s['('] = { m_editing.select_enclosed, 'parens' }
keys.ct.s['['] = { m_editing.select_enclosed, 'brackets' }
keys.ct.s['{'] = { m_editing.select_enclosed, 'braces' }
keys.ct.s.w = { m_editing.current_word, 'select' }
keys.ct.s.l = { m_editing.select_line }
keys.ct.s.p = { m_editing.select_paragraph }
keys.ct.s.b = { m_editing.select_indented_block }
keys.ct.s.s = { m_editing.select_scope }
-- Search
keys.cf = { t.find.focus } -- find/replace
-- Find Next is an when find pane is focused.
-- Find Prev is ap when find pane is focused.
-- Replace is ar when find pane is focused.
keys.cg = { m_editing.goto_line }
-- Tools
keys['f2'] = { t.command_entry.focus }
-- Snippets
local m_snippets = _m.textadept.lsnippets
keys.ci = { m_snippets.insert }
keys.csi = { m_snippets.prev }
keys.cai = { m_snippets.cancel_current }
keys.casi = { m_snippets.list }
keys.ai = { m_snippets.show_style }
-- Multiple Line Editing
local m_mlines = _m.textadept.mlines
keys.cm = {}
keys.cm.a = { m_mlines.add }
keys.cm.sa = { m_mlines.add_multiple }
keys.cm.r = { m_mlines.remove }
keys.cm.sr = { m_mlines.remove_multiple }
keys.cm.u = { m_mlines.update }
keys.cm.c = { m_mlines.clear }
-- Buffers
keys['c\t'] = { 'goto_buffer', v, 1, false }
keys['cs\t'] = { 'goto_buffer', v, -1, false }
local function toggle_setting(setting)
local state = buffer[setting]
if type(state) == 'boolean' then
buffer[setting] = not state
elseif type(state) == 'number' then
buffer[setting] = buffer[setting] == 0 and 1 or 0
end
t.events.update_ui() -- for updating statusbar
end
keys.ct.v.e = { toggle_setting, 'view_eol' }
keys.ct.v.w = { toggle_setting, 'wrap_mode' }
keys.ct.v.i = { toggle_setting, 'indentation_guides' }
keys.ct.v['\t'] = { toggle_setting, 'use_tabs' }
keys.ct.v[' '] = { toggle_setting, 'view_ws' }
keys['f5'] = { 'colourise', b, 0, -1 }
-- Views
keys['ca\t'] = { t.goto_view, 1, false }
keys['csa\t'] = { t.goto_view, -1, false }
keys.ct.ss = { 'split', v } -- vertical
keys.ct.s = { 'split', v, false } -- horizontal
keys.ct.w = { function() view:unsplit() return true end }
keys.ct.sw = { function() while view:unsplit() do end end }
-- TODO: { function() view.size = view.size + 10 end }
-- TODO: { function() view.size = view.size - 10 end }
-- Project Manager
local function pm_activate(text) t.pm.entry_text = text t.pm.activate() end
keys.csp = { function() if t.pm.width > 0 then t.pm.toggle_visible() end end }
keys.cp = { function()
if t.pm.width == 0 then t.pm.toggle_visible() end
t.pm.focus()
end }
keys.cap = {
c = { pm_activate, 'ctags' },
b = { pm_activate, 'buffers' },
f = { pm_activate, '/' },
-- TODO: { pm_activate, 'macros' }
m = { pm_activate, 'modules' },
}
-- Miscellaneous not in standard menu.
-- Recent files.
local RECENT_FILES = 1
t.events.add_handler('user_list_selection',
function(type, text) if type == RECENT_FILES then t.io.open(text) end end)
keys.ao = { function()
local buffer = buffer
local list = ''
local sep = buffer.auto_c_separator
buffer.auto_c_separator = ('|'):byte()
for _, filename in ipairs(t.io.recent_files) do
list = filename..'|'..list
end
buffer:user_list_show( RECENT_FILES, list:sub(1, -2) )
buffer.auto_c_separator = sep
end }
|
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- Defines the key commands used by the Textadept key command manager.
-- For non-ascii keys, see textadept.keys for string aliases.
-- This set of key commands is pretty standard among other text editors.
module('textadept.key_commands_std', package.seeall)
--[[
C: B D H J K L R U
A: A B C D E F G H J K L M N P Q R S T U V W X Y Z
CS: A B C D F G H J K L M N O Q R T U V X Y Z
SA: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CA: A B C D E F G H J K L M N O Q R S T U V W X Y Z
CSA: A B C D E F G H J K L M N O P Q R S T U V W X Y Z
]]--
---
-- Global container that holds all key commands.
-- @class table
-- @name keys
_G.keys = {}
local keys = keys
keys.clear_sequence = 'esc'
local b, v = 'buffer', 'view'
local t = textadept
keys.ct = {} -- Textadept command chain
-- File
keys.cn = { t.new_buffer }
keys.co = { t.io.open }
-- TODO: { 'reload', b }
keys.cs = { 'save', b }
keys.css = { 'save_as', b }
keys.cw = { 'close', b }
keys.csw = { t.io.close_all }
-- TODO: { t.io.load_session } after prompting with open dialog
-- TODO: { t.io.save_session } after prompting with save dialog
-- TODO: quit
-- Edit
local m_editing = _m.textadept.editing
-- Undo is cz.
-- Redo is cy.
-- Cut is cx.
-- Copy is cc.
-- Paste is cv.
-- Delete is delete.
-- Select All is ca.
keys.ce = { m_editing.match_brace }
keys.cse = { m_editing.match_brace, 'select' }
keys['c\n'] = { m_editing.autocomplete_word, '%w_' }
keys.cq = { m_editing.block_comment }
-- TODO: { m_editing.current_word, 'delete' }
-- TODO: { m_editing.transpose_chars }
-- TODO: { m_editing.squeeze }
-- TODO: { m_editing.move_line, 'up' }
-- TODO: { m_editing.move_line, 'down' }
-- TODO: { m_editing.convert_indentation }
-- TODO: { m_editing.smart_cutcopy }
-- TODO: { m_editing.smart_cutcopy, 'copy' }
-- TODO: { m_editing.smart_paste }
-- TODO: { m_editing.smart_paste, 'cycle' }
-- TODO: { m_editing.smart_paste, 'reverse' }
-- TODO: { m_editing.ruby_exec }
-- TODO: { m_editing.lua_exec }
keys.ac = { -- enClose in...
t = { m_editing.enclose, 'tag' },
st = { m_editing.enclose, 'single_tag' },
['"'] = { m_editing.enclose, 'dbl_quotes' },
["'"] = { m_editing.enclose, 'sng_quotes' },
['('] = { m_editing.enclose, 'parens' },
['['] = { m_editing.enclose, 'brackets' },
['{'] = { m_editing.enclose, 'braces' },
c = { m_editing.enclose, 'chars' },
}
keys.as = { -- select in...
e = { m_editing.select_enclosed },
t = { m_editing.select_enclosed, 'tags' },
['"'] = { m_editing.select_enclosed, 'dbl_quotes' },
["'"] = { m_editing.select_enclosed, 'sng_quotes' },
['('] = { m_editing.select_enclosed, 'parens' },
['['] = { m_editing.select_enclosed, 'brackets' },
['{'] = { m_editing.select_enclosed, 'braces' },
w = { m_editing.current_word, 'select' },
l = { m_editing.select_line },
p = { m_editing.select_paragraph },
b = { m_editing.select_indented_block },
s = { m_editing.select_scope },
g = { m_editing.grow_selection, 1 },
}
-- Search
keys.cf = { t.find.focus } -- find/replace
-- Find Next is an when find pane is focused.
-- Find Prev is ap when find pane is focused.
-- Replace is ar when find pane is focused.
keys.cg = { m_editing.goto_line }
-- Tools
keys['f2'] = { t.command_entry.focus }
-- Snippets
local m_snippets = _m.textadept.lsnippets
keys.ci = { m_snippets.insert }
keys.csi = { m_snippets.prev }
keys.cai = { m_snippets.cancel_current }
keys.casi = { m_snippets.list }
keys.ai = { m_snippets.show_style }
-- Multiple Line Editing
local m_mlines = _m.textadept.mlines
keys.cm = {}
keys.cm.a = { m_mlines.add }
keys.cm.sa = { m_mlines.add_multiple }
keys.cm.r = { m_mlines.remove }
keys.cm.sr = { m_mlines.remove_multiple }
keys.cm.u = { m_mlines.update }
keys.cm.c = { m_mlines.clear }
-- Buffers
keys['c\t'] = { 'goto_buffer', v, 1, false }
keys['ca\t'] = { 'goto_buffer', v, -1, false }
local function toggle_setting(setting)
local state = buffer[setting]
if type(state) == 'boolean' then
buffer[setting] = not state
elseif type(state) == 'number' then
buffer[setting] = buffer[setting] == 0 and 1 or 0
end
t.events.update_ui() -- for updating statusbar
end
keys.ct.v = {
e = { toggle_setting, 'view_eol' },
w = { toggle_setting, 'wrap_mode' },
i = { toggle_setting, 'indentation_guides' },
['\t'] = { toggle_setting, 'use_tabs' },
[' '] = { toggle_setting, 'view_ws' },
}
keys['f5'] = { 'colourise', b, 0, -1 }
-- Views
keys.cv = {
n = { t.goto_view, 1, false },
p = { t.goto_view, -1, false },
ss = { 'split', v }, -- vertical
s = { 'split', v, false }, -- horizontal
w = { function() view:unsplit() return true end },
sw = { function() while view:unsplit() do end end },
-- TODO: { function() view.size = view.size + 10 end }
-- TODO: { function() view.size = view.size - 10 end }
}
-- Project Manager
local function pm_activate(text) t.pm.entry_text = text t.pm.activate() end
keys.csp = { function() if t.pm.width > 0 then t.pm.toggle_visible() end end }
keys.cp = { function()
if t.pm.width == 0 then t.pm.toggle_visible() end
t.pm.focus()
end }
keys.cap = {
c = { pm_activate, 'ctags' },
b = { pm_activate, 'buffers' },
f = { pm_activate, '/' },
-- TODO: { pm_activate, 'macros' }
m = { pm_activate, 'modules' },
}
-- Miscellaneous not in standard menu.
-- Recent files.
local RECENT_FILES = 1
t.events.add_handler('user_list_selection',
function(type, text) if type == RECENT_FILES then t.io.open(text) end end)
keys.ao = { function()
local buffer = buffer
local list = ''
local sep = buffer.auto_c_separator
buffer.auto_c_separator = ('|'):byte()
for _, filename in ipairs(t.io.recent_files) do
list = filename..'|'..list
end
buffer:user_list_show( RECENT_FILES, list:sub(1, -2) )
buffer.auto_c_separator = sep
end }
|
Fixed some conflicting key commands; core/ext/key_commands_std.lua
|
Fixed some conflicting key commands; core/ext/key_commands_std.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
d86fd4212d7427d1a5be6dfb864991c0fd1a4738
|
src/patch/ui/lib/mppatch_modutils.lua
|
src/patch/ui/lib/mppatch_modutils.lua
|
-- Copyright (c) 2015-2016 Lymia Alusyia <[email protected]>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local patch = _mpPatch.patch
function _mpPatch.overrideWithModList(list)
_mpPatch.debugPrint("Overriding mods...")
patch.NetPatch.reset()
for _, mod in ipairs(list) do
local id = mod.ID or mod.ModID
_mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(id, mod.Version).."...")
patch.NetPatch.pushMod(id, mod.Version)
end
patch.NetPatch.overrideModList()
patch.NetPatch.install()
end
function _mpPatch.overrideModsFromActivatedList()
local modList = Modding.GetActivatedMods()
if modList and #modList > 0 then
_mpPatch.overrideWithModList(modList)
end
end
function _mpPatch.overrideModsFromPreGame()
local modList = _mpPatch.decodeModsList()
if modList and _mpPatch.isModding then
_mpPatch.overrideWithModList(modList)
end
end
_mpPatch._mt.registerProperty("areModsEnabled", function()
return #Modding.GetActivatedMods() > 0
end)
function _mpPatch.getModName(uuid, version)
local details = Modding.GetInstalledModDetails(uuid, version) or {}
return details.Name or "<unknown mod "..uuid.." v"..version..">"
end
_mpPatch._mt.registerLazyVal("installedMods", function()
local installed = {}
for _, v in pairs(Modding.GetInstalledMods()) do
installed[v.ID.."_"..v.Version] = true
end
return installed
end)
function _mpPatch.isModInstalled(uuid, version)
return not not _mpPatch.installedMods[uuid.."_"..version]
end
-- Mod dependency listing
function _mpPatch.normalizeDlcName(name)
return name:gsub("-", ""):upper()
end
function _mpPatch.getModDependencies(modList)
local dlcDependencies = {}
for row in GameInfo.DownloadableContent() do
dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)] = {}
end
for _, mod in ipairs(modList) do
local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) }
for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do
if assoc.Type == 2 then
if assoc.PackageID == "*" then
for row in GameInfo.DownloadableContent() do
table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info)
end
else
local normName = _mpPatch.normalizeDlcName(assoc.PackageID)
if dlcDependencies[normName] then
table.insert(dlcDependencies[normName], info)
end
end
end
end
end
return dlcDependencies
end
-- UUID encoding/decoding for storing a mod list in PreGame's options table
local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8)
local function encodeUUID(uuidString)
uuidString = uuidString:gsub("-", "")
local uuids = {uuidString:match(uuidRegex)}
if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end
return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end)
end
local function decodeUUID(table)
return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table))
end
-- Enroll/decode mods into the PreGame option table
_mpPatch._mt.registerProperty("isModding", function()
return _mpPatch.getGameOption("HAS_MODS") == 1
end)
local function enrollModName(id, name)
_mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name)
for i=1,#name do
_mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i))
end
end
local function enrollMod(id, uuid, version)
local modName = _mpPatch.getModName(uuid, version)
_mpPatch.debugPrint("- Enrolling mod "..modName)
_mpPatch.setGameOption("MOD_"..id.."_VERSION", version)
for i, v in ipairs(encodeUUID(uuid)) do
_mpPatch.setGameOption("MOD_"..id.."_"..i, v)
end
enrollModName(id, modName)
end
function _mpPatch.enrollModsList(modList)
_mpPatch.debugPrint("Enrolling mods...")
if #modList > 0 then
_mpPatch.setGameOption("HAS_MODS", 1)
_mpPatch.setGameOption("MOD_COUNT", #modList)
for i, v in ipairs(modList) do
enrollMod(i, v.ID, v.Version)
end
else
_mpPatch.setGameOption("HAS_MODS", 0)
end
end
local function decodeModName(id)
local charTable = {}
for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do
charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i))
end
return table.concat(charTable)
end
local function decodeMod(id)
local uuidTable = {}
for i=1,8 do
uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i)
end
return {
ID = decodeUUID(uuidTable),
Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"),
Name = decodeModName(id)
}
end
function _mpPatch.decodeModsList()
if not _mpPatch.isModding then return nil end
local modList = {}
for i=1,_mpPatch.getGameOption("MOD_COUNT") do
modList[i] = decodeMod(i)
end
return modList
end
|
-- Copyright (c) 2015-2016 Lymia Alusyia <[email protected]>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local patch = _mpPatch.patch
function _mpPatch.overrideWithModList(list)
_mpPatch.debugPrint("Overriding mods...")
patch.NetPatch.reset()
for _, mod in ipairs(list) do
local id = mod.ID or mod.ModID
_mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(id, mod.Version).."...")
patch.NetPatch.pushMod(id, mod.Version)
end
patch.NetPatch.overrideModList()
patch.NetPatch.install()
end
function _mpPatch.overrideModsFromActivatedList()
local modList = Modding.GetActivatedMods()
if modList and #modList > 0 then
_mpPatch.overrideWithModList(modList)
end
end
function _mpPatch.overrideModsFromPreGame()
local modList = _mpPatch.decodeModsList()
if modList and _mpPatch.isModding then
_mpPatch.overrideWithModList(modList)
end
end
_mpPatch._mt.registerProperty("areModsEnabled", function()
return #Modding.GetActivatedMods() > 0
end)
function _mpPatch.getModName(uuid, version)
local details = Modding.GetInstalledModDetails(uuid, version) or {}
return details.Name or "<unknown mod "..uuid.." v"..version..">"
end
_mpPatch._mt.registerLazyVal("installedMods", function()
local installed = {}
for _, v in pairs(Modding.GetInstalledMods()) do
installed[v.ID.."_"..v.Version] = true
end
return installed
end)
function _mpPatch.isModInstalled(uuid, version)
return not not _mpPatch.installedMods[uuid.."_"..version]
end
-- Mod dependency listing
function _mpPatch.normalizeDlcName(name)
return name:gsub("-", ""):upper()
end
function _mpPatch.getModDependencies(modList)
local dlcDependencies = {}
for _, mod in ipairs(modList) do
local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) }
for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do
if assoc.Type == 2 then
if assoc.PackageID == "*" then
for row in GameInfo.DownloadableContent() do
table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info)
end
else
local normName = _mpPatch.normalizeDlcName(assoc.PackageID)
if not dlcDependencies[normName] then
dlcDependencies[normName] = {}
end
table.insert(dlcDependencies[normName], info)
end
end
end
end
return dlcDependencies
end
-- UUID encoding/decoding for storing a mod list in PreGame's options table
local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8)
local function encodeUUID(uuidString)
uuidString = uuidString:gsub("-", "")
local uuids = {uuidString:match(uuidRegex)}
if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end
return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end)
end
local function decodeUUID(table)
return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table))
end
-- Enroll/decode mods into the PreGame option table
_mpPatch._mt.registerProperty("isModding", function()
return _mpPatch.getGameOption("HAS_MODS") == 1
end)
local function enrollModName(id, name)
_mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name)
for i=1,#name do
_mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i))
end
end
local function enrollMod(id, uuid, version)
local modName = _mpPatch.getModName(uuid, version)
_mpPatch.debugPrint("- Enrolling mod "..modName)
_mpPatch.setGameOption("MOD_"..id.."_VERSION", version)
for i, v in ipairs(encodeUUID(uuid)) do
_mpPatch.setGameOption("MOD_"..id.."_"..i, v)
end
enrollModName(id, modName)
end
function _mpPatch.enrollModsList(modList)
_mpPatch.debugPrint("Enrolling mods...")
if #modList > 0 then
_mpPatch.setGameOption("HAS_MODS", 1)
_mpPatch.setGameOption("MOD_COUNT", #modList)
for i, v in ipairs(modList) do
enrollMod(i, v.ID, v.Version)
end
else
_mpPatch.setGameOption("HAS_MODS", 0)
end
end
local function decodeModName(id)
local charTable = {}
for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do
charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i))
end
return table.concat(charTable)
end
local function decodeMod(id)
local uuidTable = {}
for i=1,8 do
uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i)
end
return {
ID = decodeUUID(uuidTable),
Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"),
Name = decodeModName(id)
}
end
function _mpPatch.decodeModsList()
if not _mpPatch.isModding then return nil end
local modList = {}
for i=1,_mpPatch.getGameOption("MOD_COUNT") do
modList[i] = decodeMod(i)
end
return modList
end
|
Fix mod dependencies for non-installed DLC.
|
Fix mod dependencies for non-installed DLC.
|
Lua
|
mit
|
Lymia/CivV_Mod2DLC,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch
|
6a5e8d4d74bb767a307c4548eea831c814fc640e
|
mods/sponge/init.lua
|
mods/sponge/init.lua
|
minetest.register_node("sponge:sponge", {
description = "Sponge Dry",
drawtype = "normal",
tiles = {"sponge_sponge.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3},
after_place_node = function(pos, placer, itemstack, pointed_thing)
local pn = placer:get_player_name()
if pointed_thing.type ~= "node" then
return
end
if minetest.is_protected(pointed_thing.above, pn) then
return
end
local change = false
local on_water = false
-- verifier si il est dans l'eau ou a cotée
if string.find(minetest.get_node(pointed_thing.above).name, "water_source")
or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then
on_water = true
end
for i=-1,1 do
p = {x=pos.x+i, y=pos.y, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y+i, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y, z=pos.z+i}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source") then
on_water = true
end
end
if on_water == true then
for i=-3,3 do
for j=-3,3 do
for k=-3,3 do
p = {x=pos.x+i, y=pos.y+j, z=pos.z+k}
n = minetest.get_node(p)
-- On Supprime l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")then
minetest.add_node(p, {name="air"})
change = true
end
end
end
end
end
if change then
minetest.add_node(pos, {name = "sponge:sponge_wet"})
end
end
})
minetest.register_node("sponge:sponge_wet", {
description = "Wet Sponge",
drawtype = "normal",
tiles = {"sponge_sponge_wet.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3},
})
-- Sponge wet back to Sponge Dry if coocked in a furnace
minetest.register_craft({
type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet",
})
minetest.register_craft({
output = "sponge:sponge",
recipe = {
{"", "dye:black", ""},
{"dye:yellow", "wool:white", "dye:yellow"},
{"", "farming:wheat", ""},
},
})
|
minetest.register_node("sponge:sponge", {
description = "Sponge Dry",
drawtype = "normal",
tiles = {"sponge_sponge.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3},
after_place_node = function(pos, placer, itemstack, pointed_thing)
local pn = placer:get_player_name()
if pointed_thing.type ~= "node" then
return
end
if minetest.is_protected(pointed_thing.above, pn) then
return
end
local change = false
local on_water = false
-- verifier si il est dans l'eau ou a cotée
if string.find(minetest.get_node(pointed_thing.above).name, "water_source")
or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then
on_water = true
end
for i=-1,1 do
p = {x=pos.x+i, y=pos.y, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y+i, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y, z=pos.z+i}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
if on_water == true then
for i=-3,3 do
for j=-3,3 do
for k=-3,3 do
p = {x=pos.x+i, y=pos.y+j, z=pos.z+k}
n = minetest.get_node(p)
-- On Supprime l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
minetest.add_node(p, {name="air"})
change = true
end
end
end
end
end
if change then
minetest.add_node(pos, {name = "sponge:sponge_wet"})
end
end
})
minetest.register_node("sponge:sponge_wet", {
description = "Wet Sponge",
drawtype = "normal",
tiles = {"sponge_sponge_wet.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3},
})
-- Sponge wet back to Sponge Dry if coocked in a furnace
minetest.register_craft({
type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet",
})
minetest.register_craft({
output = "sponge:sponge",
recipe = {
{"", "dye:black", ""},
{"dye:yellow", "wool:white", "dye:yellow"},
{"", "farming:wheat", ""},
},
})
|
[sponge] Improve spong - Make sponges able to suck river water - Fix #281
|
[sponge] Improve spong
- Make sponges able to suck river water
- Fix #281
|
Lua
|
unlicense
|
LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server
|
a57e6e7afac22cb514f05576e571469837537525
|
examples/pcap/replay-pcap.lua
|
examples/pcap/replay-pcap.lua
|
--- Replay a pcap file.
local mg = require "moongen"
local device = require "device"
local memory = require "memory"
local stats = require "stats"
local log = require "log"
local pcap = require "pcap"
local limiter = require "software-ratecontrol"
function configure(parser)
parser:argument("dev", "Device to use."):args(1):convert(tonumber)
parser:argument("file", "File to replay."):args(1)
parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier")
parser:flag("-l --loop", "Repeat pcap file.")
local args = parser:parse()
return args
end
function master(args)
local dev = device.config{port = args.dev}
device.waitForLinks()
local rateLimiter
if args.rateMultiplier > 0 then
rateLimiter = limiter:new(dev:getTxQueue(0), "custom")
end
mg.startTask("replay", dev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier)
stats.startStatsTask{txDevices = {dev}}
mg.waitForTasks()
end
function replay(queue, file, loop, rateLimiter, multiplier)
local mempool = memory:createMemPool(4096)
local bufs = mempool:bufArray()
local pcapFile = pcap:newReader(file)
local prev = 0
local linkSpeed = queue.dev:getLinkStatus().speed
while mg.running() do
local n = pcapFile:read(bufs)
if n > 0 then
if rateLimiter ~= nil then
if prev == 0 then
prev = bufs.array[0].udata64
end
for i, buf in ipairs(bufs) do
-- ts is in microseconds
local ts = buf.udata64
if prev > ts then
ts = prev
end
local delay = ts - prev
delay = tonumber(delay * 10^3) / multiplier -- nanoseconds
delay = delay / (8000 / linkSpeed) -- delay in bytes
buf:setDelay(delay)
prev = ts
end
end
else
if loop then
pcapFile:reset()
else
break
end
end
if rateLimiter then
rateLimiter:sendN(bufs, n)
else
queue:sendN(bufs, n)
end
end
end
|
--- Replay a pcap file.
local mg = require "moongen"
local device = require "device"
local memory = require "memory"
local stats = require "stats"
local log = require "log"
local pcap = require "pcap"
local limiter = require "software-ratecontrol"
function configure(parser)
parser:argument("dev", "Device to use."):args(1):convert(tonumber)
parser:argument("file", "File to replay."):args(1)
parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier")
parser:flag("-l --loop", "Repeat pcap file.")
local args = parser:parse()
return args
end
function master(args)
local dev = device.config{port = args.dev}
device.waitForLinks()
local rateLimiter
if args.rateMultiplier > 0 then
rateLimiter = limiter:new(dev:getTxQueue(0), "custom")
end
mg.startTask("replay", dev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier)
stats.startStatsTask{txDevices = {dev}}
mg.waitForTasks()
end
function replay(queue, file, loop, rateLimiter, multiplier)
local mempool = memory:createMemPool(4096)
local bufs = mempool:bufArray()
local pcapFile = pcap:newReader(file)
local prev = 0
local linkSpeed = queue.dev:getLinkStatus().speed
while mg.running() do
local n = pcapFile:read(bufs)
if n > 0 then
if rateLimiter ~= nil then
if prev == 0 then
prev = bufs.array[0].udata64
end
for i = 1, n do
local buf = bufs[i]
-- ts is in microseconds
local ts = buf.udata64
if prev > ts then
ts = prev
end
local delay = ts - prev
delay = tonumber(delay * 10^3) / multiplier -- nanoseconds
delay = delay / (8000 / linkSpeed) -- delay in bytes
buf:setDelay(delay)
prev = ts
end
end
else
if loop then
pcapFile:reset()
else
break
end
end
if rateLimiter then
rateLimiter:sendN(bufs, n)
else
queue:sendN(bufs, n)
end
end
end
|
replay-pcap: fix out-of-bounds read
|
replay-pcap: fix out-of-bounds read
|
Lua
|
mit
|
emmericp/MoonGen,emmericp/MoonGen,emmericp/MoonGen
|
d6cc8032bb4c49580f8f41dee4a4993b39336ed5
|
src/lounge/lua/mpv.lua
|
src/lounge/lua/mpv.lua
|
#!/lounge/bin/janosh -f
local util = require("util")
local helper = require("helpers")
Janosh:set("/player/active", "false")
Janosh:set("/player/paused", "false")
--Janosh:setenv("VDPAU_OSD","1")
Janosh:setenv("DISPLAY",":0")
Janosh:system("killall -9 mpv")
local MPID, MSTDIN, MSTDOUT, MSTDERR = Janosh:popen("mpv", "-idle", "--input-unix-socket", "/tmp/mpv.socket")
Janosh:pclose(MSTDIN)
Janosh:sleep(3000)
local S1PID, S1STDIN, S1STDOUT, S1STDERR = Janosh:popen("/usr/bin/socat", "-", "/tmp/mpv.socket")
Janosh:pclose(S1STDERR)
-- unset causes wierd errors
local MpvClass = {} -- the table representing the class, which will double as the metatable for the instances
MpvClass.__index = MpvClass -- failed table lookups on the instances should fallback to the class table, to get methods
function MpvClass.new()
return setmetatable({}, MpvClass)
end
function MpvClass.jump(self, idx)
print("jump:", idx)
Janosh:publish("shairportStop","W", "")
obj = Janosh:get("/playlist/items/.")
idx = tonumber(idx);
lua_idx = idx + 1;
if lua_idx > #obj then
lua_idx = #obj
end
videoUrl = obj[lua_idx].url
title = obj[lua_idx].title
if string.match(videoUrl, "http[s]*://") then
p, i, o, e = Janosh:popen("curl", "--head", videoUrl)
line=Janosh:preadLine(o)
if line == nil then
util:exception("Can't fix item:" .. idx)
return
end
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
token=util:split(line," ")[2]
code=tonumber(token)
if code ~= 200 and code ~= 302 then
Janosh:transaction(function()
src = Janosh:get("/playlist/items/#" .. idx .. "/source").items[1].source
title = Janosh:get("/playlist/items/#" .. idx .. "/title").items[1].title
util:notify("Fixing cached item:" .. title)
items = helper:resolve(src,"youtube");
for t, v in pairs(items) do
title=t
videoUrl=v
break;
end
print("TITLE", t)
Janosh:set("/playlist/items/#" .. idx .. "/url", videoUrl)
end)
end
end
print("VIDEOURL2", videoUrl)
Janosh:transaction(function()
Janosh:set_t("/player/active", "true")
util:notifyLong(title)
print("LOAD", idx)
self:cmd("loadfile", videoUrl)
Janosh:set_t("/playlist/index", idx)
self:play();
end)
end
function MpvClass.previous(self)
util:notify("previous")
self:jump(tonumber(Janosh:get("/playlist/index").index) - 1)
end
function MpvClass.next(self)
util:notify("next")
self:jump(tonumber(Janosh:get("/playlist/index").index) + 1)
end
function MpvClass.seek(self, seconds)
self:cmd("seek", seconds, "absolute")
end
function MpvClass.enqueue(self, videoUrl, title, srcUrl)
util:notify("Queued: " .. title)
if title == "" then
title = "(no title)"
end
size = Janosh:size("/playlist/items/.")
Janosh:mkobj_t("/playlist/items/#" .. size .. "/.")
Janosh:set_t("/playlist/items/#" .. size .. "/url", videoUrl)
Janosh:set_t("/playlist/items/#" .. size .. "/title", title)
Janosh:set_t("/playlist/items/#" .. size .. "/source", srcUrl)
print("enqueuend")
end
function MpvClass.add(self, videoUrl, title, srcUrl)
self:enqueue(videoUrl, title, srcUrl)
if Janosh:get("/player/active").active == "false" then
self:jump(10000000) -- jump to the ned of the playlist
end
end
function MpvClass.run(self)
print("run")
Janosh:thread(function()
while true do
line=""
pos=""
len=""
while true do
line = Janosh:preadLine(MSTDERR)
-- print("STDERR:", line)
if line == nil then break end
tokens = util:split(line, " ")
if #tokens >= 4 and (tokens[2] ~= pos or tokens[4] ~= len) then
info = {}
info[1] = tokens[2]
pos = tokens[2]
info[2] = tokens[4]
len = tokens[4]
Janosh:publish("playerTimePos","W",JSON:encode(info))
end
end
Janosh:sleep(1000)
end
end)()
Janosh:thread(function()
while true do
line=""
while true do
line = Janosh:preadLine(S1STDOUT)
print("RECEIVED:", line)
if line == nil then break end
obj = JSON:decode(line)
if obj.event == "idle" then
self:onIdle()
elseif obj.event == "playback-restart" then
-- self:sotrack()
-- elseif string.find(line, CACHEEMPTY) then
-- self:cache_empty()
-- elseif string.find(line, TIMEPOS) then
-- times=util:split(line:gsub(TIMEPOS,""), "/")
-- Janosh:publish("playerTimePos", "W", JSON:encode(times))
end
end
Janosh:sleep(1000)
end
end)()
while true do
line=""
while true do
line = Janosh:preadLine(MSTDOUT)
if line == nil then break end
print("STDOUT", line)
end
Janosh:sleep(1000)
end
end
function MpvClass.cmd(self, ...)
local arg={...}
print("cmd:", unpack(arg))
obj = {}
obj["command"] = {}
for i, a in ipairs(arg) do
obj["command"][i]=a
end
print(JSON:encode(obj))
Janosh:pwrite(S1STDIN, JSON:encode(obj) .. "\n")
end
function MpvClass.forward(self)
util:notify("Forward")
self:cmd("seek", "10")
end
function MpvClass.forwardMore(self)
util:notify("Forward more")
self:cmd("seek", "60")
end
function MpvClass.rewind(self)
util:notify("Rewind")
self:cmd("seek", "-10")
end
function MpvClass.rewindMore(self)
util:notify("Rewind more")
self:cmd("seek", "-60")
end
function MpvClass.pause(self)
util:notify("Pause")
self:cmd("set_property","pause",true)
Janosh:set_t("/player/paused", "true")
end
function MpvClass.play(self)
util:notify("Play")
self:cmd("set_property","pause",false)
Janosh:set_t("/player/paused", "false")
end
function MpvClass.cache_empty(self)
Janosh:publish("notifySend", "Network Problem!")
end
function MpvClass.onIdle(self)
print("onIdle")
obj = Janosh:get("/playlist/.")
idx = tonumber(obj.index)
len = #obj.items
if idx + 1 < len then
Janosh:publish("backgroundRefresh", "W", "")
self:jump(tostring(idx + 1))
else
Janosh:publish("backgroundRefresh", "W", "")
Janosh:set_t("/player/active","false")
end
end
function MpvClass.loadFile(self,path)
Janosh:set_t("/player/active", "true")
self:cmd("loadfile ", path)
end
return MpvClass:new()
|
#!/lounge/bin/janosh -f
local util = require("util")
local helper = require("helpers")
Janosh:set("/player/active", "false")
Janosh:set("/player/paused", "false")
--Janosh:setenv("VDPAU_OSD","1")
Janosh:setenv("DISPLAY",":0")
Janosh:system("killall -9 mpv")
local MPID, MSTDIN, MSTDOUT, MSTDERR = Janosh:popen("mpv", "-idle", "--input-unix-socket", "/tmp/mpv.socket")
Janosh:pclose(MSTDIN)
Janosh:sleep(3000)
local S1PID, S1STDIN, S1STDOUT, S1STDERR = Janosh:popen("/usr/bin/socat", "-", "/tmp/mpv.socket")
Janosh:pclose(S1STDERR)
-- unset causes wierd errors
local MpvClass = {} -- the table representing the class, which will double as the metatable for the instances
MpvClass.__index = MpvClass -- failed table lookups on the instances should fallback to the class table, to get methods
function MpvClass.new()
return setmetatable({}, MpvClass)
end
function MpvClass.jump(self, idx)
print("jump:", idx)
Janosh:publish("shairportStop","W", "")
obj = Janosh:get("/playlist/items/.")
idx = tonumber(idx);
lua_idx = idx + 1;
print("IDX:", lua_idx, #obj)
if lua_idx > #obj then
lua_idx = #obj
idx = #obj - 1
end
videoUrl = obj[lua_idx].url
title = obj[lua_idx].title
if string.match(videoUrl, "http[s]*://") then
p, i, o, e = Janosh:popen("curl", "--head", videoUrl)
line=Janosh:preadLine(o)
if line == nil then
util:exception("Can't fix item:" .. idx)
return
end
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
token=util:split(line," ")[2]
code=tonumber(token)
if code ~= 200 and code ~= 302 then
Janosh:transaction(function()
src = Janosh:get("/playlist/items/#" .. idx .. "/source").items[1].source
title = Janosh:get("/playlist/items/#" .. idx .. "/title").items[1].title
util:notify("Fixing cached item:" .. title)
items = helper:resolve(src,"youtube");
for t, v in pairs(items) do
title=t
videoUrl=v
break;
end
print("TITLE", t)
Janosh:set("/playlist/items/#" .. idx .. "/url", videoUrl)
end)
end
end
print("VIDEOURL2", videoUrl)
Janosh:transaction(function()
Janosh:set_t("/player/active", "true")
util:notifyLong(title)
print("LOAD", idx)
self:cmd("loadfile", videoUrl)
Janosh:set_t("/playlist/index", idx)
self:play();
end)
end
function MpvClass.previous(self)
util:notify("previous")
self:jump(tonumber(Janosh:get("/playlist/index").index) - 1)
end
function MpvClass.next(self)
util:notify("next")
self:jump(tonumber(Janosh:get("/playlist/index").index) + 1)
end
function MpvClass.seek(self, seconds)
self:cmd("seek", seconds, "absolute")
end
function MpvClass.enqueue(self, videoUrl, title, srcUrl)
util:notify("Queued: " .. title)
if title == "" then
title = "(no title)"
end
size = Janosh:size("/playlist/items/.")
Janosh:mkobj_t("/playlist/items/#" .. size .. "/.")
Janosh:set_t("/playlist/items/#" .. size .. "/url", videoUrl)
Janosh:set_t("/playlist/items/#" .. size .. "/title", title)
Janosh:set_t("/playlist/items/#" .. size .. "/source", srcUrl)
print("enqueuend")
end
function MpvClass.add(self, videoUrl, title, srcUrl)
self:enqueue(videoUrl, title, srcUrl)
if Janosh:get("/player/active").active == "false" then
self:jump(10000000) -- jump to the end of the playlist
end
end
function MpvClass.run(self)
print("run")
Janosh:thread(function()
while true do
line=""
pos=""
len=""
while true do
line = Janosh:preadLine(MSTDERR)
-- print("STDERR:", line)
if line == nil then break end
tokens = util:split(line, " ")
if #tokens >= 4 and (tokens[2] ~= pos or tokens[4] ~= len) then
info = {}
info[1] = tokens[2]
pos = tokens[2]
info[2] = tokens[4]
len = tokens[4]
Janosh:publish("playerTimePos","W",JSON:encode(info))
end
end
Janosh:sleep(1000)
end
end)()
Janosh:thread(function()
while true do
line=""
while true do
line = Janosh:preadLine(S1STDOUT)
print("RECEIVED:", line)
if line == nil then break end
obj = JSON:decode(line)
if obj.event == "idle" then
self:onIdle()
elseif obj.event == "playback-restart" then
-- self:sotrack()
-- elseif string.find(line, CACHEEMPTY) then
-- self:cache_empty()
-- elseif string.find(line, TIMEPOS) then
-- times=util:split(line:gsub(TIMEPOS,""), "/")
-- Janosh:publish("playerTimePos", "W", JSON:encode(times))
end
end
Janosh:sleep(1000)
end
end)()
while true do
line=""
while true do
line = Janosh:preadLine(MSTDOUT)
if line == nil then break end
print("STDOUT", line)
end
Janosh:sleep(1000)
end
end
function MpvClass.cmd(self, ...)
local arg={...}
print("cmd:", unpack(arg))
obj = {}
obj["command"] = {}
for i, a in ipairs(arg) do
obj["command"][i]=a
end
print(JSON:encode(obj))
Janosh:pwrite(S1STDIN, JSON:encode(obj) .. "\n")
end
function MpvClass.forward(self)
util:notify("Forward")
self:cmd("seek", "10")
end
function MpvClass.forwardMore(self)
util:notify("Forward more")
self:cmd("seek", "60")
end
function MpvClass.rewind(self)
util:notify("Rewind")
self:cmd("seek", "-10")
end
function MpvClass.rewindMore(self)
util:notify("Rewind more")
self:cmd("seek", "-60")
end
function MpvClass.pause(self)
util:notify("Pause")
self:cmd("set_property","pause",true)
Janosh:set_t("/player/paused", "true")
end
function MpvClass.play(self)
util:notify("Play")
self:cmd("set_property","pause",false)
Janosh:set_t("/player/paused", "false")
end
function MpvClass.cache_empty(self)
Janosh:publish("notifySend", "Network Problem!")
end
function MpvClass.onIdle(self)
print("onIdle")
obj = Janosh:get("/playlist/.")
idx = tonumber(obj.index)
len = #obj.items
if idx + 1 < len then
Janosh:publish("backgroundRefresh", "W", "")
self:jump(tostring(idx + 1))
else
Janosh:publish("backgroundRefresh", "W", "")
Janosh:set_t("/player/active","false")
end
end
function MpvClass.loadFile(self,path)
Janosh:set_t("/player/active", "true")
self:cmd("loadfile ", path)
end
return MpvClass:new()
|
fix bug in playlist handling
|
fix bug in playlist handling
|
Lua
|
agpl-3.0
|
screeninvader/ScreenInvader,screeninvader/ScreenInvader
|
96c3b953e5071c274272abe7f107a8528686e7f1
|
notion/cfg_tiling.lua
|
notion/cfg_tiling.lua
|
--
-- Notion tiling module configuration file
--
-- Bindings for the tilings.
defbindings("WTiling", {
bdoc("Go to frame right of current frame."),
kpress(META.."Right", "ioncore.goto_next(_sub, 'right')"),
bdoc("Go to frame left of current frame."),
kpress(META.."Left", "ioncore.goto_next(_sub, 'left')"),
bdoc("Go to frame above current frame."),
kpress(META.."Up", "ioncore.goto_next(_sub, 'up', {no_ascend=_})"),
bdoc("Go to frame below current frame."),
kpress(META.."Down", "ioncore.goto_next(_sub, 'down', {no_ascend=_})"),
bdoc("Split current frame vertically."),
kpress(META.."minus", "WTiling.split_at(_, _sub, 'bottom', true)"),
bdoc("Split current frame horizontally."),
kpress(META.."Shift+backslash", "WTiling.split_at(_, _sub, 'right', true)"),
bdoc("Destroy current frame."),
kpress(META.."Shift+equal", "WTiling.unsplit_at(_, _sub)"),
})
-- Frame bindings.
defbindings("WFrame.floating", {
submap(META.."K", {
bdoc("Tile frame, if no tiling exists on the workspace"),
kpress("B", "mod_tiling.mkbottom(_)"),
}),
})
-- Context menu for tiled workspaces.
defctxmenu("WTiling", "Tiling", {
menuentry("Destroy frame",
"WTiling.unsplit_at(_, _sub)"),
menuentry("Split vertically",
"WTiling.split_at(_, _sub, 'bottom', true)"),
menuentry("Split horizontally",
"WTiling.split_at(_, _sub, 'right', true)"),
menuentry("Flip", "WTiling.flip_at(_, _sub)"),
menuentry("Transpose", "WTiling.transpose_at(_, _sub)"),
menuentry("Untile", "mod_tiling.untile(_)"),
submenu("Float split", {
menuentry("At left",
"WTiling.set_floating_at(_, _sub, 'toggle', 'left')"),
menuentry("At right",
"WTiling.set_floating_at(_, _sub, 'toggle', 'right')"),
menuentry("Above",
"WTiling.set_floating_at(_, _sub, 'toggle', 'up')"),
menuentry("Below",
"WTiling.set_floating_at(_, _sub, 'toggle', 'down')"),
}),
submenu("At root", {
menuentry("Split vertically",
"WTiling.split_top(_, 'bottom')"),
menuentry("Split horizontally",
"WTiling.split_top(_, 'right')"),
menuentry("Flip", "WTiling.flip_at(_)"),
menuentry("Transpose", "WTiling.transpose_at(_)"),
}),
})
-- Extra context menu extra entries for floatframes.
defctxmenu("WFrame.floating", "Floating frame", {
append=true,
menuentry("New tiling", "mod_tiling.mkbottom(_)"),
})
|
--
-- Notion tiling module configuration file
--
-- Bindings for the tilings.
defbindings("WTiling", {
bdoc("Go to frame right of current frame."),
kpress(META.."Right", "ioncore.goto_next(_sub, 'right')"),
bdoc("Go to frame left of current frame."),
kpress(META.."Left", "ioncore.goto_next(_sub, 'left')"),
bdoc("Go to frame above current frame."),
kpress(META.."Up", "ioncore.goto_next(_sub, 'up', {no_ascend=_})"),
bdoc("Go to frame below current frame."),
kpress(META.."Down", "ioncore.goto_next(_sub, 'down', {no_ascend=_})"),
bdoc("Split current frame vertically."),
kpress(META.."bracketright", "WTiling.split_at(_, _sub, 'bottom', true)"),
bdoc("Split current frame horizontally."),
kpress(META.."bracketleft", "WTiling.split_at(_, _sub, 'right', true)"),
bdoc("Split screen vertically."),
kpress(META.."Shift+bracketright", "WTiling.split_top(_, 'bottom')"),
bdoc("Split screen horizontally."),
kpress(META.."Shift+bracketleft", "WTiling.split_top(_, 'right')"),
bdoc("Destroy current frame."),
kpress(META.."Shift+apostrophe", "WTiling.unsplit_at(_, _sub)"),
})
-- Frame bindings.
defbindings("WFrame.floating", {
submap(META.."K", {
bdoc("Tile frame, if no tiling exists on the workspace"),
kpress("B", "mod_tiling.mkbottom(_)"),
}),
})
-- Context menu for tiled workspaces.
defctxmenu("WTiling", "Tiling", {
menuentry("Destroy frame",
"WTiling.unsplit_at(_, _sub)"),
menuentry("Split vertically",
"WTiling.split_at(_, _sub, 'bottom', true)"),
menuentry("Split horizontally",
"WTiling.split_at(_, _sub, 'right', true)"),
menuentry("Flip", "WTiling.flip_at(_, _sub)"),
menuentry("Transpose", "WTiling.transpose_at(_, _sub)"),
menuentry("Untile", "mod_tiling.untile(_)"),
submenu("Float split", {
menuentry("At left",
"WTiling.set_floating_at(_, _sub, 'toggle', 'left')"),
menuentry("At right",
"WTiling.set_floating_at(_, _sub, 'toggle', 'right')"),
menuentry("Above",
"WTiling.set_floating_at(_, _sub, 'toggle', 'up')"),
menuentry("Below",
"WTiling.set_floating_at(_, _sub, 'toggle', 'down')"),
}),
submenu("At root", {
menuentry("Split vertically",
"WTiling.split_top(_, 'bottom')"),
menuentry("Split horizontally",
"WTiling.split_top(_, 'right')"),
menuentry("Flip", "WTiling.flip_at(_)"),
menuentry("Transpose", "WTiling.transpose_at(_)"),
}),
})
-- Extra context menu extra entries for floatframes.
defctxmenu("WFrame.floating", "Floating frame", {
append=true,
menuentry("New tiling", "mod_tiling.mkbottom(_)"),
})
|
adding root splits and fixing merge.
|
adding root splits and fixing merge.
|
Lua
|
mit
|
moaxcp/notion-config
|
848b91f5ab66f90e4c1d5ed2ca8f6e20acb9fcdf
|
languages/unicode.lua
|
languages/unicode.lua
|
local icu = require("justenoughicu")
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function (self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
self.lasttype = "sp"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = false
self.lasttype = false
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (thistype and thistype ~= self.lasttype and not self.isWordType[thistype]) then
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
if not self.isWordType[thistype] then self.lasttype = chardata[cp] and chardata[cp].linebreak end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
self.lasttype = "sp"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
local char = item.text
self:addToken(char, item)
local cp = SU.codepoint(char)
self.lasttype = chardata[cp] and chardata[cp].linebreak
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
self:init()
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
}
|
local icu = require("justenoughicu")
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function (self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
self.lasttype = "sp"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = false
self.lasttype = false
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (thistype and thistype ~= self.lasttype and not self.isWordType[thistype]) then
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
self.lasttype = "sp"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
local char = item.text
self:addToken(char, item)
local cp = SU.codepoint(char)
self.lasttype = chardata[cp] and chardata[cp].linebreak
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
self:init()
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
}
|
fix(languages): Remove superfluous line
|
fix(languages): Remove superfluous line
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
62f92c1162cde6fc005d85a6f3079ed5556438c8
|
terminal.lua
|
terminal.lua
|
local Terminal = {}
--local api.EditorSheet = api.SpriteSheet(api.Image("/editorsheet.png"),24,12)
Terminal.blinktime = 0.5
Terminal.blinktimer = 0
Terminal.blinkstate = false
Terminal.textbuffer = {}
Terminal.textcolors = {}
Terminal.linesLimit = 14
Terminal.lengthLimit = 43
Terminal.currentLine = 1
Terminal.rootDir = "/"
function Terminal:wrap_string(str,ml)
local ml = ml or (Terminal.lengthLimit-5)-(self.rootDir:len()+1)
local lt = api.floor(str:len()/ml+0.99)
if lt <= 1 then return {str} end
local t = {}
for i = 1, lt+1 do
table.insert(t,str:sub(0,ml-1))
str=str:sub(ml,-1)
end
return t
end
function Terminal:tout(text,col,skipnl,pathLen)
local text = text or ""
local length = pathLen and (Terminal.lengthLimit-5)-(self.rootDir:len()+1) or Terminal.lengthLimit
for line,str in ipairs(self:wrap_string(text,length)) do
self:tout_line(str,col,skipnl)
end
end
function Terminal:tout_line(text,col,skipnl)
self.textcolors[self.currentLine] = col or self.textcolors[self.currentLine]
if skipnl then
self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "")
if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end
else
self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "")
if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end
if self.currentLine == self.linesLimit then
for i=2,self.linesLimit do self.textbuffer[i-1] = self.textbuffer[i] end --Shiftup all the text
for i=2,self.linesLimit do self.textcolors[i-1] = self.textcolors[i] end
self.textbuffer[self.currentLine] = "" --Add a new line
else
self.currentLine = self.currentLine + 1
end
end
self:_redraw()
end
function Terminal:setLine(l) self.currentLine = api.floor(l or 1) if self.currentLine > 20 then self.currentLine = 20 elseif self.currentLine < 1 then self.currentLine = 1 end end
function Terminal:splitCommand(str)
local t = {}
for val in str:gmatch("%S+") do
if not t[0] then t[0] = val else table.insert(t, val) end
end
return t
end
function Terminal:_init()
for i=1,self.linesLimit do table.insert(self.textbuffer,"") end --Clean the framebuffer
for i=1,self.linesLimit do table.insert(self.textcolors,8) end
api.keyrepeat(true)
self:tout("-[[liko12]]-")
self:tout(_LK12VER,_LK12VERC)
self:tout()
self:tout("A PICO-8 CLONE WITH EXTRA ABILITIES",7)
self:tout("TYPE HELP FOR HELP",10)
self:tout(self.rootDir.."> ",8,true)
end
function Terminal:_update(dt)
self.blinktimer = self.blinktimer+dt if self.blinktimer > self.blinktime then self.blinktimer = self.blinktimer - self.blinktime self.blinkstate = not self.blinkstate end
local curlen = self.textbuffer[self.currentLine]:len()
api.color(self.blinkstate and 5 or 1)
api.rect(curlen > 0 and ((curlen)*4+8+3) or 10,(self.currentLine)*8+2,4,5)
end
function Terminal:_redraw()
api.clear(1)
for line,text in ipairs(self.textbuffer) do
api.color(self.textcolors[line])
if text == "-[[liko12]]-" then --THE SECRET PHASE
api.SpriteGroup(67,9,line*8,6,1,1,1,api.EditorSheet)
else
api.print_grid(text,2,line+1)
end
end
end
function Terminal:_kpress(k,sc,ir)
if k == "return" then
self:tout()
local splitted = self:splitCommand(self.textbuffer[self.currentLine-1])
local CMDFunc = require("terminal_commands")[string.lower(splitted[1] or "")]
if CMDFunc then
CMDFunc(unpack(splitted))
elseif splitted[1] then
self:tout("UNKNOWN COMMAND '"..splitted[1].."' !",15)
end
self:tout(self.rootDir.."> ",8,true,true)
end
if k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end
end
function Terminal:_tinput(t)
if t == "\\" then return end --This thing is so bad, so GO AWAY
if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end
end
function Terminal:_tpress()
--This means the user is using a touch device
self.linesLimit = 7
api.showkeyboard(true)
end
function Terminal:setRoot(path)
self.rootDir = path or "/"
end
return Terminal
|
local lume = require("libraries.lume")
local Terminal = {}
--local api.EditorSheet = api.SpriteSheet(api.Image("/editorsheet.png"),24,12)
Terminal.blinktime = 0.5
Terminal.blinktimer = 0
Terminal.blinkstate = false
Terminal.textbuffer = {}
Terminal.textcolors = {}
Terminal.linesLimit = 14
Terminal.lengthLimit = 43
Terminal.currentLine = 1
Terminal.rootDir = "/"
function Terminal:wrap_string(str,ml)
local ml = ml or (Terminal.lengthLimit-5)-(self.rootDir:len()+1)
local lt = api.floor(str:len()/ml+0.99)
if lt <= 1 then return {str} end
local t = {}
for i = 1, lt+1 do
table.insert(t,str:sub(0,ml-1))
str=str:sub(ml,-1)
end
return t
end
function Terminal:tout(text,col,skipnl,pathLen)
local text = text or ""
local length = pathLen and (Terminal.lengthLimit-5)-(self.rootDir:len()+1) or Terminal.lengthLimit
for _,line in ipairs(lume.split(text, "\n")) do
for _,wrapped_line in ipairs(self:wrap_string(line,length)) do
self:tout_line(wrapped_line,col,skipnl)
end
end
end
function Terminal:tout_line(text,col,skipnl)
self.textcolors[self.currentLine] = col or self.textcolors[self.currentLine]
if skipnl then
self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "")
if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end
else
self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "")
if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end
if self.currentLine == self.linesLimit then
for i=2,self.linesLimit do self.textbuffer[i-1] = self.textbuffer[i] end --Shiftup all the text
for i=2,self.linesLimit do self.textcolors[i-1] = self.textcolors[i] end
self.textbuffer[self.currentLine] = "" --Add a new line
else
self.currentLine = self.currentLine + 1
end
end
self:_redraw()
end
function Terminal:setLine(l) self.currentLine = api.floor(l or 1) if self.currentLine > 20 then self.currentLine = 20 elseif self.currentLine < 1 then self.currentLine = 1 end end
function Terminal:splitCommand(str)
local t = {}
for val in str:gmatch("%S+") do
if not t[0] then t[0] = val else table.insert(t, val) end
end
return t
end
function Terminal:_init()
for i=1,self.linesLimit do table.insert(self.textbuffer,"") end --Clean the framebuffer
for i=1,self.linesLimit do table.insert(self.textcolors,8) end
api.keyrepeat(true)
self:tout("-[[liko12]]-")
self:tout(_LK12VER,_LK12VERC)
self:tout()
self:tout("A PICO-8 CLONE WITH EXTRA ABILITIES",7)
self:tout("TYPE HELP FOR HELP",10)
self:tout(self.rootDir.."> ",8,true)
end
function Terminal:_update(dt)
self.blinktimer = self.blinktimer+dt if self.blinktimer > self.blinktime then self.blinktimer = self.blinktimer - self.blinktime self.blinkstate = not self.blinkstate end
local curlen = self.textbuffer[self.currentLine]:len()
api.color(self.blinkstate and 5 or 1)
api.rect(curlen > 0 and ((curlen)*4+8+3) or 10,(self.currentLine)*8+2,4,5)
end
function Terminal:_redraw()
api.clear(1)
for line,text in ipairs(self.textbuffer) do
api.color(self.textcolors[line])
if text == "-[[liko12]]-" then --THE SECRET PHASE
api.SpriteGroup(67,9,line*8,6,1,1,1,api.EditorSheet)
else
api.print_grid(text,2,line+1)
end
end
end
function Terminal:_kpress(k,sc,ir)
if k == "return" then
self:tout()
local splitted = self:splitCommand(self.textbuffer[self.currentLine-1])
local CMDFunc = require("terminal_commands")[string.lower(splitted[1] or "")]
if CMDFunc then
CMDFunc(unpack(splitted))
elseif splitted[1] then
self:tout("UNKNOWN COMMAND '"..splitted[1].."' !",15)
end
self:tout(self.rootDir.."> ",8,true,true)
end
if k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end
end
function Terminal:_tinput(t)
if t == "\\" then return end --This thing is so bad, so GO AWAY
if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end
end
function Terminal:_tpress()
--This means the user is using a touch device
self.linesLimit = 7
api.showkeyboard(true)
end
function Terminal:setRoot(path)
self.rootDir = path or "/"
end
return Terminal
|
Fix terminal's tout to support multiple-line strings.
|
Fix terminal's tout to support multiple-line strings.
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
31a44a71b9e13c5a49049df92f9e9be333563236
|
script/c80600029.lua
|
script/c80600029.lua
|
--ヴァンパイア・ソーサラー
function c80600029.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c80600029.condition)
e1:SetTarget(c80600029.target)
e1:SetOperation(c80600029.operation)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(80600029,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(c80600029.ntcost)
e2:SetOperation(c80600029.ntop)
c:RegisterEffect(e2)
end
function c80600029.condition(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and (r==REASON_EFFECT or r==REASON_BATTLE)
end
function c80600029.filter(c)
return (
c:IsAttribute(ATTRIBUTE_DARK) or
c:IsType(TYPE_SPELL) or
c:IsType(TYPE_TRAP)
)
and c:IsAbleToHand() and c:IsSetCard(0x92)
end
function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80600029.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DECREASE_TRIBUTE)
e1:SetTargetRange(LOCATION_HAND,0)
e1:SetTarget(c80600029.rfilter)
e1:SetCountLimit(1)
e1:SetValue(0x2)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80600029.rfilter(e,c)
return c:IsSetCard(0x92)
end
|
--ヴァンパイア・ソーサラー
function c80600029.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c80600029.condition)
e1:SetTarget(c80600029.target)
e1:SetOperation(c80600029.operation)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(80600029,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(c80600029.ntcost)
e2:SetOperation(c80600029.ntop)
c:RegisterEffect(e2)
end
function c80600029.condition(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and (e:GetHandler():IsReason(REASON_EFFECT) or e:GetHandler():IsReason(REASON_BATTLE))
end
function c80600029.filter(c)
return (
c:IsAttribute(ATTRIBUTE_DARK) or
c:IsType(TYPE_SPELL) or
c:IsType(TYPE_TRAP)
)
and c:IsAbleToHand() and c:IsSetCard(0x92)
end
function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80600029.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DECREASE_TRIBUTE)
e1:SetTargetRange(LOCATION_HAND,0)
e1:SetTarget(c80600029.rfilter)
e1:SetCountLimit(1)
e1:SetValue(0x2)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80600029.rfilter(e,c)
return c:IsSetCard(0x92)
end
|
fix fixed effect not activating
|
fix
fixed effect not activating
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher
|
449c65f7377613eea85907edf2ccd46e99abac4e
|
LuaAndCparticipants.lua
|
LuaAndCparticipants.lua
|
-- http://kodomo.fbb.msu.ru/wiki/Main/LuaAndC/Participants
local participants = {
{'Александра Галицына', 'agalicina', 'agalitsyna', 'https://github.com/agalitsyna/LOF.git'},
{'Анна Колупаева', 'kolupaeva', 'AnyaKol',
'https://github.com/AnyaKol/Lua_C'},
{'Александра Бойко', 'boyko.s', 'boykos', },
{'Андрей Сигорских', 'crescent8547', 'CarolusRex8547',
'https://github.com/Talianash/GlobinDetector-2015'},
{'Иван Русинов', 'is_rusinov', 'isrusin', },
{'Игорь Поляков', 'ranhummer', 'RanHum', cw=6},
{'Борис Нагаев', 'bnagaev', 'starius',
'https://github.com/LuaAndC/LuaAndC'},
{'Татьяна Шугаева', 'talianash', 'Talianash',
'https://github.com/Talianash/GlobinDetector-2015',
cw=5},
{'Дарья Диброва', 'udavdasha', 'udavdasha', },
{'Павел Долгов', '', 'zer0main',
{'https://github.com/zer0main/battleship',
'https://github.com/zer0main/bin_game_mvc'}},
{'Роман Кудрин', 'explover', 'explover', cw=4},
{'Анастасия Князева', 'nknjasewa', 'nknjasewa', },
{'Иван Ильницкий', 'ilnitsky', 'ilnitsky', },
{'Наталия Кашко', 'nataliya.kashko', 'natilika', cw=5},
{'Дмитрий Пензар', 'darkvampirewolf', 'dmitrypenzar1996',
'https://github.com/dmitrypenzar1996/Trees_Construction_Visualization.git',
cw=9},
{'Злобин Александр', 'alexander.zlobin', 'AlxTheEvil'},
{'Просвиров Кирилл', 'prosvirov.k', 'Akado2009',
cw=11},
{'Михаил Молдован', 'mikemoldovan', 'mikemoldovan', cw=5},
{'Андрей Демкив', 'andrei-demkiv', 'Andrei-demkiv', cw=4},
{'Валяева Анна', 'kuararo', 'kirushka', cw=3},
{'Дианкин Игорь', 'diankin', 'Warrdale', cw=3},
{'Горбатенко Владислав', 'vladislaw_aesc', 'ubiquinone'},
{'Николаева Дарья', 'chlamidomonas', 'chlamidomonas'},
}
local unpack = unpack or table.unpack
local function cwMark(cw)
if cw >= 5 then
return 'отлично'
elseif cw == 4 then
return 'хорошо'
elseif cw == 3 then
return 'зачтена'
else
return ''
end
end
print("||Имя, тесты||Github||Учебные проекты||[[/../cw|Контрольная]]||")
for _, participant in ipairs(participants) do
local name, kodomo, github, projecturls =
unpack(participant)
local cw = participant.cw
local mark = ' '
if cw then
mark = ("%d б., %s"):format(cw, cwMark(cw))
end
local kodomolink, quizlink
if kodomo then
kodomolink = ('[[http://kodomo.fbb.msu.ru/~%s|%s]]')
:format(kodomo, name)
quizlink = ('[[http://kodomoquiz.tk/admin/user/%s|#]]')
:format(kodomo)
else
kodomolink = name
quizlink = ''
end
local githublink = ('[[https://github.com/%s|%s]]')
:format(github, github)
local projectlinks = {}
if projecturls then
if type(projecturls) == 'string' then
projecturls = {projecturls}
end
assert(type(projecturls) == 'table')
for _, projecturl in ipairs(projecturls) do
local projectname = projecturl:match(
'https://github.com/[^/]+/([^/]+)/?')
local projectlink = ('[[%s|%s]]')
:format(projecturl, projectname)
table.insert(projectlinks, projectlink)
end
end
print(("||%s %s||%s||%s||%s||"):format(kodomolink,
quizlink, githublink,
table.concat(projectlinks, ', '), mark))
end
|
-- http://kodomo.fbb.msu.ru/wiki/Main/LuaAndC/Participants
local participants = {
{'Александра Галицына', 'agalicina', 'agalitsyna', 'https://github.com/agalitsyna/LOF.git'},
{'Анна Колупаева', 'kolupaeva', 'AnyaKol',
'https://github.com/AnyaKol/Lua_C'},
{'Александра Бойко', 'boyko.s', 'boykos', },
{'Андрей Сигорских', 'crescent8547', 'CarolusRex8547',
'https://github.com/Talianash/GlobinDetector-2015'},
{'Иван Русинов', 'is_rusinov', 'isrusin', },
{'Игорь Поляков', 'ranhummer', 'RanHum', cw=6},
{'Борис Нагаев', 'bnagaev', 'starius',
'https://github.com/LuaAndC/LuaAndC'},
{'Татьяна Шугаева', 'talianash', 'Talianash',
'https://github.com/Talianash/GlobinDetector-2015',
cw=5},
{'Дарья Диброва', 'udavdasha', 'udavdasha', },
{'Павел Долгов', '', 'zer0main',
{'https://github.com/zer0main/battleship',
'https://github.com/zer0main/bin_game_mvc'}},
{'Роман Кудрин', 'explover', 'explover', cw=4},
{'Анастасия Князева', 'nknjasewa', 'nknjasewa', },
{'Иван Ильницкий', 'ilnitsky', 'ilnitsky', },
{'Наталия Кашко', 'nataliya.kashko', 'natilika', cw=5},
{'Дмитрий Пензар', 'darkvampirewolf', 'dmitrypenzar1996',
'https://github.com/dmitrypenzar1996/Trees_Construction_Visualization.git',
cw=9},
{'Злобин Александр', 'alexander.zlobin', 'AlxTheEvil'},
{'Просвиров Кирилл', 'prosvirov.k', 'Akado2009',
cw=11},
{'Михаил Молдован', 'mikemoldovan', 'mikemoldovan', cw=5},
{'Андрей Демкив', 'andrei-demkiv', 'Andrei-demkiv', cw=4},
{'Валяева Анна', 'kuararo', 'kirushka', cw=3},
{'Дианкин Игорь', 'diankin', 'Warrdale', cw=3},
{'Горбатенко Владислав', 'vladislaw_aesc', 'ubiquinone'},
{'Николаева Дарья', 'chlamidomonas', 'chlamidomonas'},
}
local unpack = unpack or table.unpack
local function cwMark(cw)
if cw >= 5 then
return 'отлично'
elseif cw == 4 then
return 'хорошо'
elseif cw == 3 then
return 'зачтена'
else
return ''
end
end
print("||Имя, тесты||Github||Учебные проекты||[[/../cw|Контрольная]]||")
for _, participant in ipairs(participants) do
local name, kodomo, github, projecturls =
unpack(participant)
local cw = participant.cw
local mark = ' '
if cw then
mark = ("%d б., %s"):format(cw, cwMark(cw))
end
local kodomolink, quizlink
if kodomo then
kodomolink = ('[[http://kodomo.fbb.msu.ru/~%s|%s]]')
:format(kodomo, name)
quizlink = ('[[http://kodomoquiz.tk/admin/user/%s|#]]')
:format(kodomo)
else
kodomolink = name
quizlink = ''
end
local githublink = ('[[https://github.com/%s|%s]]')
:format(github, github)
local projectlinks = {}
if projecturls then
if type(projecturls) == 'string' then
projecturls = {projecturls}
end
assert(type(projecturls) == 'table')
for _, projecturl in ipairs(projecturls) do
local projectname = projecturl:match(
'https://github.com/[^/]+/([^/]+)/?')
local projectlink = ('[[%s|%s]]')
:format(projecturl, projectname)
table.insert(projectlinks, projectlink)
end
else
projectlinks = {' '}
end
print(("||%s %s||%s||%s||%s||"):format(kodomolink,
quizlink, githublink,
table.concat(projectlinks, ', '), mark))
end
|
Fix style mistake
|
Fix style mistake
|
Lua
|
mit
|
hbucius/LuaAndC,LuaAndC/LuaAndC
|
d1eaa36b064994d0db43181fbd7423696c7df6e4
|
site/api/lib/aaa.lua
|
site/api/lib/aaa.lua
|
--[[
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.
]]--
-- This is aaa.lua - AAA filter for ASF.
-- Get a list of PMCs the user is a part of
function getPMCs(r, uid)
local groups = {}
local ldapdata = io.popen( ([[ldapsearch -x -LLL "(|(memberUid=%s)(member=uid=%s,ou=people,dc=apache,dc=org))" cn]]):format(uid,uid) )
local data = ldapdata:read("*a")
for match in data:gmatch("dn: cn=([-a-zA-Z0-9]+),ou=pmc,ou=committees,ou=groups,dc=apache,dc=org") do
table.insert(groups, match)
end
return groups
end
-- Is $uid a member of the org?
function isMember(r, uid)
-- First, check the 30 minute cache
local NOWISH = math.floor(os.time() / 1800)
local MEMBER_KEY = "isMember_" .. NOWISH .. "_" .. uid
local t = r:ivm_get(MEMBER_KEY)
-- If cached, then just return the value
if t then
return tonumber(t) == 1
-- Otherwise, look in LDAP
else
local ldapdata = io.popen([[ldapsearch -x -LLL -b cn=member,ou=groups,dc=apache,dc=org]])
local data = ldapdata:read("*a")
for match in data:gmatch("memberUid: ([-a-z0-9_.]+)") do
-- Found it?
if match == uid then
-- Set cache
r:ivm_set(MEMBER_KEY, "1")
return true
end
end
end
-- Set cache
r:ivm_set(MEMBER_KEY, "0")
return false
end
-- Get a list of domains the user has private email access to (or wildcard if org member)
function getRights(r, usr)
local xuid = usr.uid or usr.email or "|||"
uid = xuid:match("([-a-zA-Z0-9._]+)") -- whitelist
local rights = {}
-- bad char in uid?
if not uid or xuid ~= uid then
return rights
end
-- check if oauth was through an oauth portal that can give privacy rights
local authority = false
for k, v in pairs(config.admin_oauth or {}) do
if r.strcmp_match(oauth_domain, v) then
authority = true
break
end
end
-- if not a 'good' oauth, then let's forget all about it
if not authority then
return rights
end
-- Check if uid has member (admin) rights
if usr.admin or isMember(r, uid) then
table.insert(rights, "*")
-- otherwise, get PMC list and construct array
else
local list = getPMCs(r, uid)
for k, v in pairs(list) do
table.insert(rights, v .. ".apache.org")
end
end
return rights
end
-- module defs
return {
rights = getRights
}
|
--[[
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.
]]--
-- This is aaa.lua - AAA filter for ASF.
local config = require 'lib/config'
-- Get a list of PMCs the user is a part of
function getPMCs(r, uid)
local groups = {}
local ldapdata = io.popen( ([[ldapsearch -x -LLL "(|(memberUid=%s)(member=uid=%s,ou=people,dc=apache,dc=org))" cn]]):format(uid,uid) )
local data = ldapdata:read("*a")
for match in data:gmatch("dn: cn=([-a-zA-Z0-9]+),ou=pmc,ou=committees,ou=groups,dc=apache,dc=org") do
table.insert(groups, match)
end
return groups
end
-- Is $uid a member of the org?
function isMember(r, uid)
-- First, check the 30 minute cache
local NOWISH = math.floor(os.time() / 1800)
local MEMBER_KEY = "isMember_" .. NOWISH .. "_" .. uid
local t = r:ivm_get(MEMBER_KEY)
-- If cached, then just return the value
if t then
return tonumber(t) == 1
-- Otherwise, look in LDAP
else
local ldapdata = io.popen([[ldapsearch -x -LLL -b cn=member,ou=groups,dc=apache,dc=org]])
local data = ldapdata:read("*a")
for match in data:gmatch("memberUid: ([-a-z0-9_.]+)") do
-- Found it?
if match == uid then
-- Set cache
r:ivm_set(MEMBER_KEY, "1")
return true
end
end
end
-- Set cache
r:ivm_set(MEMBER_KEY, "0")
return false
end
-- Get a list of domains the user has private email access to (or wildcard if org member)
function getRights(r, usr)
if not usr.credentials then
return {}
end
local xuid = usr.credentials.uid or usr.credentials.email or "|||"
local uid = xuid:match("([-a-zA-Z0-9._]+)") -- whitelist
local rights = {}
-- bad char in uid?
if not uid or xuid ~= uid then
return rights
end
-- Check that we used oauth, bail if not
local oauth_domain = usr.internal and usr.internal.oauth_used or nil
if not oauth_domain then
return {}
end
-- check if oauth was through an oauth portal that can give privacy rights
local authority = false
for k, v in pairs(config.admin_oauth or {}) do
if r.strcmp_match(oauth_domain, v) then
authority = true
break
end
end
-- if not a 'good' oauth, then let's forget all about it
if not authority then
return rights
end
-- Check if uid has member (admin) rights
if usr.internal.admin or isMember(r, uid) then
table.insert(rights, "*")
-- otherwise, get PMC list and construct array
else
local list = getPMCs(r, uid)
for k, v in pairs(list) do
table.insert(rights, v .. ".apache.org")
end
end
return rights
end
-- module defs
return {
rights = getRights
}
|
Bug: lib/aaa.lua various bugs
|
Bug: lib/aaa.lua various bugs
This relates to #140
Some bugs still remain, but the code is at least usable
|
Lua
|
apache-2.0
|
quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail,jimjag/ponymail,jimjag/ponymail,quenda/ponymail,quenda/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,jimjag/ponymail
|
2f785c75ecad700eb45b0ad7a7359b3a6c11df9e
|
modules/dokpro.lua
|
modules/dokpro.lua
|
local htmlparser = require'htmlparser'
local trim = function(s)
if not s then return nil end
return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)')
end
local parseData = function(data)
if(data:match('ordboksdatabasene')) then
return nil, 'Service down. :('
end
-- This page is a typical example of someone using XHTML+CSS+JS, while still
-- coding like they used to back in 1998.
data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub(' ', '')
local words = {}
local lookup = data:match('>([^<]+)</a>')
data = data:match('(<span class="oppslagsord b".->.-)</td>')
if(data) then
local doc = htmlparser.parsestr(data)
local word = doc[1][1]
-- Workaround for mis matched word (partial match)
if type(word) == type({}) then
word = doc[1][1][1]
end
local entry = {
lookup = {},
meaning = {},
examples = {},
}
local text = {}
-- Here be dragons. This is why we can't have nice things
for _, w in pairs(doc) do
if _ ~= '_tag' then
if type(w) == type("") then
table.insert(text, w)
elseif type(w) == type({}) then
if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then
table.insert(text, ivar2.util.italic(w[1]))
-- Extract definitions
elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then
for _, t in pairs(w) do
if type(t) == type("") and t ~= "span" then
table.insert(text, t)
elseif type(w) == type({}) then
if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then
for _, f in pairs(t) do
if type(f) == type("") and f ~= 'span' then
table.insert(text, f)
elseif type(f[1]) == type("") and trim(f[1]) ~= "" then
table.insert(text, string.format("[%s]", ivar2.util.bold(f[1])))
end
end
end
end
end
elseif type(w[1]) == type("") then
if w[1] ~= word then
table.insert(text, w[1])
end
end
end
end
end
entry.meaning = trim(table.concat(text))
table.insert(entry.lookup, word)
table.insert(words, entry)
end
return words
end
local handleInput = function(self, source, destination, word, ordbok)
if not ordbok then ordbok = 'bokmaal' end
local query = ivar2.util.urlEncode(word)
ivar2.util.simplehttp(
"http://www.nob-ordbok.uio.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query,
function(data)
local words, err = parseData(data)
local out = {}
if(words) then
local n = #word + 23
for i=1, #words do
local word = words[i]
local lookup = table.concat(word.lookup, ', ')
local definition = word.meaning
if(word.examples[1]) then
if(definition and #definition < 35) then
definition = definition .. ' ' .. word.examples[1]
else
definition = word.examples[1]
end
end
if(definition) then
local message = string.format('\002[%s]\002: %s', lookup, definition)
n = n + #message
table.insert(out, message)
end
end
end
if(#out > 0) then
self:Msg('privmsg', destination, source, '%s', table.concat(out, ', '))
else
self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.')
end
end
)
end
return {
PRIVMSG = {
['^%pdokpro (.+)$'] = handleInput,
['^%pordbok (.+)$'] = handleInput,
['^%pbokmål (.+)$'] = handleInput,
['^%pnynorsk (.+)$'] = function(self, source, destination, word)
handleInput(self, source, destination, word, 'nynorsk')
end
},
}
|
local htmlparser = require'htmlparser'
local trim = function(s)
if not s then return nil end
return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)')
end
local parseData = function(data)
if(data:match('ordboksdatabasene')) then
return nil, 'Service down. :('
end
-- This page is a typical example of someone using XHTML+CSS+JS, while still
-- coding like they used to back in 1998.
data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub(' ', '')
local words = {}
local lookup = data:match('>([^<]+)</a>')
data = data:match('(<span class="oppslagsord b".->.-)</td>')
if(data) then
local doc = htmlparser.parsestr(data)
local word = doc[1][1]
-- Workaround for mis matched word (partial match)
if type(word) == type({}) then
word = doc[1][1][1]
end
-- First entry
local entry = {
lookup = {},
meaning = {},
examples = {},
}
local addentry = function(lookup)
entry = {
lookup = {},
meaning = {},
examples = {},
}
table.insert(entry.lookup, lookup)
table.insert(words, entry)
end
local add = function(item)
if not item then return end
table.insert(entry.meaning, item)
end
-- Here be dragons. This is why we can't have nice things
for _, w in pairs(doc) do
if _ ~= '_tag' then
if type(w) == type("") then
add(w)
elseif type(w) == type({}) then
if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then
add(ivar2.util.italic(w[1]))
elseif w['_attr'] and w['_attr'].class == 'oppslagsord b' then
local lookup = {}
for _, t in pairs(w) do
if type(t) == type("") and t ~= "span" then
table.insert(lookup, t)
elseif type(t[1]) == type("") and t[1] ~= "span" then
table.insert(lookup, t[1])
end
end
addentry(table.concat(lookup))
-- Extract definitions
elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then
for _, t in pairs(w) do
if type(t) == type("") and t ~= "span" then
-- Utvidet + kompakt leads to dupes.
-- add(t)
elseif type(w) == type({}) then
if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then
for _, f in pairs(t) do
if type(f) == type("") and f ~= 'span' then
add(f)
elseif type(f[1]) == type("") and trim(f[1]) ~= "" then
add(string.format("[%s]", ivar2.util.bold(f[1])))
end
end
end
end
end
elseif type(w[1]) == type("") then
if w[1] ~= word then
add(w[1])
end
end
end
end
end
for _,entry in pairs(words) do
entry.meaning = trim(table.concat(entry.meaning))
end
end
return words
end
local handleInput = function(self, source, destination, word, ordbok)
if not ordbok then ordbok = 'bokmaal' end
local query = ivar2.util.urlEncode(word)
ivar2.util.simplehttp(
"http://www.nob-ordbok.uio.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query,
function(data)
local words, err = parseData(data)
local out = {}
if(words) then
local n = #word + 23
for i=1, #words do
local word = words[i]
local lookup = table.concat(word.lookup, ', ')
local definition = word.meaning
if(word.examples[1]) then
if(definition and #definition < 35) then
definition = definition .. ' ' .. word.examples[1]
else
definition = word.examples[1]
end
end
if(definition) then
local message = string.format('\002[%s]\002: %s', lookup, definition)
n = n + #message
table.insert(out, message)
end
end
end
if(#out > 0) then
self:Msg('privmsg', destination, source, '%s', table.concat(out, ', '))
else
self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.')
end
end
)
end
return {
PRIVMSG = {
['^%pdokpro (.+)$'] = handleInput,
['^%pordbok (.+)$'] = handleInput,
['^%pbokmål (.+)$'] = handleInput,
['^%pnynorsk (.+)$'] = function(self, source, destination, word)
handleInput(self, source, destination, word, 'nynorsk')
end
},
}
|
dokpro: more html parsing fixes
|
dokpro: more html parsing fixes
Former-commit-id: e6ff0b940d36ae5585c915e429809e66fd7cc611 [formerly 7a600b727205da4eb8f49cbdd31eac55e881bef6]
Former-commit-id: b48910d19e83d3708a43cdfac7279b95ae83c7d2
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
b17c77eeadba3c98f56836d32007c712342cf421
|
plugins/wikipedia.lua
|
plugins/wikipedia.lua
|
local command = 'wikipedia <query>'
local doc = [[```
/wikipedia <query>
Returns an article from Wikipedia.
Aliases: /w, /wiki
```]]
local triggers = {
'^/wikipedia[@'..bot.username..']*',
'^/wiki[@'..bot.username..']*',
'^/w[@'..bot.username..']*$',
'^/w[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local gurl = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q=site:wikipedia.org%20'
local wurl = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=4000&exsectionformat=plain&titles='
local jstr, res = HTTPS.request(gurl .. URL.escape(input))
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if not jdat.responseData then
sendReply(msg, config.errors.connection)
return
end
if not jdat.responseData.results[1] then
sendReply(msg, config.errors.results)
return
end
--
local url = jdat.responseData.results[1].url
local title = jdat.responseData.results[1].titleNoFormatting:gsub(' %- Wikipedia, the free encyclopedia', '')
jstr, res = HTTPS.request(wurl .. URL.escape(title))
if res ~= 200 then
sendReply(msg, config.error.connection)
return
end
local text = JSON.decode(jstr).query.pages
for k,v in pairs(text) do
text = v.extract
break -- Seriously, there's probably a way more elegant solution.
end
if not text then
sendReply(msg, config.errors.results)
return
end
text = text:gsub('</?.->', '')
local l = text:find('<h2>')
if l then
text = text:sub(1, l-1)
end
title = title:gsub('%(.+%)', '')
--local output = '[' .. title .. '](' .. url .. ')\n' .. text:gsub('%[.+]%','')
--local output = '*' .. title .. '*\n' .. text:gsub('%[.+]%','') .. '\n[Read more.](' .. url .. ')'
local output = text:gsub('%[.+%]',''):gsub(title, '*'..title..'*') .. '\n'
if url:find('%(') then
output = output .. url:gsub('_', '\\_')
else
output = output .. '[Read more.](' .. url .. ')'
end
--
--[[ Comment the previous block and uncomment this one for full-message,
-- "unlinked" link previews.
-- Invisible zero-width, non-joiner.
local output = '[](' .. jdat.responseData.results[1].url .. ')'
]]--
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
local command = 'wikipedia <query>'
local doc = [[```
/wikipedia <query>
Returns an article from Wikipedia.
Aliases: /w, /wiki
```]]
local triggers = {
'^/wikipedia[@'..bot.username..']*',
'^/wiki[@'..bot.username..']*',
'^/w[@'..bot.username..']*$',
'^/w[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local gurl = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q=site:wikipedia.org%20'
local wurl = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=4000&exsectionformat=plain&titles='
local jstr, res = HTTPS.request(gurl .. URL.escape(input))
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if not jdat.responseData then
sendReply(msg, config.errors.connection)
return
end
if not jdat.responseData.results[1] then
sendReply(msg, config.errors.results)
return
end
--
local url = jdat.responseData.results[1].url
local title = jdat.responseData.results[1].titleNoFormatting:gsub(' %- Wikipedia, the free encyclopedia', '')
jstr, res = HTTPS.request(wurl .. URL.escape(title))
if res ~= 200 then
sendReply(msg, config.error.connection)
return
end
local text = JSON.decode(jstr).query.pages
for k,v in pairs(text) do
text = v.extract
break -- Seriously, there's probably a way more elegant solution.
end
if not text then
sendReply(msg, config.errors.results)
return
end
local l = text:find('<h2>')
if l then
text = text:sub(1, l-1)
end
text = text:gsub('</?.->', '')
title = title:gsub('%(.+%)', '')
--local output = '[' .. title .. '](' .. url .. ')\n' .. text:gsub('%[.+]%','')
--local output = '*' .. title .. '*\n' .. text:gsub('%[.+]%','') .. '\n[Read more.](' .. url .. ')'
local output = text:gsub('%[.+%]',''):gsub(title, '*'..title..'*') .. '\n'
if url:find('%(') then
output = output .. url:gsub('_', '\\_')
else
output = output .. '[Read more.](' .. url .. ')'
end
--
--[[ Comment the previous block and uncomment this one for full-message,
-- "unlinked" link previews.
-- Invisible zero-width, non-joiner.
local output = '[](' .. jdat.responseData.results[1].url .. ')'
]]--
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
fixed bug in wikipedia.lua
|
fixed bug in wikipedia.lua
|
Lua
|
mit
|
barreeeiroo/BarrePolice,topkecleon/otouto,bb010g/otouto,TiagoDanin/SiD,Brawl345/Brawlbot-v2
|
913588f8a001e102501ecb3293ef65403eef10a5
|
item/bottles.lua
|
item/bottles.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE common SET com_script='item.bottles' WHERE com_itemid IN (2500, 2496, 2497, 2501, 2499);
require("base.common")
module("item.bottles", package.seeall)
function InitDrinks()
if ( drinkList == nil) then
-- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...}
drinkList={};
drinkList[2500] = { "Weinflasche", "bottle of wine", 2498,
{{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} }; -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher
drinkList[2496] = { "Wasserflasche", "bottle of water", 2498,
{ {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } };
drinkList[2497] = { "Metflasche", "bottle of mead", 2498,
{ {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } };
drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498,
{ {1908, 1909} } }; -- Krug
drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498,
{ {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } };
-- init descriptions
BottleQualDe={"randvolle ","volle ","halbvolle ","fast leere "};
BottleQualEn={"brimfull ", "full ","half full ","almost empty "};
BottleQualLm={8,6,3,1};
end
end
function UseItem(User, SourceItem)
if firstcall==nil then
InitDrinks();
firstcall=1;
end
local progress = User:getQuestProgress(1);
local food = drinkList[ SourceItem.id ];
if (food ~= nil ) then
Evilrockentrance(User, SourceItem, ltstate)
local TargetItem = base.common.GetTargetItem(User, SourceItem);
if( TargetItem ) then
for i, combo in pairs(food[4]) do
if combo[1] == TargetItem.id then
-- fill drink
if (TargetItem.number > 1) then
world:erase( TargetItem, 1 );
User:createItem( combo[2], 1, 333,nil);
else
TargetItem.id = combo[2];
world:changeItem(TargetItem);
end
world:makeSound(10,User.pos)
-- create leftovers
if( SourceItem.quality > 199 ) then
-- reduce one portion
world:changeQuality( SourceItem, -100 );
else
if( math.random( 50 ) <= 1 ) then
base.common.InformNLS( User,
"Die leere Flasche ist angeschlagen und unbrauchbar.",
"The empty bottle is broken and no longer usable.");
else
local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")};
local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy);
base.common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more.");
end
end
world:erase(SourceItem,1);
end
-- cancel after one found item
break;
end -- found item
end -- search loop
else
base.common.InformNLS( User,
"Nimm die Flasche und ein Trinkgef in deine Hnde.",
"Take the bottle and a drinking vessel in your hands.");
end
else
User:inform("unkown bottle item ");
end
end
function LookAtItem(User, Item)
local lookAt = base.lookat.GenerateLookAt(User, Item)
if firstcall==nil then
InitDrinks();
firstcall=1;
end
local food = drinkList[ Item.id ];
if food == nil then
User:inform("unkown bottle item ");
return
end
-- decode item quality, extract duration
local itemDura=math.mod(Item.quality,100);
local itemQual=(Item.quality-itemDura)/100;
--User:inform("portions "..itemQual);
-- build description
local DisplayText="";
-- build quality text
for i,qualLimit in pairs(BottleQualLm) do
if (itemQual>=qualLimit ) then
DisplayText = base.common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] );
break;
end
end
DisplayText = DisplayText..base.common.GetNLS( User, food[1], food[2] );
lookAt.description = DisplayText
world:itemInform(User, Item, lookAt)
end
function Evilrockentrance(User, SourceItem, ltstate)
local checkBucket = world:getItemOnField(position(997,199,2))
if checkBucket.id == 51 and SourceItem.id == 2496 then
local foundSource
-- check for empty bucket
TargetItem = base.common.GetItemInArea(User.pos, 51);
if (TargetItem ~= nil) then
if not base.common.IsLookingAt( User, position(997,199,2) ) then -- check looking direction
base.common.TurnTo( User, position(997,199,2) ); -- turn if necessary
end
foundSource=true
end
if not foundSource then
-- nothing found to fill the bucket.
base.common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water.");
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 10, 25);
User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.")
return
end
world:swap(checkBucket,52,999)
--[[ local checkFullBucket = world:getItemOnField(position(997,199,3))
if checkFullBucket.id == 52 then
checkFullBucket.wear=255
world:changeItem(checkFullBucket)
end ]]
triggerfield.evilrock.RemoveEntranceTrap(User)
local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items
if SourceItem.number == 1 then
world:erase(SourceItem,1)
return
end
end
end
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE common SET com_script='item.bottles' WHERE com_itemid IN (2500, 2496, 2497, 2501, 2499);
require("base.common")
require("base.lookat")
module("item.bottles", package.seeall)
function InitDrinks()
if ( drinkList == nil) then
-- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...}
drinkList={};
drinkList[2500] = { "Weinflasche", "bottle of wine", 2498,
{{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} }; -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher
drinkList[2496] = { "Wasserflasche", "bottle of water", 2498,
{ {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } };
drinkList[2497] = { "Metflasche", "bottle of mead", 2498,
{ {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } };
drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498,
{ {1908, 1909} } }; -- Krug
drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498,
{ {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } };
-- init descriptions
BottleQualDe={"Randvolle ","Volle ","Halbvolle ","Fast leere "};
BottleQualEn={"Brimfull ", "Full ","Half full ","Almost empty "};
BottleQualLm={8,6,3,1};
end
end
function UseItem(User, SourceItem)
if firstcall==nil then
InitDrinks();
firstcall=1;
end
local progress = User:getQuestProgress(1);
local food = drinkList[ SourceItem.id ];
if (food ~= nil ) then
Evilrockentrance(User, SourceItem, ltstate)
local TargetItem = base.common.GetTargetItem(User, SourceItem);
if( TargetItem ) then
for i, combo in pairs(food[4]) do
if combo[1] == TargetItem.id then
-- fill drink
if (TargetItem.number > 1) then
world:erase( TargetItem, 1 );
User:createItem( combo[2], 1, 333,nil);
else
TargetItem.id = combo[2];
world:changeItem(TargetItem);
end
world:makeSound(10,User.pos)
-- create leftovers
if( SourceItem.quality > 199 ) then
-- reduce one portion
world:changeQuality( SourceItem, -100 );
else
if( math.random( 50 ) <= 1 ) then
base.common.InformNLS( User,
"Die leere Flasche ist angeschlagen und unbrauchbar.",
"The empty bottle is broken and no longer usable.");
else
local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")};
local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy);
base.common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more.");
end
end
world:erase(SourceItem,1);
end
-- cancel after one found item
break;
end -- found item
end -- search loop
else
base.common.InformNLS( User,
"Nimm die Flasche und ein Trinkgef in deine Hnde.",
"Take the bottle and a drinking vessel in your hands.");
end
else
User:inform("unkown bottle item ");
end
end
function LookAtItem(User, Item)
local lookAt = base.lookat.GenerateLookAt(User, Item)
if firstcall==nil then
InitDrinks();
firstcall=1;
end
local food = drinkList[ Item.id ];
if food == nil then
User:inform("unkown bottle item ");
return
end
-- decode item quality, extract duration
local itemDura=math.mod(Item.quality,100);
local itemQual=(Item.quality-itemDura)/100;
--User:inform("portions "..itemQual);
-- build description
local DisplayText="";
-- build quality text
for i,qualLimit in pairs(BottleQualLm) do
if (itemQual>=qualLimit ) then
DisplayText = base.common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] );
break;
end
end
DisplayText = DisplayText..base.common.GetNLS( User, food[1], food[2] );
if lookAt.description ~= nil then -- append the label
DisplayText = DisplayText..". "..lookAt.description;
end
lookAt.description = DisplayText
world:itemInform(User, Item, lookAt)
end
function Evilrockentrance(User, SourceItem, ltstate)
local checkBucket = world:getItemOnField(position(997,199,2))
if checkBucket.id == 51 and SourceItem.id == 2496 then
local foundSource
-- check for empty bucket
TargetItem = base.common.GetItemInArea(User.pos, 51);
if (TargetItem ~= nil) then
if not base.common.IsLookingAt( User, position(997,199,2) ) then -- check looking direction
base.common.TurnTo( User, position(997,199,2) ); -- turn if necessary
end
foundSource=true
end
if not foundSource then
-- nothing found to fill the bucket.
base.common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water.");
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 10, 25);
User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.")
return
end
world:swap(checkBucket,52,999)
--[[ local checkFullBucket = world:getItemOnField(position(997,199,3))
if checkFullBucket.id == 52 then
checkFullBucket.wear=255
world:changeItem(checkFullBucket)
end ]]
triggerfield.evilrock.RemoveEntranceTrap(User)
local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items
if SourceItem.number == 1 then
world:erase(SourceItem,1)
return
end
end
end
|
Fix labels on big bottles
|
Fix labels on big bottles
(Mantis 0009518)
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
|
6d238397f45a544aef63d9ecf4f534859ca1268a
|
kong/dao/migrations/cassandra.lua
|
kong/dao/migrations/cassandra.lua
|
return {
{
name = "2015-01-12-175310_skeleton",
up = function(db, kong_config)
local keyspace_name = kong_config.cassandra_keyspace
local strategy, strategy_properties = kong_config.cassandra_repl_strategy, ""
-- Format strategy options
if strategy == "SimpleStrategy" then
strategy_properties = string.format(", 'replication_factor': %s", kong_config.cassandra_repl_factor)
elseif strategy == "NetworkTopologyStrategy" then
local dcs = {}
for dc_name, dc_repl in pairs(kong_config.cassandra_data_centers) do
table.insert(dcs, string.format("'%s': %s", dc_name, dc_repl))
end
if #dcs > 0 then
strategy_properties = string.format(", %s", table.concat(dcs, ", "))
end
else
-- Strategy unknown
return "invalid replication_strategy class"
end
-- Format final keyspace creation query
local keyspace_str = string.format([[
CREATE KEYSPACE IF NOT EXISTS "%s"
WITH REPLICATION = {'class': '%s'%s};
]], keyspace_name, strategy, strategy_properties)
local res, err = db:query(keyspace_str, nil, nil, nil, true)
if not res then
return err
end
local res, err = db:query [[
CREATE TABLE IF NOT EXISTS schema_migrations(
id text PRIMARY KEY,
migrations list<text>
);
]]
if not res then
return err
end
end,
down = [[
DROP TABLE schema_migrations;
]]
},
{
name = "2015-01-12-175310_init_schema",
up = [[
CREATE TABLE IF NOT EXISTS consumers(
id uuid,
custom_id text,
username text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON consumers(custom_id);
CREATE INDEX IF NOT EXISTS ON consumers(username);
CREATE TABLE IF NOT EXISTS apis(
id uuid,
name text,
request_host text,
request_path text,
strip_request_path boolean,
upstream_url text,
preserve_host boolean,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON apis(name);
CREATE INDEX IF NOT EXISTS ON apis(request_host);
CREATE INDEX IF NOT EXISTS ON apis(request_path);
CREATE TABLE IF NOT EXISTS plugins(
id uuid,
api_id uuid,
consumer_id uuid,
name text,
config text, -- serialized plugin configuration
enabled boolean,
created_at timestamp,
PRIMARY KEY (id, name)
);
CREATE INDEX IF NOT EXISTS ON plugins(name);
CREATE INDEX IF NOT EXISTS ON plugins(api_id);
CREATE INDEX IF NOT EXISTS ON plugins(consumer_id);
]],
down = [[
DROP TABLE consumers;
DROP TABLE apis;
DROP TABLE plugins;
]]
},
{
name = "2015-11-23-817313_nodes",
up = [[
CREATE TABLE IF NOT EXISTS nodes(
name text,
cluster_listening_address text,
created_at timestamp,
PRIMARY KEY (name)
) WITH default_time_to_live = 3600;
CREATE INDEX IF NOT EXISTS ON nodes(cluster_listening_address);
]],
down = [[
DROP TABLE nodes;
]]
},
{
name = "2016-02-25-160900_remove_null_consumer_id",
up = function(_, _, dao)
local rows, err = dao.plugins:find_all {consumer_id = "00000000-0000-0000-0000-000000000000"}
if err then
return err
end
for _, row in ipairs(rows) do
row.consumer_id = nil
local _, err = dao.plugins:update(row, row, {full = true})
if err then
return err
end
end
end
},
{
name = "2016-02-29-121813_remove_ttls",
up = [[
ALTER TABLE nodes WITH default_time_to_live = 0;
]],
down = [[
ALTER TABLE nodes WITH default_time_to_live = 3600;
]]
}
}
|
return {
{
name = "2015-01-12-175310_skeleton",
up = function(db, kong_config)
local keyspace_name = kong_config.cassandra_keyspace
local strategy, strategy_properties = kong_config.cassandra_repl_strategy, ""
-- Format strategy options
if strategy == "SimpleStrategy" then
strategy_properties = string.format(", 'replication_factor': %s", kong_config.cassandra_repl_factor)
elseif strategy == "NetworkTopologyStrategy" then
local dcs = {}
for _, dc_conf in ipairs(kong_config.cassandra_data_centers) do
local dc_name, dc_repl = string.match(dc_conf, "(%w+):(%d+)")
if dc_name and dc_repl then
table.insert(dcs, string.format("'%s': %s", dc_name, dc_repl))
else
return "invalid cassandra_data_centers configuration"
end
end
if #dcs > 0 then
strategy_properties = string.format(", %s", table.concat(dcs, ", "))
end
else
-- Strategy unknown
return "invalid replication_strategy class"
end
-- Format final keyspace creation query
local keyspace_str = string.format([[
CREATE KEYSPACE IF NOT EXISTS "%s"
WITH REPLICATION = {'class': '%s'%s};
]], keyspace_name, strategy, strategy_properties)
local res, err = db:query(keyspace_str, nil, nil, nil, true)
if not res then
return err
end
local res, err = db:query [[
CREATE TABLE IF NOT EXISTS schema_migrations(
id text PRIMARY KEY,
migrations list<text>
);
]]
if not res then
return err
end
end,
down = [[
DROP TABLE schema_migrations;
]]
},
{
name = "2015-01-12-175310_init_schema",
up = [[
CREATE TABLE IF NOT EXISTS consumers(
id uuid,
custom_id text,
username text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON consumers(custom_id);
CREATE INDEX IF NOT EXISTS ON consumers(username);
CREATE TABLE IF NOT EXISTS apis(
id uuid,
name text,
request_host text,
request_path text,
strip_request_path boolean,
upstream_url text,
preserve_host boolean,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON apis(name);
CREATE INDEX IF NOT EXISTS ON apis(request_host);
CREATE INDEX IF NOT EXISTS ON apis(request_path);
CREATE TABLE IF NOT EXISTS plugins(
id uuid,
api_id uuid,
consumer_id uuid,
name text,
config text, -- serialized plugin configuration
enabled boolean,
created_at timestamp,
PRIMARY KEY (id, name)
);
CREATE INDEX IF NOT EXISTS ON plugins(name);
CREATE INDEX IF NOT EXISTS ON plugins(api_id);
CREATE INDEX IF NOT EXISTS ON plugins(consumer_id);
]],
down = [[
DROP TABLE consumers;
DROP TABLE apis;
DROP TABLE plugins;
]]
},
{
name = "2015-11-23-817313_nodes",
up = [[
CREATE TABLE IF NOT EXISTS nodes(
name text,
cluster_listening_address text,
created_at timestamp,
PRIMARY KEY (name)
) WITH default_time_to_live = 3600;
CREATE INDEX IF NOT EXISTS ON nodes(cluster_listening_address);
]],
down = [[
DROP TABLE nodes;
]]
},
{
name = "2016-02-25-160900_remove_null_consumer_id",
up = function(_, _, dao)
local rows, err = dao.plugins:find_all {consumer_id = "00000000-0000-0000-0000-000000000000"}
if err then
return err
end
for _, row in ipairs(rows) do
row.consumer_id = nil
local _, err = dao.plugins:update(row, row, {full = true})
if err then
return err
end
end
end
},
{
name = "2016-02-29-121813_remove_ttls",
up = [[
ALTER TABLE nodes WITH default_time_to_live = 0;
]],
down = [[
ALTER TABLE nodes WITH default_time_to_live = 3600;
]]
}
}
|
fix(cassandra) migrations with NetworkTopology and explicit datacenters
|
fix(cassandra) migrations with NetworkTopology and explicit datacenters
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,jerizm/kong,icyxp/kong,Mashape/kong,Vermeille/kong,akh00/kong,Kong/kong,li-wl/kong,salazar/kong,ccyphers/kong,shiprabehera/kong,beauli/kong,jebenexer/kong
|
c16f18a866d49d7ac602219978ac9cc9a09d3dc7
|
love2d/world.lua
|
love2d/world.lua
|
require "tileset"
require "map"
require "pawn"
require "mapGenerator"
function love.game.newWorld()
local o = {}
o.mapG = nil
o.map = nil
o.mapWidth = 32
o.mapHeight = 24
o.tileset = nil
o.offsetX = 0
o.offsetY = 0
o.zoom = 1
o.offsetX = 0
o.offsetY = 0
o.goalX = 7
o.goalY =7
o.init = function()
o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight)
o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1)
o.map = love.game.newMap(o.mapWidth, o.mapHeight)
o.map.setTileset(o.tileset)
o.map.init()
--test
for i = 1, o.mapWidth do
for k = 1, o.mapHeight do
-- field
if MapGenerator.getID(o.mapG, i, k) == 1 then
o.map.setTileLayer(i, k, 1, 0)
elseif MapGenerator.getID(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k, 1, 2)
end
--objects
if MapGenerator.getObject(o.mapG, i, k) == 1 then
o.map.setTileLayer(i, k, 2, 3)
elseif MapGenerator.getObject(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k, 2, 22)
elseif MapGenerator.getObject(o.mapG, i, k) == 4 then
o.map.setTileLayer(i, k, 2, 18)
else
o.map.setTileLayer(i, k, 2, 63)
end
--objects 2
if MapGenerator.getObject(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k - 1, 3, 14)
else
o.map.setTileLayer(i, k - 1, 3, 63)
end
end
end
o.pawns = {}
local pawn = love.game.newPawn(o)
table.insert(o.pawns, pawn)
end
o.update = function(dt)
if love.keyboard.isDown("left") then
o.offsetX = o.offsetX + dt * 100
elseif love.keyboard.isDown("right") then
o.offsetX = o.offsetX - dt * 100
end
if love.keyboard.isDown("up") then
o.offsetY = o.offsetY + dt * 100
elseif love.keyboard.isDown("down") then
o.offsetY = o.offsetY - dt * 100
end
o.map.update(dt)
for i = 1, #o.pawns do
o.pawns[i].update(dt)
end
for i = 1, o.mapWidth do
for k = 1, o.mapHeight do
if MapGenerator.getObject(o.mapG, i, k) == 4 then
o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4))
end
end
end
end
o.draw = function()
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1)
for i = 1, #o.pawns do
o.pawns[i].draw(o.offsetX, o.offsetY)
end
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2)
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3)
o.drawMapCursor()
end
o.zoomIn = function(z)
z = z or 2
o.zoom = o.zoom * z
o.map.setZoom(o.zoom)
for i = 1, #o.pawns do
o.pawns[i].setZoom(o.zoom)
end
end
o.zoomOut = function(z)
z = z or 2
o.zoom = o.zoom / z
o.map.setZoom(o.zoom)
for i = 1, #o.pawns do
o.pawns[i].setZoom(o.zoom)
end
end
o.drawMapCursor = function()
local mx = love.mouse.getX()
local my = love.mouse.getY()
--[[
local tileX, tileY = getTileFromScreen(o.map, mx, my)
tileX = tileX * o.map.tileScale
tileY = tileY * o.map.tileScale
if tileX >= 0 and tileY >= 0 and tileX < o.map.width and tileY < o.map.height then
G.setColor(255, 63, 0)
G.setLineWidth(2)
local tw = o.map.tileset.tileWidth
local th = o.map.tileset.tileHeight
if tw and th then
G.rectangle("line", tileX * tw*o.zoom - o.offsetX , tileY * th*o.zoom - o.offsetY, tw*o.zoom*o.map.tileScale, th*o.zoom*o.map.tileScale)
end
end
]]--
G.setColor(255, 63, 0)
G.rectangle("line",
math.floor((mx - o.offsetX * o.zoom) / (o.tileset.tileWidth * o.map.tileScale * o.zoom)) * (o.tileset.tileWidth * o.map.tileScale * o.zoom) + (o.offsetX * o.zoom),
math.floor((my - o.offsetY * o.zoom) / (o.tileset.tileHeight * o.map.tileScale * o.zoom)) * (o.tileset.tileHeight * o.map.tileScale * o.zoom) + (o.offsetY * o.zoom),
o.tileset.tileWidth * o.map.tileScale * o.zoom,
o.tileset.tileHeight * o.map.tileScale * o.zoom
)
end
o.setGoal = function(map, x,y)
o.goalX, o.goalY = getTileFromScreen(map,x,y)
print (x, y, o.goalX, o.goalY)
end
return o
end
getTileFromScreen = function(map, mx, my)
local ts = map.tileScale
local tw = map.tileset.tileWidth
local th = map.tileset.tileHeight
local tileX =math.floor((mx) / (tw*ts))
local tileY =math.floor((my) / (tw*ts))
return tileX, tileY
end
|
require "tileset"
require "map"
require "pawn"
require "mapGenerator"
function love.game.newWorld()
local o = {}
o.mapG = nil
o.map = nil
o.mapWidth = 32
o.mapHeight = 24
o.tileset = nil
o.offsetX = 0
o.offsetY = 0
o.zoom = 1
o.offsetX = 0
o.offsetY = 0
o.goalX = 7
o.goalY =7
o.init = function()
o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight)
o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1)
o.map = love.game.newMap(o.mapWidth, o.mapHeight)
o.map.setTileset(o.tileset)
o.map.init()
--test
for i = 1, o.mapWidth do
for k = 1, o.mapHeight do
-- field
if MapGenerator.getID(o.mapG, i, k) == 1 then
o.map.setTileLayer(i, k, 1, 0)
elseif MapGenerator.getID(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k, 1, 2)
end
--objects
if MapGenerator.getObject(o.mapG, i, k) == 1 then
o.map.setTileLayer(i, k, 2, 3)
elseif MapGenerator.getObject(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k, 2, 22)
elseif MapGenerator.getObject(o.mapG, i, k) == 4 then
o.map.setTileLayer(i, k, 2, 18)
else
o.map.setTileLayer(i, k, 2, 63)
end
--objects 2
if MapGenerator.getObject(o.mapG, i, k) == 2 then
o.map.setTileLayer(i, k - 1, 3, 14)
else
o.map.setTileLayer(i, k - 1, 3, 63)
end
end
end
o.pawns = {}
local pawn = love.game.newPawn(o)
table.insert(o.pawns, pawn)
end
o.update = function(dt)
if love.keyboard.isDown("left") then
o.offsetX = o.offsetX + dt * 100
elseif love.keyboard.isDown("right") then
o.offsetX = o.offsetX - dt * 100
end
if love.keyboard.isDown("up") then
o.offsetY = o.offsetY + dt * 100
elseif love.keyboard.isDown("down") then
o.offsetY = o.offsetY - dt * 100
end
o.map.update(dt)
for i = 1, #o.pawns do
o.pawns[i].update(dt)
end
for i = 1, o.mapWidth do
for k = 1, o.mapHeight do
if MapGenerator.getObject(o.mapG, i, k) == 4 then
o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4))
end
end
end
end
o.draw = function()
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1)
for i = 1, #o.pawns do
o.pawns[i].draw(o.offsetX, o.offsetY)
end
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2)
o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3)
o.drawMapCursor()
end
o.zoomIn = function(z)
z = z or 2
o.zoom = o.zoom * z
o.map.setZoom(o.zoom)
for i = 1, #o.pawns do
o.pawns[i].setZoom(o.zoom)
end
end
o.zoomOut = function(z)
z = z or 2
o.zoom = o.zoom / z
o.map.setZoom(o.zoom)
for i = 1, #o.pawns do
o.pawns[i].setZoom(o.zoom)
end
end
o.drawMapCursor = function()
local mx = love.mouse.getX()
local my = love.mouse.getY()
local tileX, tileY = o.getTileFromScreen(mx, my)
G.setColor(255, 63, 0)
G.rectangle("line",
tileX * (o.tileset.tileWidth * o.map.tileScale * o.zoom) + (o.offsetX * o.zoom),
tileY * (o.tileset.tileHeight * o.map.tileScale * o.zoom) + (o.offsetY * o.zoom),
o.tileset.tileWidth * o.map.tileScale * o.zoom,
o.tileset.tileHeight * o.map.tileScale * o.zoom
)
end
o.setGoal = function(map, x, y)
o.goalX, o.goalY = o.getTileFromScreen(x, y)
end
o.getTileFromScreen = function(mx, my)
local tileX = math.floor((mx - o.offsetX * o.zoom) / (o.tileset.tileWidth * o.map.tileScale * o.zoom))
local tileY = math.floor((my - o.offsetY * o.zoom) / (o.tileset.tileHeight * o.map.tileScale * o.zoom))
return tileX, tileY
end
return o
end
|
Fix mouse target.
|
Fix mouse target.
|
Lua
|
mit
|
nczempin/lizard-journey
|
4551ddaaa6099f8432313cded6392888ad72e9fe
|
tools/benchmark.lua
|
tools/benchmark.lua
|
require 'pl'
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path
require 'xlua'
require 'w2nn'
local iproc = require 'iproc'
local reconstruct = require 'reconstruct'
local image_loader = require 'image_loader'
local gm = require 'graphicsmagick'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-benchmark")
cmd:text("Options:")
cmd:option("-dir", "./data/test", 'test image directory')
cmd:option("-model1_dir", "./models/anime_style_art_rgb", 'model1 directory')
cmd:option("-model2_dir", "", 'model2 directory (optional)')
cmd:option("-method", "scale", '(scale|noise)')
cmd:option("-filter", "Catrom", "downscaling filter (Box|Lanczos|Catrom(Bicubic))")
cmd:option("-color", "y", '(rgb|y)')
cmd:option("-noise_level", 1, 'model noise level')
cmd:option("-jpeg_quality", 75, 'jpeg quality')
cmd:option("-jpeg_times", 1, 'jpeg compression times')
cmd:option("-jpeg_quality_down", 5, 'value of jpeg quality to decrease each times')
local opt = cmd:parse(arg)
torch.setdefaulttensortype('torch.FloatTensor')
if cudnn then
cudnn.fastest = true
cudnn.benchmark = false
end
local function rgb2y_matlab(x)
local y = torch.Tensor(1, x:size(2), x:size(3)):zero()
x = iproc.byte2float(x)
y:add(x[1] * 65.481)
y:add(x[2] * 128.553)
y:add(x[3] * 24.966)
y:add(16.0)
return y:byte():float()
end
local function MSE(x1, x2)
x1 = iproc.float2byte(x1):float()
x2 = iproc.float2byte(x2):float()
return (x1 - x2):pow(2):mean()
end
local function YMSE(x1, x2)
local x1_2 = rgb2y_matlab(x1)
local x2_2 = rgb2y_matlab(x2)
return (x1_2 - x2_2):pow(2):mean()
end
local function PSNR(x1, x2)
local mse = MSE(x1, x2)
return 10 * math.log10((255.0 * 255.0) / mse)
end
local function YPSNR(x1, x2)
local mse = YMSE(x1, x2)
return 10 * math.log10((255.0 * 255.0) / mse)
end
local function transform_jpeg(x, opt)
for i = 1, opt.jpeg_times do
jpeg = gm.Image(x, "RGB", "DHW")
jpeg:format("jpeg")
jpeg:samplingFactors({1.0, 1.0, 1.0})
blob, len = jpeg:toBlob(opt.jpeg_quality - (i - 1) * opt.jpeg_quality_down)
jpeg:fromBlob(blob, len)
x = jpeg:toTensor("byte", "RGB", "DHW")
end
return x
end
local function baseline_scale(x, filter)
return iproc.scale(x,
x:size(3) * 2.0,
x:size(2) * 2.0,
filter)
end
local function transform_scale(x, opt)
return iproc.scale(x,
x:size(3) * 0.5,
x:size(2) * 0.5,
opt.filter)
end
local function benchmark(opt, x, input_func, model1, model2)
local model1_mse = 0
local model2_mse = 0
local baseline_mse = 0
local model1_psnr = 0
local model2_psnr = 0
local baseline_psnr = 0
for i = 1, #x do
local ground_truth = x[i]
local input, model1_output, model2_output, baseline_output
input = input_func(ground_truth, opt)
t = sys.clock()
if input:size(3) == ground_truth:size(3) then
model1_output = reconstruct.image(model1, input)
if model2 then
model2_output = reconstruct.image(model2, input)
end
else
model1_output = reconstruct.scale(model1, 2.0, input)
if model2 then
model2_output = reconstruct.scale(model2, 2.0, input)
end
baseline_output = baseline_scale(input, opt.filter)
end
if opt.color == "y" then
model1_mse = model1_mse + YMSE(ground_truth, model1_output)
model1_psnr = model1_psnr + YPSNR(ground_truth, model1_output)
if model2 then
model2_mse = model2_mse + YMSE(ground_truth, model2_output)
model2_psnr = model2_psnr + YPSNR(ground_truth, model2_output)
end
if baseline_output then
baseline_mse = baseline_mse + YMSE(ground_truth, baseline_output)
baseline_psnr = baseline_psnr + YPSNR(ground_truth, baseline_output)
end
elseif opt.color == "rgb" then
model1_mse = model1_mse + MSE(ground_truth, model1_output)
model1_psnr = model1_psnr + PSNR(ground_truth, model1_output)
if model2 then
model2_mse = model2_mse + MSE(ground_truth, model2_output)
model2_psnr = model2_psnr + PSNR(ground_truth, model2_output)
end
if baseline_output then
baseline_mse = baseline_mse + MSE(ground_truth, baseline_output)
baseline_psnr = baseline_psnr + PSNR(ground_truth, baseline_output)
end
else
error("Unknown color: " .. opt.color)
end
if model2 then
if baseline_output then
io.stdout:write(
string.format("%d/%d; baseline_mse=%f, model1_mse=%f, model2_mse=%f, baseline_psnr=%f, model1_psnr=%f, model2_psnr=%f \r",
i, #x,
baseline_mse / i,
model1_mse / i, model2_mse / i,
baseline_psnr / i,
model1_psnr / i, model2_psnr / i
))
else
io.stdout:write(
string.format("%d/%d; model1_mse=%f, model2_mse=%f, model1_psnr=%f, model2_psnr=%f \r",
i, #x,
model1_mse / i, model2_mse / i,
model1_psnr / i, model2_psnr / i
))
end
else
if baseline_output then
io.stdout:write(
string.format("%d/%d; baseline_mse=%f, model1_mse=%f, baseline_psnr=%f, model1_psnr=%f \r",
i, #x,
baseline_mse / i, model1_mse / i,
baseline_psnr / i, model1_psnr / i
))
else
io.stdout:write(
string.format("%d/%d; model1_mse=%f, model1_psnr=%f \r",
i, #x,
model1_mse / i, model1_psnr / i
))
end
end
io.stdout:flush()
end
io.stdout:write("\n")
end
local function load_data(test_dir)
local test_x = {}
local files = dir.getfiles(test_dir, "*.*")
for i = 1, #files do
table.insert(test_x, iproc.crop_mod4(image_loader.load_float(files[i])))
xlua.progress(i, #files)
end
return test_x
end
function load_model(filename)
return torch.load(filename, "ascii")
end
print(opt)
if opt.method == "scale" then
local f1 = path.join(opt.model1_dir, "scale2.0x_model.t7")
local f2 = path.join(opt.model2_dir, "scale2.0x_model.t7")
local s1, model1 = pcall(load_model, f1)
local s2, model2 = pcall(load_model, f2)
if not s1 then
error("Load error: " .. f1)
end
if not s2 then
model2 = nil
end
local test_x = load_data(opt.dir)
benchmark(opt, test_x, transform_scale, model1, model2)
elseif opt.method == "noise" then
local f1 = path.join(opt.model1_dir, string.format("noise%d_model.t7", opt.noise_level))
local f2 = path.join(opt.model2_dir, string.format("noise%d_model.t7", opt.noise_level))
local s1, model1 = pcall(load_model, f1)
local s2, model2 = pcall(load_model, f2)
if not s1 then
error("Load error: " .. f1)
end
if not s2 then
model2 = nil
end
local test_x = load_data(opt.dir)
benchmark(opt, test_x, transform_jpeg, model1, model2)
end
|
require 'pl'
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path
require 'xlua'
require 'w2nn'
local iproc = require 'iproc'
local reconstruct = require 'reconstruct'
local image_loader = require 'image_loader'
local gm = require 'graphicsmagick'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-benchmark")
cmd:text("Options:")
cmd:option("-dir", "./data/test", 'test image directory')
cmd:option("-model1_dir", "./models/anime_style_art_rgb", 'model1 directory')
cmd:option("-model2_dir", "", 'model2 directory (optional)')
cmd:option("-method", "scale", '(scale|noise)')
cmd:option("-filter", "Catrom", "downscaling filter (Box|Lanczos|Catrom(Bicubic))")
cmd:option("-color", "y", '(rgb|y)')
cmd:option("-noise_level", 1, 'model noise level')
cmd:option("-jpeg_quality", 75, 'jpeg quality')
cmd:option("-jpeg_times", 1, 'jpeg compression times')
cmd:option("-jpeg_quality_down", 5, 'value of jpeg quality to decrease each times')
cmd:option("-range_bug", 0, 'Reproducing the dynamic range bug that is caused by MATLAB\'s rgb2ycbcr(1|0)')
local opt = cmd:parse(arg)
torch.setdefaulttensortype('torch.FloatTensor')
if cudnn then
cudnn.fastest = true
cudnn.benchmark = false
end
local function rgb2y_matlab(x)
local y = torch.Tensor(1, x:size(2), x:size(3)):zero()
x = iproc.byte2float(x)
y:add(x[1] * 65.481)
y:add(x[2] * 128.553)
y:add(x[3] * 24.966)
y:add(16.0)
return y:byte():float()
end
local function MSE(x1, x2)
x1 = iproc.float2byte(x1):float()
x2 = iproc.float2byte(x2):float()
return (x1 - x2):pow(2):mean()
end
local function YMSE(x1, x2)
if opt.range_bug == 1 then
local x1_2 = rgb2y_matlab(x1)
local x2_2 = rgb2y_matlab(x2)
return (x1_2 - x2_2):pow(2):mean()
else
local x1_2 = image.rgb2y(x1):mul(255.0)
local x2_2 = image.rgb2y(x2):mul(255.0)
return (x1_2 - x2_2):pow(2):mean()
end
end
local function PSNR(x1, x2)
local mse = MSE(x1, x2)
return 10 * math.log10((255.0 * 255.0) / mse)
end
local function YPSNR(x1, x2)
local mse = YMSE(x1, x2)
return 10 * math.log10((255.0 * 255.0) / mse)
end
local function transform_jpeg(x, opt)
for i = 1, opt.jpeg_times do
jpeg = gm.Image(x, "RGB", "DHW")
jpeg:format("jpeg")
jpeg:samplingFactors({1.0, 1.0, 1.0})
blob, len = jpeg:toBlob(opt.jpeg_quality - (i - 1) * opt.jpeg_quality_down)
jpeg:fromBlob(blob, len)
x = jpeg:toTensor("byte", "RGB", "DHW")
end
return x
end
local function baseline_scale(x, filter)
return iproc.scale(x,
x:size(3) * 2.0,
x:size(2) * 2.0,
filter)
end
local function transform_scale(x, opt)
return iproc.scale(x,
x:size(3) * 0.5,
x:size(2) * 0.5,
opt.filter)
end
local function benchmark(opt, x, input_func, model1, model2)
local model1_mse = 0
local model2_mse = 0
local baseline_mse = 0
local model1_psnr = 0
local model2_psnr = 0
local baseline_psnr = 0
for i = 1, #x do
local ground_truth = x[i]
local input, model1_output, model2_output, baseline_output
input = input_func(ground_truth, opt)
t = sys.clock()
if input:size(3) == ground_truth:size(3) then
model1_output = reconstruct.image(model1, input)
if model2 then
model2_output = reconstruct.image(model2, input)
end
else
model1_output = reconstruct.scale(model1, 2.0, input)
if model2 then
model2_output = reconstruct.scale(model2, 2.0, input)
end
baseline_output = baseline_scale(input, opt.filter)
end
if opt.color == "y" then
model1_mse = model1_mse + YMSE(ground_truth, model1_output)
model1_psnr = model1_psnr + YPSNR(ground_truth, model1_output)
if model2 then
model2_mse = model2_mse + YMSE(ground_truth, model2_output)
model2_psnr = model2_psnr + YPSNR(ground_truth, model2_output)
end
if baseline_output then
baseline_mse = baseline_mse + YMSE(ground_truth, baseline_output)
baseline_psnr = baseline_psnr + YPSNR(ground_truth, baseline_output)
end
elseif opt.color == "rgb" then
model1_mse = model1_mse + MSE(ground_truth, model1_output)
model1_psnr = model1_psnr + PSNR(ground_truth, model1_output)
if model2 then
model2_mse = model2_mse + MSE(ground_truth, model2_output)
model2_psnr = model2_psnr + PSNR(ground_truth, model2_output)
end
if baseline_output then
baseline_mse = baseline_mse + MSE(ground_truth, baseline_output)
baseline_psnr = baseline_psnr + PSNR(ground_truth, baseline_output)
end
else
error("Unknown color: " .. opt.color)
end
if model2 then
if baseline_output then
io.stdout:write(
string.format("%d/%d; baseline_mse=%f, model1_mse=%f, model2_mse=%f, baseline_psnr=%f, model1_psnr=%f, model2_psnr=%f \r",
i, #x,
baseline_mse / i,
model1_mse / i, model2_mse / i,
baseline_psnr / i,
model1_psnr / i, model2_psnr / i
))
else
io.stdout:write(
string.format("%d/%d; model1_mse=%f, model2_mse=%f, model1_psnr=%f, model2_psnr=%f \r",
i, #x,
model1_mse / i, model2_mse / i,
model1_psnr / i, model2_psnr / i
))
end
else
if baseline_output then
io.stdout:write(
string.format("%d/%d; baseline_mse=%f, model1_mse=%f, baseline_psnr=%f, model1_psnr=%f \r",
i, #x,
baseline_mse / i, model1_mse / i,
baseline_psnr / i, model1_psnr / i
))
else
io.stdout:write(
string.format("%d/%d; model1_mse=%f, model1_psnr=%f \r",
i, #x,
model1_mse / i, model1_psnr / i
))
end
end
io.stdout:flush()
end
io.stdout:write("\n")
end
local function load_data(test_dir)
local test_x = {}
local files = dir.getfiles(test_dir, "*.*")
for i = 1, #files do
table.insert(test_x, iproc.crop_mod4(image_loader.load_float(files[i])))
xlua.progress(i, #files)
end
return test_x
end
function load_model(filename)
return torch.load(filename, "ascii")
end
print(opt)
if opt.method == "scale" then
local f1 = path.join(opt.model1_dir, "scale2.0x_model.t7")
local f2 = path.join(opt.model2_dir, "scale2.0x_model.t7")
local s1, model1 = pcall(load_model, f1)
local s2, model2 = pcall(load_model, f2)
if not s1 then
error("Load error: " .. f1)
end
if not s2 then
model2 = nil
end
local test_x = load_data(opt.dir)
benchmark(opt, test_x, transform_scale, model1, model2)
elseif opt.method == "noise" then
local f1 = path.join(opt.model1_dir, string.format("noise%d_model.t7", opt.noise_level))
local f2 = path.join(opt.model2_dir, string.format("noise%d_model.t7", opt.noise_level))
local s1, model1 = pcall(load_model, f1)
local s2, model2 = pcall(load_model, f2)
if not s1 then
error("Load error: " .. f1)
end
if not s2 then
model2 = nil
end
local test_x = load_data(opt.dir)
benchmark(opt, test_x, transform_jpeg, model1, model2)
end
|
Add support to reproduce the dynamic range bug in PSNR
|
Add support to reproduce the dynamic range bug in PSNR
I think some academic paper has this bug.
|
Lua
|
mit
|
nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,higankanshi/waifu2x,vitaliylag/waifu2x
|
61a9bb2b474c600cfd87f214d19ba567585ee1e3
|
mods/creative/init.lua
|
mods/creative/init.lua
|
-- minetest/creative/init.lua
local creative_inventory = {}
-- Create detached creative inventory after loading all mods
minetest.after(0, function()
local inv = minetest.create_detached_inventory("creative", {
allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
if minetest.setting_getbool("creative_mode") then
return count
else
return 0
end
end,
allow_put = function(inv, listname, index, stack, player)
if minetest.setting_getbool("creative_mode") then
return -1
else
return 0
end
end,
allow_take = function(inv, listname, index, stack, player)
if minetest.setting_getbool("creative_mode") then
return -1
else
return 0
end
end,
on_move = function(inv, from_list, from_index, to_list, to_index, count, player)
end,
on_put = function(inv, listname, index, stack, player)
end,
on_take = function(inv, listname, index, stack, player)
print(player:get_player_name().." takes item from creative inventory; listname="..dump(listname)..", index="..dump(index)..", stack="..dump(stack))
if stack then
print("stack:get_name()="..dump(stack:get_name())..", stack:get_count()="..dump(stack:get_count()))
end
end,
})
local creative_list = {}
for name,def in pairs(minetest.registered_items) do
if (not def.groups.not_in_creative_inventory or def.groups.not_in_creative_inventory == 0)
and def.description and def.description ~= "" then
table.insert(creative_list, name)
end
end
table.sort(creative_list)
inv:set_size("main", #creative_list)
for _,itemstring in ipairs(creative_list) do
local stack = ItemStack(itemstring)
-- Make a stack of the right number of items
local stack2 = nil
if stack:get_stack_max() == 1 then
stack2 = ItemStack(stack:get_name())
else
-- Insert half full so that a taken stack can be put back
stack2 = ItemStack(stack:get_name().." "..(stack:get_stack_max()/2))
end
inv:add_item("main", stack2)
end
creative_inventory.creative_inventory_size = #creative_list
print("creative inventory size: "..dump(creative_inventory.creative_inventory_size))
end)
creative_inventory.set_creative_formspec = function(player, start_i, pagenum)
pagenum = math.floor(pagenum)
local pagemax = math.floor((creative_inventory.creative_inventory_size-1) / (6*4) + 1)
player:set_inventory_formspec("size[13,7.5]"..
--"image[6,0.6;1,2;player.png]"..
"list[current_player;main;5,3.5;8,4;]"..
"list[current_player;craft;8,0;3,3;]"..
"list[current_player;craftpreview;12,1;1,1;]"..
"list[detached:creative;main;0.3,0.5;4,6;"..tostring(start_i).."]"..
"label[2.0,6.55;"..tostring(pagenum).."/"..tostring(pagemax).."]"..
"button[0.3,6.5;1.6,1;creative_prev;<<]"..
"button[2.7,6.5;1.6,1;creative_next;>>]")
end
minetest.register_on_joinplayer(function(player)
-- If in creative mode, modify player's inventory forms
if not minetest.setting_getbool("creative_mode") then
return
end
creative_inventory.set_creative_formspec(player, 0, 1)
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
if not minetest.setting_getbool("creative_mode") then
return
end
-- Figure out current page from formspec
local current_page = 0
local formspec = player:get_inventory_formspec()
local start_i = string.match(formspec, "list%[detached:creative;main;[%d.]+,[%d.]+;[%d.]+,[%d.]+;(%d+)%]")
start_i = tonumber(start_i) or 0
if fields.creative_prev then
start_i = start_i - 4*6
end
if fields.creative_next then
start_i = start_i + 4*6
end
if start_i < 0 then
start_i = start_i + 4*6
end
if start_i >= creative_inventory.creative_inventory_size then
start_i = start_i - 4*6
end
if start_i < 0 or start_i >= creative_inventory.creative_inventory_size then
start_i = 0
end
creative_inventory.set_creative_formspec(player, start_i, start_i / (6*4) + 1)
end)
|
-- minetest/creative/init.lua
local creative_inventory = {}
creative_inventory.creative_inventory_size = 0
-- Create detached creative inventory after loading all mods
minetest.after(0, function()
local inv = minetest.create_detached_inventory("creative", {
allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
if minetest.setting_getbool("creative_mode") then
return count
else
return 0
end
end,
allow_put = function(inv, listname, index, stack, player)
if minetest.setting_getbool("creative_mode") then
return -1
else
return 0
end
end,
allow_take = function(inv, listname, index, stack, player)
if minetest.setting_getbool("creative_mode") then
return -1
else
return 0
end
end,
on_move = function(inv, from_list, from_index, to_list, to_index, count, player)
end,
on_put = function(inv, listname, index, stack, player)
end,
on_take = function(inv, listname, index, stack, player)
print(player:get_player_name().." takes item from creative inventory; listname="..dump(listname)..", index="..dump(index)..", stack="..dump(stack))
if stack then
print("stack:get_name()="..dump(stack:get_name())..", stack:get_count()="..dump(stack:get_count()))
end
end,
})
local creative_list = {}
for name,def in pairs(minetest.registered_items) do
if (not def.groups.not_in_creative_inventory or def.groups.not_in_creative_inventory == 0)
and def.description and def.description ~= "" then
table.insert(creative_list, name)
end
end
table.sort(creative_list)
inv:set_size("main", #creative_list)
for _,itemstring in ipairs(creative_list) do
local stack = ItemStack(itemstring)
-- Make a stack of the right number of items
local stack2 = nil
if stack:get_stack_max() == 1 then
stack2 = ItemStack(stack:get_name())
else
-- Insert half full so that a taken stack can be put back
stack2 = ItemStack(stack:get_name().." "..(stack:get_stack_max()/2))
end
inv:add_item("main", stack2)
end
creative_inventory.creative_inventory_size = #creative_list
print("creative inventory size: "..dump(creative_inventory.creative_inventory_size))
end)
creative_inventory.set_creative_formspec = function(player, start_i, pagenum)
pagenum = math.floor(pagenum)
local pagemax = math.floor((creative_inventory.creative_inventory_size-1) / (6*4) + 1)
player:set_inventory_formspec("size[13,7.5]"..
--"image[6,0.6;1,2;player.png]"..
"list[current_player;main;5,3.5;8,4;]"..
"list[current_player;craft;8,0;3,3;]"..
"list[current_player;craftpreview;12,1;1,1;]"..
"list[detached:creative;main;0.3,0.5;4,6;"..tostring(start_i).."]"..
"label[2.0,6.55;"..tostring(pagenum).."/"..tostring(pagemax).."]"..
"button[0.3,6.5;1.6,1;creative_prev;<<]"..
"button[2.7,6.5;1.6,1;creative_next;>>]")
end
minetest.register_on_joinplayer(function(player)
-- If in creative mode, modify player's inventory forms
if not minetest.setting_getbool("creative_mode") then
return
end
creative_inventory.set_creative_formspec(player, 0, 1)
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
if not minetest.setting_getbool("creative_mode") then
return
end
-- Figure out current page from formspec
local current_page = 0
local formspec = player:get_inventory_formspec()
local start_i = string.match(formspec, "list%[detached:creative;main;[%d.]+,[%d.]+;[%d.]+,[%d.]+;(%d+)%]")
start_i = tonumber(start_i) or 0
if fields.creative_prev then
start_i = start_i - 4*6
end
if fields.creative_next then
start_i = start_i + 4*6
end
if start_i < 0 then
start_i = start_i + 4*6
end
if start_i >= creative_inventory.creative_inventory_size then
start_i = start_i - 4*6
end
if start_i < 0 or start_i >= creative_inventory.creative_inventory_size then
start_i = 0
end
creative_inventory.set_creative_formspec(player, start_i, start_i / (6*4) + 1)
end)
|
Fix crash when a player happens to join the server quicker than the creative inventory filler is called
|
Fix crash when a player happens to join the server quicker than the creative inventory filler is called
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
200a515abd3828587e2371ebe71b8866ab43381c
|
core/ext/mime_types.lua
|
core/ext/mime_types.lua
|
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
--- Handles file-specific settings (based on file extension).
module('textadept.mime_types', package.seeall)
---
-- File extensions with their associated lexers.
-- @class table
-- @name extensions
extensions = {}
---
-- Shebang words and their associated lexers.
-- @class table
-- @name shebangs
shebangs = {}
---
-- First-line patterns and their associated lexers.
-- @class table
-- @name patterns
patterns = {}
-- Load mime-types from mime_types.conf
local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb')
if f then
for line in f:lines() do
if not line:find('^%s*%%') then
if line:find('^%s*[^#/]') then -- extension definition
local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$')
if ext and lexer_name then extensions[ext] = lexer_name end
else -- shebang or pattern
local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$')
if ch and text and lexer_name then
(ch == '#' and shebangs or patterns)[text] = lexer_name
end
end
end
end
f:close()
end
---
-- [Local function] Replacement for buffer:set_lexer_language().
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.
-- @param buffer The buffer to set the lexer language of.
-- @param lang The string language to set.
local function set_lexer_language(buffer, lang)
buffer._lexer = lang
buffer:set_lexer_language_(lang)
end
textadept.events.add_handler('buffer_new',
function()
buffer.set_lexer_language_ = buffer.set_lexer_language
buffer.set_lexer_language = set_lexer_language
end)
---
-- [Local function] Performs actions suitable for a new buffer.
-- Sets the buffer's lexer language and loads the language module.
local function handle_new()
local lexer
if buffer.filename then
lexer = extensions[buffer.filename:match('[^/\\.]+$')]
end
if not lexer then
local line = buffer:get_line(0)
if line:find('^#!') then
for word in line:gsub('[/\\]', ' '):gmatch('%S+') do
lexer = shebangs[word]
if lexer then break end
end
end
if not lexer then
for patt, lex in pairs(patterns) do
if line:find(patt) then
lexer = lex
break
end
end
end
end
buffer:set_lexer_language(lexer or 'container')
if buffer.filename then
local lang = extensions[buffer.filename:match('[^/\\.]+$')]
if lang then
local ret, err = pcall(require, lang)
if ret then
_m[lang].set_buffer_properties()
elseif not ret and not err:find("^module '"..lang.."' not found:") then
textadept.events.error(err)
end
end
end
end
---
-- [Local function] Sets the buffer's lexer based on filename, shebang words, or
-- first line pattern.
local function restore_lexer()
buffer:set_lexer_language(buffer._lexer or 'container')
end
textadept.events.add_handler('file_opened', handle_new)
textadept.events.add_handler('file_saved_as', handle_new)
textadept.events.add_handler('buffer_after_switch', restore_lexer)
textadept.events.add_handler('view_new', restore_lexer)
|
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
--- Handles file-specific settings (based on file extension).
module('textadept.mime_types', package.seeall)
---
-- File extensions with their associated lexers.
-- @class table
-- @name extensions
extensions = {}
---
-- Shebang words and their associated lexers.
-- @class table
-- @name shebangs
shebangs = {}
---
-- First-line patterns and their associated lexers.
-- @class table
-- @name patterns
patterns = {}
-- Load mime-types from mime_types.conf
local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb')
if f then
for line in f:lines() do
if not line:find('^%s*%%') then
if line:find('^%s*[^#/]') then -- extension definition
local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$')
if ext and lexer_name then extensions[ext] = lexer_name end
else -- shebang or pattern
local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$')
if ch and text and lexer_name then
(ch == '#' and shebangs or patterns)[text] = lexer_name
end
end
end
end
f:close()
end
---
-- [Local function] Replacement for buffer:set_lexer_language().
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.
-- @param buffer The buffer to set the lexer language of.
-- @param lang The string language to set.
local function set_lexer(buffer, lang)
buffer._lexer = lang
buffer:set_lexer_language(lang)
end
textadept.events.add_handler('buffer_new',
function() buffer.set_lexer = set_lexer end)
---
-- [Local function] Performs actions suitable for a new buffer.
-- Sets the buffer's lexer language and loads the language module.
local function handle_new()
local lexer
if buffer.filename then
lexer = extensions[buffer.filename:match('[^/\\.]+$')]
end
if not lexer then
local line = buffer:get_line(0)
if line:find('^#!') then
for word in line:gsub('[/\\]', ' '):gmatch('%S+') do
lexer = shebangs[word]
if lexer then break end
end
end
if not lexer then
for patt, lex in pairs(patterns) do
if line:find(patt) then
lexer = lex
break
end
end
end
end
buffer:set_lexer(lexer or 'container')
if buffer.filename then
local lang = extensions[buffer.filename:match('[^/\\.]+$')]
if lang then
local ret, err = pcall(require, lang)
if ret then
_m[lang].set_buffer_properties()
elseif not ret and not err:find("^module '"..lang.."' not found:") then
textadept.events.error(err)
end
end
end
end
---
-- [Local function] Sets the buffer's lexer based on filename, shebang words, or
-- first line pattern.
local function restore_lexer()
buffer:set_lexer_language(buffer._lexer or 'container')
end
textadept.events.add_handler('file_opened', handle_new)
textadept.events.add_handler('file_saved_as', handle_new)
textadept.events.add_handler('buffer_after_switch', restore_lexer)
textadept.events.add_handler('view_new', restore_lexer)
|
Fixed bug with lexer restoration.
|
Fixed bug with lexer restoration.
--HG--
extra : rebase_source : f993faacdece52277ecbc3289fd2044edeaef80a
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
f644e0d2708dcb5648bc3f4f2f9654d6aa3447f6
|
modules/protocol/ipv4/ipv4lua.lua
|
modules/protocol/ipv4/ipv4lua.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--local ipv4 = require('protocol/ipv4')
local ipv4_dissector = haka.dissector.new{
type = haka.helper.PacketDissector,
name = 'ipv4lua'
}
local ipv4_addr_convert = {
get = function (x) return ipv4.addr(x) end,
set = function (x) return x.packed end
}
ipv4_dissector.grammar = haka.grammar.new("ipv4", function ()
local option_header = record{
field('copy', number(1)),
field('class', number(2)),
field('number', number(5)),
}
local option_data = record{
field('len', number(8))
:validate(function (self) self.len = #self.data+2 end),
field('data', bytes()
:count(function (self) return self.len-2 end)
)
}
local option = record{
union{
option_header,
field('type', number(8))
},
optional(option_data,
function (self) return self.type ~= 0 and self.type ~= 1 end
)
}
header = record{
field('version', number(4))
:validate(function (self) self.version = 4 end),
field('hdr_len', number(4))
:convert(converter.mult(4))
:validate(function (self) self.hdr_len = self:_compute_hdr_len(self) end),
field('tos', number(8)),
field('len', number(16))
:validate(function (self) self.len = self.hdr_len + #self.payload end),
field('id', number(16)),
field('flags', record{
field('rb', flag),
field('df', flag),
field('mf', flag),
}),
field('frag_offset', number(13))
:convert(converter.mult(8)),
field('ttl', number(8)),
field('proto', number(8)),
field('checksum', number(16))
:validate(function (self)
self.checksum = 0
self.checksum = ipv4.inet_checksum_compute(self._payload:sub(0, self.hdr_len))
end),
field('src', number(32))
:convert(ipv4_addr_convert, true),
field('dst', number(32))
:convert(ipv4_addr_convert, true),
field('opt', array(option))
:untilcond(function (elem, ctx)
return ctx.iter.meter >= ctx:result(1).hdr_len or
(elem and elem.type == 0)
end),
align(32),
verify(function (self, ctx)
if ctx.iter.meter ~= self.hdr_len then
error(string.format("invalid ipv4 header size, expected %d bytes, got %d bytes", self.hdr_len, ctx.iter.meter))
end
end),
field('payload', bytes())
}
export(header)
end)
function ipv4_dissector.method:parse_payload(pkt, payload)
self.raw = pkt
ipv4_dissector.grammar:parse(payload:pos("begin"), self)
end
function ipv4_dissector.method:create_payload(pkt, payload, init)
self.raw = pkt
ipv4_dissector.grammar:create(payload:pos("begin"), self, init)
end
function ipv4_dissector.method:verify_checksum()
return ipv4.inet_checksum_compute(self._payload:sub(0, self.hdr_len)) == 0
end
function ipv4_dissector.method:install_criterion()
return { proto = self.proto }
end
function ipv4_dissector._compute_hdr_len(pkt)
local len = 20
if pkt.opt then
for _, opt in ipairs(pkt.opt) do
len = len + (opt.len or 1)
end
end
return len
end
function ipv4_dissector.method:forge_payload(pkt, payload)
if payload.modified then
self.len = nil
self.checksum = nil
end
self:validate()
end
function ipv4_dissector:create(pkt, init)
if not init then init = {} end
if not init.hdr_len then init.hdr_len = ipv4_dissector._compute_hdr_len(init) end
pkt.payload:append(haka.vbuffer_allocate(init.hdr_len))
local ip = ipv4_dissector:new(pkt)
ip:create(init, pkt)
return ip
end
return ipv4
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local ipv4 = require('protocol/ipv4')
local ipv4_dissector = haka.dissector.new{
type = haka.helper.PacketDissector,
name = 'ipv4lua'
}
local ipv4_addr_convert = {
get = function (x) return ipv4.addr(x) end,
set = function (x) return x.packed end
}
ipv4_dissector.grammar = haka.grammar.new("ipv4", function ()
local option_header = record{
field('copy', number(1)),
field('class', number(2)),
field('number', number(5)),
}
local option_data = record{
field('len', number(8))
:validate(function (self) self.len = #self.data+2 end),
field('data', bytes()
:count(function (self) return self.len-2 end)
)
}
local option = record{
union{
option_header,
field('type', number(8))
},
optional(option_data,
function (self) return self.type ~= 0 and self.type ~= 1 end
)
}
header = record{
field('version', number(4))
:validate(function (self) self.version = 4 end),
field('hdr_len', number(4))
:convert(converter.mult(4))
:validate(function (self) self.hdr_len = self:_compute_hdr_len(self) end),
field('tos', number(8)),
field('len', number(16))
:validate(function (self) self.len = self.hdr_len + #self.payload end),
field('id', number(16)),
field('flags', record{
field('rb', flag),
field('df', flag),
field('mf', flag),
}),
field('frag_offset', number(13))
:convert(converter.mult(8)),
field('ttl', number(8)),
field('proto', number(8)),
field('checksum', number(16))
:validate(function (self)
self.checksum = 0
self.checksum = ipv4.inet_checksum_compute(self._payload:sub(0, self.hdr_len))
end),
field('src', number(32))
:convert(ipv4_addr_convert, true),
field('dst', number(32))
:convert(ipv4_addr_convert, true),
field('opt', array(option))
:untilcond(function (elem, ctx)
return ctx.iter.meter >= ctx:result(1).hdr_len or
(elem and elem.type == 0)
end),
verify(function (self, ctx)
if ctx.iter.meter ~= self.hdr_len then
error(string.format("invalid ipv4 header size, expected %d bytes, got %d bytes", self.hdr_len, ctx.iter.meter))
end
return true
end),
field('payload', bytes())
}
export(header)
end)
function ipv4_dissector.method:parse_payload(pkt, payload)
self.raw = pkt
local res = ipv4_dissector.grammar.header:parse(payload:pos("begin"))
table.merge(self, res)
end
function ipv4_dissector.method:create_payload(pkt, payload, init)
self.raw = pkt
local res = ipv4_dissector.grammar.header:create(payload:pos("begin"), init)
table.merge(self, res)
end
function ipv4_dissector.method:verify_checksum()
return ipv4.inet_checksum_compute(self._payload:sub(0, self.hdr_len)) == 0
end
function ipv4_dissector.method:install_criterion()
return { proto = self.proto }
end
function ipv4_dissector._compute_hdr_len(pkt)
local len = 20
if pkt.opt then
for _, opt in ipairs(pkt.opt) do
len = len + (opt.len or 1)
end
end
return len
end
function ipv4_dissector.method:forge_payload(pkt, payload)
if payload.modified then
self.len = nil
self.checksum = nil
end
self:validate()
end
function ipv4_dissector:create(pkt, init)
if not init then init = {} end
if not init.hdr_len then init.hdr_len = ipv4_dissector._compute_hdr_len(init) end
pkt.payload:append(haka.vbuffer_allocate(init.hdr_len))
local ip = ipv4_dissector:new(pkt)
ip:create(init, pkt)
return ip
end
|
Fix ipv4lua
|
Fix ipv4lua
|
Lua
|
mpl-2.0
|
haka-security/haka,nabilbendafi/haka,nabilbendafi/haka,haka-security/haka,haka-security/haka,nabilbendafi/haka
|
bc4efb11300bfbb43e47bb0103813c9362217b7b
|
utils/generate.lua
|
utils/generate.lua
|
--[[------------------------------
Load fake WoW environment.
--]]------------------------------
local root = "../"
do
local state = {
class = "DRUID",
level = 90,
}
dofile(root .. "WoWAPI.lua")
WoWAPI:Initialize("Ovale", state)
WoWAPI:ExportSymbols()
end
do
-- Load all of the addon files.
WoWAPI:LoadAddonFile("Ovale.toc", root)
-- Pretend to fire ADDON_LOADED event.
local AceAddon = LibStub("AceAddon-3.0")
AceAddon:ADDON_LOADED()
end
local OvaleSimulationCraft = Ovale.OvaleSimulationCraft
local format = string.format
local gsub = string.gsub
local strfind = string.find
local strlower = string.lower
local strsub = string.sub
local tconcat = table.concat
local tinsert = table.insert
local wipe = table.wipe
local profilesDirectory = "../../SimulationCraft/profiles/Tier17M"
local outputDirectory = "../scripts"
-- Save original input and output handles.
local saveInput = io.input()
local saveOutput = io.output()
local files = {}
do
local dir = io.popen("dir /b " .. gsub(profilesDirectory, "/", "\\"))
for name in dir:lines() do
tinsert(files, name)
end
dir:close()
OvaleSimulationCraft:GetValidProfiles(files)
-- Create the output directory.
os.execute("mkdir " .. outputDirectory)
end
local output = {}
for _, filename in ipairs(files) do
local inputName = profilesDirectory .. "/" .. filename
io.input(inputName)
local simc = io.read("*all")
-- Valid profiles never set "optimal_raid".
if not strfind(simc, "optimal_raid=") then
-- Parse SimulationCraft profile and emit the corresponding Ovale script.
local profile = OvaleSimulationCraft:ParseProfile(simc)
local name = format("SimulationCraft: %s", strsub(profile.annotation.name, 2, -2))
wipe(output)
output[#output + 1] = "local OVALE, Ovale = ..."
output[#output + 1] = "local OvaleScripts = Ovale.OvaleScripts"
output[#output + 1] = ""
output[#output + 1] = "do"
output[#output + 1] = format(' local name = "%s"', name)
output[#output + 1] = format(' local desc = "[6.0] %s"', name)
output[#output + 1] = " local code = [["
output[#output + 1] = OvaleSimulationCraft:Emit(profile)
output[#output + 1] = "]]"
output[#output + 1] = format(' OvaleScripts:RegisterScript("%s", name, desc, code, "reference")', profile.annotation.class)
output[#output + 1] = "end"
output[#output + 1] = ""
-- Output the Lua code into the proper output file.
local outputFileName = "simulationcraft_" .. gsub(strlower(filename), ".simc", ".lua")
-- Strip the tier designation from the end of the output filename.
outputFileName = gsub(outputFileName, "_t%d+%w+%.", ".")
outputFileName = gsub(outputFileName, "_t%d+%w+_", "_")
-- Fix the name of the death knight output file.
outputFileName = gsub(outputFileName, "death_knight", "deathknight")
print("Generating " .. outputFileName)
local outputName = outputDirectory .. "/" .. outputFileName
io.output(outputName)
io.write(tconcat(output, "\n"))
end
end
-- Restore original input and output handles.
io.input(saveInput)
io.output(saveOutput)
|
--[[------------------------------
Load fake WoW environment.
--]]------------------------------
local root = "../"
do
local state = {
class = "DRUID",
level = 90,
}
dofile(root .. "WoWAPI.lua")
WoWAPI:Initialize("Ovale", state)
WoWAPI:ExportSymbols()
end
do
-- Load all of the addon files.
WoWAPI:LoadAddonFile("Ovale.toc", root)
-- Pretend to fire ADDON_LOADED event.
local AceAddon = LibStub("AceAddon-3.0")
AceAddon:ADDON_LOADED()
end
local OvaleSimulationCraft = Ovale.OvaleSimulationCraft
local format = string.format
local gsub = string.gsub
local strfind = string.find
local strlower = string.lower
local strsub = string.sub
local tconcat = table.concat
local tinsert = table.insert
local wipe = table.wipe
local profilesDirectory = "../../SimulationCraft/profiles/Tier17M"
local outputDirectory = "../scripts"
-- Save original input and output handles.
local saveInput = io.input()
local saveOutput = io.output()
local files = {}
do
local dir = io.popen("dir /b " .. gsub(profilesDirectory, "/", "\\"))
for name in dir:lines() do
tinsert(files, name)
end
dir:close()
OvaleSimulationCraft:GetValidProfiles(files)
-- Create the output directory.
local outputDir =
os.execute("mkdir " .. gsub(outputDirectory, "/", "\\"))
end
local output = {}
for _, filename in ipairs(files) do
local inputName = profilesDirectory .. "/" .. filename
io.input(inputName)
local simc = io.read("*all")
-- Valid profiles never set "optimal_raid".
if not strfind(simc, "optimal_raid=") then
-- Parse SimulationCraft profile and emit the corresponding Ovale script.
local profile = OvaleSimulationCraft:ParseProfile(simc)
local name = format("SimulationCraft: %s", strsub(profile.annotation.name, 2, -2))
wipe(output)
output[#output + 1] = "local OVALE, Ovale = ..."
output[#output + 1] = "local OvaleScripts = Ovale.OvaleScripts"
output[#output + 1] = ""
output[#output + 1] = "do"
output[#output + 1] = format(' local name = "%s"', name)
output[#output + 1] = format(' local desc = "[6.0] %s"', name)
output[#output + 1] = " local code = [["
output[#output + 1] = OvaleSimulationCraft:Emit(profile)
output[#output + 1] = "]]"
output[#output + 1] = format(' OvaleScripts:RegisterScript("%s", name, desc, code, "reference")', profile.annotation.class)
output[#output + 1] = "end"
output[#output + 1] = ""
-- Output the Lua code into the proper output file.
local outputFileName = "simulationcraft_" .. gsub(strlower(filename), ".simc", ".lua")
-- Strip the tier designation from the end of the output filename.
outputFileName = gsub(outputFileName, "_t%d+%w+%.", ".")
outputFileName = gsub(outputFileName, "_t%d+%w+_", "_")
-- Fix the name of the death knight output file.
outputFileName = gsub(outputFileName, "death_knight", "deathknight")
print("Generating " .. outputFileName)
local outputName = outputDirectory .. "/" .. outputFileName
io.output(outputName)
io.write(tconcat(output, "\n"))
end
end
-- Restore original input and output handles.
io.input(saveInput)
io.output(saveOutput)
|
Fix directory name passed to Windows "mkdir".
|
Fix directory name passed to Windows "mkdir".
|
Lua
|
mit
|
eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale
|
4f73ab09ff5413b5ff6186d9e12b47b21d0c6522
|
heartbeat.lua
|
heartbeat.lua
|
-- This scripts conducts a heartbeat for a job, and returns
-- either the new expiration or False if the lock has been
-- given to another node
--
-- Args:
-- 1) jid
-- 2) worker
-- 3) now
-- 4) [data]
if #KEYS > 0 then error('Heartbeat(): No Keys should be provided') end
local jid = assert(ARGV[1] , 'Heartbeat(): Arg "jid" missing')
local worker = assert(ARGV[2] , 'Heartbeat(): Arg "worker" missing')
local now = assert(tonumber(ARGV[3]), 'Heartbeat(): Arg "now" missing')
local data = ARGV[4]
-- We should find the heartbeat interval for this queue
-- heartbeat. First, though, we need to find the queue
-- this particular job is in
local queue = redis.call('hget', 'ql:j:' .. jid, 'queue') or ''
local _hb, _qhb = unpack(redis.call('hmget', 'ql:config', 'heartbeat', queue .. '-heartbeat'))
local expires = now + tonumber(_qhb or _hb or 60)
if data then
data = cjson.decode(data)
end
-- First, let's see if the worker still owns this job, and there is a worker
if redis.call('hget', 'ql:j:' .. jid, 'worker') ~= worker or #worker == 0 then
return false
else
-- Otherwise, optionally update the user data, and the heartbeat
if data then
-- I don't know if this is wise, but I'm decoding and encoding
-- the user data to hopefully ensure its sanity
redis.call('hmset', 'ql:j:' .. jid, 'expires', expires, 'worker', worker, 'data', cjson.encode(data))
else
redis.call('hmset', 'ql:j:' .. jid, 'expires', expires, 'worker', worker)
end
-- Update hwen this job was last updated on that worker
-- Add this job to the list of jobs handled by this worker
redis.call('zadd', 'ql:w:' .. worker .. ':jobs', expires, jid)
-- And now we should just update the locks
local queue = redis.call('hget', 'ql:j:' .. jid, 'queue')
redis.call('zadd', 'ql:q:'.. queue .. '-locks', expires, jid)
return expires
end
|
-- This scripts conducts a heartbeat for a job, and returns
-- either the new expiration or False if the lock has been
-- given to another node
--
-- Args:
-- 1) jid
-- 2) worker
-- 3) now
-- 4) [data]
if #KEYS > 0 then error('Heartbeat(): No Keys should be provided') end
local jid = assert(ARGV[1] , 'Heartbeat(): Arg "jid" missing')
local worker = assert(ARGV[2] , 'Heartbeat(): Arg "worker" missing')
local now = assert(tonumber(ARGV[3]), 'Heartbeat(): Arg "now" missing')
local data = ARGV[4]
-- We should find the heartbeat interval for this queue
-- heartbeat. First, though, we need to find the queue
-- this particular job is in
local queue = redis.call('hget', 'ql:j:' .. jid, 'queue') or ''
local _hb, _qhb = unpack(redis.call('hmget', 'ql:config', 'heartbeat', queue .. '-heartbeat'))
local expires = now + tonumber(_qhb or _hb or 60)
if data then
data = cjson.decode(data)
end
-- First, let's see if the worker still owns this job, and there is a worker
local job_worker = redis.call('hget', 'ql:j:' .. jid, 'worker')
if job_worker ~= worker or #job_worker == 0 then
return false
else
-- Otherwise, optionally update the user data, and the heartbeat
if data then
-- I don't know if this is wise, but I'm decoding and encoding
-- the user data to hopefully ensure its sanity
redis.call('hmset', 'ql:j:' .. jid, 'expires', expires, 'worker', worker, 'data', cjson.encode(data))
else
redis.call('hmset', 'ql:j:' .. jid, 'expires', expires, 'worker', worker)
end
-- Update hwen this job was last updated on that worker
-- Add this job to the list of jobs handled by this worker
redis.call('zadd', 'ql:w:' .. worker .. ':jobs', expires, jid)
-- And now we should just update the locks
local queue = redis.call('hget', 'ql:j:' .. jid, 'queue')
redis.call('zadd', 'ql:q:'.. queue .. '-locks', expires, jid)
return expires
end
|
Small bug fix
|
Small bug fix
|
Lua
|
mit
|
seomoz/qless-core,seomoz/qless-core,backupify/qless-core
|
852ba2245c156159627b6aef0873ee942cba1e79
|
wezterm/wezterm.lua
|
wezterm/wezterm.lua
|
local wezterm = require 'wezterm'
local os = require 'os'
local nvtop = { domain = "CurrentPaneDomain", args = {"nvtop"}, }
local htop = { domain = "CurrentPaneDomain", args = {"htop"}, }
local assigned_keys = {
-- emacs like keybindings
{ key = "c", mods = "LEADER", action = wezterm.action{ SpawnTab = "CurrentPaneDomain" }, },
{ key = "d", mods = "LEADER", action = wezterm.action{ CloseCurrentTab = { confirm = false }, }, },
{ key = "d", mods = "LEADER|CTRL", action = wezterm.action{ CloseCurrentPane = { confirm = false }, }, },
{ key = "[", mods = "LEADER", action = "ActivateCopyMode" },
{ key = "w", mods = "LEADER", action = wezterm.action{ CopyTo = "Clipboard" }, },
{ key = "y", mods = "LEADER", action = wezterm.action{ PasteFrom = "Clipboard" }, },
{ key = "n", mods = "LEADER", action = wezterm.action{ ActivateTabRelative = 1 }, },
{ key = "p", mods = "LEADER", action = wezterm.action{ ActivateTabRelative = -1 }, },
{ key = "'", mods = "LEADER|SHIFT", action = wezterm.action{ SplitVertical = { domain = "CurrentPaneDomain", }, }, },
{ key = "5", mods = "LEADER|SHIFT", action = wezterm.action{ SplitHorizontal = { domain = "CurrentPaneDomain", }, }, },
{ key = "o", mods = "LEADER", action = wezterm.action{ ActivatePaneDirection = "Next", }, },
{ key = "r", mods = "LEADER", action = "ReloadConfiguration", },
{ key = "r", mods = "LEADER|CTRL", action = wezterm.action{ SplitHorizontal = nvtop }, },
{ key = "r", mods = "LEADER|SHIFT", action = wezterm.action{ SplitVertical = htop }, },
{ key = "=", mods = "LEADER|SUPER", action = "IncreaseFontSize", },
{ key = "-", mods = "LEADER|SUPER", action = "DecreaseFontSize", },
{ key = "r", mods = "LEADER|SUPER", action = "ResetFontSize", },
}
for i = 0, 9 do
key_string = tostring(i)
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|ALT",
action = wezterm.action{ ActivateTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|CTRL",
action = wezterm.action{ MoveTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER",
action = wezterm.action{ ActivatePaneByIndex = i },
})
end
base_dir = wezterm.home_dir .. "/.local/share/wezterm/"
socket = base_dir .. "wezterm.socket"
local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
wezterm.on("update-right-status", function(window, pane)
local date = wezterm.strftime("%Y/%m/%d(%a) %H:%M ");
local bat = ""
for _, b in ipairs(wezterm.battery_info()) do
bat = "🔋 " .. string.format("%.0f%%", b.state_of_charge * 100)
end
window:set_right_status(wezterm.format({
{ Background = { Color = "#2b2042", }, },
{ Foreground = { Color = "#808080", }, },
{ Text = bat .. " "..date },
}));
end)
wezterm.on("format-tab-title", function(tab, tabs, panes, config, hover, max_width)
local edge_background = "#0b0022"
local background = "#1b1032"
local foreground = "#808080"
if tab.is_active then
background = "#2b2042"
foreground = "#c0c0c0"
elseif hover then
background = "#3b3052"
foreground = "#909090"
end
local edge_foreground = background
-- ensure that the titles fit in the available space,
-- and that we have room for the edges.
local title = wezterm.truncate_right(tab.active_pane.title, max_width-2)
return {
{ Background = { Color = edge_background }, },
{ Foreground = { Color = edge_foreground }, },
{ Text = SOLID_LEFT_ARROW },
{ Background = { Color = background, }, },
{ Foreground = { Color = foreground, }, },
{ Text = title },
{ Background = { Color = edge_background, }, },
{ Foreground = { Color = edge_foreground, }, },
{ Text = SOLID_RIGHT_ARROW, },
}
end)
return {
font = wezterm.font"Noto Mono for Powerline",
adjust_window_size_when_changing_font_size = false,
use_ime = true,
font_size = 10.0,
color_scheme = "Dracula",
disable_default_key_bindings = true,
leader = { key="t", mods="CTRL", timeout_milliseconds=1000 },
keys = assigned_keys,
tab_bar_at_bottom = true,
unix_domains = {
{
name = "wezterm",
socket_path = socket,
},
default_gui_startup_args = {"connect", "wezterm"},
},
daemon_options = {
stdout = base_dir .. "stdout",
stderr = base_dir .. "stderr",
pid_file = base_dir .. "pid",
}
}
|
local wezterm = require 'wezterm'
local os = require 'os'
local nvtop = { domain = "CurrentPaneDomain", args = {"nvtop"}, }
local htop = { domain = "CurrentPaneDomain", args = {"htop"}, }
local assigned_keys = {
-- emacs like keybindings
{ key = "c", mods = "LEADER", action = wezterm.action{ SpawnTab = "CurrentPaneDomain" }, },
{ key = "d", mods = "LEADER", action = wezterm.action{ CloseCurrentTab = { confirm = false }, }, },
{ key = "d", mods = "LEADER|CTRL", action = wezterm.action{ CloseCurrentPane = { confirm = false }, }, },
{ key = "[", mods = "LEADER", action = "ActivateCopyMode" },
{ key = "w", mods = "LEADER", action = wezterm.action{ CopyTo = "Clipboard" }, },
{ key = "y", mods = "LEADER", action = wezterm.action{ PasteFrom = "Clipboard" }, },
{ key = "n", mods = "LEADER", action = wezterm.action{ ActivateTabRelative = 1 }, },
{ key = "p", mods = "LEADER", action = wezterm.action{ ActivateTabRelative = -1 }, },
{ key = "'", mods = "LEADER|SHIFT", action = wezterm.action{ SplitVertical = { domain = "CurrentPaneDomain", }, }, },
{ key = "5", mods = "LEADER|SHIFT", action = wezterm.action{ SplitHorizontal = { domain = "CurrentPaneDomain", }, }, },
{ key = "o", mods = "LEADER", action = wezterm.action{ ActivatePaneDirection = "Next", }, },
{ key = "r", mods = "LEADER", action = "ReloadConfiguration", },
{ key = "r", mods = "LEADER|CTRL", action = wezterm.action{ SplitHorizontal = nvtop }, },
{ key = "r", mods = "LEADER|SHIFT", action = wezterm.action{ SplitVertical = htop }, },
{ key = "=", mods = "LEADER|SUPER", action = "IncreaseFontSize", },
{ key = "-", mods = "LEADER|SUPER", action = "DecreaseFontSize", },
{ key = "r", mods = "LEADER|SUPER", action = "ResetFontSize", },
}
for i = 0, 9 do
key_string = tostring(i)
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|ALT",
action = wezterm.action{ ActivateTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|CTRL",
action = wezterm.action{ MoveTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER",
action = wezterm.action{ ActivatePaneByIndex = i },
})
end
base_dir = wezterm.home_dir .. "/.local/share/wezterm/"
socket = base_dir .. "wezterm.socket"
local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
wezterm.on("update-right-status", function(window, pane)
local date = wezterm.strftime("%Y/%m/%d(%a) %H:%M ");
local bat = ""
for _, b in ipairs(wezterm.battery_info()) do
bat = "🔋 " .. string.format("%.0f%%", b.state_of_charge * 100)
end
window:set_right_status(wezterm.format({
{ Background = { Color = "#2b2042", }, },
{ Foreground = { Color = "#808080", }, },
{ Text = bat .. " "..date },
}));
end)
wezterm.on("format-tab-title", function(tab, tabs, panes, config, hover, max_width)
local edge_background = "#0b0022"
local background = "#1b1032"
local foreground = "#808080"
if tab.is_active then
background = "#2b2042"
foreground = "#c0c0c0"
elseif hover then
background = "#3b3052"
foreground = "#909090"
end
local edge_foreground = background
-- ensure that the titles fit in the available space,
-- and that we have room for the edges.
local title = wezterm.truncate_right(tab.active_pane.title, max_width-2)
return {
{ Background = { Color = edge_background }, },
{ Foreground = { Color = edge_foreground }, },
{ Text = SOLID_LEFT_ARROW },
{ Background = { Color = background, }, },
{ Foreground = { Color = foreground, }, },
{ Text = title },
{ Background = { Color = edge_background, }, },
{ Foreground = { Color = edge_foreground, }, },
{ Text = SOLID_RIGHT_ARROW, },
}
end)
return {
font = wezterm.font"Noto Mono for Powerline",
adjust_window_size_when_changing_font_size = false,
use_ime = true,
font_size = 10.0,
color_scheme = "Dracula",
default_gui_startup_args = { "connect", "wezterm" },
disable_default_key_bindings = true,
leader = { key="t", mods="CTRL", timeout_milliseconds=1000 },
keys = assigned_keys,
tab_bar_at_bottom = true,
unix_domains = {
{
name = "wezterm",
socket_path = socket,
},
},
daemon_options = {
stdout = base_dir .. "stdout",
stderr = base_dir .. "stderr",
pid_file = base_dir .. "pid",
}
}
|
fix wrong place
|
fix wrong place
|
Lua
|
mit
|
katsyoshi/dotfiles,katsyoshi/dotfiles,katsyoshi/dotfiles
|
70d48fcb2a8d3d1cfbf6b92375b7197b6f9db246
|
config/awesome/rc.lua
|
config/awesome/rc.lua
|
-- standard requires
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
local wibox = require("wibox")
local beautiful = require("beautiful")
-- custom requires
local errors = require("misc.errors")
local workspace = require("misc.workspace")
local input = require("misc.input")
local autostart = require("misc.autostart")
-- defines and stuff
terminal = "kitty"
editor = "nvim"
editor_cmd = terminal .. " -e " .. editor
modkey = "Mod4"
errors.init()
beautiful.init(gears.filesystem.get_configuration_dir() .. "themes/zengarden-dark/theme.lua")
beautiful.master_width_factor = 0.7
awful.layout.layouts = {
awful.layout.suit.tile,
awful.layout.suit.fair,
awful.layout.suit.floating,
awful.layout.suit.tile.top,
awful.layout.suit.max,
}
screen.connect_signal("property::geometry", workspace.set_wallpaper)
awful.screen.connect_for_each_screen(workspace.setup)
root.buttons(input.root_buttons())
root.keys(input.global_keys(modkey))
awful.rules.rules = {
{
rule = { },
properties = {
border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = input.client_keys,
buttons = input.client_buttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
}
},
{
rule = { class = "zoom " },
properties = {
tag = awful.screen.focused().tags[8],
switchtotag = false,
floating = true,
}
},
{
rule = { class = "google-chrome" },
properties = {
tag = awful.screen.focused().tags[2],
switchtotag = false,
}
},
{
rule = { class = "outlook.office365.com__owa" },
properties = {
tag = awful.screen.focused().tags[5],
switchtotag = false,
}
},
{
rule = { class = "slack" },
properties = {
tag = awful.screen.focused().tags[6],
switchtotag = false,
}
},
{
rule = { class = "obsidian" },
properties = {
tag = awful.screen.focused().tags[6],
switchtotag = false,
}
},
{
rule = { instance = "scratch" },
properties = {
floating = true,
width = 1000,
height = 600,
x = 460,
y = 240,
},
},
}
client.connect_signal("manage", function (c)
if awesome.startup
and not c.size_hints.user_position
and not c.size_hints.program_position
then
awful.placement.no_offscreen(c)
end
end)
client.connect_signal("mouse::enter", function(c)
c:emit_signal("request::activate", "mouse_enter", {raise = false})
end)
client.connect_signal("focus", function(c)
c.border_color = beautiful.border_focus
end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
autostart.init()
dofile(gears.filesystem.get_configuration_dir() .. "private.lua")
|
-- standard requires
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
local wibox = require("wibox")
local beautiful = require("beautiful")
-- custom requires
local errors = require("misc.errors")
local workspace = require("misc.workspace")
local input = require("misc.input")
local autostart = require("misc.autostart")
-- defines and stuff
terminal = "alacritty"
editor = "nvim"
editor_cmd = terminal .. " -e " .. editor
modkey = "Mod4"
errors.init()
beautiful.init(gears.filesystem.get_configuration_dir() .. "themes/zengarden-dark/theme.lua")
beautiful.master_width_factor = 0.7
awful.layout.layouts = {
awful.layout.suit.tile,
awful.layout.suit.fair,
awful.layout.suit.floating,
awful.layout.suit.tile.top,
awful.layout.suit.max,
}
screen.connect_signal("property::geometry", workspace.set_wallpaper)
awful.screen.connect_for_each_screen(workspace.setup)
root.buttons(input.root_buttons())
root.keys(input.global_keys(modkey))
awful.rules.rules = {
{
rule = { },
properties = {
border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = input.client_keys,
buttons = input.client_buttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
}
},
{
rule = { class = "zoom " },
properties = {
tag = awful.screen.focused().tags[8],
switchtotag = false,
floating = true,
}
},
{
rule = { class = "google-chrome" },
properties = {
tag = awful.screen.focused().tags[2],
switchtotag = false,
}
},
{
rule = { class = "outlook.office365.com__owa" },
properties = {
tag = awful.screen.focused().tags[5],
switchtotag = false,
}
},
{
rule = { class = "slack" },
properties = {
tag = awful.screen.focused().tags[6],
switchtotag = false,
}
},
{
rule = { class = "obsidian" },
properties = {
tag = awful.screen.focused().tags[6],
switchtotag = false,
}
},
{
rule = { instance = "scratch" },
properties = {
floating = true,
width = 1000,
height = 600,
x = 460,
y = 240,
},
},
}
client.connect_signal("manage", function (c)
if awesome.startup
and not c.size_hints.user_position
and not c.size_hints.program_position
then
awful.placement.no_offscreen(c)
end
end)
client.connect_signal("mouse::enter", function(c)
c:emit_signal("request::activate", "mouse_enter", {raise = false})
end)
client.connect_signal("focus", function(c)
c.border_color = beautiful.border_focus
end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
autostart.init()
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
local private_additions = gears.filesystem.get_configuration_dir() .. "private.lua"
if gears.filesystem.file_readable(private_additions) then
dofile(gears.filesystem.get_configuration_dir() .. "private.lua")
end
|
[awesome] fixes & alacritty
|
[awesome] fixes & alacritty
use alacritty as default terminal & fix situations where private.lua
does not exist
|
Lua
|
mit
|
tobi-wan-kenobi/dotfiles
|
bf35bb0930a4be110ecaa9153d081f3cc0f241c9
|
PhotoDeckAPIXSLT.lua
|
PhotoDeckAPIXSLT.lua
|
local LrXml = import 'LrXml'
local logger = import 'LrLogger'( 'PhotoDeckPublishLightroomPlugin' )
logger:enable('logfile')
local xsltheader = [[
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
]]
local xsltfooter = [[
<xsl:template match="request|query-string"/>
</xsl:stylesheet>
]]
local PhotoDeckAPIXSLT = {}
PhotoDeckAPIXSLT.whoami = xsltheader .. [[
<xsl:template match='/reply/user'>
local t = {
firstname = "<xsl:value-of select='firstname'/>",
lastname = "<xsl:value-of select='lastname'/>",
email = "<xsl:value-of select='email'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.websites = xsltheader .. [[
<xsl:template match='/reply/websites'>
<xsl:for-each select='website'>
local t = { <xsl:value-of select='urlname'/> =
{
hostname = "<xsl:value-of select='hostname'/>",
homeurl = "<xsl:value-of select='home-url'/>",
title = "<xsl:value-of select='title'/>",
},
}
return t
</xsl:for-each>
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.galleries = xsltheader .. [[
<xsl:template match='/reply/galleries'>
local t = {}
<xsl:for-each select='gallery'>
t["<xsl:value-of select='name'/>"] = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = "<xsl:value-of select='name'/>",
uuid = "<xsl:value-of select='uuid'/>",
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
}
t["<xsl:value-of select='uuid'/>"] = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = "<xsl:value-of select='name'/>",
uuid = "<xsl:value-of select='uuid'/>",
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
}
</xsl:for-each>
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.getPhoto = xsltheader .. [[
<xsl:template match='/reply/media'>
local t = {
uuid = "<xsl:value-of select='uuid'/>",
filename = "<xsl:value-of select='file-name'/>",
title = "<xsl:value-of select='title'/>",
description = "<xsl:value-of select='description'/>",
<xsl:apply-templates select='keywords'/>
<xsl:apply-templates select='galleries'/>
}
return t
</xsl:template>
<xsl:template match='galleries'>
galleries = {
<xsl:for-each select='gallery'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
},
</xsl:template>
<xsl:template match='keywords'>
keywords = {
<xsl:for-each select='keyword'>
"<xsl:value-of select='.'/>",
</xsl:for-each>
},
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.photosInGallery = xsltheader .. [[
<xsl:template match='/reply/gallery/*'/>
<xsl:template match='/reply/gallery/medias'>
local t = {
<xsl:for-each select='media'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.uploadPhoto = xsltheader .. [[
<xsl:template match='/reply/message'/>
<xsl:template match='/reply'>
local t = {
uuid = "<xsl:value-of select='media-uuid'/>",
path = "<xsl:value-of select='location'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.updatePhoto = xsltheader .. [[
<xsl:template match='/reply'>
local t = {
uuid = "<xsl:value-of select='media-uuid'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.galleryDisplayStyles = xsltheader .. [[
<xsl:template match='/reply/gallery-display-styles'>
local t = {}
<xsl:for-each select='gallery-display-style'>
t["<xsl:value-of select='uuid'/>"] = {
uuid = "<xsl:value-of select='uuid'/>",
name = "<xsl:value-of select='name'/>",
}
</xsl:for-each>
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.transform = function(xmlstring, xslt)
local xml = LrXml.parseXml(xmlstring)
local luastring = xml:transform(xslt)
if luastring ~= '' then
logger:trace(luastring)
else
logger:trace(xmlstring)
end
local f = assert(loadstring(luastring))
return f()
end
return PhotoDeckAPIXSLT
|
local LrXml = import 'LrXml'
local logger = import 'LrLogger'( 'PhotoDeckPublishLightroomPlugin' )
logger:enable('logfile')
local xsltheader = [[
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
]]
local xsltfooter = [[
<xsl:template match="request|query-string"/>
</xsl:stylesheet>
]]
local PhotoDeckAPIXSLT = {}
PhotoDeckAPIXSLT.whoami = xsltheader .. [[
<xsl:template match='/reply/user'>
local t = {
firstname = "<xsl:value-of select='firstname'/>",
lastname = "<xsl:value-of select='lastname'/>",
email = "<xsl:value-of select='email'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.websites = xsltheader .. [[
<xsl:template match='/reply/websites'>
local t = {}
<xsl:for-each select='website'>
t["<xsl:value-of select='urlname'/>"] = {
hostname = "<xsl:value-of select='hostname'/>",
homeurl = "<xsl:value-of select='home-url'/>",
title = "<xsl:value-of select='title'/>",
}
</xsl:for-each>
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.galleries = xsltheader .. [[
<xsl:template match='/reply/galleries'>
local t = {}
<xsl:for-each select='gallery'>
t["<xsl:value-of select='name'/>"] = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = "<xsl:value-of select='name'/>",
uuid = "<xsl:value-of select='uuid'/>",
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
}
t["<xsl:value-of select='uuid'/>"] = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = "<xsl:value-of select='name'/>",
uuid = "<xsl:value-of select='uuid'/>",
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
}
</xsl:for-each>
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.getPhoto = xsltheader .. [[
<xsl:template match='/reply/media'>
local t = {
uuid = "<xsl:value-of select='uuid'/>",
filename = "<xsl:value-of select='file-name'/>",
title = "<xsl:value-of select='title'/>",
description = "<xsl:value-of select='description'/>",
<xsl:apply-templates select='keywords'/>
<xsl:apply-templates select='galleries'/>
}
return t
</xsl:template>
<xsl:template match='galleries'>
galleries = {
<xsl:for-each select='gallery'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
},
</xsl:template>
<xsl:template match='keywords'>
keywords = {
<xsl:for-each select='keyword'>
"<xsl:value-of select='.'/>",
</xsl:for-each>
},
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.photosInGallery = xsltheader .. [[
<xsl:template match='/reply/gallery/*'/>
<xsl:template match='/reply/gallery/medias'>
local t = {
<xsl:for-each select='media'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.uploadPhoto = xsltheader .. [[
<xsl:template match='/reply/message'/>
<xsl:template match='/reply'>
local t = {
uuid = "<xsl:value-of select='media-uuid'/>",
path = "<xsl:value-of select='location'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.updatePhoto = xsltheader .. [[
<xsl:template match='/reply'>
local t = {
uuid = "<xsl:value-of select='media-uuid'/>",
}
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.galleryDisplayStyles = xsltheader .. [[
<xsl:template match='/reply/gallery-display-styles'>
local t = {}
<xsl:for-each select='gallery-display-style'>
t["<xsl:value-of select='uuid'/>"] = {
uuid = "<xsl:value-of select='uuid'/>",
name = "<xsl:value-of select='name'/>",
}
</xsl:for-each>
return t
</xsl:template>
]] .. xsltfooter
PhotoDeckAPIXSLT.transform = function(xmlstring, xslt)
local xml = LrXml.parseXml(xmlstring)
local luastring = xml:transform(xslt)
if luastring ~= '' then
logger:trace(luastring)
else
logger:trace(xmlstring)
end
local f = assert(loadstring(luastring))
return f()
end
return PhotoDeckAPIXSLT
|
Multiple websites fix
|
Multiple websites fix
|
Lua
|
mit
|
cmaion/photodeck.lrdevplugin,willthames/photodeck.lrdevplugin
|
f7c50fb33fb385b3525be606977e6c6934247c5b
|
src/pegasus/request.lua
|
src/pegasus/request.lua
|
local Request = {}
function Request:new(client)
local newObj = {}
self.__index = self
newObj.client = client
newObj.firstLine = nil
newObj._method = nil
newObj._path = nil
newObj._params = {}
newObj._headers_parsed = false
newObj._headers = {}
newObj._form = {}
newObj._is_valid = false
newObj._body = ''
return setmetatable(newObj, self)
end
Request.PATTERN_METHOD = '^(.*)%s'
Request.PATTERN_PATH = '(.*)%s'
Request.PATTERN_PROTOCOL = '(HTTP%/[0-9]%.[0-9])'
Request.PATTERN_REQUEST = (Request.PATTERN_METHOD ..
Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL)
function Request:parseFirstLine()
if (self.firstLine ~= nil) then
return
end
local status, partial
self.firstLine, status, partial = self.client:receive()
if (self.firstLine == nil and status == 'timeout' and partial == '' or status == 'closed') then
return
end
-- Parse firstline http: METHOD PATH PROTOCOL,
-- GET Makefile HTTP/1.1
local method, path, protocol = string.match(self.firstLine,
Request.PATTERN_REQUEST)
local filename, querystring = string.match(path, '^([^#?]+)(.*)')
self._path = '.' .. filename
self._query_string = querystring
self._method = method
end
Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?'
function Request:parseURLEncoded(value, _table)
--value exists and _table is empty
if value and next(_table) == nil then
for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do
_table[k] = v
end
end
return _table
end
function Request:params()
self:parseFirstLine()
return self:parseURLEncoded(self._query_string, self._params)
end
function Request:post()
local data = self:receivePost()
return self:parseURLEncoded(data, {})
end
function Request:path()
self:parseFirstLine()
return self._path
end
function Request:method()
self:parseFirstLine()
return self._method
end
Request.PATTERN_HEADER = '([%w-]+): ([%w %w]+)'
function Request:headers()
if self._headers_parsed then
return self._headers
end
self:parseFirstLine()
local data = self.client:receive()
while (data ~= nil) and (data:len() > 0) do
local key, value = string.match(data, Request.PATTERN_HEADER)
if key and value then
self._headers[key] = value
end
data = self.client:receive()
end
self._headers_parsed = true
return self._headers
end
function Request:receivePost()
self:headers()
local data, err, partial = self.client:receive(1000)
if err =='timeout' then
err = nil
data = partial
end
return data
end
return Request
|
local Request = {}
function Request:new(client)
local newObj = {}
self.__index = self
newObj.client = client
newObj.firstLine = nil
newObj._method = nil
newObj._path = nil
newObj._params = {}
newObj._headers_parsed = false
newObj._headers = {}
newObj._form = {}
newObj._is_valid = false
newObj._body = ''
newObj._content_done = 0
return setmetatable(newObj, self)
end
Request.PATTERN_METHOD = '^(.*)%s'
Request.PATTERN_PATH = '(.*)%s'
Request.PATTERN_PROTOCOL = '(HTTP%/[0-9]%.[0-9])'
Request.PATTERN_REQUEST = (Request.PATTERN_METHOD ..
Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL)
function Request:parseFirstLine()
if (self.firstLine ~= nil) then
return
end
local status, partial
self.firstLine, status, partial = self.client:receive()
if (self.firstLine == nil and status == 'timeout' and partial == '' or status == 'closed') then
return
end
-- Parse firstline http: METHOD PATH PROTOCOL,
-- GET Makefile HTTP/1.1
local method, path, protocol = string.match(self.firstLine,
Request.PATTERN_REQUEST)
local filename, querystring = string.match(path, '^([^#?]+)(.*)')
self._path = '.' .. filename
self._query_string = querystring
self._method = method
end
Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?'
function Request:parseURLEncoded(value, _table)
--value exists and _table is empty
if value and next(_table) == nil then
for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do
_table[k] = v
end
end
return _table
end
function Request:params()
self:parseFirstLine()
return self:parseURLEncoded(self._query_string, self._params)
end
function Request:post()
if self:method() ~= "POST" then return nil end
local data = self:receiveBody()
return self:parseURLEncoded(data, {})
end
function Request:path()
self:parseFirstLine()
return self._path
end
function Request:method()
self:parseFirstLine()
return self._method
end
Request.PATTERN_HEADER = '([%w-]+): ([%w %w]+)'
function Request:headers()
if self._headers_parsed then
return self._headers
end
self:parseFirstLine()
local data = self.client:receive()
while (data ~= nil) and (data:len() > 0) do
local key, value = string.match(data, Request.PATTERN_HEADER)
if key and value then
self._headers[key] = value
end
data = self.client:receive()
end
self._headers_parsed = true
self._content_length = tonumber(self._headers["Content-Length"] or 0)
return self._headers
end
function Request:receiveBody(size)
size = size or self._content_length
-- do we have content?
if self._content_done >= self._content_length then return false end
-- fetch in chunks
local fetch = math.min(self._content_length-self._content_done, size)
local data, err, partial = self.client:receive(fetch)
if err =='timeout' then
err = nil
data = partial
end
self._content_done = self._content_done + #data
return data
end
return Request
|
fix fetching content when there is none
|
fix fetching content when there is none
|
Lua
|
mit
|
EvandroLG/pegasus.lua,dieseltravis/pegasus.lua
|
cdb88a6a4d5b41082bd9fe11386e2674f748d940
|
src_lua/EnumManager.lua
|
src_lua/EnumManager.lua
|
---
--- Created by slanska
--- DateTime: 2017-11-06 11:03 PM
---
--[[
Enums in Flexilite is pretty much the same as references. When property is declared as enum,
new enum class will be automatically created, or existing enum class will
be used if classRef has valid class name.
Auto created enum class will have 2 properties: id (type will be based on type of id values in items list
- so it will be either integer or string), and text, type of 'symbol'
Item list will be used to populate data in the enum class. Existing items may be replaced, if their IDs match.
Enums are very similar to foreign key relation in standard RDBMS in sense that they store user defined ID,
not internal object ID, and do not support many-to-many relationship.
Any existing class can be used as enum class, if it has id and text special properties.
Also, auto created enum classes can be extended/modified like regular classes
Differences between enum and regular classes:
1) Enum property will be scalar or array of ID values from referenced enum item (not object ID). It will not be
defined as reference value, but as field value. So, JSON output will have values like "Status": "A"
or "Status": ["A", "B"], not like "Status": 123456
2) Implicit property 'text' will be supplied. So for enum property Order.Status there will be also
implicit property Order.Status.text. Value of this property will be taken from name and possibly
translated based on current user culture
]]
local ClassCreate = require 'flexi_CreateClass'
local json = require 'cjson'
local NameRef = require 'NameRef'
local class = require 'pl.class'
local DBObject = require 'DBObject'
-- Implements enum storage
---@class EnumManager
local EnumManager = class()
---@param DBContext DBContext
function EnumManager:_init(DBContext)
---@type DBContext
self.DBContext = DBContext
end
---@param self EnumManager
local function upsertEnumItem(self, propDef, item)
---@type ClassDef
local classDef = self.DBContext:getClassDef(propDef.D.enumDef.id)
local objId = (not classDef.D.specialProperties.uid) and item.id or nil
local data = {
[classDef.D.specialProperties.uid or '$id'] = item.id,
[classDef.D.specialProperties.text] = item.id,
-- icon, imageUrl
}
local obj = DBObject(self.DBContext, classDef, objId)
if classDef.D.specialProperties.uid.id then
obj:setProperty(classDef.D.specialProperties.uid.id, item.id)
end
if classDef.D.specialProperties.text.id then
obj:setProperty(classDef.D.specialProperties.text.id, item.text)
end
if classDef.D.specialProperties.icon.id then
obj:setProperty(classDef.D.specialProperties.icon.id, item.icon)
end
if classDef.D.specialProperties.imageUrl.id then
obj:setProperty(classDef.D.specialProperties.imageUrl.id, item.imageUrl)
end
obj:saveToDB()
end
-- Upserts enum item
---@param propDef EnumPropertyDef
---@param item table @comment with fields: id, text, icon, imageUrl
function EnumManager:upsertEnumItem(propDef, item)
-- Check if item can be added/updated now or must be deferred
if propDef.D.enumDef.id then
upsertEnumItem(self, propDef, item)
else
propDef.ClassDef.DBContext.DeferredActions:Add(nil, upsertEnumItem, self, propDef, item)
end
end
---@param propDef EnumPropertyDef
function EnumManager:ApplyEnumPropertyDef(propDef)
assert(propDef:is_a(self.DBContext.PropertyDef.Classes.EnumPropertyDef))
assert(propDef.D.enumDef, 'enumDef nor refDef set')
-- new enum definition
--[[
if text/id is set, the class must exist (at the end of request). This class must have text and uid special
properties. If text/id is not set, new class will be created with name ClassName_PropertyName.
items are optional and if set, they will be inserted or replaced into database.
Consistency for newly created or updated objects will be checked at the end of operation
]]
if propDef.D.enumDef.items then
end
self:CreateEnumClass(string.format('%s_%s',
propDef.ClassDef.Name.text, propDef.Name.text),
propDef.D.enumDef.items)
end
-- Creates class for enum type, if needed.
---@param className string
---@param items table @comment (optional) array of EnumItem
function EnumManager:CreateEnumClass(className, items)
-- Determine id type
local idType = 'integer'
if items and #items > 0 then
for i, v in ipairs(items) do
if type(v.id) ~= 'number' then
idType = type(v.id)
break
end
end
end
local def = {
properties = {
id = {
rules = {
type = idType,
minOccurrences = 1,
maxOccurrences = 1,
}
},
name = {
rules = {
type = 'symbol',
minOccurrences = 1,
maxOccurrences = 1,
}
},
},
specialProperties = {
id = 'id',
text = 'text'
}
}
-- Check if class already exists
local cls = ClassCreate(self.DBContext, className, json.encode(def), false)
-- Upsert items to enum class
if items and #items > 0 then
self:UpsertEnumItems(cls, items)
end
end
---@param className string
function EnumManager:IsClassEnum(className)
local cls = self.DBContext:LoadClassDefinition(className)
if not cls then
return false, 'Class [' .. className .. '] does not exist'
end
local result = cls.D.specialProperties.id and cls.D.specialProperties.text
return result
end
function EnumManager:UpsertEnumItems(cls, items)
if not items then
return
end
-- use flexi_DataUpdate
local stmt = self.DBContext:getStatement '' -- TODO SQL
for i, v in ipairs(items) do
local nameRef = { text = v.name }
setmetatable(nameRef, NameRef)
nameRef:resolve(cls)
stmt:reset()
stmt:bind { [1] = v.id, [2] = nameRef.id }
stmt:exec()
end
end
return EnumManager
|
---
--- Created by slanska
--- DateTime: 2017-11-06 11:03 PM
---
--[[
Enums in Flexilite is pretty much the same as references. When property is declared as enum,
new enum class will be automatically created, or existing enum class will
be used if classRef has valid class name.
Auto created enum class will have 2 properties: id (type will be based on type of id values in items list
- so it will be either integer or string), and text, type of 'symbol'
Item list will be used to populate data in the enum class. Existing items may be replaced, if their IDs match.
Enums are very similar to foreign key relation in standard RDBMS in sense that they store user defined ID,
not internal object ID, and do not support many-to-many relationship.
Any existing class can be used as enum class, if it has id and text special properties.
Also, auto created enum classes can be extended/modified like regular classes
Differences between enum and regular classes:
1) Enum property will be scalar or array of ID values from referenced enum item (not object ID). It will not be
defined as reference value, but as field value. So, JSON output will have values like "Status": "A"
or "Status": ["A", "B"], not like "Status": 123456
2) Implicit property 'text' will be supplied. So for enum property Order.Status there will be also
implicit property Order.Status.text. Value of this property will be taken from name and possibly
translated based on current user culture
]]
local ClassCreate = require 'flexi_CreateClass'
local json = require 'cjson'
local NameRef = require 'NameRef'
local class = require 'pl.class'
local DBObject = require 'DBObject'
-- Implements enum storage
---@class EnumManager
local EnumManager = class()
---@param DBContext DBContext
function EnumManager:_init(DBContext)
---@type DBContext
self.DBContext = DBContext
end
---@param self EnumManager
local function upsertEnumItem(self, propDef, item)
---@type ClassDef
local classDef = self.DBContext:getClassDef(propDef.D.enumDef.id)
local objId = (not classDef.D.specialProperties.uid) and item.id or nil
local data = {
[classDef.D.specialProperties.uid or '$id'] = item.id,
[classDef.D.specialProperties.text] = item.id,
-- icon, imageUrl
}
local obj = DBObject(self.DBContext, classDef, objId)
if classDef.D.specialProperties.uid.id then
obj:setProperty(classDef.D.specialProperties.uid.id, item.id)
end
if classDef.D.specialProperties.text.id then
obj:setProperty(classDef.D.specialProperties.text.id, item.text)
end
if classDef.D.specialProperties.icon.id then
obj:setProperty(classDef.D.specialProperties.icon.id, item.icon)
end
if classDef.D.specialProperties.imageUrl.id then
obj:setProperty(classDef.D.specialProperties.imageUrl.id, item.imageUrl)
end
obj:saveToDB()
end
-- Upserts enum item
---@param propDef EnumPropertyDef
---@param item table @comment with fields: id, text, icon, imageUrl
function EnumManager:upsertEnumItem(propDef, item)
-- Check if item can be added/updated now or must be deferred
if propDef.D.enumDef.id then
upsertEnumItem(self, propDef, item)
else
propDef.ClassDef.DBContext.DeferredActions:Add(nil, upsertEnumItem, self, propDef, item)
end
end
---@param propDef EnumPropertyDef
function EnumManager:ApplyEnumPropertyDef(propDef)
assert(propDef:is_a(self.DBContext.PropertyDef.Classes.EnumPropertyDef))
local refDef = propDef.D.enumDef or propDef.D.refDef
assert(refDef, 'Neither enumDef nor refDef set')
-- new enum definition
--[[
if text/id is set, the class must exist (at the end of request). This class must have text and uid special
properties. If text/id is not set, new class will be created with name ClassName_PropertyName.
items are optional and if set, they will be inserted or replaced into database.
Consistency for newly created or updated objects will be checked at the end of operation
]]
if refDef.items then
end
self:CreateEnumClass(string.format('%s_%s',
propDef.ClassDef.Name.text, propDef.Name.text),
refDef.items)
end
-- Creates class for enum type, if needed.
---@param className string
---@param items table @comment (optional) array of EnumItem
function EnumManager:CreateEnumClass(className, items)
-- Determine id type
local idType = 'integer'
if items and #items > 0 then
for i, v in ipairs(items) do
if type(v.id) ~= 'number' then
idType = type(v.id)
break
end
end
end
local def = {
properties = {
id = {
rules = {
type = idType,
minOccurrences = 1,
maxOccurrences = 1,
}
},
name = {
rules = {
type = 'symbol',
minOccurrences = 1,
maxOccurrences = 1,
}
},
},
specialProperties = {
id = 'id',
text = 'text'
}
}
-- Check if class already exists
local cls = ClassCreate(self.DBContext, className, json.encode(def), false)
-- Upsert items to enum class
if items and #items > 0 then
self:UpsertEnumItems(cls, items)
end
end
---@param className string
function EnumManager:IsClassEnum(className)
local cls = self.DBContext:LoadClassDefinition(className)
if not cls then
return false, 'Class [' .. className .. '] does not exist'
end
local result = cls.D.specialProperties.id and cls.D.specialProperties.text
return result
end
function EnumManager:UpsertEnumItems(cls, items)
if not items then
return
end
-- use flexi_DataUpdate
local stmt = self.DBContext:getStatement '' -- TODO SQL
for i, v in ipairs(items) do
local nameRef = { text = v.name }
setmetatable(nameRef, NameRef)
nameRef:resolve(cls)
stmt:reset()
stmt:bind { [1] = v.id, [2] = nameRef.id }
stmt:exec()
end
end
return EnumManager
|
fixing schema create
|
fixing schema create
|
Lua
|
mpl-2.0
|
slanska/flexilite,slanska/flexilite
|
20acb568fc7e223278891a769d29fa89fe55b31d
|
src/hs/finalcutpro/MenuBar.lua
|
src/hs/finalcutpro/MenuBar.lua
|
--- hs.finalcutpro.MenuBar
---
--- Represents the Final Cut Pro X menu bar, providing functions that allow different tasks to be accomplished.
---
--- Author: David Peterson ([email protected])
---
--- Standard Modules
local log = require("hs.logger").new("menubar")
local json = require("hs.json")
local axutils = require("hs.finalcutpro.axutils")
local just = require("hs.just")
local MenuBar = {}
MenuBar.MENU_MAP_FILE = "hs/finalcutpro/menumap.json"
MenuBar.ROLE = "AXMenuBar"
--- hs.finalcutpro.MenuBar:new(App) -> MenuBar
--- Function
--- Constructs a new MenuBar for the specified App.
---
--- Parameters:
--- * app - The App instance the MenuBar belongs to.
---
--- Returns:
--- * a new MenuBar instance
---
function MenuBar:new(app)
o = {
_app = app
}
setmetatable(o, self)
self.__index = self
return o
end
function MenuBar:app()
return self._app
end
function MenuBar:UI()
local appUI = self:app():UI()
return appUI and axutils.childWith(appUI, "AXRole", MenuBar.ROLE)
end
function MenuBar:getMenuMap()
if not MenuBar._menuMap then
local file = io.open(MenuBar.MENU_MAP_FILE, "r")
if file then
local content = file:read("*all")
file:close()
MenuBar._menuMap = json.decode(content)
log.d("Loaded menu map from '" .. MenuBar.MENU_MAP_FILE .. "'")
else
MenuBar._menuMap = {}
end
end
return MenuBar._menuMap
end
--- hs.finalcutpro.MenuBar:selectMenu(...) -> boolean
--- Function
--- Selects a Final Cut Pro Menu Item based on the list of menu titles in English.
---
--- Parameters:
--- * ... - The list of menu items you'd like to activate, for example:
--- select("View", "Browser", "as List")
---
--- Returns:
--- * The MenuBar, for further operations
---
function MenuBar:selectMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI then
menuItemUI:doPress()
end
return self
end
function MenuBar:isChecked(...)
local menuItemUI = self:findMenuUI(...)
return menuItemUI and self:_isMenuChecked(menuItemUI)
end
function MenuBar:isEnabled(...)
local menuItemUI = self:findMenuUI(...)
return menuItemUI and self:_isMenuChecked(menuItemUI)
end
function MenuBar:_isMenuChecked(menu)
return menu:attributeValue("AXMenuItemMarkChar") ~= nil
end
function MenuBar:checkMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI and not self:_isMenuChecked(menuItemUI) then
menuItemUI:doPress()
just.doUntil(function() return self:_isMenuChecked(menuItemUI) end)
end
return self
end
function MenuBar:uncheckMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI and self:_isMenuChecked(menuItemUI) then
menuItemUI:doPress()
just.doWhile(function() return self:_isMenuChecked(menuItemUI) end)
end
return self
end
function MenuBar:findMenuUI(...)
-- Start at the top of the menu bar list
local menuMap = self:getMenuMap()
local menuUI = self:UI()
local menuItemUI = nil
for i=1,select('#', ...) do
step = select(i, ...)
if menuMap and menuMap[step] then
-- We have the menu name in our list
local item = menuMap[step]
menuItemUI = menuUI[item.id]
menuMap = item.items
else
-- We don't have it in our list, so look it up manually. Hopefully they are in English!
log.w("Searching manually for '"..step.."'.")
menuItemUI = axutils.childWith(menuUI, "AXTitle", step)
end
if menuItemUI then
if #menuItemUI == 1 then
-- Assign the contained AXMenu to the menuUI - it contains the next set of AXMenuItems
menuUI = menuItemUI[1]
assert(not menuUI or menuUI:role() == "AXMenu")
end
else
log.w("Unable to find a menu called '"..step.."'.")
return nil
end
end
return menuItemUI
end
--- hs.finalcutpro.MenuBar:generateMenuMap() -> boolean
--- Function
--- Generates a map of the menu bar and saves it in the location specified
--- in MenuBar.MENU_MAP_FILE.
---
--- Parameters:
--- * N/A
---
--- Returns:
--- * True is successful otherwise Nil
---
function MenuBar:generateMenuMap()
local menuMap = self:_processMenuItems(self:UI())
-- Opens a file in append mode
file = io.open(MenuBar.MENU_MAP_FILE, "w")
if file then
file:write(json.encode(menuMap))
file:close()
return true
end
return nil
end
function MenuBar:_processMenuItems(menu)
local count = #menu
if count then
local items = {}
for i,child in ipairs(menu) do
local title = child:attributeValue("AXTitle")
-- log.d("Title: "..inspect(title))
if title and title ~= "" then
local item = {id = i}
local submenu = child[1]
if submenu and submenu:role() == "AXMenu" then
local children = self:_processMenuItems(submenu)
if children then
item.items = children
end
end
items[title] = item
end
end
return items
else
return nil
end
end
return MenuBar
|
--- hs.finalcutpro.MenuBar
---
--- Represents the Final Cut Pro X menu bar, providing functions that allow different tasks to be accomplished.
---
--- Author: David Peterson ([email protected])
---
--- Standard Modules
local log = require("hs.logger").new("menubar")
local json = require("hs.json")
local axutils = require("hs.finalcutpro.axutils")
local just = require("hs.just")
local MenuBar = {}
MenuBar.MENU_MAP_FILE = "hs/finalcutpro/menumap.json"
MenuBar.ROLE = "AXMenuBar"
--- hs.finalcutpro.MenuBar:new(App) -> MenuBar
--- Function
--- Constructs a new MenuBar for the specified App.
---
--- Parameters:
--- * app - The App instance the MenuBar belongs to.
---
--- Returns:
--- * a new MenuBar instance
---
function MenuBar:new(app)
o = {
_app = app
}
setmetatable(o, self)
self.__index = self
return o
end
function MenuBar:app()
return self._app
end
function MenuBar:UI()
local appUI = self:app():UI()
return appUI and axutils.childWith(appUI, "AXRole", MenuBar.ROLE)
end
function MenuBar:getMenuMap()
if not MenuBar._menuMap then
local file = io.open(MenuBar.MENU_MAP_FILE, "r")
if file then
local content = file:read("*all")
file:close()
MenuBar._menuMap = json.decode(content)
log.d("Loaded menu map from '" .. MenuBar.MENU_MAP_FILE .. "'")
else
MenuBar._menuMap = {}
end
end
return MenuBar._menuMap
end
--- hs.finalcutpro.MenuBar:selectMenu(...) -> boolean
--- Function
--- Selects a Final Cut Pro Menu Item based on the list of menu titles in English.
---
--- Parameters:
--- * ... - The list of menu items you'd like to activate, for example:
--- select("View", "Browser", "as List")
---
--- Returns:
--- * The MenuBar, for further operations
---
function MenuBar:selectMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI then
menuItemUI:doPress()
end
return self
end
function MenuBar:isChecked(...)
local menuItemUI = self:findMenuUI(...)
return menuItemUI and self:_isMenuChecked(menuItemUI)
end
function MenuBar:isEnabled(...)
local menuItemUI = self:findMenuUI(...)
return menuItemUI and menuItemUI:attributeValue("AXEnabled")
end
function MenuBar:_isMenuChecked(menu)
return menu:attributeValue("AXMenuItemMarkChar") ~= nil
end
function MenuBar:checkMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI and not self:_isMenuChecked(menuItemUI) then
menuItemUI:doPress()
just.doUntil(function() return self:_isMenuChecked(menuItemUI) end)
end
return self
end
function MenuBar:uncheckMenu(...)
local menuItemUI = self:findMenuUI(...)
if menuItemUI and self:_isMenuChecked(menuItemUI) then
menuItemUI:doPress()
just.doWhile(function() return self:_isMenuChecked(menuItemUI) end)
end
return self
end
function MenuBar:findMenuUI(...)
-- Start at the top of the menu bar list
local menuMap = self:getMenuMap()
local menuUI = self:UI()
local menuItemUI = nil
for i=1,select('#', ...) do
step = select(i, ...)
if menuMap and menuMap[step] then
-- We have the menu name in our list
local item = menuMap[step]
menuItemUI = menuUI[item.id]
menuMap = item.items
else
-- We don't have it in our list, so look it up manually. Hopefully they are in English!
log.w("Searching manually for '"..step.."'.")
menuItemUI = axutils.childWith(menuUI, "AXTitle", step)
end
if menuItemUI then
if #menuItemUI == 1 then
-- Assign the contained AXMenu to the menuUI - it contains the next set of AXMenuItems
menuUI = menuItemUI[1]
assert(not menuUI or menuUI:role() == "AXMenu")
end
else
log.w("Unable to find a menu called '"..step.."'.")
return nil
end
end
return menuItemUI
end
--- hs.finalcutpro.MenuBar:generateMenuMap() -> boolean
--- Function
--- Generates a map of the menu bar and saves it in the location specified
--- in MenuBar.MENU_MAP_FILE.
---
--- Parameters:
--- * N/A
---
--- Returns:
--- * True is successful otherwise Nil
---
function MenuBar:generateMenuMap()
local menuMap = self:_processMenuItems(self:UI())
-- Opens a file in append mode
file = io.open(MenuBar.MENU_MAP_FILE, "w")
if file then
file:write(json.encode(menuMap))
file:close()
return true
end
return nil
end
function MenuBar:_processMenuItems(menu)
local count = #menu
if count then
local items = {}
for i,child in ipairs(menu) do
local title = child:attributeValue("AXTitle")
-- log.d("Title: "..inspect(title))
if title and title ~= "" then
local item = {id = i}
local submenu = child[1]
if submenu and submenu:role() == "AXMenu" then
local children = self:_processMenuItems(submenu)
if children then
item.items = children
end
end
items[title] = item
end
end
return items
else
return nil
end
end
return MenuBar
|
Fixed bug with MenuBar:isEnabled(…)
|
Fixed bug with MenuBar:isEnabled(…)
|
Lua
|
mit
|
cailyoung/CommandPost,fcpxhacks/fcpxhacks,cailyoung/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost
|
adc3576f52da491f1aff7b0f55e4f9d3d0f84c13
|
src/nodish/net/socket.lua
|
src/nodish/net/socket.lua
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local stream = require'nodish.stream'
local ev = require'ev'
local loop = ev.Loop.default
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local watchers = {}
self.watchers = watchers
stream.readable(self)
stream.writable(self)
local sock
local connecting = false
local connected = false
local closing = false
self:once('error',function()
self:destroy()
self:emit('close')
end)
local on_connect = function()
connecting = false
connected = true
-- provide read mehod for stream
self._read = function()
if not sock then
return '',nil,true
end
local data,err = sock:read()
local closed
if data and #data == 0 then
closed = true
end
return data,err,closed
end
self:add_read_watcher(sock:getfd())
-- provide write method for stream
self._write = function(_,data)
return sock:write(data)
end
self:add_write_watcher(sock:getfd())
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
assert(not sock)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ALREADY then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
io:stop(loop)
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ISCONN then
watchers.connect = nil
on_connect()
else
self:emit(tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
self:emit(tostring(err))
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
local writable_write = self.write
self.write = function(_,data)
if connecting then
self:once('connect',function()
writable_write(_,data)
end)
elseif connected then
writable_write(_,data)
else
self:emit('error','wrong state')
end
return self
end
local writable_fin = self.fin
self.fin = function(_,data)
self:once('finish',function()
if sock then
sock:shutdown(S.c.SHUT.RD)
end
end)
writable_fin(_,data)
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local stream = require'nodish.stream'
local ev = require'ev'
local loop = ev.Loop.default
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local watchers = {}
self.watchers = watchers
stream.readable(self)
stream.writable(self)
local sock
local connecting = false
local connected = false
local closing = false
self:once('error',function()
self:destroy()
self:emit('close')
end)
local on_connect = function()
connecting = false
connected = true
-- provide read mehod for stream
self._read = function()
if not sock then
return '',nil,true
end
local data,err = sock:read()
local closed
if data and #data == 0 then
closed = true
end
return data,err,closed
end
self:add_read_watcher(sock:getfd())
-- provide write method for stream
self._write = function(_,data)
return sock:write(data)
end
self:add_write_watcher(sock:getfd())
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local _,err = sock:connect(addr)
if not err or err.errno == S.c.E.ISCONN then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
io:stop(loop)
local _,err = sock:connect(addr)
if not err or err.errno == S.c.E.ISCONN then
watchers.connect = nil
on_connect()
else
self:emit('error',tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
nexttick(function()
self:emit('error',tostring(err))
end)
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
local writable_write = self.write
self.write = function(_,data)
if connecting then
self:once('connect',function()
writable_write(_,data)
end)
elseif connected then
writable_write(_,data)
else
self:emit('error','wrong state')
end
return self
end
local writable_fin = self.fin
self.fin = function(_,data)
self:once('finish',function()
if sock then
sock:shutdown(S.c.SHUT.RD)
end
end)
writable_fin(_,data)
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
fix connect handling
|
fix connect handling
|
Lua
|
mit
|
lipp/nodish
|
9a9f6f5d2888769c756f29c5d1d2506807c8f8e4
|
frontend/ui/elements/mass_storage.lua
|
frontend/ui/elements/mass_storage.lua
|
local Device = require("device")
local UIManager = require("ui/uimanager")
local _ = require("gettext")
local MassStorage = {}
-- if required a popup will ask before entering mass storage mode
function MassStorage:requireConfirmation()
return not G_reader_settings:isTrue("mass_storage_confirmation_disabled")
end
function MassStorage:isEnabled()
return not G_reader_settings:isTrue("mass_storage_disabled")
end
-- mass storage settings menu
function MassStorage:getSettingsMenuTable()
return {
{
text = _("Disable confirmation popup"),
help_text = _([[This will ONLY affect what happens when you plug in the device!]]),
checked_func = function() return not self:requireConfirmation() end,
callback = function()
G_reader_settings:saveSetting("mass_storage_confirmation_disabled", self:requireConfirmation())
end,
},
{
text = _("Disable mass storage functionality"),
help_text = _([[In case your device uses an unsupported setup where you know it won't work properly.]]),
checked_func = function() return not self:isEnabled() end,
callback = function()
G_reader_settings:saveSetting("mass_storage_disabled", self:isEnabled())
end,
},
}
end
-- mass storage actions
function MassStorage:getActionsMenuTable()
return {
text = _("Start USB storage"),
enabled_func = function() return self:isEnabled() end,
callback = function()
self:start(true)
end,
}
end
-- exit KOReader and start mass storage mode.
function MassStorage:start(never_ask)
if not Device:canToggleMassStorage() or not self:isEnabled() then
return
end
if not never_ask and self:requireConfirmation() then
local ConfirmBox = require("ui/widget/confirmbox")
UIManager:show(ConfirmBox:new{
text = _("Share storage via USB?"),
ok_text = _("Share"),
ok_callback = function()
UIManager:quit()
UIManager._exit_code = 86
end,
})
else
UIManager:quit()
UIManager._exit_code = 86
end
end
return MassStorage
|
local Device = require("device")
local UIManager = require("ui/uimanager")
local _ = require("gettext")
local MassStorage = {}
-- if required a popup will ask before entering mass storage mode
function MassStorage:requireConfirmation()
return not G_reader_settings:isTrue("mass_storage_confirmation_disabled")
end
function MassStorage:isEnabled()
return not G_reader_settings:isTrue("mass_storage_disabled")
end
-- mass storage settings menu
function MassStorage:getSettingsMenuTable()
return {
{
text = _("Disable confirmation popup"),
help_text = _([[This will ONLY affect what happens when you plug in the device!]]),
checked_func = function() return not self:requireConfirmation() end,
callback = function()
G_reader_settings:saveSetting("mass_storage_confirmation_disabled", self:requireConfirmation())
end,
},
{
text = _("Disable mass storage functionality"),
help_text = _([[In case your device uses an unsupported setup where you know it won't work properly.]]),
checked_func = function() return not self:isEnabled() end,
callback = function()
G_reader_settings:saveSetting("mass_storage_disabled", self:isEnabled())
end,
},
}
end
-- mass storage actions
function MassStorage:getActionsMenuTable()
return {
text = _("Start USB storage"),
enabled_func = function() return self:isEnabled() end,
callback = function()
self:start(true)
end,
}
end
-- exit KOReader and start mass storage mode.
function MassStorage:start(never_ask)
if not Device:canToggleMassStorage() or not self:isEnabled() then
return
end
if not never_ask and self:requireConfirmation() then
local ConfirmBox = require("ui/widget/confirmbox")
UIManager:show(ConfirmBox:new{
text = _("Share storage via USB?"),
ok_text = _("Share"),
ok_callback = function()
-- save settings before activating USBMS:
UIManager:flushSettings()
UIManager:quit()
UIManager._exit_code = 86
end,
})
else
-- save settings before activating USBMS:
UIManager:flushSettings()
UIManager:quit()
UIManager._exit_code = 86
end
end
return MassStorage
|
[fix] Save document settings before activating USBMS (#6713)
|
[fix] Save document settings before activating USBMS (#6713)
As things were, when I activated USBMS, any bookmarks recently added and not yet stored in the sidecar file would be lost after returning to the reader. These changes fix that.
|
Lua
|
agpl-3.0
|
Frenzie/koreader,Frenzie/koreader,koreader/koreader,mwoz123/koreader,poire-z/koreader,poire-z/koreader,koreader/koreader,NiLuJe/koreader,Markismus/koreader,pazos/koreader,NiLuJe/koreader,Hzj-jie/koreader
|
eaba51d9d4fab32b7569afda6c55171114f8fb77
|
google-helpouts.lua
|
google-helpouts.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "user" and (downloaded[url] ~= true or addedtolist[url] ~= true) then
if string.match(url, "/"..item_value) or html == 0 then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, "&") then
table.insert(urls, { url=url })
check(string.gsub(url, "&", "&")
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
if item_type == "user" then
if string.match(url, "/"..item_value) then
html = read_file(file)
for newurl in string.gmatch(html, "(/[^"]+)") do
if string.match(newurl, "/"..item_value) then
check("https://helpouts.google.com"..newurl)
end
end
for newurl in string.gmatch(html, "(https?://[^"]+)") do
if string.match(newurl, "/"..item_value) or string.match(newurl, "googlevideo%.com") or string.match(newurl, "gstatic%.com") or string.match(newurl, "googleusercontent%.com") then
check(newurl)
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 15 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.5 * (math.random(75, 100) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "user" and (downloaded[url] ~= true or addedtolist[url] ~= true) then
if string.match(url, "/"..item_value) and string.match(url, "helpouts%.google%.com") then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url, origurl)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, "&") then
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
elseif string.match(origurl, "/api/offer/") then
if not (string.match(url, "photo%.jpg") or string.match(url, "/votereview/")) then
table.insert(urls, { url=url })
addedtolist[url] = true
end
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
if item_type == "user" then
if string.match(url, "/"..item_value) then
html = read_file(file)
for newurl in string.gmatch(html, '"(/[^"]+)"') do
if string.match(newurl, "/"..item_value) then
check("https://helpouts.google.com"..newurl, url)
end
end
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if (string.match(newurl, "/"..item_value) and string.match(url, "helpouts%.google%.com")) or (string.match(newurl, "googlevideo%.com") and not string.match(url, "/api/offer/")) or string.match(newurl, "gstatic%.com") or string.match(newurl, "googleusercontent%.com") then
check(newurl, url)
end
end
if string.match(html, "[0-9]+/[0-9a-zA-Z]+/%?mr=[0-9]+&nr=[0-9]+") then
check("https://helpouts.google.com/api/offer/"..item_value.."/"..string.match(html, "[0-9]+/([0-9a-zA-Z]+)/%?mr=[0-9]+&nr=[0-9]+").."?format=JSPB&authuser&xsrf=null&nr="..string.match(html, "[0-9]+/[0-9a-zA-Z]+/%?mr=[0-9]+&nr=([0-9]+)").."&mr="..string.match(html, "[0-9]+/[0-9a-zA-Z]+/%?mr=([0-9]+)&nr=[0-9]+").."&rt=j", url)
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 15 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.5 * (math.random(75, 100) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
google-helpouts.lua: fixes
|
google-helpouts.lua: fixes
|
Lua
|
unlicense
|
ArchiveTeam/google-helpouts-grab,ArchiveTeam/google-helpouts-grab
|
6861470d307bad7b66390814c1eca36ed0aac04d
|
plugins/mod_roster.lua
|
plugins/mod_roster.lua
|
-- Prosody IM v0.4
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza"
local jid_split = require "util.jid".split;
local t_concat = table.concat;
local tostring = tostring;
local handle_presence = require "core.presencemanager".handle_presence;
local rm_remove_from_roster = require "core.rostermanager".remove_from_roster;
local rm_add_to_roster = require "core.rostermanager".add_to_roster;
local rm_roster_push = require "core.rostermanager".roster_push;
local core_route_stanza = core_route_stanza;
module:add_feature("jabber:iq:roster");
module:add_iq_handler("c2s", "jabber:iq:roster",
function (session, stanza)
if stanza.tags[1].name == "query" then
if stanza.attr.type == "get" then
local roster = st.reply(stanza)
:query("jabber:iq:roster");
local ver = stanza.tags[1].attr.ver
if (not ver) or tonumber(ver) ~= (session.roster[false].version or 1) then
-- Client does not support versioning, or has stale roster
for jid in pairs(session.roster) do
if jid ~= "pending" and jid then
roster:tag("item", {
jid = jid,
subscription = session.roster[jid].subscription,
ask = session.roster[jid].ask,
name = session.roster[jid].name,
});
for group in pairs(session.roster[jid].groups) do
roster:tag("group"):text(group):up();
end
roster:up(); -- move out from item
end
end
roster.tags[1].attr.ver = tostring(session.roster[false].version or "1");
end
session.send(roster);
session.interested = true; -- resource is interested in roster updates
return true;
elseif stanza.attr.type == "set" then
local query = stanza.tags[1];
if #query.tags == 1 and query.tags[1].name == "item"
and query.tags[1].attr.xmlns == "jabber:iq:roster" and query.tags[1].attr.jid
-- Protection against overwriting roster.pending, until we move it
and query.tags[1].attr.jid ~= "pending" then
local item = query.tags[1];
local from_node, from_host = jid_split(stanza.attr.from);
local from_bare = from_node and (from_node.."@"..from_host) or from_host; -- bare JID
local node, host, resource = jid_split(item.attr.jid);
local to_bare = node and (node.."@"..host) or host; -- bare JID
if not resource and host then
if item.attr.jid ~= from_node.."@"..from_host then
if item.attr.subscription == "remove" then
local r_item = session.roster[item.attr.jid];
if r_item then
local success, err_type, err_cond, err_msg = rm_remove_from_roster(session, item.attr.jid);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
if r_item.subscription == "both" or r_item.subscription == "from" then
handle_presence(session, st.presence({type="unsubscribed"}), from_bare, to_bare,
core_route_stanza, false);
elseif r_item.subscription == "both" or r_item.subscription == "to" then
handle_presence(session, st.presence({type="unsubscribe"}), from_bare, to_bare,
core_route_stanza, false);
end
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
else
session.send(st.error_reply(stanza, "modify", "item-not-found"));
end
else
local r_item = {name = item.attr.name, groups = {}};
if r_item.name == "" then r_item.name = nil; end
if session.roster[item.attr.jid] then
r_item.subscription = session.roster[item.attr.jid].subscription;
r_item.ask = session.roster[item.attr.jid].ask;
else
r_item.subscription = "none";
end
for _, child in ipairs(item) do
if child.name == "group" then
local text = t_concat(child);
if text and text ~= "" then
r_item.groups[text] = true;
end
end
end
local success, err_type, err_cond, err_msg = rm_add_to_roster(session, item.attr.jid, r_item);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
end
else
session.send(st.error_reply(stanza, "cancel", "not-allowed"));
end
else
session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error?
end
else
session.send(st.error_reply(stanza, "modify", "bad-request"));
end
return true;
end
end
end);
|
-- Prosody IM v0.4
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza"
local jid_split = require "util.jid".split;
local jid_prep = require "util.jid".prep;
local t_concat = table.concat;
local tostring = tostring;
local handle_presence = require "core.presencemanager".handle_presence;
local rm_remove_from_roster = require "core.rostermanager".remove_from_roster;
local rm_add_to_roster = require "core.rostermanager".add_to_roster;
local rm_roster_push = require "core.rostermanager".roster_push;
local core_route_stanza = core_route_stanza;
module:add_feature("jabber:iq:roster");
module:add_iq_handler("c2s", "jabber:iq:roster",
function (session, stanza)
if stanza.tags[1].name == "query" then
if stanza.attr.type == "get" then
local roster = st.reply(stanza)
:query("jabber:iq:roster");
local ver = stanza.tags[1].attr.ver
if (not ver) or tonumber(ver) ~= (session.roster[false].version or 1) then
-- Client does not support versioning, or has stale roster
for jid in pairs(session.roster) do
if jid ~= "pending" and jid then
roster:tag("item", {
jid = jid,
subscription = session.roster[jid].subscription,
ask = session.roster[jid].ask,
name = session.roster[jid].name,
});
for group in pairs(session.roster[jid].groups) do
roster:tag("group"):text(group):up();
end
roster:up(); -- move out from item
end
end
roster.tags[1].attr.ver = tostring(session.roster[false].version or "1");
end
session.send(roster);
session.interested = true; -- resource is interested in roster updates
return true;
elseif stanza.attr.type == "set" then
local query = stanza.tags[1];
if #query.tags == 1 and query.tags[1].name == "item"
and query.tags[1].attr.xmlns == "jabber:iq:roster" and query.tags[1].attr.jid
-- Protection against overwriting roster.pending, until we move it
and query.tags[1].attr.jid ~= "pending" then
local item = query.tags[1];
local from_node, from_host = jid_split(stanza.attr.from);
local from_bare = from_node and (from_node.."@"..from_host) or from_host; -- bare JID
local jid = jid_prep(item.attr.jid);
local node, host, resource = jid_split(jid);
if not resource and host then
if jid ~= from_node.."@"..from_host then
if item.attr.subscription == "remove" then
local r_item = session.roster[jid];
if r_item then
local success, err_type, err_cond, err_msg = rm_remove_from_roster(session, jid);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, jid);
local to_bare = node and (node.."@"..host) or host; -- bare JID
if r_item.subscription == "both" or r_item.subscription == "from" then
handle_presence(session, st.presence({type="unsubscribed"}), from_bare, to_bare,
core_route_stanza, false);
elseif r_item.subscription == "both" or r_item.subscription == "to" then
handle_presence(session, st.presence({type="unsubscribe"}), from_bare, to_bare,
core_route_stanza, false);
end
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
else
session.send(st.error_reply(stanza, "modify", "item-not-found"));
end
else
local r_item = {name = item.attr.name, groups = {}};
if r_item.name == "" then r_item.name = nil; end
if session.roster[jid] then
r_item.subscription = session.roster[jid].subscription;
r_item.ask = session.roster[jid].ask;
else
r_item.subscription = "none";
end
for _, child in ipairs(item) do
if child.name == "group" then
local text = t_concat(child);
if text and text ~= "" then
r_item.groups[text] = true;
end
end
end
local success, err_type, err_cond, err_msg = rm_add_to_roster(session, jid, r_item);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, jid);
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
end
else
session.send(st.error_reply(stanza, "cancel", "not-allowed"));
end
else
session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error?
end
else
session.send(st.error_reply(stanza, "modify", "bad-request"));
end
return true;
end
end
end);
|
Fixed: mod_roster: Prep JIDs being added to roster (part of issue #57)
|
Fixed: mod_roster: Prep JIDs being added to roster (part of issue #57)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
5dff4afb03e7fbfb721285c4a95dfd2366badd64
|
src/plugins/lua/forged_recipients.lua
|
src/plugins/lua/forged_recipients.lua
|
-- Plugin for comparing smtp dialog recipients and sender with recipients and sender
-- in mime headers
local symbol_rcpt = 'FORGED_RECIPIENTS'
local symbol_sender = 'FORGED_SENDER'
function check_forged_headers(task)
local msg = task:get_message()
local smtp_rcpt = task:get_recipients(1)
local res = false
if smtp_rcpt then
local mime_rcpt = task:get_recipients(2)
local count = 0
if mime_rcpt then
count = table.maxn(mime_rcpt)
end
if count < table.maxn(smtp_rcpt) then
task:insert_result(symbol_rcpt, 1)
else
-- Find pair for each smtp recipient recipient in To or Cc headers
for _,sr in ipairs(smtp_rcpt) do
if mime_rcpt then
for _,mr in ipairs(mime_rcpt) do
if string.lower(mr['addr']) == string.lower(sr['addr']) then
res = true
break
end
end
end
if not res then
task:insert_result(symbol_rcpt, 1)
break
end
end
end
end
-- Check sender
local smtp_from = task:get_from(1)
if smtp_from then
local mime_from = task:get_from(2)
if not mime_from or not (string.lower(mime_from[1]['addr']) == string.lower(smtp_from[1]['addr'])) then
task:insert_result(symbol_sender, 1)
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('forged_recipients', 'symbol_rcpt', 'string')
rspamd_config:register_module_option('forged_recipients', 'symbol_sender', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('forged_recipients')
if opts then
if opts['symbol_rcpt'] or opts['symbol_sender'] then
if opts['symbol_rcpt'] then
symbol_rcpt = opts['symbol_rcpt']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_rcpt, 1.0, 'check_forged_headers')
end
end
if opts['symbol_sender'] then
symbol_sender = opts['symbol_sender']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_sender, 1.0)
end
end
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_callback_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
else
rspamd_config:register_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
end
end
end
|
-- Plugin for comparing smtp dialog recipients and sender with recipients and sender
-- in mime headers
local symbol_rcpt = 'FORGED_RECIPIENTS'
local symbol_sender = 'FORGED_SENDER'
function check_forged_headers(task)
local smtp_rcpt = task:get_recipients(1)
local res = false
if smtp_rcpt then
local mime_rcpt = task:get_recipients(2)
local count = 0
if mime_rcpt then
count = table.maxn(mime_rcpt)
end
if count < table.maxn(smtp_rcpt) then
task:insert_result(symbol_rcpt, 1)
else
-- Find pair for each smtp recipient recipient in To or Cc headers
for _,sr in ipairs(smtp_rcpt) do
if mime_rcpt then
for _,mr in ipairs(mime_rcpt) do
if string.lower(mr['addr']) == string.lower(sr['addr']) then
res = true
break
end
end
end
if not res then
task:insert_result(symbol_rcpt, 1)
break
end
end
end
end
-- Check sender
local smtp_from = task:get_from(1)
if smtp_from then
local mime_from = task:get_from(2)
if not mime_from or not (string.lower(mime_from[1]['addr']) == string.lower(smtp_from[1]['addr'])) then
task:insert_result(symbol_sender, 1)
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('forged_recipients', 'symbol_rcpt', 'string')
rspamd_config:register_module_option('forged_recipients', 'symbol_sender', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('forged_recipients')
if opts then
if opts['symbol_rcpt'] or opts['symbol_sender'] then
if opts['symbol_rcpt'] then
symbol_rcpt = opts['symbol_rcpt']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_rcpt, 1.0, 'check_forged_headers')
end
end
if opts['symbol_sender'] then
symbol_sender = opts['symbol_sender']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_sender, 1.0)
end
end
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_callback_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
else
rspamd_config:register_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
end
end
end
|
Fix forged_recipients plugin.
|
Fix forged_recipients plugin.
|
Lua
|
apache-2.0
|
dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,dark-al/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,amohanta/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,awhitesong/rspamd,amohanta/rspamd,amohanta/rspamd,AlexeySa/rspamd,dark-al/rspamd,dark-al/rspamd,awhitesong/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,awhitesong/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,dark-al/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,awhitesong/rspamd
|
84e292faf0f7cbb8f9bf9ded2804cd9caa478089
|
hammerspoon/luncher.lua
|
hammerspoon/luncher.lua
|
local hyper = {"cmd", "shift"}
local browsers = {{"Google Chrome", "Safari"}}
local editorAndIDEs = {{"com.github.atom", "org.vim.MacVim", "Emacs", "com.jetbrains.intellij.ce"}}
local emails = {{"com.mailplaneapp.Mailplane3"}}
local chats = {{"HipChat", "WeChat", "Messages"}}
local tweets = {{"Tweetbot"}}
local terminals = {{"com.googlecode.iterm2"}}
local reminders = {{"Reminders", "Quip"}}
local debuggers = {{"com.postmanlabs.mac"}}
hs.hotkey.bind(hyper, "s", function() toggleApps(browsers) end)
hs.hotkey.bind(hyper, "a", function() toggleApps(emails) end)
hs.hotkey.bind(hyper, "x", function() toggleApps(editorAndIDEs) end)
hs.hotkey.bind(hyper, "w", function() toggleApps(chats) end)
hs.hotkey.bind(hyper, "o", function() toggleApps(tweets) end)
hs.hotkey.bind(hyper, "j", function() toggleApps(terminals) end)
hs.hotkey.bind(hyper, "k", function() toggleApps(debuggers) end)
-- hs.hotkey.bind(hyper, "r", function() toggleApps(reminders) end)
function getAppNames (appList)
return appList[1]
end
function getLastUsedApp (appList)
return appList["LAST_USED_APP"]
end
function setLastUsedApp (appList, app)
appList["LAST_USED_APP"] = app
end
function toggleApps (appList)
local appNames = getAppNames(appList)
local lastUsedApp = getLastUsedApp(appList)
local appMap, nameArray, totalCount = filterOpenApps(appNames)
if totalCount == 0 then
local app = appNames[1]
hs.alert.show("Open " .. app)
setLastUsedApp(appList, app);
return hs.application.open(app)
end
local foundLastUsed, index = false, 1
for _, appName in pairs(nameArray) do
if lastUsedApp == appName then
local appObj = appMap[appName]
if appObj:isFrontmost() then
foundLastUsed = true
index = _
break
else
return toggleApp(appObj)
end
end
end
if foundLastUsed then
return toggleNextApp(index, totalCount, nameArray, appMap, appList)
end
index = 0
for _, appName in pairs(nameArray) do
if appMap[appName]:isFrontmost() then
index = _
break
end
end
return toggleNextApp(index, totalCount, nameArray, appMap, appList)
end
function toggleNextApp (current, totalCount, nameArray, map, appList)
local index = math.fmod(current, totalCount) + 1
local appName = nameArray[index]
local appObj = map[appName]
setLastUsedApp(appList, appName)
return toggleApp(appObj)
end
function filterOpenApps (apps)
local map, names = {}, {}
for _, app in pairs(apps) do
appObj = hs.application.get(app)
if appObj then
map[app] = appObj
names[#names + 1] = app
end
end
return map, names, #names
end
function toggleApp (app)
if app:isFrontmost() then
hs.application.hide(app)
else
app:activate()
end
end
|
local hyper = {"cmd", "shift"}
local browsers = {{"Google Chrome", "Safari"}}
local editorAndIDEs = {{"com.github.atom", "org.vim.MacVim", "Emacs", "com.jetbrains.intellij.ce"}}
local emails = {{"com.mailplaneapp.Mailplane3"}}
local chats = {{"HipChat", "WeChat", "Messages"}}
local tweets = {{"Tweetbot"}}
local terminals = {{"com.googlecode.iterm2"}}
local reminders = {{"Reminders", "Quip"}}
local debuggers = {{"com.postmanlabs.mac"}}
hs.hotkey.bind(hyper, "s", function() toggleApps(browsers) end)
hs.hotkey.bind(hyper, "a", function() toggleApps(emails) end)
hs.hotkey.bind(hyper, "x", function() toggleApps(editorAndIDEs) end)
hs.hotkey.bind(hyper, "w", function() toggleApps(chats) end)
hs.hotkey.bind(hyper, "o", function() toggleApps(tweets) end)
hs.hotkey.bind(hyper, "j", function() toggleApps(terminals) end)
hs.hotkey.bind(hyper, "k", function() toggleApps(debuggers) end)
-- hs.hotkey.bind(hyper, "r", function() toggleApps(reminders) end)
function getAppNames (appList)
return appList[1]
end
function getLastUsedApp (appList)
return appList["LAST_USED_APP"]
end
function setLastUsedApp (appList, app)
appList["LAST_USED_APP"] = app
end
function toggleApps (appList)
local appNames = getAppNames(appList)
local lastUsedApp = getLastUsedApp(appList)
local appMap, nameArray, totalCount = filterOpenApps(appNames)
if totalCount == 0 then
return openFirstApp(appNames)
end
local foundLastUsed, index = false, 1
for _, appName in pairs(nameArray) do
if lastUsedApp == appName then
local appObj = appMap[appName]
if appObj:isFrontmost() then
foundLastUsed = true
index = _
break
else
return toggleApp(appObj)
end
end
end
if foundLastUsed then
return toggleNextApp(index, totalCount, nameArray, appMap, appList)
end
index = 0
for _, appName in pairs(nameArray) do
if appMap[appName]:isFrontmost() then
index = _
break
end
end
return toggleNextApp(index, totalCount, nameArray, appMap, appList)
end
function toggleNextApp (current, totalCount, nameArray, map, appList)
local index = math.fmod(current, totalCount) + 1
local appName = nameArray[index]
local appObj = map[appName]
setLastUsedApp(appList, appName)
return toggleApp(appObj)
end
function filterOpenApps (apps)
local map, names = {}, {}
for _, app in pairs(apps) do
appObj = hs.application.get(app)
if appObj then
map[app] = appObj
names[#names + 1] = app
end
end
return map, names, #names
end
function toggleApp (app)
if app:isFrontmost() then
hs.application.hide(app)
else
app:activate()
end
end
function openFirstApp (apps)
for _, app in pairs(apps) do
local result = hs.application.launchOrFocus(app)
if result then
hs.alert.show("Open " .. app)
return setLastUsedApp(appList, app)
end
end
return hs.alert.show("No app found in:\n" .. table.concat(apps, "\n"))
end
|
Fix #4; Try to open first available app if the no app is open in the app group
|
Fix #4; Try to open first available app if the no app is open in the app group
|
Lua
|
mit
|
xcv58/Hammerspoon-xcv58
|
e791afe05f6e94e4f54869c5017632cb5a7af281
|
classes/actor.lua
|
classes/actor.lua
|
mrequire "classes/class"
mrequire "classes/dialogue"
mrequire "classes/item"
mrequire "classes/task"
Actors = { }
newclass("Actor",
function(id, name, costume, color)
local actor = {
id = id,
name = name,
costume = CostumeController.new(costume),
speed = 150,
inventory = { },
color = color or { 1, 0, 1 },
goal = nil,
prop = nil,
loop = nil,
stop = false,
onGoal = nil,
pressing = { },
hitHotspot = nil
}
record /Actors, id = actor
Actors[id] = actor
return actor
end
)
function Actor.getActor(id)
return Actors[id]
end
function Actor:location()
return self.prop:getLoc()
end
function Actor:hitTest(x, y)
local hs = self.costume:hitTest(x, y)
if hs == true or not hs then
self.hitHotspot = nil
else
hs.proxy = self
self.hitHotspot = hs
end
return hs
end
function Actor:joinScene()
local prop = game.makeProp()
prop.actor = self
self.prop = prop
self.costume:setProp(prop)
self.costume:refresh()
if not self.loop then
self.loop = MOAIThread.new()
self.loop:run(self.mainLoop, self)
end
end
function Actor:leaveScene()
self.prop.actor = nil
game.destroyProp(self.prop)
self.prop = nil
self.stop = true
end
function Actor:teleport(x, y)
if self.prop then
self.prop:setLoc(x, y)
end
end
function Actor:teleportRel(x, y)
local sx, sy = self:location()
self:teleport(sx + x, sy + y)
end
function Actor:walkToAsync(x, y, onGoal)
self.stop = true
self.goal = { x, y }
self.onGoal = onGoal
end
function Actor:giveItem(id)
self.inventory[id] = Item.getItem(id)
end
function Actor:removeItem(id)
self.inventory[id] = nil
end
function Actor:hasItem(id)
return self.inventory[id]
end
function Actor:say(msg)
local x, y = self:location()
self.costume:setPose("talk")
local label = game.showMessage(msg, x, y, unpack(self.color))
Task.sleep(Dialogue.time(msg))
game.hideMessage(label)
self.costume:setPose("idle")
end
function Actor:stopWalking()
self.stop = true
Task.sleep(0.001)
end
function Actor:walkTo(x, y)
local sx, sy = self:location()
local path = room:getPath(sx, sy, x, y, 1, 1)
local has_path = #path ~= 0
if has_path then
self.costume:setPose("walk")
end
while #path ~= 0 do
local goal = path[1]
table.remove(path, 1)
self:moveToXY(unpack(goal))
if self.stop then path = { } end
end
if has_path then
self.costume:setPose("idle")
end
end
function Actor:moveToXY(x, y)
if self.prop and not self.stop then
local sx, sy = self:location()
local dx, dy = x - sx, y - sy
local dist = math.sqrt(dx * dx + dy * dy)
self.costume:setDirection({ dx, dy })
MOAIThread.blockOnAction(self.prop:moveLoc(dx, dy, dist / self.speed, MOAIEaseType.LINEAR))
sx, sy = self:location()
-- do unpressing
for hotspot in pairs(self.pressing) do
if not hotspot:hitTest(sx, sy) then
local events = room.events[hotspot.id]
if events and events.unpress then
start(events.unpress, self)
end
self.pressing[hotspot] = nil
end
end
-- do pressing
local hotspot = game.getHotspotAtXY(sx, sy)
if hotspot and not self.pressing[hotspot] then
local events = room.events[hotspot.id]
if events and events.press then
start(events.press, self)
end
self.pressing[hotspot] = true
end
end
end
function Actor:mainLoop()
while self.prop do
local _, y = self:location()
self.prop:setPriority(y)
if self.goal then
local goal = self.goal
self.goal = nil
self.stop = false
self:walkTo(unpack(goal))
if not self.stop and self.onGoal then
self:onGoal()
self.onGoal = nil
end
end
coroutine.yield()
end
self.loop = nil
end
|
mrequire "classes/class"
mrequire "classes/dialogue"
mrequire "classes/item"
mrequire "classes/task"
Actors = { }
newclass("Actor",
function(id, name, costume, color)
local actor = {
id = id,
name = name,
costume = CostumeController.new(costume),
speed = 150,
inventory = { },
color = color or { 1, 0, 1 },
goal = nil,
prop = nil,
loop = nil,
stop = false,
action = nil,
onGoal = nil,
pressing = { },
hitHotspot = nil
}
record /Actors, id = actor
Actors[id] = actor
return actor
end
)
function Actor.getActor(id)
return Actors[id]
end
function Actor:location()
return self.prop:getLoc()
end
function Actor:hitTest(x, y)
local hs = self.costume:hitTest(x, y)
if hs == true or not hs then
self.hitHotspot = nil
else
hs.proxy = self
self.hitHotspot = hs
end
return hs
end
function Actor:joinScene()
local prop = game.makeProp()
prop.actor = self
self.prop = prop
self.costume:setProp(prop)
self.costume:refresh()
if not self.loop then
self.loop = MOAIThread.new()
self.loop:run(self.mainLoop, self)
end
end
function Actor:leaveScene()
self.prop.actor = nil
game.destroyProp(self.prop)
self.prop = nil
self.stop = true
end
function Actor:teleport(x, y)
if self.prop then
self.prop:setLoc(x, y)
self.prop:setPriority(y)
end
end
function Actor:teleportRel(x, y)
local sx, sy = self:location()
self:teleport(sx + x, sy + y)
end
function Actor:walkToAsync(x, y, onGoal)
if self.action then
self.action:stop()
end
self.stop = true
self.goal = { x, y }
self.onGoal = onGoal
end
function Actor:giveItem(id)
self.inventory[id] = Item.getItem(id)
end
function Actor:removeItem(id)
self.inventory[id] = nil
end
function Actor:hasItem(id)
return self.inventory[id]
end
function Actor:say(msg)
local x, y = self:location()
self.costume:setPose("talk")
local label = game.showMessage(msg, x, y, unpack(self.color))
Task.sleep(Dialogue.time(msg))
game.hideMessage(label)
self.costume:setPose("idle")
end
function Actor:stopWalking()
self.stop = true
if self.action then
self.action:stop()
end
end
function Actor:walkTo(x, y)
local sx, sy = self:location()
local path = room:getPath(sx, sy, x, y, 1, 1)
local has_path = #path ~= 0
if has_path then
self.costume:setPose("walk")
end
while #path ~= 0 do
local goal = path[1]
table.remove(path, 1)
self:moveToXY(unpack(goal))
if self.stop then path = { } end
end
if has_path then
self.costume:setPose("idle")
end
end
function Actor:moveToXY(x, y)
if self.prop and not self.stop then
local sx, sy = self:location()
local dx, dy = x - sx, y - sy
local dist = math.sqrt(dx * dx + dy * dy)
self.costume:setDirection({ dx, dy })
self.action = self.prop:moveLoc(dx, dy, dist / self.speed, MOAIEaseType.LINEAR)
while self.action:isBusy() do
sx, sy = self:location()
-- do unpressing
for hotspot in pairs(self.pressing) do
if not hotspot:hitTest(sx, sy) then
local events = room.events[hotspot.id]
if events and events.unpress then
start(events.unpress, self)
end
self.pressing[hotspot] = nil
end
end
-- do pressing
local hotspot = game.getHotspotAtXY(sx, sy)
if hotspot and not self.pressing[hotspot] then
local events = room.events[hotspot.id]
if events and events.press then
start(events.press, self)
end
self.pressing[hotspot] = true
end
self.prop:setPriority(sy)
coroutine.yield(0)
end
self.action = nil
end
end
function Actor:mainLoop()
while self.prop do
local _, y = self:location()
if self.goal then
local goal = self.goal
self.goal = nil
self.stop = false
self:walkTo(unpack(goal))
if not self.stop and self.onGoal then
self:onGoal()
self.onGoal = nil
end
end
coroutine.yield()
end
self.loop = nil
end
|
Fixed issues due to blocking walking
|
Fixed issues due to blocking walking
Walking to XY doesn't block the main actor thread anymore, which means we can do finer grained pressing, prioritizing and walk canceling
|
Lua
|
mit
|
isovector/adventure,isovector/adventure
|
86d137059fd6f54a9969668fcf42f1c9d5dd5a4d
|
game/scripts/vscripts/modules/structures/structures.lua
|
game/scripts/vscripts/modules/structures/structures.lua
|
Structures = Structures or class({})
ModuleRequire(..., "data")
ModuleRequire(..., "shops")
ModuleLinkLuaModifier(..., "modifier_arena_healer")
ModuleLinkLuaModifier(..., "modifier_arena_courier")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_arena")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_invulnerability", "modifier_fountain_aura_arena")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_enemy")
Events:Register("activate", function ()
local gameMode = GameRules:GetGameModeEntity()
gameMode:SetFountainConstantManaRegen(0)
gameMode:SetFountainPercentageHealthRegen(0)
gameMode:SetFountainPercentageManaRegen(0)
Structures:AddHealers()
Structures:CreateShops()
end)
Events:Register("bosses/kill/cursed_zeld", function ()
Notifications:TopToAll({ text="#structures_fountain_protection_weak_line1", duration = 7 })
Notifications:TopToAll({ text="#structures_fountain_protection_weak_line2", duration = 7 })
end)
Events:Register("bosses/respawn/cursed_zeld", function ()
Notifications:TopToAll({ text="#structures_fountain_protection_strong_line1", duration = 7 })
Notifications:TopToAll({ text="#structures_fountain_protection_strong_line2", duration = 7 })
end)
function Structures:AddHealers()
for _,v in ipairs(Entities:FindAllByClassname("npc_dota_healer")) do
local model = TEAM_HEALER_MODELS[v:GetTeamNumber()]
v:SetOriginalModel(model.mdl)
v:SetModel(model.mdl)
if model.color then v:SetRenderColor(unpack(model.color)) end
v:RemoveModifierByName("modifier_invulnerable")
v:AddNewModifier(v, nil, "modifier_arena_healer", nil)
v:FindAbilityByName("healer_taste_of_armor"):SetLevel(1)
v:FindAbilityByName("healer_bottle_refill"):SetLevel(1)
end
end
function Structures:GiveCourier(hero)
local playerId = hero:GetPlayerID()
local tn = hero:GetTeamNumber()
local cour_item = hero:AddItem(CreateItem("item_courier", hero, hero))
TEAMS_COURIERS[hero:GetTeamNumber()] = true
Timers:CreateTimer(0.03, function()
for _,courier in ipairs(Entities:FindAllByClassname("npc_dota_courier")) do
local owner = courier:GetOwner()
if IsValidEntity(owner) and owner:GetPlayerID() == playerId then
courier:SetOwner(nil)
courier:UpgradeToFlyingCourier()
courier:AddNewModifier(courier, nil, "modifier_arena_courier", nil)
TEAMS_COURIERS[tn] = courier
end
end
end)
end
|
Structures = Structures or class({})
ModuleRequire(..., "data")
ModuleRequire(..., "shops")
ModuleLinkLuaModifier(..., "modifier_arena_healer")
ModuleLinkLuaModifier(..., "modifier_arena_courier")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_arena")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_invulnerability", "modifier_fountain_aura_arena")
ModuleLinkLuaModifier(..., "modifier_fountain_aura_enemy")
Events:Register("activate", function ()
local gameMode = GameRules:GetGameModeEntity()
gameMode:SetFountainConstantManaRegen(0)
gameMode:SetFountainPercentageHealthRegen(0)
gameMode:SetFountainPercentageManaRegen(0)
Structures:AddHealers()
Structures:CreateShops()
end)
Events:Register("bosses/kill/cursed_zeld", function ()
Notifications:TopToAll({ text="#structures_fountain_protection_weak_line1", duration = 7 })
Notifications:TopToAll({ text="#structures_fountain_protection_weak_line2", duration = 7 })
end)
Events:Register("bosses/respawn/cursed_zeld", function ()
Notifications:TopToAll({ text="#structures_fountain_protection_strong_line1", duration = 7 })
Notifications:TopToAll({ text="#structures_fountain_protection_strong_line2", duration = 7 })
end)
function Structures:AddHealers()
for _,v in ipairs(Entities:FindAllByClassname("npc_dota_healer")) do
local model = TEAM_HEALER_MODELS[v:GetTeamNumber()]
v:SetOriginalModel(model.mdl)
v:SetModel(model.mdl)
if model.color then v:SetRenderColor(unpack(model.color)) end
v:RemoveModifierByName("modifier_invulnerable")
v:AddNewModifier(v, nil, "modifier_arena_healer", nil)
v:FindAbilityByName("healer_taste_of_armor"):SetLevel(1)
v:FindAbilityByName("healer_bottle_refill"):SetLevel(1)
end
end
function Structures:GiveCourier(hero)
local team = hero:GetTeamNumber()
if not TEAMS_COURIERS[team] then
local courier = CreateUnitByName("npc_dota_courier", hero:GetAbsOrigin(), true, hero, hero:GetPlayerOwner(), team)
courier:AddNewModifier(courier, nil, "modifier_arena_courier", nil)
TEAMS_COURIERS[team] = courier
end
TEAMS_COURIERS[team]:SetControllableByPlayer(hero:GetPlayerID(), true)
end
|
fix(structures): update courier spawn method
|
fix(structures): update courier spawn method
|
Lua
|
mit
|
ark120202/aabs
|
b7fd1a7083837cc65773b4a064afc31784f6b4b9
|
tarantoolapp/commands/dep.lua
|
tarantoolapp/commands/dep.lua
|
local errno = require 'errno'
local fio = require 'fio'
local yaml = require 'yaml'
local fileio = require 'tarantoolapp.fileio'
local util = require 'tarantoolapp.util'
local cfg
local function printf(f, ...)
print(string.format('[%s] ' .. f, cfg.name, ...))
end
local function errorf(f, ...)
print(string.format('[%s] ' .. f, cfg.name, ...))
os.exit(1)
end
local function _string_split(s, sep)
sep = sep or ','
local parts = {}
for word in string.gmatch(s, string.format('([^%s]+)', sep)) do
table.insert(parts, word)
end
return parts
end
local function ensure_rocksservers(path)
local dir = fio.dirname(path)
if not fileio.path.is_dir(dir) then
fileio.mkdir(dir)
end
if fileio.path.exists(path) then
local f = fio.open(path)
if not f then
errorf("Failed to open file %s: %s", path, errno.strerror())
end
local data = f:read(f:stat().size)
f:close()
if data:match('rocks%.tarantool%.org') and data:match('rocks%.moonscript%.org') then
printf('Already have proper rocks servers')
return
end
else
local directory = fio.dirname(path)
if not fio.mktree(directory) then
errorf('Error while creating %s: %s', directory, errno.strerror())
end
end
printf("Patch %s with proper rocks servers", path)
local fh = fio.open(path, {'O_CREAT', 'O_APPEND', 'O_RDWR'}, 0664)
if not fh then
errorf("Failed to open file %s: %s", path, errno.strerror())
end
fh:write('\nrocks_servers = {[[http://rocks.tarantool.org/]], [[https://rocks.moonscript.org]]}\n')
fh:close()
end
local function execute(cmd)
local raw_cmd = table.concat(cmd, ' ')
printf("%s...", raw_cmd)
local res = os.execute('exec ' .. raw_cmd)
if res ~= 0 then
errorf('%s failed', raw_cmd)
end
return res
end
local function cmd_luarocks(subcommand, dep, tree)
assert(subcommand ~= nil, 'subcommand is required')
assert(dep ~= nil, 'dep is required')
local cmd = {'luarocks', subcommand, dep}
if tree then
table.insert(cmd, '--tree='..tree)
end
return execute(cmd)
end
local function cmd_tarantoolctl(subcommand, dep, tree)
assert(subcommand ~= nil, 'subcommand is required')
assert(dep ~= nil, 'dep is required')
local cmd = {'tarantoolctl', 'rocks', subcommand, dep}
return execute(cmd)
end
local function _gencmd(command, subcommand)
return function(dep, tree)
return command(subcommand, dep, tree)
end
end
local luarocks_install = _gencmd(cmd_luarocks, 'install')
local luarocks_remove = _gencmd(cmd_luarocks, 'remove')
local luarocks_make = _gencmd(cmd_luarocks, 'make')
local tarantoolctl_install = _gencmd(cmd_tarantoolctl, 'install')
local function description()
return "Install dependencies"
end
local function argparse(argparser, cmd)
cmd:option('-m --meta-file', 'path to meta.yaml file')
:default('./meta.yaml')
cmd:option('-t --tree', 'path to directory that will hold the dependencies')
:default('.rocks')
:convert(fio.abspath)
cmd:option('--luarocks-config', 'path to luarocks config')
:default(fio.pathjoin(os.getenv('HOME'), '.luarocks', 'config.lua'))
cmd:option('--only', 'install only these sections (deps, tntdeps or localdeps)')
:args("*"):action("concat")
end
local function run(args)
local luaroot = debug.getinfo(1, 'S')
local source = fio.abspath(luaroot.source:match('^@(.+)'))
local appname = fio.basename(fio.dirname(source))
assert(args.meta_file ~= '', 'meta file is required')
args.meta_file = fio.abspath(args.meta_file)
local meta_file = fio.open(args.meta_file)
if meta_file == nil then
errorf('Meta file %s does not exist', args.meta_file)
end
local metatext = meta_file:read(meta_file:stat().size)
local tree = fio.abspath(args.tree)
local only_sections
if args.only and #args.only > 0 then
only_sections = {}
for _, s in ipairs(args.only) do
if s == 'local_deps' or s == 'localdeps' or s == 'local' then
only_sections.localdeps = true
elseif s == 'tnt_deps' or s == 'tntdeps' or s == 'tnt' or s == 'tarantool' then
only_sections.tntdeps = true
elseif s == 'deps' then
only_sections.deps = true
end
end
end
args.only = only_sections
print('Using the following options:\n' .. yaml.encode(args))
cfg = metatext:match('^%s*%{') and require 'json'.decode(metatext) or yaml.decode(metatext)
cfg.name = cfg.name or appname
assert(cfg.name, 'Name must be defined')
ensure_rocksservers(args.luarocks_config)
printf('Installing dependencies...')
local deps = cfg.deps or {}
local tnt_deps = cfg.tnt_deps or cfg.tntdeps or {}
local local_deps = cfg.local_deps or cfg.localdeps or {}
if args.only == nil or args.only.deps then
for _, dep in ipairs(deps) do
printf("Installing dep '%s'", dep)
luarocks_install(dep, tree)
printf("Installed dep '%s'\n\n", dep)
end
end
if args.only == nil or args.only.tntdeps then
for _, dep in ipairs(tnt_deps) do
printf("Installing tarantool dep '%s'", dep)
tarantoolctl_install(dep, tree)
printf("Installed tarantool dep '%s'\n\n", dep)
end
end
if args.only == nil or args.only.localdeps then
local cwd = fio.cwd()
for _, dep in ipairs(local_deps) do
local dep_root
local dep_info = _string_split(dep, ':')
if #dep_info > 1 then
dep = dep_info[1]
dep_root = dep_info[2]
else
dep_root = fio.dirname(dep)
end
printf("Installing local dep '%s' with root at '%s'", dep, dep_root)
dep = fio.abspath(dep)
dep_root = fio.abspath(dep_root)
fio.chdir(dep_root) -- local rocks must be installed from within the project root
local ok, res = pcall(luarocks_remove, dep, tree)
if not ok then
printf(res)
end
luarocks_make(dep, tree)
fio.chdir(cwd)
printf("Installed local dep '%s'\n\n", dep)
end
end
printf('Done.')
end
return {
description = description,
argparse = argparse,
run = run,
}
|
local errno = require 'errno'
local fio = require 'fio'
local yaml = require 'yaml'
local fileio = require 'tarantoolapp.fileio'
local util = require 'tarantoolapp.util'
local cfg
local function printf(f, ...)
print(string.format('[%s] ' .. f, cfg.name, ...))
end
local function raisef(f, ...)
error(string.format('[%s] ' .. f, cfg.name, ...))
end
local function errorf(f, ...)
print(string.format('[%s] ' .. f, cfg.name, ...))
os.exit(1)
end
local function _string_split(s, sep)
sep = sep or ','
local parts = {}
for word in string.gmatch(s, string.format('([^%s]+)', sep)) do
table.insert(parts, word)
end
return parts
end
local function ensure_rocksservers(path)
local dir = fio.dirname(path)
if not fileio.path.is_dir(dir) then
fileio.mkdir(dir)
end
if fileio.path.exists(path) then
local f = fio.open(path)
if not f then
errorf("Failed to open file %s: %s", path, errno.strerror())
end
local data = f:read(f:stat().size)
f:close()
if data:match('rocks%.tarantool%.org') and (data:match('rocks%.moonscript%.org') or data:match('luarocks%.org')) then
printf('Already have proper rocks servers')
return
end
else
local directory = fio.dirname(path)
if not fio.mktree(directory) then
errorf('Error while creating %s: %s', directory, errno.strerror())
end
end
printf("Patch %s with proper rocks servers", path)
local fh = fio.open(path, {'O_CREAT', 'O_APPEND', 'O_RDWR'}, 0664)
if not fh then
errorf("Failed to open file %s: %s", path, errno.strerror())
end
fh:write('\nrocks_servers = {[[http://rocks.tarantool.org]], [[https://luarocks.org]]}\n')
fh:close()
end
local function execute(cmd)
local raw_cmd = table.concat(cmd, ' ')
printf("%s...", raw_cmd)
local res = os.execute('exec ' .. raw_cmd)
if res ~= 0 then
raisef('%s failed', raw_cmd)
end
return res
end
local function cmd_luarocks(subcommand, dep, tree)
assert(subcommand ~= nil, 'subcommand is required')
assert(dep ~= nil, 'dep is required')
local cmd = {'luarocks', subcommand, dep}
if tree then
table.insert(cmd, '--tree='..tree)
end
return execute(cmd)
end
local function cmd_tarantoolctl(subcommand, dep, tree)
assert(subcommand ~= nil, 'subcommand is required')
assert(dep ~= nil, 'dep is required')
local cmd = {'tarantoolctl', 'rocks', subcommand, dep}
return execute(cmd)
end
local function _gencmd(command, subcommand)
return function(dep, tree)
return command(subcommand, dep, tree)
end
end
local luarocks_install = _gencmd(cmd_luarocks, 'install')
local luarocks_remove = _gencmd(cmd_luarocks, 'remove')
local luarocks_make = _gencmd(cmd_luarocks, 'make')
local tarantoolctl_install = _gencmd(cmd_tarantoolctl, 'install')
local function description()
return "Install dependencies"
end
local function argparse(argparser, cmd)
cmd:option('-m --meta-file', 'path to meta.yaml file')
:default('./meta.yaml')
:convert(fio.abspath)
cmd:option('-t --tree', 'path to directory that will hold the dependencies')
:default('.rocks')
:convert(fio.abspath)
cmd:option('--luarocks-config', 'path to luarocks config')
:default(fio.pathjoin(os.getenv('HOME'), '.luarocks', 'config.lua'))
cmd:option('--only', 'install only these sections (deps, tntdeps or localdeps)')
:args("*"):action("concat")
end
local function run(args)
local luaroot = debug.getinfo(1, 'S')
local source = fio.abspath(luaroot.source:match('^@(.+)'))
local appname = fio.basename(fio.dirname(source))
assert(args.meta_file ~= '', 'meta file is required')
local meta_file = fio.open(args.meta_file)
if meta_file == nil then
util.errorf('Couldn\'t open %s: %s', args.meta_file, errno.strerror())
end
local metatext = meta_file:read(meta_file:stat().size)
local tree = fio.abspath(args.tree)
local only_sections
if args.only and #args.only > 0 then
only_sections = {}
for _, s in ipairs(args.only) do
if s == 'local_deps' or s == 'localdeps' or s == 'local' then
only_sections.localdeps = true
elseif s == 'tnt_deps' or s == 'tntdeps' or s == 'tnt' or s == 'tarantool' then
only_sections.tntdeps = true
elseif s == 'deps' then
only_sections.deps = true
end
end
end
args.only = only_sections
print('Using the following options:\n' .. yaml.encode(args))
cfg = metatext:match('^%s*%{') and require 'json'.decode(metatext) or yaml.decode(metatext)
cfg.name = cfg.name or appname
assert(cfg.name, 'Name must be defined')
ensure_rocksservers(args.luarocks_config)
printf('Installing dependencies...')
local deps = cfg.deps or {}
local tnt_deps = cfg.tnt_deps or cfg.tntdeps or {}
local local_deps = cfg.local_deps or cfg.localdeps or {}
if args.only == nil or args.only.deps then
for _, dep in ipairs(deps) do
printf("Installing dep '%s'", dep)
luarocks_install(dep, tree)
printf("Installed dep '%s'\n\n", dep)
end
end
if args.only == nil or args.only.tntdeps then
for _, dep in ipairs(tnt_deps) do
printf("Installing tarantool dep '%s'", dep)
tarantoolctl_install(dep, tree)
printf("Installed tarantool dep '%s'\n\n", dep)
end
end
if args.only == nil or args.only.localdeps then
local cwd = fio.cwd()
for _, dep in ipairs(local_deps) do
local dep_root
local dep_info = _string_split(dep, ':')
if #dep_info > 1 then
dep = dep_info[1]
dep_root = dep_info[2]
else
dep_root = fio.dirname(dep)
end
printf("Installing local dep '%s' with root at '%s'", dep, dep_root)
dep = fio.abspath(dep)
dep_root = fio.abspath(dep_root)
fio.chdir(dep_root) -- local rocks must be installed from within the project root
local ok, res = pcall(luarocks_remove, dep, tree)
if not ok then
printf(res)
end
luarocks_make(dep, tree)
fio.chdir(cwd)
printf("Installed local dep '%s'\n\n", dep)
end
end
printf('Done.')
end
return {
description = description,
argparse = argparse,
run = run,
}
|
fix dep local
|
fix dep local
|
Lua
|
mit
|
moonlibs/tarantoolapp,moonlibs/tarantoolapp
|
339d5cd178d2adca9c52b57ca6b22e567d203e41
|
core/componentmanager.lua
|
core/componentmanager.lua
|
-- Prosody IM v0.4
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local eventmanager = require "core.eventmanager";
local modulemanager = require "core.modulemanager";
local core_route_stanza = core_route_stanza;
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local hosts = hosts;
local pairs, type, tostring = pairs, type, tostring;
local components = {};
local disco_items = require "util.multitable".new();
local NULL = {};
require "core.discomanager".addDiscoItemsHandler("*host", function(reply, to, from, node)
if #node == 0 and hosts[to] then
for jid in pairs(disco_items:get(to) or NULL) do
reply:tag("item", {jid = jid}):up();
end
return true;
end
end);
require "core.eventmanager".add_event_hook("server-starting", function () core_route_stanza = _G.core_route_stanza; end);
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" then
core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
end
end
function load_enabled_components(config)
local defined_hosts = config or configmanager.getconfig();
for host, host_config in pairs(defined_hosts) do
if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
hosts[host] = { type = "component", host = host, connected = false, s2sout = {} };
components[host] = default_component_handler;
local ok, err = modulemanager.load(host, host_config.core.component_module);
if not ok then
log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err));
else
log("info", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
eventmanager.add_event_hook("server-starting", load_enabled_components);
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if not component then component = components[stanza.attr.to]; end -- hack to allow hooking node@server/resource and server/resource
if not component then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
if component then
log("debug", "%s stanza being handled by component: %s", stanza.name, host);
component(origin, stanza, hosts[host]);
else
log("error", "Component manager recieved a stanza for a non-existing component: " .. stanza.attr.to);
end
end
function create_component(host, component)
-- TODO check for host well-formedness
local session = session or { type = "component", host = host, connected = true, s2sout = {} };
return session;
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
components[host] = component;
hosts[host] = session or create_component(host, component);
-- add to disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:set(host:sub(host:find(".", 1, true)+1), host, true);
end
-- FIXME only load for a.b.c if b.c has dialback, and/or check in config
modulemanager.load(host, "dialback");
log("debug", "component added: "..host);
return session or hosts[host];
else
log("error", "Attempt to set component for existing host: "..host);
end
end
function deregister_component(host)
if components[host] then
modulemanager.unload(host, "dialback");
host.connected = nil;
local host_config = configmanager.getconfig()[host];
if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
-- Set default handler
components[host] = default_component_handler;
else
-- Component not in config, or disabled, remove
hosts[host] = nil;
components[host] = nil;
end
-- remove from disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:remove(host:sub(host:find(".", 1, true)+1), host);
end
log("debug", "component removed: "..host);
return true;
else
log("error", "Attempt to remove component for non-existing host: "..host);
end
end
function set_component_handler(host, handler)
components[host] = handler;
end
return _M;
|
-- Prosody IM v0.4
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local eventmanager = require "core.eventmanager";
local modulemanager = require "core.modulemanager";
local core_route_stanza = core_route_stanza;
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local hosts = hosts;
local pairs, type, tostring = pairs, type, tostring;
local components = {};
local disco_items = require "util.multitable".new();
local NULL = {};
require "core.discomanager".addDiscoItemsHandler("*host", function(reply, to, from, node)
if #node == 0 and hosts[to] then
for jid in pairs(disco_items:get(to) or NULL) do
reply:tag("item", {jid = jid}):up();
end
return true;
end
end);
require "core.eventmanager".add_event_hook("server-starting", function () core_route_stanza = _G.core_route_stanza; end);
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" then
core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
end
end
function load_enabled_components(config)
local defined_hosts = config or configmanager.getconfig();
for host, host_config in pairs(defined_hosts) do
if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
hosts[host] = { type = "component", host = host, connected = false, s2sout = {} };
components[host] = default_component_handler;
local ok, err = modulemanager.load(host, host_config.core.component_module);
if not ok then
log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err));
else
log("info", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
eventmanager.add_event_hook("server-starting", load_enabled_components);
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if not component then component = components[stanza.attr.to]; end -- hack to allow hooking node@server/resource and server/resource
if not component then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
if component then
log("debug", "%s stanza being handled by component: %s", stanza.name, host);
component(origin, stanza, hosts[host]);
else
log("error", "Component manager recieved a stanza for a non-existing component: " .. stanza.attr.to);
end
end
function create_component(host, component)
-- TODO check for host well-formedness
return { type = "component", host = host, connected = true, s2sout = {} };
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
components[host] = component;
hosts[host] = session or create_component(host, component);
-- add to disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:set(host:sub(host:find(".", 1, true)+1), host, true);
end
-- FIXME only load for a.b.c if b.c has dialback, and/or check in config
modulemanager.load(host, "dialback");
log("debug", "component added: "..host);
return session or hosts[host];
else
log("error", "Attempt to set component for existing host: "..host);
end
end
function deregister_component(host)
if components[host] then
modulemanager.unload(host, "dialback");
host.connected = nil;
local host_config = configmanager.getconfig()[host];
if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
-- Set default handler
components[host] = default_component_handler;
else
-- Component not in config, or disabled, remove
hosts[host] = nil;
components[host] = nil;
end
-- remove from disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:remove(host:sub(host:find(".", 1, true)+1), host);
end
log("debug", "component removed: "..host);
return true;
else
log("error", "Attempt to remove component for non-existing host: "..host);
end
end
function set_component_handler(host, handler)
components[host] = handler;
end
return _M;
|
core.componentmanager: Fix global access
|
core.componentmanager: Fix global access
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
592bb1c7a5315e4f2582dad415e03e42f5a43cad
|
src/lua-factory/sources/grl-euronews.lua
|
src/lua-factory/sources/grl-euronews.lua
|
--[[
* Copyright (C) 2014 Bastien Nocera
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
EURONEWS_URL = 'http://euronews.hexaglobe.com/json/'
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-euronews-lua",
name = "Euronews",
description = "A source for watching Euronews online",
supported_keys = { "id", "title", "url" },
supported_media = 'video',
icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg',
tags = { 'news', 'tv', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media_id)
if grl.get_options("skip") > 0 then
grl.callback()
else
grl.fetch(EURONEWS_URL, "euronews_fetch_cb")
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function euronews_fetch_cb(results)
local json = {}
json = grl.lua.json.string_to_table(results)
if not json or json.stat == "fail" or not json.primary then
grl.callback()
return
end
for index, item in pairs(json.primary) do
local media = create_media(index, item)
if media ~= nil then
grl.callback(media, -1)
end
end
grl.callback()
end
-------------
-- Helpers --
-------------
function get_lang(id)
local langs = {}
langs.ru = "Russian"
langs.hu = "Hungarian"
langs.de = "German"
langs.fa = "Persian"
langs.ua = "Ukrainian"
langs.ar = "Arabic"
langs.es = "Spanish; Castilian"
langs.gr = "Greek, Modern (1453-)"
langs.tr = "Turkish"
langs.pe = "Persian" -- Duplicate?
langs.en = "English"
langs.it = "Italian"
langs.fr = "French"
langs.pt = "Portuguese"
if not langs[id] then
grl.warning('Could not find language ' .. id)
return id
end
return grl.dgettext('iso_639', langs[id])
end
function create_media(lang, item)
local media = {}
if item.rtmp_flash["750"].name == 'UNAVAILABLE' then
return nil
end
media.type = "video"
media.id = lang
media.title = "Euronews " .. get_lang(lang)
media.url = item.rtmp_flash["750"].server ..
item.rtmp_flash["750"].name ..
" playpath=" .. item.rtmp_flash["750"].name ..
" swfVfy=1 " ..
"swfUrl=http://euronews.com/media/player_live_1_14.swf "..
"live=1"
return media
end
|
--[[
* Copyright (C) 2014 Bastien Nocera
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
EURONEWS_URL = 'http://euronews.hexaglobe.com/json/'
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-euronews-lua",
name = "Euronews",
description = "A source for watching Euronews online",
supported_keys = { "id", "title", "url" },
supported_media = 'video',
icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg',
tags = { 'news', 'tv', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media, options, callback)
if options.skip > 0 then
callback()
else
grl.fetch(EURONEWS_URL, euronews_fetch_cb, callback)
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function euronews_fetch_cb(results, callback)
local json = {}
json = grl.lua.json.string_to_table(results)
if not json or json.stat == "fail" or not json.primary then
callback()
return
end
for index, item in pairs(json.primary) do
local media = create_media(index, item)
if media ~= nil then
callback(media, -1)
end
end
callback()
end
-------------
-- Helpers --
-------------
function get_lang(id)
local langs = {}
langs.ru = "Russian"
langs.hu = "Hungarian"
langs.de = "German"
langs.fa = "Persian"
langs.ua = "Ukrainian"
langs.ar = "Arabic"
langs.es = "Spanish; Castilian"
langs.gr = "Greek, Modern (1453-)"
langs.tr = "Turkish"
langs.pe = "Persian" -- Duplicate?
langs.en = "English"
langs.it = "Italian"
langs.fr = "French"
langs.pt = "Portuguese"
if not langs[id] then
grl.warning('Could not find language ' .. id)
return id
end
return grl.dgettext('iso_639', langs[id])
end
function create_media(lang, item)
local media = {}
if item.rtmp_flash["750"].name == 'UNAVAILABLE' then
return nil
end
media.type = "video"
media.id = lang
media.title = "Euronews " .. get_lang(lang)
media.url = item.rtmp_flash["750"].server ..
item.rtmp_flash["750"].name ..
" playpath=" .. item.rtmp_flash["750"].name ..
" swfVfy=1 " ..
"swfUrl=http://euronews.com/media/player_live_1_14.swf "..
"live=1"
return media
end
|
lua-factory: port grl-euronews.lua to the new lua system
|
lua-factory: port grl-euronews.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <[email protected]>
|
Lua
|
lgpl-2.1
|
GNOME/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins
|
72f9c5690f0ae09b1226b588df4bfda230b1ade4
|
filechooser.lua
|
filechooser.lua
|
require "rendertext"
require "keys"
require "graphics"
FileChooser = {
-- Class vars:
-- font for displaying file/dir names
face = freetype.newBuiltinFace("sans", 25),
fhash = "s25",
-- font for paging display
sface = freetype.newBuiltinFace("sans", 16),
sfhash = "s16",
-- spacing between lines
spacing = 40,
-- state buffer
dirs = nil,
files = nil,
items = 0,
path = "",
page = 1,
current = 1,
oldcurrent = 0,
}
function FileChooser:readdir()
self.dirs = {}
self.files = {}
for f in lfs.dir(self.path) do
if lfs.attributes(self.path.."/"..f, "mode") == "directory" and f ~= "." and not string.match(f, "^%.[^.]") then
table.insert(self.dirs, f)
elseif string.match(f, ".+%.[pP][dD][fF]$") then
table.insert(self.files, f)
end
end
table.sort(self.dirs)
table.sort(self.files)
end
function FileChooser:setPath(newPath)
self.path = newPath
self:readdir()
self.items = #self.dirs + #self.files
if self.items == 0 then
return nil
end
self.page = 1
self.current = 1
return true
end
function FileChooser:rotationMode()
--[[
return code for four kinds of rotation mode:
0 for no rotation,
1 for landscape with bottom on the right side of screen, etc.
2
---------
| |
| |
| |
3 | | 1
| |
| |
| |
---------
0
--]]
orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r"))
updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r"))
mode = orie_fd:read() + (updown_fd:read() * 2)
return mode
end
function FileChooser:choose(ypos, height)
local perpage = math.floor(height / self.spacing) - 1
local pagedirty = true
local markerdirty = false
prevItem = function ()
if self.current == 1 then
if self.page > 1 then
self.current = perpage
self.page = self.page - 1
pagedirty = true
end
else
self.current = self.current - 1
markerdirty = true
end
end
nextItem = function ()
if self.current == perpage then
if self.page < (self.items / perpage) then
self.current = 1
self.page = self.page + 1
pagedirty = true
end
else
if self.page ~= math.floor(self.items / perpage) + 1
or self.current + (self.page-1)*perpage < self.items then
self.current = self.current + 1
markerdirty = true
end
end
end
while true do
if pagedirty then
fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0)
local c
for c = 1, perpage do
local i = (self.page - 1) * perpage + c
if i <= #self.dirs then
-- resembles display in midnight commander: adds "/" prefix for directories
renderUtf8Text(fb.bb, 39, ypos + self.spacing*c, self.face, self.fhash, "/", true)
renderUtf8Text(fb.bb, 50, ypos + self.spacing*c, self.face, self.fhash, self.dirs[i], true)
elseif i <= self.items then
renderUtf8Text(fb.bb, 50, ypos + self.spacing*c, self.face, self.fhash, self.files[i-#self.dirs], true)
end
end
renderUtf8Text(fb.bb, 39, ypos + self.spacing * perpage + 32, self.sface, self.sfhash,
"Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true)
markerdirty = true
end
if markerdirty then
if not pagedirty then
if self.oldcurrent > 0 then
fb.bb:paintRect(30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3, 0)
fb:refresh(1, 30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3)
end
end
fb.bb:paintRect(30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3, 15)
if not pagedirty then
fb:refresh(1, 30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3)
end
self.oldcurrent = self.current
markerdirty = false
end
if pagedirty then
fb:refresh(0, 0, ypos, fb.bb:getWidth(), height)
pagedirty = false
end
local ev = input.waitForEvent()
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
if ev.code == KEY_FW_UP then
if self:rotationMode() == 0 then
prevItem()
elseif self:rotationMode() == 2 then
nextItem()
end
elseif ev.code == KEY_FW_DOWN then
if self:rotationMode() == 0 then
nextItem()
elseif self:rotationMode() == 2 then
prevItem()
end
elseif ev.code == KEY_FW_LEFT then
if self:rotationMode() == 1 then
prevItem()
elseif self:rotationMode() == 3 then
nextItem()
end
elseif ev.code == KEY_FW_RIGHT then
if self:rotationMode() == 1 then
nextItem()
elseif self:rotationMode() == 3 then
prevItem()
end
elseif ev.code == KEY_PGFWD then
if self.page < (self.items / perpage) then
if self.current + self.page*perpage > self.items then
self.current = self.items - self.page*perpage
end
self.page = self.page + 1
pagedirty = true
else
self.current = self.items - (self.page-1)*perpage
markerdirty = true
end
elseif ev.code == KEY_PGBCK then
if self.page > 1 then
self.page = self.page - 1
pagedirty = true
else
self.current = 1
markerdirty = true
end
elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then
local newdir = self.dirs[perpage*(self.page-1)+self.current]
if newdir == ".." then
local path = string.gsub(self.path, "(.*)/[^/]+/?$", "%1")
self:setPath(path)
elseif newdir then
local path = self.path.."/"..newdir
self:setPath(path)
else
return self.path.."/"..self.files[perpage*(self.page-1)+self.current - #self.dirs]
end
pagedirty = true
elseif ev.code == KEY_BACK then
return nil
end
end
end
end
|
require "rendertext"
require "keys"
require "graphics"
FileChooser = {
-- Class vars:
-- font for displaying file/dir names
face = freetype.newBuiltinFace("sans", 25),
fhash = "s25",
-- font for paging display
sface = freetype.newBuiltinFace("sans", 16),
sfhash = "s16",
-- spacing between lines
spacing = 40,
-- state buffer
dirs = nil,
files = nil,
items = 0,
path = "",
page = 1,
current = 1,
oldcurrent = 0,
}
function FileChooser:readdir()
self.dirs = {}
self.files = {}
for f in lfs.dir(self.path) do
if lfs.attributes(self.path.."/"..f, "mode") == "directory" and f ~= "." and not string.match(f, "^%.[^.]") then
table.insert(self.dirs, f)
elseif string.match(f, ".+%.[pP][dD][fF]$") then
table.insert(self.files, f)
end
end
table.sort(self.dirs)
table.sort(self.files)
end
function FileChooser:setPath(newPath)
self.path = newPath
self:readdir()
self.items = #self.dirs + #self.files
if self.items == 0 then
return nil
end
self.page = 1
self.current = 1
return true
end
function FileChooser:rotationMode()
--[[
return code for four kinds of rotation mode:
0 for no rotation,
1 for landscape with bottom on the right side of screen, etc.
2
---------
| |
| |
| |
3 | | 1
| |
| |
| |
---------
0
--]]
if KEY_FW_DOWN == 116 then
return 0
end
orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r"))
updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r"))
mode = orie_fd:read() + (updown_fd:read() * 2)
return mode
end
function FileChooser:choose(ypos, height)
local perpage = math.floor(height / self.spacing) - 1
local pagedirty = true
local markerdirty = false
prevItem = function ()
if self.current == 1 then
if self.page > 1 then
self.current = perpage
self.page = self.page - 1
pagedirty = true
end
else
self.current = self.current - 1
markerdirty = true
end
end
nextItem = function ()
if self.current == perpage then
if self.page < (self.items / perpage) then
self.current = 1
self.page = self.page + 1
pagedirty = true
end
else
if self.page ~= math.floor(self.items / perpage) + 1
or self.current + (self.page-1)*perpage < self.items then
self.current = self.current + 1
markerdirty = true
end
end
end
while true do
if pagedirty then
fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0)
local c
for c = 1, perpage do
local i = (self.page - 1) * perpage + c
if i <= #self.dirs then
-- resembles display in midnight commander: adds "/" prefix for directories
renderUtf8Text(fb.bb, 39, ypos + self.spacing*c, self.face, self.fhash, "/", true)
renderUtf8Text(fb.bb, 50, ypos + self.spacing*c, self.face, self.fhash, self.dirs[i], true)
elseif i <= self.items then
renderUtf8Text(fb.bb, 50, ypos + self.spacing*c, self.face, self.fhash, self.files[i-#self.dirs], true)
end
end
renderUtf8Text(fb.bb, 39, ypos + self.spacing * perpage + 32, self.sface, self.sfhash,
"Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true)
markerdirty = true
end
if markerdirty then
if not pagedirty then
if self.oldcurrent > 0 then
fb.bb:paintRect(30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3, 0)
fb:refresh(1, 30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3)
end
end
fb.bb:paintRect(30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3, 15)
if not pagedirty then
fb:refresh(1, 30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3)
end
self.oldcurrent = self.current
markerdirty = false
end
if pagedirty then
fb:refresh(0, 0, ypos, fb.bb:getWidth(), height)
pagedirty = false
end
local ev = input.waitForEvent()
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
if ev.code == KEY_FW_UP then
if self:rotationMode() == 0 then
prevItem()
elseif self:rotationMode() == 2 then
nextItem()
end
elseif ev.code == KEY_FW_DOWN then
if self:rotationMode() == 0 then
nextItem()
elseif self:rotationMode() == 2 then
prevItem()
end
elseif ev.code == KEY_FW_LEFT then
if self:rotationMode() == 1 then
prevItem()
elseif self:rotationMode() == 3 then
nextItem()
end
elseif ev.code == KEY_FW_RIGHT then
if self:rotationMode() == 1 then
nextItem()
elseif self:rotationMode() == 3 then
prevItem()
end
elseif ev.code == KEY_PGFWD then
if self.page < (self.items / perpage) then
if self.current + self.page*perpage > self.items then
self.current = self.items - self.page*perpage
end
self.page = self.page + 1
pagedirty = true
else
self.current = self.items - (self.page-1)*perpage
markerdirty = true
end
elseif ev.code == KEY_PGBCK then
if self.page > 1 then
self.page = self.page - 1
pagedirty = true
else
self.current = 1
markerdirty = true
end
elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then
local newdir = self.dirs[perpage*(self.page-1)+self.current]
if newdir == ".." then
local path = string.gsub(self.path, "(.*)/[^/]+/?$", "%1")
self:setPath(path)
elseif newdir then
local path = self.path.."/"..newdir
self:setPath(path)
else
return self.path.."/"..self.files[perpage*(self.page-1)+self.current - #self.dirs]
end
pagedirty = true
elseif ev.code == KEY_BACK then
return nil
end
end
end
end
|
fix: detect emu mode in rotationMode
|
fix: detect emu mode in rotationMode
if in emu mode, simply return 0
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,ashang/koreader,koreader/koreader-base,apletnev/koreader-base,chrox/koreader,poire-z/koreader,NiLuJe/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader,NickSavage/koreader,pazos/koreader,houqp/koreader,poire-z/koreader,Frenzie/koreader,apletnev/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,houqp/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader,apletnev/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,koreader/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,lgeek/koreader,chihyang/koreader,Frenzie/koreader,Frenzie/koreader-base,mwoz123/koreader,mihailim/koreader,Markismus/koreader,robert00s/koreader,Frenzie/koreader-base,koreader/koreader,houqp/koreader-base,frankyifei/koreader-base,koreader/koreader-base,noname007/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,ashhher3/koreader,koreader/koreader-base,houqp/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader,frankyifei/koreader
|
39afac1826ecbea9a6cad46eb1bc3c7bc8868884
|
src/application.lua
|
src/application.lua
|
if not cfg.data.sta_ssid then
print('Wifi: No config')
return
end
if not (cfg.data.mqtt_user and cfg.data.mqtt_password) then
print('MQTT: No config')
return
end
local queue_report = nil
local send_report = nil
local flush_data = nil
local mq_prefix = "/nodes/" .. node_id
local mq = mqtt.Client(node_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password)
local mq_connected = false
mq_data = {}
mq_data_ptr = 0
-- Register MQTT event handlers
mq:lwt("/lwt", "offline", 0, 0)
mq:on("connect", function(conn)
print("MQTT: Connected")
mq_connected = true
-- Subscribe to all command topics
for topic, handler in pairs(cmds) do
if topic:sub(1, 1) ~= '/' then
topic = mq_prefix .. '/commands/' .. topic
end
print('MQTT: Subscribing, topic:', topic)
mq:subscribe(topic, 0, function(conn) end)
end
send_report()
collectgarbage()
end)
mq:on("offline", function(conn)
print("MQTT: Disconnected")
mq_connected = false
end)
mq:on("message", function(conn, topic, data)
print("MQTT: Received, topic:", topic)
local part = topic:sub(1, #mq_prefix + 1) == mq_prefix .. '/' and topic:sub(#mq_prefix + 1) or topic
local cmd = part:match('/commands/(.+)') or part
local res = handleCmd(cmd, data)
if res ~= nil then
mq_data[#mq_data + 1] = { mq_prefix .. '/responses' .. part, res }
flush_data()
end
cmd = nil
part = nil
res = nil
collectgarbage()
if data ~= nil then
print("MQTT: Data:", data)
end
end)
flush_data = function(callback)
mq_data_ptr = mq_data_ptr + 1
if mq_data_ptr > #mq_data then
mq_data = {}
mq_data_ptr = 0
if callback ~= nil then
callback()
end
else
local d = mq_data[mq_data_ptr]
mq:publish(d[1], d[2], 0, 0, function(conn)
flush_data(callback)
end)
d = nil
end
collectgarbage()
end
queue_report = function()
if cfg.data.sleep then
if mq_connected then
mq:close()
end
node.dsleep(cfg.data.report_interval * 1000 * 1000, 4)
else
tmr.stop(0)
tmr.alarm(0, cfg.data.report_interval * 1000, 0, function()
send_report()
collectgarbage()
end)
end
end
send_report = function()
if not cfg.data.sleep then
queue_report()
end
if not wifi.sta.getip() then
print('Report: No Wifi')
wifi.sta.connect()
elseif not mq_connected then
print('Report: No MQTT')
mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure)
else
print('Report: Sending..')
local data = triggerModules('_report_data')
data = tablesMerge(data)
mq_data = {}
for i, v in pairs(data) do
mq_data[mq_prefix .. i] = v
end
data = nil
collectgarbage()
flush_data(function()
print('Report: Finished')
if cfg.data.sleep then
queue_report()
end
end)
end
end
wifi.setphymode(wifi.PHYMODE_N)
wifi.setmode(wifi.STATION)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
-- wifi.sta.eventMonStop(1)
print("WIFI: Connected")
send_report()
end)
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function()
print("WIFI: Connecting..")
end)
if cfg.data.sta_ip and cfg.data.sta_gateway and cfg.data.sta_netmask then
wifi.sta.setip({
ip = cfg.data.sta_ip,
netmask = cfg.data.sta_netmask,
gateway = cfg.data.sta_gateway
})
end
wifi.sta.eventMonStart(100)
wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk)
send_report()
|
if not cfg.data.sta_ssid then
print('Wifi: No config')
return
end
if not (cfg.data.mqtt_user and cfg.data.mqtt_password) then
print('MQTT: No config')
return
end
local queue_report = nil
local send_report = nil
local flush_data = nil
local mq_prefix = "/nodes/" .. node_id
local mq = mqtt.Client(node_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password)
local mq_connected = false
mq_data = {}
mq_data_ptr = 0
-- Register MQTT event handlers
mq:lwt("/lwt", "offline", 0, 0)
mq:on("connect", function(conn)
print("MQTT: Connected")
mq_connected = true
-- Subscribe to all command topics
for topic, handler in pairs(cmds) do
if topic:sub(1, 1) ~= '/' then
topic = mq_prefix .. '/commands/' .. topic
end
print('MQTT: Subscribing, topic:', topic)
mq:subscribe(topic, 0, function(conn) end)
end
send_report()
collectgarbage()
end)
mq:on("offline", function(conn)
print("MQTT: Disconnected")
mq_connected = false
end)
mq:on("message", function(conn, topic, data)
print("MQTT: Received, topic:", topic)
local part = topic:sub(1, #mq_prefix + 1) == mq_prefix .. '/' and topic:sub(#mq_prefix + 1) or topic
local cmd = part:match('/commands/(.+)') or part
local res = handleCmd(cmd, data)
if res ~= nil then
mq_data[#mq_data + 1] = { mq_prefix .. '/responses' .. part, res }
flush_data()
end
cmd = nil
part = nil
res = nil
collectgarbage()
if data ~= nil then
print("MQTT: Data:", data)
end
end)
flush_data = function(callback)
mq_data_ptr = mq_data_ptr + 1
if mq_data_ptr > #mq_data then
mq_data = {}
mq_data_ptr = 0
if callback ~= nil then
callback()
end
else
local d = mq_data[mq_data_ptr]
mq:publish(d[1], d[2], 0, 0, function(conn)
flush_data(callback)
end)
d = nil
end
collectgarbage()
end
queue_report = function()
if cfg.data.sleep then
if mq_connected then
mq:close()
end
node.dsleep(cfg.data.report_interval * 1000 * 1000, 4)
else
tmr.stop(0)
tmr.alarm(0, cfg.data.report_interval * 1000, 0, function()
send_report()
collectgarbage()
end)
end
end
send_report = function()
if not cfg.data.sleep then
queue_report()
end
if not wifi.sta.getip() then
print('Report: No Wifi')
wifi.sta.connect()
elseif not mq_connected then
print('Report: No MQTT')
mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure)
else
print('Report: Sending..')
mq_data = triggerModules('_report_data')
mq_data = tablesMerge(mq_data)
for _, v in pairs(mq_data) do
v[1] = mq_prefix .. v[1]
end
collectgarbage()
flush_data(function()
print('Report: Finished')
if cfg.data.sleep then
queue_report()
end
end)
end
end
wifi.setphymode(wifi.PHYMODE_N)
wifi.setmode(wifi.STATION)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
-- wifi.sta.eventMonStop(1)
print("WIFI: Connected")
send_report()
end)
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function()
print("WIFI: Connecting..")
end)
if cfg.data.sta_ip and cfg.data.sta_gateway and cfg.data.sta_netmask then
wifi.sta.setip({
ip = cfg.data.sta_ip,
netmask = cfg.data.sta_netmask,
gateway = cfg.data.sta_gateway
})
end
wifi.sta.eventMonStart(100)
wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk)
send_report()
|
bugfix to the bugfix for prefixing report data with mq_prefix
|
bugfix to the bugfix for prefixing report data with mq_prefix
Signed-off-by: Kalman Olah <[email protected]>
|
Lua
|
mit
|
kalmanolah/kalmon-ESP8266
|
7dd1921b0aac56fc517072a4f6b4b6bdb8d575e8
|
src/core/packet.lua
|
src/core/packet.lua
|
module(...,package.seeall)
local debug = false
local ffi = require("ffi")
local C = ffi.C
local buffer = require("core.buffer")
local freelist = require("core.freelist")
local lib = require("core.lib")
local memory = require("core.memory")
require("core.packet_h")
initial_fuel = 1000
max_packets = 1e6
packets_fl = freelist.new("struct packet *", max_packets)
packets = ffi.new("struct packet[?]", max_packets)
local packet_size = ffi.sizeof("struct packet")
function module_init ()
for i = 0, max_packets-1 do
free(packets[i])
end
end
-- Return a packet, or nil if none is available.
function allocate ()
return freelist.remove(packets_fl) or error("out of packets")
end
-- Append data to a packet.
function add_iovec (p, b, length, offset)
if debug then assert(p.niovecs < C.PACKET_IOVEC_MAX, "packet iovec overflow") end
offset = offset or 0
if debug then assert(length + offset <= b.size) end
local iovec = p.iovecs[p.niovecs]
iovec.buffer = b
iovec.length = length
iovec.offset = offset
p.niovecs = p.niovecs + 1
p.length = p.length + length
end
-- Prepend data to a packet.
function prepend_iovec (p, b, length, offset)
if debug then assert(p.niovecs < C.PACKET_IOVEC_MAX, "packet iovec overflow") end
offset = offset or 0
if debug then assert(length + offset <= b.size) end
for i = p.niovecs, 1, -1 do
ffi.copy(p.iovecs[i], p.iovecs[i-1], ffi.sizeof("struct packet_iovec"))
end
local iovec = p.iovecs[0]
iovec.buffer = b
iovec.length = length
iovec.offset = offset
p.niovecs = p.niovecs + 1
p.length = p.length + length
end
function niovecs (p)
return p.niovecs
end
function iovec (p, n)
return p.iovecs[n]
end
-- Merge all buffers into one. Throws an exception if a single buffer
-- cannot hold the entire packet.
--
-- XXX Should work also with packets that are bigger than a single
-- buffer, i.e. reduce the number of buffers to the minimal set
-- required to hold the entire packet.
function coalesce (p)
if p.niovecs == 1 then return end
local b = buffer.allocate()
assert(p.length <= b.size, "packet too big to coalesce")
local length = 0
for i = 0, p.niovecs-1, 1 do
local iovec = p.iovecs[i]
ffi.copy(b.pointer + length, iovec.buffer.pointer + iovec.offset, iovec.length)
buffer.free(iovec.buffer)
length = length + iovec.length
end
p.niovecs, p.length = 0, 0
add_iovec(p, b, length)
end
-- The same as coalesce(), but allocate new packet
-- while leaving original packet unchanged
function clone (p)
local new_p = allocate()
local b = buffer.allocate()
assert(p.length <= b.size, "packet too big to coalesce")
local length = 0
for i = 0, p.niovecs - 1 do
local iovec = p.iovecs[i]
ffi.copy(b.pointer + length, iovec.buffer.pointer + iovec.offset, iovec.length)
length = length + iovec.length
end
add_iovec(new_p, b, length)
return new_p
end
-- The opposite of coalesce
-- Scatters the data through chunks
function scatter (p, sg_list)
assert(#sg_list + 1 <= C.PACKET_IOVEC_MAX)
local cloned = clone(p) -- provide coalesced copy
local result = allocate()
local iovec = cloned.iovecs[0]
local offset = 0 -- the offset in the cloned buffer
-- always append one big chunk in the end, to cover the case
-- where the supplied sgs are not sufficient to hold all the data
-- also if we get an empty sg_list this will make a single iovec packet
local pattern_list = lib.deepcopy(sg_list)
pattern_list[#pattern_list + 1] = {4096}
for _,sg in ipairs(pattern_list) do
local sg_len = sg[1]
local sg_offset = sg[2] or 0
local b = buffer.allocate()
assert(sg_len + sg_offset <= b.size)
local to_copy = math.min(sg_len, iovec.length - offset)
ffi.copy(b.pointer + sg_offset, iovec.buffer.pointer + iovec.offset + offset, to_copy)
add_iovec(result, b, to_copy, sg_offset)
-- advance the offset in the source buffer
offset = offset + to_copy
assert(offset <= iovec.length)
if offset == iovec.length then
-- we don't have more data to copy
break
end
end
packet.deref(cloned)
return result
end
-- use this function if you want to modify a packet received by an app
-- you cannot modify a packet if it is owned more then one app
-- it will create a copy for you as needed
function want_modify (p)
if p.refcount == 1 then
return p
end
packet.deref(p)
return clone(p)
end
-- fill's an allocated packet with data from a string
function fill_data (p, d, offset)
offset = offset or 0
local iovec = p.iovecs[0]
assert (offset+#d <= iovec.length, "can't fit on first iovec") -- TODO: handle more iovecs
ffi.copy (iovec.buffer.pointer + iovec.offset + offset, d, #d)
end
-- creates a packet from a given binary string
function from_data (d)
local p = allocate()
local b = buffer.allocate()
local size = math.min(#d, b.size)
add_iovec(p, b, size)
fill_data(p, d)
return p
end
-- Increase the reference count for packet p by n (default n=1).
function ref (p, n)
if p.refcount > 0 then
p.refcount = p.refcount + (n or 1)
end
return p
end
-- Decrease the reference count for packet p.
-- The packet will be recycled if the reference count reaches 0.
function deref (p, n)
n = n or 1
if p.refcount > 0 then
assert(p.refcount >= n)
if n == p.refcount then
free(p)
else
p.refcount = p.refcount - n
end
end
end
-- Tenured packets are not reused by defref().
function tenure (p)
p.refcount = 0
end
-- Free a packet and all of its buffers.
function free (p)
for i = 0, p.niovecs-1 do
buffer.free(p.iovecs[i].buffer)
end
ffi.fill(p, packet_size, 0)
p.refcount = 1
p.fuel = initial_fuel
freelist.add(packets_fl, p)
end
function iovec_dump (iovec)
local b = iovec.buffer
local l = math.min(iovec.length, b.size-iovec.offset)
if l < 1 then return '' end
o={[-1]=string.format([[
offset: %d
length: %d
buffer.pointer: %s
buffer.physical: %X
buffer.size: %d
]], iovec.offset, iovec.length, b.pointer, tonumber(b.physical), b.size)}
for i = 0, l-1 do
o[i] = bit.tohex(b.pointer[i+iovec.offset], -2)
end
return table.concat(o, ' ', -1, l-1)
end
function report (p)
local result = string.format([[
refcount: %d
fuel: %d
info.flags: %X
info.gso_flags: %X
info.hdr_len: %d
info.gso_size: %d
info.csum_start: %d
info.csum_offset: %d
niovecs: %d
length: %d
]],
p.refcount, p.fuel, p.info.flags, p.info.gso_flags,
p.info.hdr_len, p.info.gso_size, p.info.csum_start,
p.info.csum_offset, p.niovecs, p.length
)
for i = 0, p.niovecs-1 do
result = result .. string.format([[
iovec #%d: %s
]], i, iovec_dump(p.iovecs[i]))
end
return result
end
module_init()
|
module(...,package.seeall)
local debug = false
local ffi = require("ffi")
local C = ffi.C
local buffer = require("core.buffer")
local freelist = require("core.freelist")
local lib = require("core.lib")
local memory = require("core.memory")
require("core.packet_h")
initial_fuel = 1000
max_packets = 1e6
packets_fl = freelist.new("struct packet *", max_packets)
packets = ffi.new("struct packet[?]", max_packets)
local packet_size = ffi.sizeof("struct packet")
function module_init ()
for i = 0, max_packets-1 do
free(packets[i])
end
end
-- Return a packet, or nil if none is available.
function allocate ()
return freelist.remove(packets_fl) or error("out of packets")
end
-- Append data to a packet.
function add_iovec (p, b, length, offset)
if debug then assert(p.niovecs < C.PACKET_IOVEC_MAX, "packet iovec overflow") end
offset = offset or 0
if debug then assert(length + offset <= b.size) end
local iovec = p.iovecs[p.niovecs]
iovec.buffer = b
iovec.length = length
iovec.offset = offset
p.niovecs = p.niovecs + 1
p.length = p.length + length
end
-- Prepend data to a packet.
function prepend_iovec (p, b, length, offset)
if debug then assert(p.niovecs < C.PACKET_IOVEC_MAX, "packet iovec overflow") end
offset = offset or 0
if debug then assert(length + offset <= b.size) end
for i = p.niovecs, 1, -1 do
ffi.copy(p.iovecs[i], p.iovecs[i-1], ffi.sizeof("struct packet_iovec"))
end
local iovec = p.iovecs[0]
iovec.buffer = b
iovec.length = length
iovec.offset = offset
p.niovecs = p.niovecs + 1
p.length = p.length + length
end
function niovecs (p)
return p.niovecs
end
function iovec (p, n)
return p.iovecs[n]
end
-- Merge all buffers into one. Throws an exception if a single buffer
-- cannot hold the entire packet.
--
-- XXX Should work also with packets that are bigger than a single
-- buffer, i.e. reduce the number of buffers to the minimal set
-- required to hold the entire packet.
function coalesce (p)
if p.niovecs == 1 then return end
local b = buffer.allocate()
assert(p.length <= b.size, "packet too big to coalesce")
local length = 0
for i = 0, p.niovecs-1, 1 do
local iovec = p.iovecs[i]
ffi.copy(b.pointer + length, iovec.buffer.pointer + iovec.offset, iovec.length)
buffer.free(iovec.buffer)
length = length + iovec.length
end
p.niovecs, p.length = 0, 0
add_iovec(p, b, length)
end
-- The same as coalesce(), but allocate new packet
-- while leaving original packet unchanged
function clone (p)
local new_p = allocate()
local b = buffer.allocate()
assert(p.length <= b.size, "packet too big to coalesce")
local length = 0
for i = 0, p.niovecs - 1 do
local iovec = p.iovecs[i]
ffi.copy(b.pointer + length, iovec.buffer.pointer + iovec.offset, iovec.length)
length = length + iovec.length
end
add_iovec(new_p, b, length)
return new_p
end
-- The opposite of coalesce
-- Scatters the data through chunks
function scatter (p, sg_list)
assert(#sg_list + 1 <= C.PACKET_IOVEC_MAX)
local cloned = clone(p) -- provide coalesced copy
local result = allocate()
local iovec = cloned.iovecs[0]
local offset = 0 -- the offset in the cloned buffer
-- always append one big chunk in the end, to cover the case
-- where the supplied sgs are not sufficient to hold all the data
-- also if we get an empty sg_list this will make a single iovec packet
local pattern_list = lib.deepcopy(sg_list)
pattern_list[#pattern_list + 1] = {4096}
for _,sg in ipairs(pattern_list) do
local sg_len = sg[1]
local sg_offset = sg[2] or 0
local b = buffer.allocate()
assert(sg_len + sg_offset <= b.size)
local to_copy = math.min(sg_len, iovec.length - offset)
ffi.copy(b.pointer + sg_offset, iovec.buffer.pointer + iovec.offset + offset, to_copy)
add_iovec(result, b, to_copy, sg_offset)
-- advance the offset in the source buffer
offset = offset + to_copy
assert(offset <= iovec.length)
if offset == iovec.length then
-- we don't have more data to copy
break
end
end
packet.deref(cloned)
return result
end
-- use this function if you want to modify a packet received by an app
-- you cannot modify a packet if it is owned more then one app
-- it will create a copy for you as needed
function want_modify (p)
if p.refcount == 1 then
return p
end
local new_p = clone(p)
packet.deref(p)
return new_p
end
-- fill's an allocated packet with data from a string
function fill_data (p, d, offset)
offset = offset or 0
local iovec = p.iovecs[0]
assert (offset+#d <= iovec.length, "can't fit on first iovec") -- TODO: handle more iovecs
ffi.copy (iovec.buffer.pointer + iovec.offset + offset, d, #d)
end
-- creates a packet from a given binary string
function from_data (d)
local p = allocate()
local b = buffer.allocate()
local size = math.min(#d, b.size)
add_iovec(p, b, size)
fill_data(p, d)
return p
end
-- Increase the reference count for packet p by n (default n=1).
function ref (p, n)
if p.refcount > 0 then
p.refcount = p.refcount + (n or 1)
end
return p
end
-- Decrease the reference count for packet p.
-- The packet will be recycled if the reference count reaches 0.
function deref (p, n)
n = n or 1
if p.refcount > 0 then
assert(p.refcount >= n)
if n == p.refcount then
free(p)
else
p.refcount = p.refcount - n
end
end
end
-- Tenured packets are not reused by defref().
function tenure (p)
p.refcount = 0
end
-- Free a packet and all of its buffers.
function free (p)
for i = 0, p.niovecs-1 do
buffer.free(p.iovecs[i].buffer)
end
ffi.fill(p, packet_size, 0)
p.refcount = 1
p.fuel = initial_fuel
freelist.add(packets_fl, p)
end
function iovec_dump (iovec)
local b = iovec.buffer
local l = math.min(iovec.length, b.size-iovec.offset)
if l < 1 then return '' end
o={[-1]=string.format([[
offset: %d
length: %d
buffer.pointer: %s
buffer.physical: %X
buffer.size: %d
]], iovec.offset, iovec.length, b.pointer, tonumber(b.physical), b.size)}
for i = 0, l-1 do
o[i] = bit.tohex(b.pointer[i+iovec.offset], -2)
end
return table.concat(o, ' ', -1, l-1)
end
function report (p)
local result = string.format([[
refcount: %d
fuel: %d
info.flags: %X
info.gso_flags: %X
info.hdr_len: %d
info.gso_size: %d
info.csum_start: %d
info.csum_offset: %d
niovecs: %d
length: %d
]],
p.refcount, p.fuel, p.info.flags, p.info.gso_flags,
p.info.hdr_len, p.info.gso_size, p.info.csum_start,
p.info.csum_offset, p.niovecs, p.length
)
for i = 0, p.niovecs-1 do
result = result .. string.format([[
iovec #%d: %s
]], i, iovec_dump(p.iovecs[i]))
end
return result
end
module_init()
|
packet.lua: Fix broken clone().
|
packet.lua: Fix broken clone().
|
Lua
|
apache-2.0
|
dpino/snabb,eugeneia/snabb,kbara/snabb,wingo/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,lukego/snabb,virtualopensystems/snabbswitch,eugeneia/snabb,andywingo/snabbswitch,Igalia/snabb,Igalia/snabbswitch,wingo/snabbswitch,pavel-odintsov/snabbswitch,pirate/snabbswitch,justincormack/snabbswitch,virtualopensystems/snabbswitch,kbara/snabb,snabbco/snabb,kbara/snabb,snabbco/snabb,kbara/snabb,fhanik/snabbswitch,dpino/snabbswitch,eugeneia/snabb,eugeneia/snabb,plajjan/snabbswitch,andywingo/snabbswitch,wingo/snabb,mixflowtech/logsensor,aperezdc/snabbswitch,alexandergall/snabbswitch,dwdm/snabbswitch,hb9cwp/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,virtualopensystems/snabbswitch,heryii/snabb,wingo/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,dpino/snabb,plajjan/snabbswitch,fhanik/snabbswitch,dpino/snabb,kellabyte/snabbswitch,plajjan/snabbswitch,Igalia/snabb,mixflowtech/logsensor,heryii/snabb,javierguerragiraldez/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,dpino/snabb,justincormack/snabbswitch,pirate/snabbswitch,lukego/snabb,lukego/snabbswitch,alexandergall/snabbswitch,andywingo/snabbswitch,alexandergall/snabbswitch,lukego/snabb,xdel/snabbswitch,aperezdc/snabbswitch,lukego/snabbswitch,snabbco/snabb,heryii/snabb,javierguerragiraldez/snabbswitch,justincormack/snabbswitch,wingo/snabb,andywingo/snabbswitch,lukego/snabbswitch,dpino/snabb,pavel-odintsov/snabbswitch,plajjan/snabbswitch,wingo/snabb,wingo/snabb,lukego/snabbswitch,snabbnfv-goodies/snabbswitch,Igalia/snabb,aperezdc/snabbswitch,SnabbCo/snabbswitch,kellabyte/snabbswitch,mixflowtech/logsensor,dwdm/snabbswitch,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,snabbco/snabb,eugeneia/snabb,kbara/snabb,Igalia/snabbswitch,snabbco/snabb,dpino/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,dpino/snabbswitch,xdel/snabbswitch,aperezdc/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,snabbco/snabb,heryii/snabb,wingo/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,justincormack/snabbswitch,wingo/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,hb9cwp/snabbswitch,kellabyte/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,fhanik/snabbswitch,Igalia/snabbswitch,snabbco/snabb,hb9cwp/snabbswitch,lukego/snabb,eugeneia/snabbswitch,xdel/snabbswitch,Igalia/snabb,dpino/snabb,wingo/snabb,eugeneia/snabbswitch,javierguerragiraldez/snabbswitch,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,kbara/snabb,pirate/snabbswitch,eugeneia/snabb
|
1f13986318d04343f9cd10d85208c25c13612ea2
|
lua/drivers.lua
|
lua/drivers.lua
|
local mod = {}
local dpdkc = require "dpdkc"
local ffi = require "ffi"
mod.net_i40e = require "driver.i40e"
mod.net_ixgbe = require "driver.ixgbe"
mod.net_ixgbevf = require "driver.ixgbevf"
mod.net_igb = require "driver.igb"
mod.net_virtio = require "driver.virtio"
mod.net_vmxnet3 = require "driver.vmxnet3"
mod.net_mlx5 = require "driver.mlx5"
function mod.initDriver(dev)
local device = require "device"
local driver = mod[dev:getDriverName()]
if driver then
if not getmetatable(driver) then
driver.__index = driver
driver.__eq = device.__devicePrototype.__eq
driver.__tostring = device.__devicePrototype.__tostring
setmetatable(driver, device.__devicePrototype)
end
setmetatable(dev, driver)
end
dev.driverInfo = dev.driverInfo or {}
end
-- retrieve driver-specific information
-- required for driver-specific configuration variables
function mod.getDriverInfo(driverName)
return (mod[driverName] or {}).driverInfo or {}
end
return mod
|
local mod = {}
local dpdkc = require "dpdkc"
local ffi = require "ffi"
mod.net_i40e = require "driver.i40e"
mod.net_ixgbe = require "driver.ixgbe"
mod.net_ixgbevf = require "driver.ixgbevf"
mod.net_e1000_igb = require "driver.igb"
mod.net_e1000_em = require "driver.igb"
mod.net_virtio = require "driver.virtio"
mod.net_vmxnet3 = require "driver.vmxnet3"
mod.net_mlx5 = require "driver.mlx5"
function mod.initDriver(dev)
local device = require "device"
local driver = mod[dev:getDriverName()]
if driver then
if not getmetatable(driver) then
driver.__index = driver
driver.__eq = device.__devicePrototype.__eq
driver.__tostring = device.__devicePrototype.__tostring
setmetatable(driver, device.__devicePrototype)
end
setmetatable(dev, driver)
end
dev.driverInfo = dev.driverInfo or {}
end
-- retrieve driver-specific information
-- required for driver-specific configuration variables
function mod.getDriverInfo(driverName)
return (mod[driverName] or {}).driverInfo or {}
end
return mod
|
fix driver patching for gigabit nics
|
fix driver patching for gigabit nics
|
Lua
|
mit
|
emmericp/libmoon,emmericp/libmoon,scholzd/libmoon,libmoon/libmoon,emmericp/libmoon,libmoon/libmoon,libmoon/libmoon,scholzd/libmoon,scholzd/libmoon
|
a824fd6a69ffb2e84068860a7b7e1ca485655743
|
lexers/perl.lua
|
lexers/perl.lua
|
-- Copyright 2006-2012 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Perl LPeg lexer.
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local M = { _NAME = 'perl' }
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '#' * l.nonnewline_esc^0
local block_comment = #P('=') * l.starts_line('=' * l.alpha *
(l.any - l.newline * '=cut')^0 * (l.newline * '=cut')^-1)
local comment = token(l.COMMENT, block_comment + line_comment)
local delimiter_matches = { ['('] = ')', ['['] = ']', ['{'] = '}', ['<'] = '>' }
local literal_delimitted = P(function(input, index) -- for single delimiter sets
local delimiter = input:sub(index, index)
if not delimiter:find('%w') then -- only non alpha-numerics
local match_pos, patt
if delimiter_matches[delimiter] then
-- Handle nested delimiter/matches in strings.
local s, e = delimiter, delimiter_matches[delimiter]
patt = l.delimited_range(s..e, '\\', true, true)
else
patt = l.delimited_range(delimiter, '\\', true)
end
match_pos = lpeg.match(patt, input, index)
return match_pos or #input + 1
end
end)
local literal_delimitted2 = P(function(input, index) -- for 2 delimiter sets
local delimiter = input:sub(index, index)
if not delimiter:find('%w') then -- only non alpha-numerics
local match_pos, patt
if delimiter_matches[delimiter] then
-- Handle nested delimiter/matches in strings.
local s, e = delimiter, delimiter_matches[delimiter]
patt = l.delimited_range(s..e, '\\', true, true)
else
patt = l.delimited_range(delimiter, '\\', true)
end
first_match_pos = lpeg.match(patt, input, index)
final_match_pos = lpeg.match(patt, input, first_match_pos - 1)
if not final_match_pos then -- using (), [], {}, or <> notation
final_match_pos = lpeg.match(l.space^0 * patt, input, first_match_pos)
end
return final_match_pos or #input + 1
end
end)
-- Strings.
local sq_str = l.delimited_range("'", '\\', true)
local dq_str = l.delimited_range('"', '\\', true)
local cmd_str = l.delimited_range('`', '\\', true)
local heredoc = '<<' * P(function(input, index)
local s, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f;]+', index)
if s == index and delimiter then
local end_heredoc = '[\n\r\f]+'
local _, e = input:find(end_heredoc..delimiter, e)
return e and e + 1 or #input + 1
end
end)
local lit_str = 'q' * P('q')^-1 * literal_delimitted
local lit_array = 'qw' * literal_delimitted
local lit_cmd = 'qx' * literal_delimitted
local lit_match = 'm' * literal_delimitted * S('cgimosx')^0
local lit_sub = 's' * literal_delimitted2 * S('ecgimosx')^0
local lit_tr = (P('tr') + 'y') * literal_delimitted2 * S('cds')^0
local regex_str = l.delimited_range('/', '\\', false, true, '\n') * S('imosx')^0
local lit_regex = 'qr' * literal_delimitted * S('imosx')^0
local string = token(l.STRING, sq_str + dq_str + cmd_str + heredoc + lit_str +
lit_array + lit_cmd + lit_match + lit_sub +
lit_tr) +
token(l.REGEX, regex_str + lit_regex)
-- Numbers.
local number = token(l.NUMBER, l.float + l.integer)
-- Keywords.
local keyword = token(l.KEYWORD, word_match {
'STDIN', 'STDOUT', 'STDERR', 'BEGIN', 'END', 'CHECK', 'INIT',
'require', 'use',
'break', 'continue', 'do', 'each', 'else', 'elsif', 'foreach', 'for', 'if',
'last', 'local', 'my', 'next', 'our', 'package', 'return', 'sub', 'unless',
'until', 'while', '__FILE__', '__LINE__', '__PACKAGE__',
'and', 'or', 'not', 'eq', 'ne', 'lt', 'gt', 'le', 'ge'
})
-- Functions.
local func = token(l.FUNCTION, word_match({
'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller',
'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'closedir',
'close', 'connect', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined',
'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent',
'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists',
'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline',
'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname',
'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent',
'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname',
'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid',
'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt',
'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl',
'join', 'keys', 'kill', 'lcfirst', 'lc', 'length', 'link', 'listen',
'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv',
'msgsnd', 'new', 'oct', 'opendir', 'open', 'ord', 'pack', 'pipe', 'pop',
'pos', 'printf', 'print', 'prototype', 'push', 'quotemeta', 'rand', 'readdir',
'read', 'readlink', 'recv', 'redo', 'ref', 'rename', 'reset', 'reverse',
'rewinddir', 'rindex', 'rmdir', 'scalar', 'seekdir', 'seek', 'select',
'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent',
'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent',
'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown',
'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf',
'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysread',
'sysseek', 'system', 'syswrite', 'telldir', 'tell', 'tied', 'tie', 'time',
'times', 'truncate', 'ucfirst', 'uc', 'umask', 'undef', 'unlink', 'unpack',
'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray',
'warn', 'write'
}, '2'))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Variables.
local special_var = '$' * ('^' * S('ADEFHILMOPSTWX')^-1 +
S('\\"[]\'&`+*.,;=%~?@$<>(|/!-') + ':' * (l.any - ':') +
l.digit^1)
local plain_var = ('$#' + S('$@%')) * P('$')^0 * l.word
local variable = token(l.VARIABLE, special_var + plain_var)
-- Operators.
local operator = token(l.OPERATOR, S('-<>+*!~\\=/%&|^&.?:;()[]{}'))
M._rules = {
{ 'whitespace', ws },
{ 'keyword', keyword },
{ 'function', func },
{ 'string', string },
{ 'identifier', identifier },
{ 'comment', comment },
{ 'number', number },
{ 'variable', variable },
{ 'operator', operator },
{ 'any_char', l.any_char },
}
M._foldsymbols = {
_patterns = { '[%[%]{}]', '#' },
[l.OPERATOR] = { ['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1 },
[l.COMMENT] = { ['#'] = l.fold_line_comments('#') }
}
return M
|
-- Copyright 2006-2012 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Perl LPeg lexer.
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local M = { _NAME = 'perl' }
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '#' * l.nonnewline_esc^0
local block_comment = #P('=') * l.starts_line('=' * l.alpha *
(l.any - l.newline * '=cut')^0 * (l.newline * '=cut')^-1)
local comment = token(l.COMMENT, block_comment + line_comment)
local delimiter_matches = { ['('] = ')', ['['] = ']', ['{'] = '}', ['<'] = '>' }
local literal_delimitted = P(function(input, index) -- for single delimiter sets
local delimiter = input:sub(index, index)
if not delimiter:find('%w') then -- only non alpha-numerics
local match_pos, patt
if delimiter_matches[delimiter] then
-- Handle nested delimiter/matches in strings.
local s, e = delimiter, delimiter_matches[delimiter]
patt = l.delimited_range(s..e, '\\', true, true)
else
patt = l.delimited_range(delimiter, '\\', true)
end
match_pos = lpeg.match(patt, input, index)
return match_pos or #input + 1
end
end)
local literal_delimitted2 = P(function(input, index) -- for 2 delimiter sets
local delimiter = input:sub(index, index)
if not delimiter:find('%w') then -- only non alpha-numerics
local match_pos, patt
if delimiter_matches[delimiter] then
-- Handle nested delimiter/matches in strings.
local s, e = delimiter, delimiter_matches[delimiter]
patt = l.delimited_range(s..e, '\\', true, true)
else
patt = l.delimited_range(delimiter, '\\', true)
end
first_match_pos = lpeg.match(patt, input, index)
final_match_pos = lpeg.match(patt, input, first_match_pos - 1)
if not final_match_pos then -- using (), [], {}, or <> notation
final_match_pos = lpeg.match(l.space^0 * patt, input, first_match_pos)
end
return final_match_pos or #input + 1
end
end)
-- Strings.
local sq_str = l.delimited_range("'", '\\', true)
local dq_str = l.delimited_range('"', '\\', true)
local cmd_str = l.delimited_range('`', '\\', true)
local heredoc = '<<' * P(function(input, index)
local s, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f;]+', index)
if s == index and delimiter then
local end_heredoc = '[\n\r\f]+'
local _, e = input:find(end_heredoc..delimiter, e)
return e and e + 1 or #input + 1
end
end)
local lit_str = 'q' * P('q')^-1 * literal_delimitted
local lit_array = 'qw' * literal_delimitted
local lit_cmd = 'qx' * literal_delimitted
local lit_match = 'm' * literal_delimitted * S('cgimosx')^0
local lit_sub = 's' * literal_delimitted2 * S('ecgimosx')^0
local lit_tr = (P('tr') + 'y') * literal_delimitted2 * S('cds')^0
local regex_str = l.delimited_range('/', '\\', false, true, '\n') * S('imosx')^0
local lit_regex = 'qr' * literal_delimitted * S('imosx')^0
local string = token(l.STRING, sq_str + dq_str + cmd_str + heredoc + lit_str +
lit_array + lit_cmd + lit_match + lit_sub +
lit_tr) +
token(l.REGEX, regex_str + lit_regex)
-- Numbers.
local number = token(l.NUMBER, l.float + l.integer)
-- Keywords.
local keyword = token(l.KEYWORD, word_match {
'STDIN', 'STDOUT', 'STDERR', 'BEGIN', 'END', 'CHECK', 'INIT',
'require', 'use',
'break', 'continue', 'do', 'each', 'else', 'elsif', 'foreach', 'for', 'if',
'last', 'local', 'my', 'next', 'our', 'package', 'return', 'sub', 'unless',
'until', 'while', '__FILE__', '__LINE__', '__PACKAGE__',
'and', 'or', 'not', 'eq', 'ne', 'lt', 'gt', 'le', 'ge'
})
-- Functions.
local func = token(l.FUNCTION, word_match({
'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller',
'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'closedir',
'close', 'connect', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined',
'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent',
'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists',
'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline',
'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname',
'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent',
'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname',
'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid',
'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt',
'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl',
'join', 'keys', 'kill', 'lcfirst', 'lc', 'length', 'link', 'listen',
'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv',
'msgsnd', 'new', 'oct', 'opendir', 'open', 'ord', 'pack', 'pipe', 'pop',
'pos', 'printf', 'print', 'prototype', 'push', 'quotemeta', 'rand', 'readdir',
'read', 'readlink', 'recv', 'redo', 'ref', 'rename', 'reset', 'reverse',
'rewinddir', 'rindex', 'rmdir', 'scalar', 'seekdir', 'seek', 'select',
'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent',
'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent',
'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown',
'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf',
'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysread',
'sysseek', 'system', 'syswrite', 'telldir', 'tell', 'tied', 'tie', 'time',
'times', 'truncate', 'ucfirst', 'uc', 'umask', 'undef', 'unlink', 'unpack',
'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray',
'warn', 'write'
}, '2'))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Variables.
local special_var = '$' * ('^' * S('ADEFHILMOPSTWX')^-1 +
S('\\"[]\'&`+*.,;=%~?@<>(|/!-') +
':' * (l.any - ':') + P('$') * -l.word + l.digit^1)
local plain_var = ('$#' + S('$@%')) * P('$')^0 * l.word
local variable = token(l.VARIABLE, special_var + plain_var)
-- Operators.
local operator = token(l.OPERATOR, S('-<>+*!~\\=/%&|^&.?:;()[]{}'))
-- Markers.
local marker = token(l.COMMENT, word_match { '__DATA__', '__END__' } * l.any^0)
M._rules = {
{ 'whitespace', ws },
{ 'keyword', keyword },
{ 'marker', marker },
{ 'function', func },
{ 'string', string },
{ 'identifier', identifier },
{ 'comment', comment },
{ 'number', number },
{ 'variable', variable },
{ 'operator', operator },
{ 'any_char', l.any_char },
}
M._foldsymbols = {
_patterns = { '[%[%]{}]', '#' },
[l.OPERATOR] = { ['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1 },
[l.COMMENT] = { ['#'] = l.fold_line_comments('#') }
}
return M
|
Fixed bug with '$$' variables and added DATA and END markers; lexers/perl.lua
|
Fixed bug with '$$' variables and added DATA and END markers; lexers/perl.lua
|
Lua
|
mit
|
rgieseke/scintillua
|
1cefd279465c32c7ad15e0990ddc950c41603c44
|
frontend/apps/cloudstorage/dropboxapi.lua
|
frontend/apps/cloudstorage/dropboxapi.lua
|
local DocumentRegistry = require("document/documentregistry")
local JSON = require("json")
local http = require("socket.http")
local ltn12 = require("ltn12")
local socket = require("socket")
local socketutil = require("socketutil")
local _ = require("gettext")
local DropBoxApi = {
}
local API_URL_INFO = "https://api.dropboxapi.com/2/users/get_current_account"
local API_LIST_FOLDER = "https://api.dropboxapi.com/2/files/list_folder"
local API_DOWNLOAD_FILE = "https://content.dropboxapi.com/2/files/download"
function DropBoxApi:fetchInfo(token)
local sink = {}
socketutil:set_timeout()
local request = {
url = API_URL_INFO,
method = "POST",
headers = {
["Authorization"] = "Bearer " .. token,
},
sink = ltn12.sink.table(sink),
}
local headers_request = socket.skip(1, http.request(request))
socketutil:reset_timeout()
local result_response = table.concat(sink)
if headers_request == nil then
return nil
end
if result_response ~= "" then
local _, result = pcall(JSON.decode, result_response)
return result
else
return nil
end
end
function DropBoxApi:fetchListFolders(path, token)
if path == nil or path == "/" then path = "" end
local data = "{\"path\": \"" .. path .. "\",\"recursive\": false,\"include_media_info\": false,"..
"\"include_deleted\": false,\"include_has_explicit_shared_members\": false}"
local sink = {}
socketutil:set_timeout()
local request = {
url = API_LIST_FOLDER,
method = "POST",
headers = {
["Authorization"] = "Bearer ".. token,
["Content-Type"] = "application/json",
["Content-Length"] = #data,
},
source = ltn12.source.string(data),
sink = ltn12.sink.table(sink),
}
local headers_request = socket.skip(1, http.request(request))
socketutil:reset_timeout()
if headers_request == nil then
return nil
end
local result_response = table.concat(sink)
if result_response ~= "" then
local ret, result = pcall(JSON.decode, result_response)
if ret then
return result
else
return nil
end
else
return nil
end
end
function DropBoxApi:downloadFile(path, token, local_path)
local data1 = "{\"path\": \"" .. path .. "\"}"
socketutil:set_timeout(socketutil.FILE_BLOCK_TIMEOUT, socketutil.FILE_TOTAL_TIMEOUT)
local code_return = socket.skip(1, http.request{
url = API_DOWNLOAD_FILE,
method = "GET",
headers = {
["Authorization"] = "Bearer ".. token,
["Dropbox-API-Arg"] = data1,
},
sink = ltn12.sink.file(io.open(local_path, "w")),
})
socketutil:reset_timeout()
return code_return
end
-- folder_mode - set to true when we want to see only folder.
-- We see also extra folder "Long-press to select current directory" at the beginning.
function DropBoxApi:listFolder(path, token, folder_mode)
local dropbox_list = {}
local dropbox_file = {}
local tag, text
local ls_dropbox = self:fetchListFolders(path, token)
if ls_dropbox == nil or ls_dropbox.entries == nil then return false end
for _, files in ipairs(ls_dropbox.entries) do
text = files.name
tag = files[".tag"]
if tag == "folder" then
text = text .. "/"
if folder_mode then tag = "folder_long_press" end
table.insert(dropbox_list, {
text = text,
url = files.path_display,
type = tag,
})
--show only file with supported formats
elseif tag == "file" and (DocumentRegistry:hasProvider(text)
or G_reader_settings:isTrue("show_unsupported")) and not folder_mode then
table.insert(dropbox_file, {
text = text,
url = files.path_display,
type = tag,
})
end
end
--sort
table.sort(dropbox_list, function(v1,v2)
return v1.text < v2.text
end)
table.sort(dropbox_file, function(v1,v2)
return v1.text < v2.text
end)
-- Add special folder.
if folder_mode then
table.insert(dropbox_list, 1, {
text = _("Long-press to select current folder"),
url = path,
type = "folder_long_press",
})
end
for _, files in ipairs(dropbox_file) do
table.insert(dropbox_list, {
text = files.text,
url = files.url,
type = files.type,
})
end
return dropbox_list
end
function DropBoxApi:showFiles(path, token)
local dropbox_files = {}
local tag, text
local ls_dropbox = self:fetchListFolders(path, token)
if ls_dropbox == nil or ls_dropbox.entries == nil then return false end
for _, files in ipairs(ls_dropbox.entries) do
text = files.name
tag = files[".tag"]
if tag == "file" and (DocumentRegistry:hasProvider(text) or G_reader_settings:isTrue("show_unsupported")) then
table.insert(dropbox_files, {
text = text,
url = files.path_display,
size = files.size,
})
end
end
return dropbox_files
end
return DropBoxApi
|
local DocumentRegistry = require("document/documentregistry")
local JSON = require("json")
local http = require("socket.http")
local logger = require("logger")
local ltn12 = require("ltn12")
local socket = require("socket")
local socketutil = require("socketutil")
local _ = require("gettext")
local DropBoxApi = {
}
local API_URL_INFO = "https://api.dropboxapi.com/2/users/get_current_account"
local API_LIST_FOLDER = "https://api.dropboxapi.com/2/files/list_folder"
local API_DOWNLOAD_FILE = "https://content.dropboxapi.com/2/files/download"
local API_LIST_ADD_FOLDER = "https://api.dropboxapi.com/2/files/list_folder/continue"
function DropBoxApi:fetchInfo(token)
local sink = {}
socketutil:set_timeout()
local request = {
url = API_URL_INFO,
method = "POST",
headers = {
["Authorization"] = "Bearer " .. token,
},
sink = ltn12.sink.table(sink),
}
local headers_request = socket.skip(1, http.request(request))
socketutil:reset_timeout()
local result_response = table.concat(sink)
if headers_request == nil then
return nil
end
if result_response ~= "" then
local _, result = pcall(JSON.decode, result_response)
return result
else
return nil
end
end
function DropBoxApi:fetchListFolders(path, token)
if path == nil or path == "/" then path = "" end
local data = "{\"path\": \"" .. path .. "\",\"recursive\": false,\"include_media_info\": false,"..
"\"include_deleted\": false,\"include_has_explicit_shared_members\": false}"
local sink = {}
socketutil:set_timeout()
local request = {
url = API_LIST_FOLDER,
method = "POST",
headers = {
["Authorization"] = "Bearer ".. token,
["Content-Type"] = "application/json",
["Content-Length"] = #data,
},
source = ltn12.source.string(data),
sink = ltn12.sink.table(sink),
}
local headers_request = socket.skip(1, http.request(request))
socketutil:reset_timeout()
if headers_request == nil then
return nil
end
local result_response = table.concat(sink)
if result_response ~= "" then
local ret, result = pcall(JSON.decode, result_response)
if ret then
-- Check if more results, and then get them
if result.has_more then
logger.dbg("Found additional files")
result = self:fetchAdditionalFolders(result, token)
end
return result
else
return nil
end
else
return nil
end
end
function DropBoxApi:downloadFile(path, token, local_path)
local data1 = "{\"path\": \"" .. path .. "\"}"
socketutil:set_timeout(socketutil.FILE_BLOCK_TIMEOUT, socketutil.FILE_TOTAL_TIMEOUT)
local code_return = socket.skip(1, http.request{
url = API_DOWNLOAD_FILE,
method = "GET",
headers = {
["Authorization"] = "Bearer ".. token,
["Dropbox-API-Arg"] = data1,
},
sink = ltn12.sink.file(io.open(local_path, "w")),
})
socketutil:reset_timeout()
return code_return
end
-- folder_mode - set to true when we want to see only folder.
-- We see also extra folder "Long-press to select current directory" at the beginning.
function DropBoxApi:listFolder(path, token, folder_mode)
local dropbox_list = {}
local dropbox_file = {}
local tag, text
local ls_dropbox = self:fetchListFolders(path, token)
if ls_dropbox == nil or ls_dropbox.entries == nil then return false end
for _, files in ipairs(ls_dropbox.entries) do
text = files.name
tag = files[".tag"]
if tag == "folder" then
text = text .. "/"
if folder_mode then tag = "folder_long_press" end
table.insert(dropbox_list, {
text = text,
url = files.path_display,
type = tag,
})
--show only file with supported formats
elseif tag == "file" and (DocumentRegistry:hasProvider(text)
or G_reader_settings:isTrue("show_unsupported")) and not folder_mode then
table.insert(dropbox_file, {
text = text,
url = files.path_display,
type = tag,
})
end
end
--sort
table.sort(dropbox_list, function(v1,v2)
return v1.text < v2.text
end)
table.sort(dropbox_file, function(v1,v2)
return v1.text < v2.text
end)
-- Add special folder.
if folder_mode then
table.insert(dropbox_list, 1, {
text = _("Long-press to select current folder"),
url = path,
type = "folder_long_press",
})
end
for _, files in ipairs(dropbox_file) do
table.insert(dropbox_list, {
text = files.text,
url = files.url,
type = files.type,
})
end
return dropbox_list
end
function DropBoxApi:showFiles(path, token)
local dropbox_files = {}
local tag, text
local ls_dropbox = self:fetchListFolders(path, token)
if ls_dropbox == nil or ls_dropbox.entries == nil then return false end
for _, files in ipairs(ls_dropbox.entries) do
text = files.name
tag = files[".tag"]
if tag == "file" and (DocumentRegistry:hasProvider(text) or G_reader_settings:isTrue("show_unsupported")) then
table.insert(dropbox_files, {
text = text,
url = files.path_display,
size = files.size,
})
end
end
return dropbox_files
end
function DropBoxApi:fetchAdditionalFolders(response, token)
local out = response
local cursor = response.cursor
repeat
local data = "{\"cursor\": \"" .. cursor .. "\"}"
local sink = {}
socketutil:set_timeout()
local request = {
url = API_LIST_ADD_FOLDER,
method = "POST",
headers = {
["Authorization"] = "Bearer ".. token,
["Content-Type"] = "application/json",
["Content-Length"] = #data,
},
source = ltn12.source.string(data),
sink = ltn12.sink.table(sink),
}
local headers_request = socket.skip(1, http.request(request))
socketutil:reset_timeout()
if headers_request == nil then
return nil
end
local result_response = table.concat(sink)
local ret, result = pcall(JSON.decode, result_response)
if not ret then
return nil
end
for __, v in ipairs(result.entries) do
table.insert(out.entries, v)
end
if result.has_more then
cursor = result.cursor
end
until not result.has_more
return out
end
return DropBoxApi
|
DropboxAPI: Handle pagination (#7621)
|
DropboxAPI: Handle pagination (#7621)
Fix #7600
Co-authored-by: NiLuJe <[email protected]>
Co-authored-by: Frans de Jonge <[email protected]>
|
Lua
|
agpl-3.0
|
koreader/koreader,NiLuJe/koreader,poire-z/koreader,NiLuJe/koreader,poire-z/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader,mwoz123/koreader
|
b08ea4ea1d4f5f39d2efe50231d59262a7ea3a49
|
.build.1.lua
|
.build.1.lua
|
local modules = {}
function addModules( mods )
if type(mods) ~= "table" then
mods = {mods}
end
for _, mod in mods do
if table.contains( modules, mod ) == false then
modules.insert( mod )
zpm.submodules( mod )
zpm.export [[
includedirs "]] .. mod .. [["
]]
end
end
project( "Boost" )
local usesCpp = false
if zpm.option( "Accumulators" ) then
addModules({"config",
"numeric",
"predef",
"concept",
"exception",
"chrono",
"functional",
"intrusive",
"utility",
"detail",
"container",
"iterator",
"bind",
"circular_buffer",
"range",
"math",
"timer",
"type_traits",
"move",
"function",
"preprocessor",
"parameter",
"system",
"smart_ptr",
"tuple",
"accumulators",
"serialization",
"fusion",
"typeof",
"algorithm",
"pending",
"random",
"integer",
"core",
"mpl",
"optional",
"ratio",
"test",
"io"})
end
warnings "Off"
if usesCpp then
kind "StaticLib"
else
kind "Utility"
end
zpm.export [[
includedirs "include/"
flags "C++14"
defines "BOOST_ALL_NO_LIB"
]]
|
local modules = {}
function addModules( mods )
if type(mods) ~= "table" then
mods = {mods}
end
for _, mod in mods do
if table.contains( modules, mod ) == false then
modules.insert( mod )
zpm.submodules( mod )
zpm.export "includedirs \"".. mod .."\""
end
end
project( "Boost" )
local usesCpp = false
if zpm.option( "Accumulators" ) then
addModules({"config",
"numeric",
"predef",
"concept",
"exception",
"chrono",
"functional",
"intrusive",
"utility",
"detail",
"container",
"iterator",
"bind",
"circular_buffer",
"range",
"math",
"timer",
"type_traits",
"move",
"function",
"preprocessor",
"parameter",
"system",
"smart_ptr",
"tuple",
"accumulators",
"serialization",
"fusion",
"typeof",
"algorithm",
"pending",
"random",
"integer",
"core",
"mpl",
"optional",
"ratio",
"test",
"io"})
end
warnings "Off"
if usesCpp then
kind "StaticLib"
else
kind "Utility"
end
zpm.export [[
includedirs "include/"
flags "C++14"
defines "BOOST_ALL_NO_LIB"
]]
|
Syntax fix
|
Syntax fix
|
Lua
|
mit
|
Zefiros-Software/Boost,Zefiros-Software/Boost
|
1f22216d7c615cdf3cf17644aabcbc3bfa969533
|
lualib/snax/gateserver.lua
|
lualib/snax/gateserver.lua
|
local skynet = require "skynet"
local netpack = require "skynet.netpack"
local socketdriver = require "skynet.socketdriver"
local gateserver = {}
local socket -- listen socket
local queue -- message queue
local maxclient -- max client
local client_number = 0
local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })
local nodelay = false
local connection = {}
function gateserver.openclient(fd)
if connection[fd] then
socketdriver.start(fd)
end
end
function gateserver.closeclient(fd)
local c = connection[fd]
if c then
connection[fd] = false
socketdriver.close(fd)
end
end
function gateserver.start(handler)
assert(handler.message)
assert(handler.connect)
function CMD.open( source, conf )
assert(not socket)
local address = conf.address or "0.0.0.0"
local port = assert(conf.port)
maxclient = conf.maxclient or 1024
nodelay = conf.nodelay
skynet.error(string.format("Listen on %s:%d", address, port))
socket = socketdriver.listen(address, port)
socketdriver.start(socket)
if handler.open then
return handler.open(source, conf)
end
end
function CMD.close()
assert(socket)
socketdriver.close(socket)
end
local MSG = {}
local function dispatch_msg(fd, msg, sz)
if connection[fd] then
handler.message(fd, msg, sz)
else
skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz)))
end
end
MSG.data = dispatch_msg
local function dispatch_queue()
local fd, msg, sz = netpack.pop(queue)
if fd then
-- may dispatch even the handler.message blocked
-- If the handler.message never block, the queue should be empty, so only fork once and then exit.
skynet.fork(dispatch_queue)
dispatch_msg(fd, msg, sz)
for fd, msg, sz in netpack.pop, queue do
dispatch_msg(fd, msg, sz)
end
end
end
MSG.more = dispatch_queue
function MSG.open(fd, msg)
if client_number >= maxclient then
socketdriver.close(fd)
return
end
if nodelay then
socketdriver.nodelay(fd)
end
connection[fd] = true
client_number = client_number + 1
handler.connect(fd, msg)
end
local function close_fd(fd)
local c = connection[fd]
if c ~= nil then
connection[fd] = nil
client_number = client_number - 1
end
end
function MSG.close(fd)
if fd ~= socket then
if handler.disconnect then
handler.disconnect(fd)
end
close_fd(fd)
else
socket = nil
end
end
function MSG.error(fd, msg)
if fd == socket then
socketdriver.close(fd)
skynet.error("gateserver close listen socket, accpet error:",msg)
else
if handler.error then
handler.error(fd, msg)
end
close_fd(fd)
end
end
function MSG.warning(fd, size)
if handler.warning then
handler.warning(fd, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = function ( msg, sz )
return netpack.filter( queue, msg, sz)
end,
dispatch = function (_, _, q, type, ...)
queue = q
if type then
MSG[type](...)
end
end
}
skynet.start(function()
skynet.dispatch("lua", function (_, address, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(address, ...)))
else
skynet.ret(skynet.pack(handler.command(cmd, address, ...)))
end
end)
end)
end
return gateserver
|
local skynet = require "skynet"
local netpack = require "skynet.netpack"
local socketdriver = require "skynet.socketdriver"
local gateserver = {}
local socket -- listen socket
local queue -- message queue
local maxclient -- max client
local client_number = 0
local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })
local nodelay = false
local connection = {}
function gateserver.openclient(fd)
if connection[fd] then
socketdriver.start(fd)
end
end
function gateserver.closeclient(fd)
local c = connection[fd]
if c then
connection[fd] = false
socketdriver.close(fd)
end
end
function gateserver.start(handler)
assert(handler.message)
assert(handler.connect)
function CMD.open( source, conf )
assert(not socket)
local address = conf.address or "0.0.0.0"
local port = assert(conf.port)
maxclient = conf.maxclient or 1024
nodelay = conf.nodelay
skynet.error(string.format("Listen on %s:%d", address, port))
socket = socketdriver.listen(address, port)
socketdriver.start(socket)
if handler.open then
return handler.open(source, conf)
end
end
function CMD.close()
assert(socket)
socketdriver.close(socket)
end
local MSG = {}
local function dispatch_msg(fd, msg, sz)
if connection[fd] then
handler.message(fd, msg, sz)
else
skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz)))
end
end
MSG.data = dispatch_msg
local function dispatch_queue()
local fd, msg, sz = netpack.pop(queue)
if fd then
-- may dispatch even the handler.message blocked
-- If the handler.message never block, the queue should be empty, so only fork once and then exit.
skynet.fork(dispatch_queue)
dispatch_msg(fd, msg, sz)
for fd, msg, sz in netpack.pop, queue do
dispatch_msg(fd, msg, sz)
end
end
end
MSG.more = dispatch_queue
function MSG.open(fd, msg)
if client_number >= maxclient then
socketdriver.close(fd)
return
end
if nodelay then
socketdriver.nodelay(fd)
end
connection[fd] = true
client_number = client_number + 1
handler.connect(fd, msg)
end
local function close_fd(fd)
local c = connection[fd]
if c ~= nil then
connection[fd] = nil
client_number = client_number - 1
end
end
function MSG.close(fd)
if fd ~= socket then
if handler.disconnect then
handler.disconnect(fd)
end
close_fd(fd)
else
socket = nil
end
end
function MSG.error(fd, msg)
if fd == socket then
skynet.error("gateserver accpet error:",msg)
else
if handler.error then
handler.error(fd, msg)
end
close_fd(fd)
end
end
function MSG.warning(fd, size)
if handler.warning then
handler.warning(fd, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = function ( msg, sz )
return netpack.filter( queue, msg, sz)
end,
dispatch = function (_, _, q, type, ...)
queue = q
if type then
MSG[type](...)
end
end
}
skynet.start(function()
skynet.dispatch("lua", function (_, address, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(address, ...)))
else
skynet.ret(skynet.pack(handler.command(cmd, address, ...)))
end
end)
end)
end
return gateserver
|
fix #1188
|
fix #1188
|
Lua
|
mit
|
JiessieDawn/skynet,hongling0/skynet,JiessieDawn/skynet,xjdrew/skynet,icetoggle/skynet,korialuo/skynet,icetoggle/skynet,hongling0/skynet,xcjmine/skynet,wangyi0226/skynet,xjdrew/skynet,cloudwu/skynet,pigparadise/skynet,bigrpg/skynet,pigparadise/skynet,bigrpg/skynet,bigrpg/skynet,cloudwu/skynet,sanikoyes/skynet,hongling0/skynet,wangyi0226/skynet,korialuo/skynet,cloudwu/skynet,ag6ag/skynet,xjdrew/skynet,wangyi0226/skynet,sanikoyes/skynet,korialuo/skynet,ag6ag/skynet,sanikoyes/skynet,JiessieDawn/skynet,icetoggle/skynet,ag6ag/skynet,xcjmine/skynet,pigparadise/skynet,xcjmine/skynet
|
4eae9de1bb4d7b9bd4c3b40af62d76ef59307c1b
|
UCDanticheat/togglecontrol.lua
|
UCDanticheat/togglecontrol.lua
|
addCommandHandler("tog",
function ()
outputDebugString(tostring(not isControlEnabled("fire")))
toggleControl("fire", not isControlEnabled("fire"))
end
)
local aimKeys = getBoundKeys("aim_weapon")
local fireKeys = getBoundKeys("fire")
local exceptedWeapons = {[41] = true}
local exceptedSlots = {[0] = true, [1] = true, [8] = true, [10] = true, [11] = true, [12] = true}
local disallowedTeams = {["Citizens"] = true, ["Not logged in"] = true}
function fireCheck(button, state)
if (localPlayer.vehicle) then return end
if (fireKeys[button] and state == true) then
if (exports.UCDsafeZones:isElementWithinSafeZone(localPlayer) or (not exports.UCDturfing:isElementInLV(localPlayer) and disallowedTeams[localPlayer.team.name])) then
toggleControl("fire", false)
return
end
if (exceptedSlots[localPlayer.weaponSlot] or exceptedWeapons[localPlayer:getWeapon()]) then
return
end
--outputDebugString("fire")
if (not getControlState("aim_weapon")) then
toggleControl("fire", false)
--outputDebugString("not aiming")
end
end
if (fireKeys[button] and state == false) then
if (not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer) and not localPlayer.frozen) then
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, fireCheck)
function aimCheck(button, state)
if (localPlayer.vehicle) then return end
if (aimKeys[button] and state == true) then
--if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) and localPlayer.weaponSlot ~= 11 and not exceptedWeapons[localPlayer:getWeapon()] and not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) or exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
outputDebugString("true")
toggleControl("aim_weapon", false)
toggleControl("fire", false)
else
outputDebugString("false")
toggleControl("aim_weapon", true)
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, aimCheck)
|
addCommandHandler("tog",
function ()
outputDebugString(tostring(not isControlEnabled("fire")))
toggleControl("fire", not isControlEnabled("fire"))
end
)
local aimKeys = getBoundKeys("aim_weapon")
local fireKeys = getBoundKeys("fire")
local exceptedWeapons = {[0] = true, [41] = true}
local exceptedSlots = {[0] = true, [1] = true, [8] = true, [10] = true, [11] = true, [12] = true}
local disallowedTeams = {["Citizens"] = true, ["Not logged in"] = true}
-- Firing checks (also disables firing without aiming)
function fireCheck(button, state)
if (localPlayer.vehicle) then return end
if (fireKeys[button] and state == true) then
-- If they are in a safezone, disable firing regardless of everything else
if (exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
toggleControl("fire", false)
return
end
-- If they are in not in LV, are a civilian and are not currently using their fists then
if (not exports.UCDturfing:isElementInLV(localPlayer) and disallowedTeams[localPlayer.team.name] and localPlayer:getWeapon() ~= 0) then
toggleControl("fire", false)
return
end
if (exceptedSlots[localPlayer.weaponSlot] or exceptedWeapons[localPlayer:getWeapon()]) then
return
end
--outputDebugString("fire")
if (not getControlState("aim_weapon")) then
toggleControl("fire", false)
--outputDebugString("not aiming")
end
end
if (fireKeys[button] and state == false) then
if (not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer) and not localPlayer.frozen) then
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, fireCheck)
function aimCheck(button, state)
if (localPlayer.vehicle) then return end
if (aimKeys[button] and state == true) then
--if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) and localPlayer.weaponSlot ~= 11 and not exceptedWeapons[localPlayer:getWeapon()] and not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) or exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
outputDebugString("true")
toggleControl("aim_weapon", false)
toggleControl("fire", false)
else
outputDebugString("false")
toggleControl("aim_weapon", true)
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, aimCheck)
|
UCDanticheat
|
UCDanticheat
- Fixed the toggle control not allowing players to use their fists.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
e16bc88f148ffa743757ea101776a61fb3048a7b
|
lua/shdict.lua
|
lua/shdict.lua
|
local _M = {
_VERSION = "1.2.0"
}
local cjson = require "cjson"
local function decode(value)
if value then
return cjson.decode(value)
end
return nil
end
local function make_cache(cache, prefix)
local shm = ngx.shared[prefix]
if shm then
cache.count = 1
cache.data[1] = shm
return
end
for i=1,64
do
shm = ngx.shared[prefix .. "_" .. i]
if not shm then
break
end
cache.data[i] = shm
ngx.log(ngx.DEBUG, prefix .. "_" .. i, " found")
end
cache.count = #cache.data
if cache.count == 0 then
error("shared memory [", prefix, "] is not defined")
end
end
local shdict_class = {}
function shdict_class:get(key)
return self.__caches.get(key):get(key)
end
function shdict_class:object_get(key)
local value, flags = self.__caches.get(key):get(key)
return decode(value), flags
end
function shdict_class:get_stale(key)
return self.__caches.get(key):get_stale(key)
end
function shdict_class:object_get_stale(key)
local value, flags, stale = self.__caches.get(key):get_stale(key)
return decode(value), flags, stale
end
function shdict_class:set(key, value, exptime, flags)
return self.__caches.get(key):set(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_set(key, value, exptime, flags)
return self.__caches.get(key):set(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:safe_set(key, value, exptime, flags)
return self.__caches.get(key):safe_set(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_safe_set(key, value, exptime, flags)
return self.__caches.get(key):safe_set(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:add(key, value, exptime, flags)
return self.__caches.get(key):add(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_add(key, value, exptime, flags)
return self.__caches.get(key):add(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:safe_add(key, value, exptime, flags)
return self.__caches.get(key):safe_add(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_safe_add(key, value, exptime, flags)
return self.__caches.get(key):safe_add(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:replace(key, value, exptime, flags)
return self.__caches.get(key):replace(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_replace(key, value, exptime, flags)
return self.__caches.get(key):replace(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:delete(key)
return self.__caches.get(key):delete(key)
end
function shdict_class:incr(key, value, init)
return self.__caches.get(key):incr(key, value, init or 0)
end
function shdict_class:lpush(key, value)
return self.__caches.get(key):lpush(key, value)
end
function shdict_class:object_lpush(key, value)
return self.__caches.get(key):lpush(key, cjson.encode(value))
end
function shdict_class:rpush(key, value)
return self.__caches.get(key):rpush(key, value)
end
function shdict_class:object_rpush(key, value)
return self.__caches.get(key):rpush(key, cjson.encode(value))
end
function shdict_class:lpop(key)
return self.__caches.get(key):lpop(key)
end
function shdict_class:object_lpop(key)
local value, err = self.__caches.get(key):lpop(key)
return decode(value), err
end
function shdict_class:rpop(key)
return self.__caches.get(key):rpop(key)
end
function shdict_class:object_rpop(key)
local value, err = self.__caches.get(key):rpop(key)
return decode(value), err
end
function shdict_class:llen(key)
return self.__caches.get(key):llen(key)
end
function shdict_class:flush_all()
for i=1,self.__caches.count
do
self.__caches.data[i]:flush_all()
end
end
function shdict_class:flush_expired()
for i=1,self.__caches.count
do
self.__caches.data[i]:flush_expired()
end
end
local function get_keys(dict, max_count)
local keys = {}
local part, total = max_count / dict.__caches.count, 0
for i=1,dict.__caches.count
do
if part ~= 0 and i == dict.__caches.count then
part = max_count - total
end
keys[i] = dict.__caches.data[i]:get_keys(part)
total = total + #keys[i]
end
return keys
end
function shdict_class:get_keys(max_count)
local parts = get_keys(self, max_count or 0)
local keys = {}
for i=1,#parts
do
for j=1,#parts[i]
do
keys[#keys + 1] = parts[i][j]
end
end
return keys
end
function shdict_class:get_values(max_count)
local keys = get_keys(self, max_count or 0)
local r = {}
local v, f
for i=1,#keys
do
for j=1,#keys[i]
do
v, f = self.__caches.data[i]:get(keys[i][j])
r[#r + 1] = { value = v, flags = f }
end
end
return r
end
function shdict_class:get_objects(max_count)
local keys = get_keys(self, max_count or 0)
local r = {}
local v, f
for i=1,#keys
do
for j=1,#keys[i]
do
v, f = self.__caches.data[i]:get(keys[i][j])
r[#r + 1] = { object = decode(v), flags = f }
end
end
return r
end
function shdict_class:fun(key, fun, exptime)
return self.__caches.get(key):fun(key, fun, exptime or 0)
end
function shdict_class:object_fun(key, fun, exptime)
local value, flags = self.__caches.get(key):fun(key, function(value, flags)
local object, new_flags = fun(decode(value), flags)
if object then
return cjson.encode(object), new_flags
end
return nil, new_flags
end, exptime or 0)
return decode(value), flags
end
function _M.new(name)
local dict = {
__caches = {
count = 0,
data = {}
}
}
local caches = dict.__caches
caches.get = function(key)
if caches.count == 1 then
return caches.data[1]
end
if caches.last_key == key then
return caches.last_shm
end
caches.last_key = key
caches.last_shm = caches.data[1 + ngx.crc32_short(key) % caches.count]
return caches.last_shm
end
make_cache(caches, name)
return setmetatable(dict, { __index = shdict_class } )
end
return _M
|
local _M = {
_VERSION = "1.8.2"
}
local cjson = require "cjson"
local function decode(value)
if value then
return cjson.decode(value)
end
return nil
end
local function make_cache(cache, prefix)
local shm = ngx.shared[prefix]
if shm then
cache.count = 1
cache.data[1] = shm
return
end
for i=1,64
do
shm = ngx.shared[prefix .. "_" .. i]
if not shm then
break
end
cache.data[i] = shm
ngx.log(ngx.DEBUG, prefix .. "_" .. i, " found")
end
cache.count = #cache.data
if cache.count == 0 then
error("shared memory [", prefix, "] is not defined")
end
end
local shdict_class = {}
function shdict_class:get(key)
return self.__caches.get(key):get(key)
end
function shdict_class:object_get(key)
local value, flags = self.__caches.get(key):get(key)
return decode(value), flags
end
function shdict_class:get_stale(key)
return self.__caches.get(key):get_stale(key)
end
function shdict_class:object_get_stale(key)
local value, flags, stale = self.__caches.get(key):get_stale(key)
return decode(value), flags, stale
end
function shdict_class:set(key, value, exptime, flags)
return self.__caches.get(key):set(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_set(key, value, exptime, flags)
return self.__caches.get(key):set(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:safe_set(key, value, exptime, flags)
return self.__caches.get(key):safe_set(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_safe_set(key, value, exptime, flags)
return self.__caches.get(key):safe_set(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:add(key, value, exptime, flags)
return self.__caches.get(key):add(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_add(key, value, exptime, flags)
return self.__caches.get(key):add(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:safe_add(key, value, exptime, flags)
return self.__caches.get(key):safe_add(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_safe_add(key, value, exptime, flags)
return self.__caches.get(key):safe_add(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:replace(key, value, exptime, flags)
return self.__caches.get(key):replace(key, value, exptime or 0, flags or 0)
end
function shdict_class:object_replace(key, value, exptime, flags)
return self.__caches.get(key):replace(key, cjson.encode(value), exptime or 0, flags or 0)
end
function shdict_class:delete(key)
return self.__caches.get(key):delete(key)
end
function shdict_class:incr(key, value, init)
return self.__caches.get(key):incr(key, value, init or 0)
end
function shdict_class:lpush(key, value)
return self.__caches.get(key):lpush(key, value)
end
function shdict_class:object_lpush(key, value)
return self.__caches.get(key):lpush(key, cjson.encode(value))
end
function shdict_class:rpush(key, value)
return self.__caches.get(key):rpush(key, value)
end
function shdict_class:object_rpush(key, value)
return self.__caches.get(key):rpush(key, cjson.encode(value))
end
function shdict_class:lpop(key)
return self.__caches.get(key):lpop(key)
end
function shdict_class:object_lpop(key)
local value, err = self.__caches.get(key):lpop(key)
return decode(value), err
end
function shdict_class:rpop(key)
return self.__caches.get(key):rpop(key)
end
function shdict_class:object_rpop(key)
local value, err = self.__caches.get(key):rpop(key)
return decode(value), err
end
function shdict_class:llen(key)
return self.__caches.get(key):llen(key)
end
function shdict_class:flush_all()
for i=1,self.__caches.count
do
self.__caches.data[i]:flush_all()
end
end
function shdict_class:flush_expired(max_count)
local part, n = (max_count or 0) / self.__caches.count, 0
for i=1,self.__caches.count
do
if part ~= 0 and i == self.__caches.count then
part = max_count - n
end
local expired = self.__caches.data[i]:flush_expired(part) or 0
n = n + expired
end
return n
end
local function get_keys(dict, max_count)
local keys = {}
local part, total = max_count / dict.__caches.count, 0
for i=1,dict.__caches.count
do
if part ~= 0 and i == dict.__caches.count then
part = max_count - total
end
keys[i] = dict.__caches.data[i]:get_keys(part)
total = total + #keys[i]
end
return keys
end
function shdict_class:get_keys(max_count)
local parts = get_keys(self, max_count or 0)
local keys = {}
for i=1,#parts
do
for j=1,#parts[i]
do
keys[#keys + 1] = parts[i][j]
end
end
return keys
end
function shdict_class:get_values(max_count)
local keys = get_keys(self, max_count or 0)
local r = {}
local v, f
for i=1,#keys
do
for j=1,#keys[i]
do
v, f = self.__caches.data[i]:get(keys[i][j])
r[#r + 1] = { value = v, flags = f }
end
end
return r
end
function shdict_class:get_objects(max_count)
local keys = get_keys(self, max_count or 0)
local r = {}
local v, f
for i=1,#keys
do
for j=1,#keys[i]
do
v, f = self.__caches.data[i]:get(keys[i][j])
r[#r + 1] = { object = decode(v), flags = f }
end
end
return r
end
function shdict_class:fun(key, fun, exptime)
return self.__caches.get(key):fun(key, fun, exptime or 0)
end
function shdict_class:object_fun(key, fun, exptime)
local value, flags = self.__caches.get(key):fun(key, function(value, flags)
local object, new_flags = fun(decode(value), flags)
if object then
return cjson.encode(object), new_flags
end
return nil, new_flags
end, exptime or 0)
return decode(value), flags
end
function _M.new(name)
local dict = {
__caches = {
count = 0,
data = {}
}
}
local caches = dict.__caches
caches.get = function(key)
if caches.count == 1 then
return caches.data[1]
end
if caches.last_key == key then
return caches.last_shm
end
caches.last_key = key
caches.last_shm = caches.data[1 + ngx.crc32_short(key) % caches.count]
return caches.last_shm
end
make_cache(caches, name)
return setmetatable(dict, { __index = shdict_class } )
end
return _M
|
fix flush_expired: returning value
|
fix flush_expired: returning value
|
Lua
|
bsd-2-clause
|
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
|
7a727b26ab4ebd3914e28a977d258b4c4f598677
|
vim/plugin/setup.lua
|
vim/plugin/setup.lua
|
-- vim.lsp.set_log_level("debug")
local lspconfig = require "lspconfig"
local lsp_spinner = require "lsp_spinner"
lsp_spinner.setup {
placeholder = " ",
}
local function on_attach(client, bufnr)
require("lsp_spinner").on_attach(client, bufnr)
end
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, {
virtual_text = {
prefix = "",
spacing = 2,
},
})
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
capabilities.textDocument.completion.completionItem.resolveSupport = {
properties = {
"documentation",
"detail",
"additionalTextEdits",
},
}
lsp_spinner.init_capabilities(capabilities)
local nvim_lsp = require "lspconfig"
local servers = {
"bashls",
"clangd",
"cmake",
"gopls",
"graphql",
"pyright",
"rust_analyzer",
"terraformls",
"zls",
}
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
capabilities = capabilities,
on_attach = on_attach,
}
end
require("lspconfig").sourcekit.setup {
capabilities = capabilities,
filetypes = { "swift" },
on_attach = on_attach,
}
require("lsp_signature").on_attach {
bind = true,
hint_prefix = "",
-- TODO: the border is huge, but these don't seem to work
-- handler_opts = {
-- border = "single"
-- },
}
require("compe").setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = "enable",
throttle_time = 80,
source_timeout = 200,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = true,
source = {
path = true,
buffer = {
ignored_filetypes = { "gitconfig", "gitcommit", "gitrebase", "git" },
},
nvim_lsp = true,
nvim_lua = true,
},
}
function has_highlights(lang)
local supported = {
c = true,
cpp = true,
}
return supported[lang] ~= nil
end
require("nvim-treesitter.configs").setup {
ensure_installed = "maintained",
ignore_install = { "zig" }, -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2049
highlight = {
enable = true,
additional_vim_regex_highlighting = false,
is_supported = has_highlights,
},
textsubjects = {
enable = true,
keymaps = {
["."] = "textsubjects-smart",
},
},
textobjects = {
select = {
enable = true,
keymaps = {
["af"] = "@function.outer",
["if"] = "@function.inner",
["ic"] = "@call.outer",
},
},
lsp_interop = {
enable = true,
peek_definition_code = {
["df"] = "@function.outer",
["dF"] = "@class.outer",
},
},
},
}
|
-- vim.lsp.set_log_level("debug")
local lspconfig = require "lspconfig"
local lsp_spinner = require "lsp_spinner"
lsp_spinner.setup {
placeholder = " ",
}
local function on_attach(client, bufnr)
require("lsp_spinner").on_attach(client, bufnr)
end
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, {
virtual_text = {
prefix = "",
spacing = 2,
},
})
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
capabilities.textDocument.completion.completionItem.resolveSupport = {
properties = {
"documentation",
"detail",
"additionalTextEdits",
},
}
lsp_spinner.init_capabilities(capabilities)
local nvim_lsp = require "lspconfig"
local servers = {
"bashls",
"clangd",
"cmake",
"gopls",
"graphql",
"pyright",
"rust_analyzer",
"terraformls",
"zls",
}
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
capabilities = capabilities,
on_attach = on_attach,
}
end
require("lspconfig").sourcekit.setup {
capabilities = capabilities,
filetypes = { "swift" },
on_attach = on_attach,
}
require("lsp_signature").on_attach {
bind = true,
hint_prefix = "",
-- TODO: the border is huge, but these don't seem to work
-- handler_opts = {
-- border = "single"
-- },
}
require("compe").setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = "enable",
throttle_time = 80,
source_timeout = 200,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = true,
source = {
path = true,
buffer = {
ignored_filetypes = { "gitconfig", "gitcommit", "gitrebase", "git" },
},
nvim_lsp = true,
nvim_lua = true,
},
}
function has_highlights(lang)
local supported = {
c = true,
cpp = true,
}
return supported[lang] ~= nil
end
require("nvim-treesitter.configs").setup {
ensure_installed = "all",
ignore_install = {
"phpdoc", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2837
"zig", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2049
},
highlight = {
enable = true,
additional_vim_regex_highlighting = false,
is_supported = has_highlights,
},
textsubjects = {
enable = true,
keymaps = {
["."] = "textsubjects-smart",
},
},
textobjects = {
select = {
enable = true,
keymaps = {
["af"] = "@function.outer",
["if"] = "@function.inner",
["ic"] = "@call.outer",
},
},
lsp_interop = {
enable = true,
peek_definition_code = {
["df"] = "@function.outer",
["dF"] = "@class.outer",
},
},
},
}
|
[nvim] Fix treesitter compat
|
[nvim] Fix treesitter compat
|
Lua
|
mit
|
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
|
d63570877410809583719c44f637ed4aa4525b93
|
src/daemon.lua
|
src/daemon.lua
|
--[[
transitd daemon main file
@file daemon.lua
@license The MIT License (MIT)
@author Alex <[email protected]>
@author William Fleurant <[email protected]>
@author Serg <[email protected]>
@copyright 2016 Alex
@copyright 2016 William Fleurant
@copyright 2016 Serg
--]]
local config = require("config")
local db = require("db")
local threadman = require("threadman")
local scanner = require("scanner")
local socket = require("socket")
local gateway = require("gateway")
local start = true
while start do
print("[transitd]", "starting up...")
db.prepareDatabase()
db.purge()
local gatewayEnabled = config.gateway.enabled == "yes";
-- configure gateway functionality
if gatewayEnabled then gateway.setup() end
threadman.setup()
-- start conneciton manager
threadman.startThreadInFunction('conman', 'run')
-- start shell script runner
if (config.gateway.enabled == "yes" and (config.gateway.onRegister ~= "" or config.gateway.onRelease ~= ""))
or (config.gateway.enabled ~= "yes" and (config.subscriber.onConnect ~= "" or config.subscriber.onDisconnect ~= "")) then
threadman.startThreadInFunction('shrunner', 'run')
end
-- start network scan if one hasn't already been started
scanner.startScan()
-- TODO: set up SIGTERM callback
-- send shutdown message
-- threadman.notify({type="exit"})
-- start http server
threadman.startThreadInFunction('httpd', 'run')
-- start monitor thread
threadman.startThreadInFunction('monitor', 'run')
-- wait until exit message is issued, send heartbeats
local retval = 0
local listener = threadman.registerListener("main",{"exit","error","info","config"})
while true do
local msg = "";
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
if msg["retval"] then retval = msg["retval"] end
break
end
if msg["type"] == "error" or msg["type"] == "info" then
print("[transitd]", msg["type"])
for k,v in pairs(msg) do
if k ~= "type" then
print("["..msg["type"].."]", k, v)
end
end
end
if msg["type"] == "config" then
set_config(msg.setting, msg.value)
end
end
end
if msg ~= nil and msg["type"] == "exit" then
start = msg["restart"]
break
end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
if gatewayEnabled then gateway.teardown() end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
end
print("[transitd]", "exiting.")
os.exit(retval)
|
--[[
transitd daemon main file
@file daemon.lua
@license The MIT License (MIT)
@author Alex <[email protected]>
@author William Fleurant <[email protected]>
@author Serg <[email protected]>
@copyright 2016 Alex
@copyright 2016 William Fleurant
@copyright 2016 Serg
--]]
local config = require("config")
local db = require("db")
local threadman = require("threadman")
local scanner = require("scanner")
local socket = require("socket")
local gateway = require("gateway")
local start = true
while start do
print("[transitd]", "starting up...")
db.prepareDatabase()
db.purge()
local gatewayEnabled = config.gateway.enabled == "yes";
-- configure gateway functionality
if gatewayEnabled then gateway.setup() end
threadman.setup()
-- start conneciton manager
threadman.startThreadInFunction('conman', 'run')
-- start shell script runner
if (config.gateway.enabled == "yes" and (config.gateway.onRegister ~= "" or config.gateway.onRelease ~= ""))
or (config.gateway.enabled ~= "yes" and (config.subscriber.onConnect ~= "" or config.subscriber.onDisconnect ~= "")) then
threadman.startThreadInFunction('shrunner', 'run')
end
-- start network scan if one hasn't already been started
scanner.startScan()
-- TODO: set up SIGTERM callback
-- send shutdown message
-- threadman.notify({type="exit"})
-- start http server
threadman.startThreadInFunction('httpd', 'run')
-- start monitor thread
threadman.startThreadInFunction('monitor', 'run')
-- wait until exit message is issued, send heartbeats
local retval = 0
local listener = threadman.registerListener("main",{"exit","error","info","config"})
while true do
local msg = "";
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
if msg["retval"] then retval = msg["retval"] end
break
end
if msg["type"] == "error" or msg["type"] == "info" then
print("[transitd]", msg["type"])
for k,v in pairs(msg) do
if k ~= "type" then
if type(v) == "table" then v = cjson_safe.encode(v) end
print("["..msg["type"].."]", k, v)
end
end
end
if msg["type"] == "config" then
set_config(msg.setting, msg.value)
end
end
end
if msg ~= nil and msg["type"] == "exit" then
start = msg["restart"]
break
end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
if gatewayEnabled then gateway.teardown() end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
end
print("[transitd]", "exiting.")
os.exit(retval)
|
Small fix
|
Small fix
|
Lua
|
mit
|
pdxmeshnet/mnigs,pdxmeshnet/mnigs,intermesh-networks/transitd,transitd/transitd,intermesh-networks/transitd,transitd/transitd,transitd/transitd
|
41eccd4ca6fe51f8174dd43744e7a4bab4daf2cb
|
src/luarocks/new_version.lua
|
src/luarocks/new_version.lua
|
--- Module implementing the LuaRocks "new_version" command.
-- Utility function that writes a new rockspec, updating data from a previous one.
local new_version = {}
local util = require("luarocks.util")
local download = require("luarocks.download")
local fetch = require("luarocks.fetch")
local persist = require("luarocks.persist")
local fs = require("luarocks.fs")
local type_check = require("luarocks.type_check")
util.add_run_function(new_version)
new_version.help_summary = "Auto-write a rockspec for a new version of a rock."
new_version.help_arguments = "[--tag=<tag>] [<package>|<rockspec>] [<new_version>] [<new_url>]"
new_version.help = [[
This is a utility function that writes a new rockspec, updating data
from a previous one.
If a package name is given, it downloads the latest rockspec from the
default server. If a rockspec is given, it uses it instead. If no argument
is given, it looks for a rockspec same way 'luarocks make' does.
If the version number is not given and tag is passed using --tag,
it is used as the version, with 'v' removed from beginning.
Otherwise, it only increments the revision number of the given
(or downloaded) rockspec.
If a URL is given, it replaces the one from the old rockspec with the
given URL. If a URL is not given and a new version is given, it tries
to guess the new URL by replacing occurrences of the version number
in the URL or tag. It also tries to download the new URL to determine
the new MD5 checksum.
If a tag is given, it replaces the one from the old rockspec. If there is
an old tag but no new one passed, it is guessed in the same way URL is.
WARNING: it writes the new rockspec to the current directory,
overwriting the file if it already exists.
]]
local function try_replace(tbl, field, old, new)
if not tbl[field] then
return false
end
local old_field = tbl[field]
local new_field = tbl[field]:gsub(old, new)
if new_field ~= old_field then
util.printout("Guessing new '"..field.."' field as "..new_field)
tbl[field] = new_field
return true
end
return false
end
-- Try to download source file using URL from a rockspec.
-- If it specified MD5, update it.
-- @return (true, false) if MD5 was not specified or it stayed same,
-- (true, true) if MD5 changed, (nil, string) on error.
local function check_url_and_update_md5(out_rs)
local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_rs.package)
if not file then
util.printerr("Warning: invalid URL - "..temp_dir)
return true, false
end
local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, out_rs.source.url, out_rs.source.dir)
if not inferred_dir then
return nil, found_dir
end
if found_dir and found_dir ~= inferred_dir then
out_rs.source.dir = found_dir
end
if file then
if out_rs.source.md5 then
util.printout("File successfully downloaded. Updating MD5 checksum...")
local new_md5, err = fs.get_md5(file)
if not new_md5 then
return nil, err
end
local old_md5 = out_rs.source.md5
out_rs.source.md5 = new_md5
return true, new_md5 ~= old_md5
else
util.printout("File successfully downloaded.")
return true, false
end
end
end
local function update_source_section(out_rs, url, tag, old_ver, new_ver)
if tag then
out_rs.source.tag = tag
end
if url then
out_rs.source.url = url
return check_url_and_update_md5(out_rs)
end
if new_ver == old_ver then
return true
end
if out_rs.source.dir then
try_replace(out_rs.source, "dir", old_ver, new_ver)
end
if out_rs.source.file then
try_replace(out_rs.source, "file", old_ver, new_ver)
end
if try_replace(out_rs.source, "url", old_ver, new_ver) then
return check_url_and_update_md5(out_rs)
end
if tag or try_replace(out_rs.source, "tag", old_ver, new_ver) then
return true
end
-- Couldn't replace anything significant, use the old URL.
local ok, md5_changed = check_url_and_update_md5(out_rs)
if not ok then
return nil, md5_changed
end
if md5_changed then
util.printerr("Warning: URL is the same, but MD5 has changed. Old rockspec is broken.")
end
return true
end
function new_version.command(flags, input, version, url)
if not input then
local err
input, err = util.get_default_rockspec()
if not input then
return nil, err
end
end
assert(type(input) == "string")
local filename = input
if not input:match("rockspec$") then
local err
filename, err = download.download("rockspec", input)
if not filename then
return nil, err
end
end
local valid_rs, err = fetch.load_rockspec(filename)
if not valid_rs then
return nil, err
end
local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$")
local new_ver, new_rev
if flags.tag and not version then
version = flags.tag:gsub("^v", "")
end
if version then
new_ver, new_rev = version:match("(.*)%-(%d+)$")
new_rev = tonumber(new_rev)
if not new_rev then
new_ver = version
new_rev = 1
end
else
new_ver = old_ver
new_rev = tonumber(old_rev) + 1
end
local new_rockver = new_ver:gsub("-", "")
local out_rs = persist.load_into_table(filename)
local out_name = out_rs.package:lower()
out_rs.version = new_rockver.."-"..new_rev
local ok, err = update_source_section(out_rs, url, flags.tag, old_ver, new_ver)
if not ok then return nil, err end
if out_rs.build and out_rs.build.type == "module" then
out_rs.build.type = "builtin"
end
local out_filename = out_name.."-"..new_rockver.."-"..new_rev..".rockspec"
persist.save_from_table(out_filename, out_rs, type_check.rockspec_order)
util.printout("Wrote "..out_filename)
local valid_out_rs, err = fetch.load_local_rockspec(out_filename)
if not valid_out_rs then
return nil, "Failed loading generated rockspec: "..err
end
return true
end
return new_version
|
--- Module implementing the LuaRocks "new_version" command.
-- Utility function that writes a new rockspec, updating data from a previous one.
local new_version = {}
local util = require("luarocks.util")
local download = require("luarocks.download")
local fetch = require("luarocks.fetch")
local persist = require("luarocks.persist")
local fs = require("luarocks.fs")
local type_check = require("luarocks.type_check")
util.add_run_function(new_version)
new_version.help_summary = "Auto-write a rockspec for a new version of a rock."
new_version.help_arguments = "[--tag=<tag>] [<package>|<rockspec>] [<new_version>] [<new_url>]"
new_version.help = [[
This is a utility function that writes a new rockspec, updating data
from a previous one.
If a package name is given, it downloads the latest rockspec from the
default server. If a rockspec is given, it uses it instead. If no argument
is given, it looks for a rockspec same way 'luarocks make' does.
If the version number is not given and tag is passed using --tag,
it is used as the version, with 'v' removed from beginning.
Otherwise, it only increments the revision number of the given
(or downloaded) rockspec.
If a URL is given, it replaces the one from the old rockspec with the
given URL. If a URL is not given and a new version is given, it tries
to guess the new URL by replacing occurrences of the version number
in the URL or tag. It also tries to download the new URL to determine
the new MD5 checksum.
If a tag is given, it replaces the one from the old rockspec. If there is
an old tag but no new one passed, it is guessed in the same way URL is.
WARNING: it writes the new rockspec to the current directory,
overwriting the file if it already exists.
]]
local function try_replace(tbl, field, old, new)
if not tbl[field] then
return false
end
local old_field = tbl[field]
local new_field = tbl[field]:gsub(old, new)
if new_field ~= old_field then
util.printout("Guessing new '"..field.."' field as "..new_field)
tbl[field] = new_field
return true
end
return false
end
-- Try to download source file using URL from a rockspec.
-- If it specified MD5, update it.
-- @return (true, false) if MD5 was not specified or it stayed same,
-- (true, true) if MD5 changed, (nil, string) on error.
local function check_url_and_update_md5(out_rs)
local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_rs.package)
if not file then
util.printerr("Warning: invalid URL - "..temp_dir)
return true, false
end
local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, out_rs.source.url, out_rs.source.dir)
if not inferred_dir then
return nil, found_dir
end
if found_dir and found_dir ~= inferred_dir then
out_rs.source.dir = found_dir
end
if file then
if out_rs.source.md5 then
util.printout("File successfully downloaded. Updating MD5 checksum...")
local new_md5, err = fs.get_md5(file)
if not new_md5 then
return nil, err
end
local old_md5 = out_rs.source.md5
out_rs.source.md5 = new_md5
return true, new_md5 ~= old_md5
else
util.printout("File successfully downloaded.")
return true, false
end
end
end
local function update_source_section(out_rs, url, tag, old_ver, new_ver)
if tag then
out_rs.source.tag = tag
end
if url then
out_rs.source.url = url
return check_url_and_update_md5(out_rs)
end
if new_ver == old_ver then
return true
end
if out_rs.source.dir then
try_replace(out_rs.source, "dir", old_ver, new_ver)
end
if out_rs.source.file then
try_replace(out_rs.source, "file", old_ver, new_ver)
end
if try_replace(out_rs.source, "url", old_ver, new_ver) then
return check_url_and_update_md5(out_rs)
end
if tag or try_replace(out_rs.source, "tag", old_ver, new_ver) then
return true
end
-- Couldn't replace anything significant, use the old URL.
local ok, md5_changed = check_url_and_update_md5(out_rs)
if not ok then
return nil, md5_changed
end
if md5_changed then
util.printerr("Warning: URL is the same, but MD5 has changed. Old rockspec is broken.")
end
return true
end
function new_version.command(flags, input, version, url)
if not input then
local err
input, err = util.get_default_rockspec()
if not input then
return nil, err
end
end
assert(type(input) == "string")
local filename, err
if input:match("rockspec$") then
filename, err = fetch.fetch_url(input)
if not filename then
return nil, err
end
else
filename, err = download.download("rockspec", input)
if not filename then
return nil, err
end
end
local valid_rs, err = fetch.load_rockspec(filename)
if not valid_rs then
return nil, err
end
local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$")
local new_ver, new_rev
if flags.tag and not version then
version = flags.tag:gsub("^v", "")
end
if version then
new_ver, new_rev = version:match("(.*)%-(%d+)$")
new_rev = tonumber(new_rev)
if not new_rev then
new_ver = version
new_rev = 1
end
else
new_ver = old_ver
new_rev = tonumber(old_rev) + 1
end
local new_rockver = new_ver:gsub("-", "")
local out_rs, err = persist.load_into_table(filename)
local out_name = out_rs.package:lower()
out_rs.version = new_rockver.."-"..new_rev
local ok, err = update_source_section(out_rs, url, flags.tag, old_ver, new_ver)
if not ok then return nil, err end
if out_rs.build and out_rs.build.type == "module" then
out_rs.build.type = "builtin"
end
local out_filename = out_name.."-"..new_rockver.."-"..new_rev..".rockspec"
persist.save_from_table(out_filename, out_rs, type_check.rockspec_order)
util.printout("Wrote "..out_filename)
local valid_out_rs, err = fetch.load_local_rockspec(out_filename)
if not valid_out_rs then
return nil, "Failed loading generated rockspec: "..err
end
return true
end
return new_version
|
Fix crash when given a remote rockspec.
|
Fix crash when given a remote rockspec.
|
Lua
|
mit
|
luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,keplerproject/luarocks,xpol/luavm,robooo/luarocks,robooo/luarocks,xpol/luavm,keplerproject/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luavm,tarantool/luarocks,xpol/luainstaller,xpol/luarocks,robooo/luarocks,xpol/luainstaller,xpol/luarocks,xpol/luainstaller,xpol/luavm,xpol/luarocks,xpol/luavm,luarocks/luarocks,xpol/luarocks,luarocks/luarocks,tarantool/luarocks,xpol/luainstaller
|
e4a807db741c48710fdb63161a3aa1ac9b2fba7b
|
script/c80600046.lua
|
script/c80600046.lua
|
--CNo.96 ブラック・ストーム
function c80600046.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_DARK),3),4)
c:EnableReviveLimit()
--battle
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE)
e1:SetValue(1)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--atk u/d
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(80600046,1))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_ATTACK_ANNOUNCE)
e3:SetCountLimit(1)
e3:SetCondition(c80600046.atkcon)
e3:SetCost(c80600046.atkcost)
e3:SetTarget(c80600046.atktg)
e3:SetOperation(c80600046.atkop)
c:RegisterEffect(e3)
end
function c80600046.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,55727845)
end
function c80600046.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c80600046.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
local at=Duel.GetAttackTarget()
if chk==0 then return ((at and at:IsFaceup() and Duel.GetAttacker()==e:GetHandler()) or at==e:GetHandler())
and not e:GetHandler():IsStatus(STATUS_CHAINING) end
Duel.SetTargetCard(e:GetHandler():GetBattleTarget())
end
function c80600046.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and c:IsFaceup() and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local atk=tc:GetAttack()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(0)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(atk)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
end
end
|
--CNo.96 ブラック・ストーム
function c80600046.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_DARK),3),4)
c:EnableReviveLimit()
--battle
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PRE_BATTLE_DAMAGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c80600046.damcon)
e1:SetOperation(c80600046.damop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--atk u/d
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(80600046,1))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_ATTACK_ANNOUNCE)
e3:SetCountLimit(1)
e3:SetCondition(c80600046.atkcon)
e3:SetCost(c80600046.atkcost)
e3:SetTarget(c80600046.atktg)
e3:SetOperation(c80600046.atkop)
c:RegisterEffect(e3)
end
function c80600046.damcon(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler()
return ec and ep==tp and (Duel.GetAttacker()==ec or Duel.GetAttackTarget()==ec)
end
function c80600046.damop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeBattleDamage(1-tp,ev,false)
end
function c80600046.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,55727845)
end
function c80600046.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c80600046.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
local at=Duel.GetAttackTarget()
if chk==0 then return ((at and at:IsFaceup() and Duel.GetAttacker()==e:GetHandler()) or at==e:GetHandler())
and not e:GetHandler():IsStatus(STATUS_CHAINING) end
Duel.SetTargetCard(e:GetHandler():GetBattleTarget())
end
function c80600046.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and c:IsFaceup() and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local atk=tc:GetAttack()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(0)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(atk)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
end
end
|
fix
|
fix
fixed controller not receving battle damage
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher
|
ba18cd806ad3b1d05fce1b1eaa4c70f0a576551b
|
lualib/sys/db/redis.lua
|
lualib/sys/db/redis.lua
|
local dispatch = require "sys.socketdispatch"
local type = type
local assert = assert
local tostring = tostring
local tonumber = tonumber
local tinsert = table.insert
local tunpack = table.unpack
local tconcat = table.concat
local sub = string.sub
local upper = string.upper
local format = string.format
local redis = {}
local redis_mt = { __index = redis }
local header = "+-:*$"
local response_header = {}
response_header[header:byte(1)] = function (sock, res) --'+'
return true, res
end
response_header[header:byte(2)] = function (sock, res) --'-'
return false, res
end
response_header[header:byte(3)] = function (sock, res) --':'
return true, tonumber(res)
end
response_header[header:byte(5)] = function (sock, res) --'$'
local nr = tonumber(res)
if nr < 0 then
return true, nil
end
local param = sock:read(nr + 2)
return true, sub(param, 1, -3)
end
local function read_response(sock)
local data = sock:readline("\r\n")
local head = data:byte(1)
local func = response_header[head]
return func(sock, sub(data, 2))
end
response_header[header:byte(4)] = function (sock, res) --'*'
local nr = tonumber(res)
if nr < 0 then
return true, nil
end
local cmd_success = true
local cmd_res = {}
for i = 1, nr do
local success, data = read_response(sock)
cmd_success = cmd_success and success
tinsert(cmd_res, data)
end
return cmd_success, cmd_res
end
local function cache_(func)
return setmetatable({}, { mode = "kv", __index = func })
end
local cache_head = cache_(function (self, key)
local s = format("*%d", key)
self[key] = s
return s
end)
local cache_count = cache_(function (self, key)
local s = format("\r\n$%d\r\n", key)
self[key] = s
return s
end)
local function pack_cmd(cmd, param)
assert(type(param) == "table")
local count = #param
local lines = {
cache_head[count + 1],
cache_count[#cmd],
cmd,
}
local idx = 4
for i = 1, count do
local v = tostring(param[i])
lines[idx] = cache_count[#v]
idx = idx + 1
lines[idx] = v
idx = idx + 1
end
lines[idx] = "\r\n"
return lines
end
local function pack_table(cmd, out)
local len = #cmd
local oi = #out + 1
out[oi] = cache_head[len]
oi = oi + 1
for i = 1, len do
local v = tostring(cmd[i])
out[oi] = cache_count[#v]
oi = oi + 1
out[oi] = v
oi = oi + 1
end
out[oi] = "\r\n"
end
local function redis_login(auth, db)
if not auth and not db then
return
end
return function(sock)
local ok, err
if auth then
local req = format("AUTH %s\r\n", auth)
ok, err = sock:request(req, read_response)
if not ok then
return ok, err
end
end
if db then
local req = format("SELECT %s\r\n", db)
ok, err = sock:request(req, read_response)
if not ok then
return ok, err
end
end
return true
end
end
function redis:connect(config)
local obj = {
sock = dispatch:create {
addr = config.addr,
auth = redis_login(config.auth, config.db)
},
}
obj.sock:connect()
return setmetatable(obj, redis_mt)
end
function redis:select()
assert(~"please specify the dbid when redis:create")
end
setmetatable(redis, {__index = function (self, k)
local cmd = upper(k)
local f = function (self, p1, ...)
local sock = self.sock
local str
if type(p1) == "table" then
str = pack_cmd(cmd, p1)
else
str = pack_cmd(cmd, {p1, ...})
end
return sock:request(str, read_response)
end
self[k] = f
return f
end
})
function redis:pipeline(req, ret)
local out = {}
local cmd_len = #req
for i = 1, cmd_len do
pack_table(req[i], out)
end
local read
if not ret then
return self.sock:request(out, function(sock)
local ok, res
for i = 1, cmd_len do
ok, res = read_response(sock)
end
return ok, res
end)
else
return self.sock:request(out, function(sock)
local ok, res
local j = 0
for i = 1, cmd_len do
ok, res = read_response(sock)
j = j + 1
ret[j] = ok
j = j + 1
ret[j] = res
end
return true, j
end)
end
end
return redis
|
local dispatch = require "sys.socketdispatch"
local type = type
local assert = assert
local tostring = tostring
local tonumber = tonumber
local tinsert = table.insert
local tunpack = table.unpack
local tconcat = table.concat
local sub = string.sub
local upper = string.upper
local format = string.format
local redis = {}
local redis_mt = { __index = redis }
local header = "+-:*$"
local response_header = {}
response_header[header:byte(1)] = function (sock, res) --'+'
return true, res
end
response_header[header:byte(2)] = function (sock, res) --'-'
return false, res
end
response_header[header:byte(3)] = function (sock, res) --':'
return true, tonumber(res)
end
response_header[header:byte(5)] = function (sock, res) --'$'
local nr = tonumber(res)
if nr < 0 then
return true, nil
end
local param = sock:read(nr + 2)
return true, sub(param, 1, -3)
end
local function read_response(sock)
local data = sock:readline("\r\n")
local head = data:byte(1)
local func = response_header[head]
return func(sock, sub(data, 2))
end
response_header[header:byte(4)] = function (sock, res) --'*'
local nr = tonumber(res)
if nr < 0 then
return true, nil
end
local cmd_success = true
local cmd_res = {}
for i = 1, nr do
local success, data = read_response(sock)
cmd_success = cmd_success and success
cmd_res[i] = data
end
return cmd_success, cmd_res
end
local function cache_(func)
return setmetatable({}, { mode = "kv", __index = func })
end
local cache_head = cache_(function (self, key)
local s = format("*%d", key)
self[key] = s
return s
end)
local cache_count = cache_(function (self, key)
local s = format("\r\n$%d\r\n", key)
self[key] = s
return s
end)
local function compose(cmd, param)
assert(type(param) == "table")
local count = #param
local lines = {
cache_head[count + 1],
cache_count[#cmd],
cmd,
}
local idx = 4
for i = 1, count do
local v = tostring(param[i])
lines[idx] = cache_count[#v]
idx = idx + 1
lines[idx] = v
idx = idx + 1
end
lines[idx] = "\r\n"
return lines
end
local function composetable(cmd, out)
local len = #cmd
local oi = #out + 1
out[oi] = cache_head[len]
oi = oi + 1
for i = 1, len do
local v = tostring(cmd[i])
out[oi] = cache_count[#v]
oi = oi + 1
out[oi] = v
oi = oi + 1
end
out[oi] = "\r\n"
end
local function redis_login(auth, db)
if not auth and not db then
return
end
return function(sock)
local ok, err
if auth then
local req = format("AUTH %s\r\n", auth)
ok, err = sock:request(req, read_response)
if not ok then
return ok, err
end
end
if db then
local req = format("SELECT %s\r\n", db)
ok, err = sock:request(req, read_response)
if not ok then
return ok, err
end
end
return true
end
end
function redis:connect(config)
local obj = {
sock = dispatch:create {
addr = config.addr,
auth = redis_login(config.auth, config.db)
},
}
obj.sock:connect()
return setmetatable(obj, redis_mt)
end
function redis:select()
assert(~"please specify the dbid when redis:create")
end
setmetatable(redis, {__index = function (self, k)
local cmd = upper(k)
local f = function (self, p1, ...)
local sock = self.sock
local str
if type(p1) == "table" then
str = compose(cmd, p1)
else
str = compose(cmd, {p1, ...})
end
return sock:request(str, read_response)
end
self[k] = f
return f
end
})
function redis:pipeline(req, ret)
local out = {}
local cmd_len = #req
for i = 1, cmd_len do
composetable(req[i], out)
end
local read
if not ret then
return self.sock:request(out, function(sock)
local ok, res
for i = 1, cmd_len do
ok, res = read_response(sock)
end
return ok, res
end)
else
return self.sock:request(out, function(sock)
local ok, res
local j = 0
for i = 1, cmd_len do
ok, res = read_response(sock)
j = j + 1
ret[j] = ok
j = j + 1
ret[j] = res
end
return true, j
end)
end
end
return redis
|
bugfix redis null element in arrays
|
bugfix redis null element in arrays
|
Lua
|
mit
|
findstr/silly
|
d52158855af0cf214ff24a8aa06a738166b58661
|
src/lua/snabb-shm.lua
|
src/lua/snabb-shm.lua
|
#!/usr/bin/env luajit
-- Copyright 2012 Snabb Gmbh.
local ffi = require("ffi")
local fabric = ffi.load("fabric")
ffi.cdef(io.open("/home/luke/hacking/QEMU/net/snabb-shm-dev.h"):read("*a"))
ffi.cdef(io.open("/home/luke/hacking/snabb-fabric/src/c/fabric.h"):read("*a"))
print("loaded ffi'ery")
print(ffi.sizeof("struct snabb_shm_dev"))
local shm = fabric.open_shm("/tmp/ba");
-- shm.tx_head = ffi.C.SHM_RING_SIZE
print(shm.magic)
-- shm.tx_head = 0
print("head = " .. shm.tx_head .. " tail = " .. shm.tx_tail)
-- Print availability
print("available = " .. shm.tx_tail - shm.tx_head)
-- Print size of first packet
print("size[" .. shm.tx_head .. "] = " .. shm.tx_ring[shm.tx_head].length)
shm.tx_head = shm.tx_head + 1
-- Dump a packet out as pcap
ffi.cdef[[
struct pcap {
/* file header */
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
/* record header */
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
}
]]
local pcap = ffi.new("struct pcap")
pcap.magic_number = 0xa1b2c3d4
pcap.version_major = 2
pcap.version_minor = 4
pcap.snaplen = 65535
pcap.network = 1
pcap.incl_len = shm.tx_ring[shm.tx_head].length
pcap.orig_len = pcap.incl_len
print("writing pcap file..")
io.output("/tmp/x.pcap", "w")
io.write(ffi.string(pcap, ffi.sizeof(pcap)))
io.write(ffi.string(shm.tx_ring[shm.tx_head].data, shm.tx_ring[shm.tx_head].length))
io.close()
|
#!/usr/bin/env luajit
-- Copyright 2012 Snabb Gmbh.
local ffi = require("ffi")
local C = ffi.C
local fabric = ffi.load("fabric")
ffi.cdef(io.open("/home/luke/hacking/QEMU/net/snabb-shm-dev.h"):read("*a"))
ffi.cdef(io.open("/home/luke/hacking/snabb-fabric/src/c/fabric.h"):read("*a"))
print("loaded ffi'ery")
print(ffi.sizeof("struct snabb_shm_dev"))
local shm = fabric.open_shm("/tmp/ba");
-- Return true if `shm' is a valid shared memory packet device.
function check_shm_file (shm)
return shm.magic == 0x57ABB000 and shm.version == 1
end
-- Return true if a packet is available.
function available (shm)
return shm.tx_tail ~= shm.tx_head + 1 % C.SHM_RING_SIZE
end
-- Return the current shm_packet in the ring.
function packet (shm)
return shm.tx_ring[shm.tx_head]
end
-- Advance to the next packet in the ring.
function next (shm)
shm.tx_head = (shm.tx_head + 1) % C.SHM_RING_SIZE
end
-- shm.tx_head = C.SHM_RING_SIZE
print("Ring valid: " .. tostring(check_shm_file(shm)))
-- shm.tx_head = 0
print("head = " .. shm.tx_head .. " tail = " .. shm.tx_tail)
-- Print availability
print("available: " .. tostring(available(shm)))
-- Print size of first packet
print("size[" .. shm.tx_head .. "] = " .. packet(shm).length)
next(shm)
-- Dump a packet out as pcap
ffi.cdef[[
struct pcap_file {
/* file header */
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
}
struct pcap_record {
/* record header */
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
}
]]
local pcap_file = ffi.new("struct pcap_file")
pcap_file.magic_number = 0xa1b2c3d4
pcap_file.version_major = 2
pcap_file.version_minor = 4
pcap_file.snaplen = 65535
pcap_file.network = 1
print("writing pcap file..")
file = io.open("/tmp/x.pcap", "w")
file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file)))
local pcap_record = ffi.new("struct pcap_record")
while true do
if available(shm) then
print("Writing a " .. packet(shm).length .. " byte packet..")
io.flush()
pcap_record.incl_len = shm.tx_ring[shm.tx_head].length
pcap_record.orig_len = pcap_record.incl_len
file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record)))
file:write(ffi.string(shm.tx_ring[shm.tx_head].data, shm.tx_ring[shm.tx_head].length))
file:flush()
next(shm)
else
print("nuthin' doin' " .. shm.tx_head .. " " .. shm.tx_tail)
end
end
file:close()
|
snabb-shm: Now continuously dumping packets to a pcap file. (Buggy.)
|
snabb-shm: Now continuously dumping packets to a pcap file. (Buggy.)
|
Lua
|
apache-2.0
|
andywingo/snabbswitch,dwdm/snabbswitch,lukego/snabb,lukego/snabbswitch,kellabyte/snabbswitch,dpino/snabb,Igalia/snabbswitch,virtualopensystems/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,wingo/snabb,aperezdc/snabbswitch,SnabbCo/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,snabbco/snabb,lukego/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,Igalia/snabbswitch,virtualopensystems/snabbswitch,aperezdc/snabbswitch,hb9cwp/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,pavel-odintsov/snabbswitch,mixflowtech/logsensor,Igalia/snabb,alexandergall/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,pirate/snabbswitch,dpino/snabb,javierguerragiraldez/snabbswitch,fhanik/snabbswitch,xdel/snabbswitch,dpino/snabb,snabbco/snabb,kellabyte/snabbswitch,heryii/snabb,alexandergall/snabbswitch,justincormack/snabbswitch,kellabyte/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,lukego/snabb,wingo/snabbswitch,andywingo/snabbswitch,dwdm/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,andywingo/snabbswitch,lukego/snabb,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,dpino/snabb,alexandergall/snabbswitch,javierguerragiraldez/snabbswitch,xdel/snabbswitch,fhanik/snabbswitch,eugeneia/snabb,hb9cwp/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,snabbco/snabb,Igalia/snabb,aperezdc/snabbswitch,snabbnfv-goodies/snabbswitch,wingo/snabb,justincormack/snabbswitch,heryii/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,heryii/snabb,wingo/snabb,lukego/snabb,snabbnfv-goodies/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,snabbco/snabb,dpino/snabbswitch,andywingo/snabbswitch,heryii/snabb,virtualopensystems/snabbswitch,Igalia/snabb,kbara/snabb,kbara/snabb,fhanik/snabbswitch,wingo/snabbswitch,Igalia/snabb,lukego/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,wingo/snabb,kbara/snabb,wingo/snabb,Igalia/snabb,plajjan/snabbswitch,eugeneia/snabbswitch,dpino/snabbswitch,wingo/snabbswitch,pirate/snabbswitch,justincormack/snabbswitch,heryii/snabb,dpino/snabbswitch,mixflowtech/logsensor,kbara/snabb,kbara/snabb,lukego/snabbswitch,snabbco/snabb,pirate/snabbswitch,wingo/snabb,alexandergall/snabbswitch,justincormack/snabbswitch,hb9cwp/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabb,wingo/snabbswitch,eugeneia/snabb,aperezdc/snabbswitch,xdel/snabbswitch,eugeneia/snabb,dpino/snabb,pavel-odintsov/snabbswitch,dwdm/snabbswitch,dpino/snabb,Igalia/snabbswitch,kbara/snabb
|
2138ed6593ba52e5cf56316705321b16d424ad67
|
content/gatheringcraft/stonecutting.lua
|
content/gatheringcraft/stonecutting.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- no static tool
-- Chisel ( 737 )
-- raw stones (735) --> stone blocks
-- stone blocks (733) --> small stones (1266)
local common = require("base.common")
local gathering = require("content.gathering")
module("content.gatheringcraft.stonecutting", package.seeall)
function StartGathering(User, SourceItem, ltstate)
gathering.InitGathering();
local stonecutting = gathering.stonecutting;
-- we have to distinguish if we work on raw stones or stone blocks
-- otherwise we would not be able to detect when to stop working on raw stones and the script would continue to work on stone blocks
local WorkOnStone = {}; -- an array that holds the id of the item we're working on for each user
local Stones = {};
Stones[735] = {};
Stones[735].productId = 733;
Stones[735].amount = 1;
Stones[735].nameDE = "rohen Steine";
Stones[735].nameEN = "raw stones";
Stones[733] = {};
Stones[733].productId = 1266;
Stones[733].amount = 10;
Stones[733].nameDE = "Steinquader";
Stones[733].nameEN = "stone blocks";
common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
User:talk(Character.say, "#me unterbricht "..common.GetGenderText(User, "seine", "ihre").." Arbeit.", "#me interrupts "..common.GetGenderText(User, "his", "her").." work.")
return
end
-- if not common.CheckItem( User, SourceItem ) then -- security check
-- return
-- end
-- additional tool item is needed
if (User:countItemAt("all",737)==0) then
common.HighInformNLS( User,
"Du brauchst einen Meiel um Steine zu behauen.",
"You need a chisel for cutting stone." );
return
end
local toolItem = User:getItemAt(5);
if ( toolItem.id ~= 737 ) then
toolItem = User:getItemAt(6);
if ( toolItem.id ~= 737 ) then
common.HighInformNLS( User,
"Du musst den Meiel in der Hand haben!",
"You have to hold the chisel in your hand!" );
return
end
end
if not common.FitForWork( User ) then -- check minimal food points
return
end
-- any other checks?
if (User:countItemAt("all",733)==0 and User:countItemAt("all",735)==0) then -- check for items to work on
common.HighInformNLS( User,
"Du brauchst rohe Steine oder Steinquader um sie zu behauen.",
"You need raw stones or stone blocks for cutting them." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
stonecutting.SavedWorkTime[User.id] = stonecutting:GenWorkTime(User, toolItem);
User:startAction( stonecutting.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talk(Character.say, "#me beginnt Steine zu behauen.", "#me starts to cut stones.")
-- save the item we're working on
if ( User:countItemAt("all",735) > 0 ) then
WorkOnStone[User.id] = 735; -- if there are raw stones, we work on those
else
WorkOnStone[User.id] = 733; -- no raw stones? Then there must be stone blocks
end
return
end
-- since we're here, we're working
-- But do we still have the stone type we're really working on?
if ( User:countItemAt("all",WorkOnStone[User.id]) == 0 ) then
common.HighInformNLS( User,
"Du hast keine " .. Stones[WorkOnStone[User.id]].nameDE .. " mehr.",
"You have no " .. Stones[WorkOnStone[User.id]].nameEN .. " anymore." );
return;
end
if stonecutting:FindRandomItem(User) then
return
end
User:learn( stonecutting.LeadSkill, stonecutting.SavedWorkTime[User.id], stonecutting.LearnLimit);
User:eraseItem( WorkOnStone[User.id], 1 ); -- erase the item we're working on
local notCreated = User:createItem( Stones[WorkOnStone[User.id]].productId, Stones[WorkOnStone[User.id]].amount, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( Stones[WorkOnStone[User.id]].productId, notCreated, User.pos, true, 333, nil );
common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
if (User:countItemAt("all",WorkOnStone[User.id])>0) then -- there are still items we can work on
stonecutting.SavedWorkTime[User.id] = stonecutting:GenWorkTime(User, toolItem);
User:startAction( stonecutting.SavedWorkTime[User.id], 0, 0, 0, 0);
else -- no items left
common.HighInformNLS( User,
"Du hast keine " .. Stones[WorkOnStone[User.id]].nameDE .. " mehr.",
"You have no " .. Stones[WorkOnStone[User.id]].nameEN .. " anymore." );
end
end
if common.GatheringToolBreaks( User, toolItem, stonecutting:GenWorkTime(User, toolItem) ) then -- damage and possibly break the tool
common.HighInformNLS(User,
"Dein alter Meiel zerbricht.",
"Your old chisel breaks.");
return
end
end
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- no static tool
-- Chisel ( 737 )
-- raw stones (735) --> stone blocks
-- stone blocks (733) --> small stones (1266)
local common = require("base.common")
local gathering = require("content.gathering")
module("content.gatheringcraft.stonecutting", package.seeall)
local WorkOnStone = {} -- an array that holds the id of the item we're working on for each user
function StartGathering(User, SourceItem, ltstate)
gathering.InitGathering();
local stonecutting = gathering.stonecutting;
-- we have to distinguish if we work on raw stones or stone blocks
-- otherwise we would not be able to detect when to stop working on raw stones and the script would continue to work on stone blocks
local Stones = {};
Stones[735] = {};
Stones[735].productId = 733;
Stones[735].amount = 1;
Stones[735].nameDE = "rohen Steine";
Stones[735].nameEN = "raw stones";
Stones[733] = {};
Stones[733].productId = 1266;
Stones[733].amount = 10;
Stones[733].nameDE = "Steinquader";
Stones[733].nameEN = "stone blocks";
common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
User:talk(Character.say, "#me unterbricht "..common.GetGenderText(User, "seine", "ihre").." Arbeit.", "#me interrupts "..common.GetGenderText(User, "his", "her").." work.")
return
end
-- if not common.CheckItem( User, SourceItem ) then -- security check
-- return
-- end
-- additional tool item is needed
if (User:countItemAt("all",737)==0) then
common.HighInformNLS( User,
"Du brauchst einen Meiel um Steine zu behauen.",
"You need a chisel for cutting stone." );
return
end
local toolItem = User:getItemAt(5);
if ( toolItem.id ~= 737 ) then
toolItem = User:getItemAt(6);
if ( toolItem.id ~= 737 ) then
common.HighInformNLS( User,
"Du musst den Meiel in der Hand haben!",
"You have to hold the chisel in your hand!" );
return
end
end
if not common.FitForWork( User ) then -- check minimal food points
return
end
-- any other checks?
if (User:countItemAt("all",733)==0 and User:countItemAt("all",735)==0) then -- check for items to work on
common.HighInformNLS( User,
"Du brauchst rohe Steine oder Steinquader um sie zu behauen.",
"You need raw stones or stone blocks for cutting them." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
stonecutting.SavedWorkTime[User.id] = stonecutting:GenWorkTime(User, toolItem);
User:startAction( stonecutting.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talk(Character.say, "#me beginnt Steine zu behauen.", "#me starts to cut stones.")
-- save the item we're working on
if ( User:countItemAt("all",735) > 0 ) then
WorkOnStone[User.id] = 735; -- if there are raw stones, we work on those
else
WorkOnStone[User.id] = 733; -- no raw stones? Then there must be stone blocks
end
return
end
-- since we're here, we're working
-- But do we still have the stone type we're really working on?
if ( User:countItemAt("all",WorkOnStone[User.id]) == 0 ) then
common.HighInformNLS( User,
"Du hast keine " .. Stones[WorkOnStone[User.id]].nameDE .. " mehr.",
"You have no " .. Stones[WorkOnStone[User.id]].nameEN .. " anymore." );
return;
end
if stonecutting:FindRandomItem(User) then
return
end
User:learn( stonecutting.LeadSkill, stonecutting.SavedWorkTime[User.id], stonecutting.LearnLimit);
User:eraseItem( WorkOnStone[User.id], 1 ); -- erase the item we're working on
local notCreated = User:createItem( Stones[WorkOnStone[User.id]].productId, Stones[WorkOnStone[User.id]].amount, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( Stones[WorkOnStone[User.id]].productId, notCreated, User.pos, true, 333, nil );
common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
if (User:countItemAt("all",WorkOnStone[User.id])>0) then -- there are still items we can work on
stonecutting.SavedWorkTime[User.id] = stonecutting:GenWorkTime(User, toolItem);
User:startAction( stonecutting.SavedWorkTime[User.id], 0, 0, 0, 0);
else -- no items left
common.HighInformNLS( User,
"Du hast keine " .. Stones[WorkOnStone[User.id]].nameDE .. " mehr.",
"You have no " .. Stones[WorkOnStone[User.id]].nameEN .. " anymore." );
end
end
if common.GatheringToolBreaks( User, toolItem, stonecutting:GenWorkTime(User, toolItem) ) then -- damage and possibly break the tool
common.HighInformNLS(User,
"Dein alter Meiel zerbricht.",
"Your old chisel breaks.");
return
end
end
|
fix #0010734
|
fix #0010734
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content
|
0e9d8e7ac35755835e016eb4912ac367e1b49078
|
SVUI_Skins/components/blizzard/macro.lua
|
SVUI_Skins/components/blizzard/macro.lua
|
--[[
##############################################################################
S V U I By: Failcoder
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
HELPERS
##########################################################
]]--
local MacroButtonList = {
"MacroSaveButton", "MacroCancelButton", "MacroDeleteButton", "MacroNewButton", "MacroExitButton", "MacroEditButton", "MacroFrameTab1", "MacroFrameTab2", "MacroPopupOkayButton", "MacroPopupCancelButton"
}
local MacroButtonList2 = {
"MacroDeleteButton", "MacroNewButton", "MacroExitButton"
}
--[[
##########################################################
MACRO UI MODR
##########################################################
]]--
local function MacroUIStyle()
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.macro ~= true then return end
SV.API:Set("Window", MacroFrame, true)
SV.API:Set("CloseButton", MacroFrameCloseButton)
SV.API:Set("ScrollBar", MacroButtonScrollFrame)
SV.API:Set("ScrollBar", MacroFrameScrollFrame)
SV.API:Set("ScrollBar", MacroPopupScrollFrame)
MacroFrame:SetWidth(360)
local parentStrata = MacroFrame:GetFrameStrata()
local parentLevel = MacroFrame:GetFrameLevel()
for i = 1, #MacroButtonList do
local button = _G[MacroButtonList[i]]
if(button) then
button:SetFrameStrata(parentStrata)
button:SetFrameLevel(parentLevel + 1)
button:RemoveTextures()
button:SetStyle("Button")
end
end
for i = 1, #MacroButtonList2 do
local button = _G[MacroButtonList2[i]]
if(button) then
local a1,p,a2,x,y = button:GetPoint()
button:SetPoint(a1,p,a2,x,-25)
end
end
local firstTab
for i = 1, 2 do
local tab = _G[("MacroFrameTab%d"):format(i)]
if(tab) then
tab:SetHeight(22)
if(i == 1) then
tab:SetPoint("TOPLEFT", MacroFrame, "TOPLEFT", 85, -39)
firstTab = tab
elseif(firstTab) then
tab:SetPoint("LEFT", firstTab, "RIGHT", 4, 0)
end
end
end
MacroFrameText:SetFont(SV.media.font.default, 12, "NONE")
MacroFrameTextBackground:RemoveTextures()
MacroFrameTextBackground:SetStyle("Frame", 'Transparent')
MacroPopupFrame:RemoveTextures()
MacroPopupFrame:SetStyle("Frame", 'Transparent')
MacroPopupScrollFrameScrollBar:RemoveTextures()
MacroPopupScrollFrameScrollBar:SetStyle("Frame", "Pattern")
MacroPopupScrollFrameScrollBar.Panel:SetPoint("TOPLEFT", 51, 2)
MacroPopupScrollFrameScrollBar.Panel:SetPoint("BOTTOMRIGHT", -4, 4)
MacroPopupEditBox:SetStyle("Editbox")
MacroPopupNameLeft:SetTexture("")
MacroPopupNameMiddle:SetTexture("")
MacroPopupNameRight:SetTexture("")
MacroFrameInset:Die()
MacroButtonContainer:RemoveTextures()
SV.API:Set("ScrollBar", MacroButtonScrollFrame)
MacroButtonScrollFrameScrollBar:SetStyle("!_Frame", "Inset")
MacroPopupFrame:HookScript("OnShow", function(c)
c:ClearAllPoints()
c:SetPoint("TOPLEFT", MacroFrame, "TOPRIGHT", 5, -2)
end)
MacroFrameSelectedMacroButton:SetFrameStrata(parentStrata)
MacroFrameSelectedMacroButton:SetFrameLevel(parentLevel + 1)
MacroFrameSelectedMacroButton:RemoveTextures()
MacroFrameSelectedMacroButton:SetStyle("ActionSlot")
MacroFrameSelectedMacroButtonIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
MacroFrameSelectedMacroButtonIcon:InsetPoints()
MacroEditButton:ClearAllPoints()
MacroEditButton:SetPoint("BOTTOMLEFT", MacroFrameSelectedMacroButton.Panel, "BOTTOMRIGHT", 10, 0)
MacroFrameCharLimitText:ClearAllPoints()
MacroFrameCharLimitText:SetPoint("BOTTOM", MacroFrameTextBackground, -25, -35)
for i = 1, MAX_ACCOUNT_MACROS do
local button = _G["MacroButton"..i]
if(button) then
button:RemoveTextures()
button:SetStyle("ActionSlot")
local icon = _G["MacroButton"..i.."Icon"]
if(icon) then
icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
icon:InsetPoints()
icon:SetDrawLayer("OVERLAY")
end
local popup = _G["MacroPopupButton"..i]
if(popup) then
popup:RemoveTextures()
popup:SetStyle("Button")
popup:SetBackdropColor(0, 0, 0, 0)
local popupIcon = _G["MacroPopupButton"..i.."Icon"]
if(popupIcon) then
popupIcon:InsetPoints()
popupIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
end
end
end
end
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveBlizzardStyle("Blizzard_MacroUI", MacroUIStyle)
|
--[[
##############################################################################
S V U I By: Failcoder
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
HELPERS
##########################################################
]]--
local MacroButtonList = {
"MacroSaveButton", "MacroCancelButton", "MacroDeleteButton", "MacroNewButton", "MacroExitButton", "MacroEditButton", "MacroFrameTab1", "MacroFrameTab2", "MacroPopupOkayButton", "MacroPopupCancelButton"
}
local MacroButtonList2 = {
"MacroDeleteButton", "MacroNewButton", "MacroExitButton"
}
--[[
##########################################################
MACRO UI MODR
##########################################################
]]--
local function MacroUIStyle()
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.macro ~= true then return end
SV.API:Set("Window", MacroFrame, true)
SV.API:Set("CloseButton", MacroFrameCloseButton)
SV.API:Set("ScrollBar", MacroButtonScrollFrame)
SV.API:Set("ScrollBar", MacroFrameScrollFrame)
SV.API:Set("ScrollBar", MacroPopupScrollFrame)
MacroFrame:SetWidth(360)
for i = 1, #MacroButtonList do
local button = _G[MacroButtonList[i]]
if(button) then
button:SetFrameStrata("DIALOG")
SV.API:Set("Button", button)
end
end
for i = 1, #MacroButtonList2 do
local button = _G[MacroButtonList2[i]]
if(button) then
local a1,p,a2,x,y = button:GetPoint()
button:SetPoint(a1,p,a2,x,-25)
end
end
local firstTab
for i = 1, 2 do
local tab = _G[("MacroFrameTab%d"):format(i)]
if(tab) then
tab:SetHeight(22)
if(i == 1) then
tab:SetPoint("TOPLEFT", MacroFrame, "TOPLEFT", 85, -39)
firstTab = tab
elseif(firstTab) then
tab:SetPoint("LEFT", firstTab, "RIGHT", 4, 0)
end
end
end
MacroFrameText:SetFont(SV.media.font.default, 12, "NONE")
MacroFrameTextBackground:RemoveTextures()
MacroFrameTextBackground:SetStyle("Frame", 'Transparent')
MacroPopupFrame:RemoveTextures()
MacroPopupFrame:SetStyle("Frame", 'Transparent')
MacroPopupFrame.BorderBox:RemoveTextures()
SV.API:Set("EditBox", MacroPopupEditBox)
MacroPopupScrollFrameScrollBar:RemoveTextures()
--MacroPopupScrollFrameScrollBar:SetStyle("ScrollBar", "Pattern")
--MacroPopupScrollFrameScrollBar.Panel:SetPoint("TOPLEFT", 51, 2)
--MacroPopupScrollFrameScrollBar.Panel:SetPoint("BOTTOMRIGHT", -4, 4)
--MacroPopupEditBox:SetStyle("Editbox")
MacroPopupNameLeft:SetTexture("")
MacroPopupNameMiddle:SetTexture("")
MacroPopupNameRight:SetTexture("")
MacroPopupCancelButton:SetPoint("BOTTOM", MacroPopupFrame, "BOTTOMLEFT", 0, -25)
MacroFrameInset:Die()
MacroButtonContainer:RemoveTextures()
SV.API:Set("ScrollBar", MacroButtonScrollFrame)
MacroButtonScrollFrameScrollBar:SetStyle("Frame", "Inset")
MacroPopupFrame:HookScript("OnShow", function(c)
c:ClearAllPoints()
c:SetPoint("TOPLEFT", MacroFrame, "TOPRIGHT", 5, -2)
end)
MacroFrameSelectedMacroButton:SetFrameStrata(parentStrata)
MacroFrameSelectedMacroButton:SetFrameLevel(parentLevel + 1)
MacroFrameSelectedMacroButton:RemoveTextures()
MacroFrameSelectedMacroButton:SetStyle("ActionSlot")
MacroFrameSelectedMacroButtonIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
MacroFrameSelectedMacroButtonIcon:InsetPoints()
MacroEditButton:ClearAllPoints()
MacroEditButton:SetPoint("BOTTOMLEFT", MacroFrameSelectedMacroButton.Panel, "BOTTOMRIGHT", 10, 0)
MacroFrameCharLimitText:ClearAllPoints()
MacroFrameCharLimitText:SetPoint("BOTTOM", MacroFrameTextBackground, -25, -35)
for i = 1, MAX_ACCOUNT_MACROS do
local button = _G["MacroButton"..i]
if(button) then
button:RemoveTextures()
button:SetStyle("ActionSlot")
local icon = _G["MacroButton"..i.."Icon"]
if(icon) then
icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
icon:InsetPoints()
icon:SetDrawLayer("OVERLAY")
end
local popup = _G["MacroPopupButton"..i]
if(popup) then
popup:RemoveTextures()
popup:SetStyle("Button")
popup:SetBackdropColor(0, 0, 0, 0)
local popupIcon = _G["MacroPopupButton"..i.."Icon"]
if(popupIcon) then
popupIcon:InsetPoints()
popupIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
end
end
end
end
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveBlizzardStyle("Blizzard_MacroUI", MacroUIStyle)
|
Fix #141
|
Fix #141
|
Lua
|
mit
|
FailcoderAddons/supervillain-ui,finalsliver/supervillain-ui
|
6e10cc712958d76154ccebb83bf6096673b474a5
|
agents/monitoring/tests/check/apache.lua
|
agents/monitoring/tests/check/apache.lua
|
local async = require('async')
local fs = require('fs')
local testUtil = require('monitoring/default/util/test')
local path = require('path')
local fmt = require('string').format
local ApacheCheck = require('monitoring/default/check').ApacheCheck
local PORT = 32321
local HOST = '127.0.0.1'
local exports = {}
exports['test_apache'] = function(test, asserts)
local url = fmt('http://%s:%s/server-status?auto', HOST, PORT)
local ch = ApacheCheck:new({id='foo', period=30, details={url=url}})
local server
local response
function reqCallback(req, res)
if not response then
local filePath = path.join(process.cwd(), '/agents/monitoring/tests/fixtures/checks/apache_server_status.txt')
response = fs.readFileSync(filePath)
end
res:writeHead(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #response
})
res:finish(response)
end
async.series({
function(callback)
testUtil.runTestHTTPServer(PORT, HOST, reqCallback, function(err, _server)
server = _server
callback(err)
end)
end,
function(callback)
ch:run(function(result)
local metrics = result:getMetrics()['none']
asserts.equal(result:getState(), 'available')
asserts.equal(metrics['ReqPerSec']['v'], '136.982')
asserts.equal(metrics['Uptime']['v'], '246417')
asserts.equal(metrics['Total_Accesses']['v'], '33754723')
callback()
end)
end
}, function(err)
if server then
server:close()
end
test.done()
end)
end
return exports
|
local async = require('async')
local fs = require('fs')
local testUtil = require('monitoring/default/util/test')
local path = require('path')
local fmt = require('string').format
local ApacheCheck = require('monitoring/default/check').ApacheCheck
local PORT = 32321
local HOST = '127.0.0.1'
local exports = {}
exports['test_apache'] = function(test, asserts)
local url = fmt('http://%s:%s/server-status?auto', HOST, PORT)
local ch = ApacheCheck:new({id='foo', period=30, details={url=url}})
local server
local response
function reqCallback(req, res)
if not response then
local filePath = path.join(process.cwd(), 'agents', 'monitoring', 'tests',
'fixtures', 'checks', 'apache_server_status.txt')
response = fs.readFileSync(filePath)
end
res:writeHead(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #response
})
res:finish(response)
end
async.series({
function(callback)
testUtil.runTestHTTPServer(PORT, HOST, reqCallback, function(err, _server)
server = _server
callback(err)
end)
end,
function(callback)
ch:run(function(result)
local metrics = result:getMetrics()['none']
asserts.equal(result:getState(), 'available')
asserts.equal(metrics['ReqPerSec']['v'], '136.982')
asserts.equal(metrics['Uptime']['v'], '246417')
asserts.equal(metrics['Total_Accesses']['v'], '33754723')
callback()
end)
end
}, function(err)
if server then
server:close()
end
asserts.equals(err, nil)
test.done()
end)
end
return exports
|
fix pathing for win32 porting team
|
fix pathing for win32 porting team
|
Lua
|
apache-2.0
|
AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent
|
e9cfdba22a43e4ef9caf29b4f711ab27231426a0
|
lualib/snax/hotfix.lua
|
lualib/snax/hotfix.lua
|
local si = require "snax.interface"
local io = io
local hotfix = {}
local function envid(f)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
return
end
if name == "_ENV" then
return debug.upvalueid(f, i)
end
i = i + 1
end
end
local function collect_uv(f , uv, env)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
local id = debug.upvalueid(f, i)
if uv[name] then
assert(uv[name].id == id, string.format("ambiguity local value %s", name))
else
uv[name] = { func = f, index = i, id = id }
if type(value) == "function" then
if envid(value) == env then
collect_uv(value, uv, env)
end
end
end
i = i + 1
end
end
local function collect_all_uv(funcs)
local global = {}
for _, v in pairs(funcs) do
if v[4] then
collect_uv(v[4], global, envid(v[4]))
end
end
return global
end
local function loader(source)
return function (filename, ...)
return load(source, "=patch", ...)
end
end
local function find_func(funcs, group , name)
for _, desc in pairs(funcs) do
local _, g, n = table.unpack(desc)
if group == g and name == n then
return desc
end
end
end
local dummy_env = {}
local function patch_func(funcs, global, group, name, f)
local desc = assert(find_func(funcs, group, name) , string.format("Patch mismatch %s.%s", group, name))
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
elseif value == nil or value == dummy_env then
local old_uv = global[name]
if old_uv then
debug.upvaluejoin(f, i, old_uv.func, old_uv.index)
end
end
i = i + 1
end
desc[4] = f
end
local function inject(funcs, source, ...)
local patch = si("patch", dummy_env, loader(source))
local global = collect_all_uv(funcs)
for _, v in pairs(patch) do
local _, group, name, f = table.unpack(v)
if f then
patch_func(funcs, global, group, name, f)
end
end
local hf = find_func(patch, "system", "hotfix")
if hf and hf[4] then
return hf[4](...)
end
end
return function (funcs, source, ...)
return pcall(inject, funcs, source, ...)
end
|
local si = require "snax.interface"
local io = io
local hotfix = {}
local function envid(f)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
return
end
if name == "_ENV" then
return debug.upvalueid(f, i)
end
i = i + 1
end
end
local function collect_uv(f , uv, env)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
local id = debug.upvalueid(f, i)
if uv[name] then
assert(uv[name].id == id, string.format("ambiguity local value %s", name))
else
uv[name] = { func = f, index = i, id = id }
if type(value) == "function" then
if envid(value) == env then
collect_uv(value, uv, env)
end
end
end
i = i + 1
end
end
local function collect_all_uv(funcs)
local global = {}
for _, v in pairs(funcs) do
if v[4] then
collect_uv(v[4], global, envid(v[4]))
end
end
if not global["_ENV"] then
global["_ENV"] = {func = collect_uv, index = 1}
end
return global
end
local function loader(source)
return function (filename, ...)
return load(source, "=patch", ...)
end
end
local function find_func(funcs, group , name)
for _, desc in pairs(funcs) do
local _, g, n = table.unpack(desc)
if group == g and name == n then
return desc
end
end
end
local dummy_env = {}
local function patch_func(funcs, global, group, name, f)
local desc = assert(find_func(funcs, group, name) , string.format("Patch mismatch %s.%s", group, name))
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
elseif value == nil or value == dummy_env then
local old_uv = global[name]
if old_uv then
debug.upvaluejoin(f, i, old_uv.func, old_uv.index)
end
end
i = i + 1
end
desc[4] = f
end
local function inject(funcs, source, ...)
local patch = si("patch", dummy_env, loader(source))
local global = collect_all_uv(funcs)
for _, v in pairs(patch) do
local _, group, name, f = table.unpack(v)
if f then
patch_func(funcs, global, group, name, f)
end
end
local hf = find_func(patch, "system", "hotfix")
if hf and hf[4] then
return hf[4](...)
end
end
return function (funcs, source, ...)
return pcall(inject, funcs, source, ...)
end
|
'hotfix' code cannot use '_ENV'
|
'hotfix' code cannot use '_ENV'
If there's no global variable or function used in any interface of a snax service,the upvalue "_ENV" for 'hotfix' is not set. This modify is not complete, it depend's on the 'collect_uv' method having upvalue '_ENV',maybe other good method to get upvalue index of '_ENV'.
|
Lua
|
mit
|
codingabc/skynet,chfg007/skynet,bigrpg/skynet,asanosoyokaze/skynet,matinJ/skynet,ilylia/skynet,wangyi0226/skynet,enulex/skynet,matinJ/skynet,chfg007/skynet,javachengwc/skynet,lc412/skynet,nightcj/mmo,longmian/skynet,KittyCookie/skynet,LiangMa/skynet,MoZhonghua/skynet,great90/skynet,bttscut/skynet,vizewang/skynet,QuiQiJingFeng/skynet,longmian/skynet,cpascal/skynet,boyuegame/skynet,lawnight/skynet,ludi1991/skynet,vizewang/skynet,firedtoad/skynet,jiuaiwo1314/skynet,sanikoyes/skynet,helling34/skynet,xjdrew/skynet,Ding8222/skynet,iskygame/skynet,matinJ/skynet,cdd990/skynet,lawnight/skynet,icetoggle/skynet,lc412/skynet,cloudwu/skynet,zhangshiqian1214/skynet,sundream/skynet,lc412/skynet,boyuegame/skynet,ag6ag/skynet,Ding8222/skynet,czlc/skynet,Markal128/skynet,zhangshiqian1214/skynet,cpascal/skynet,Zirpon/skynet,u20024804/skynet,gitfancode/skynet,enulex/skynet,zzh442856860/skynet,KAndQ/skynet,LiangMa/skynet,enulex/skynet,bingo235/skynet,zzh442856860/skynet,liuxuezhan/skynet,felixdae/skynet,bttscut/skynet,codingabc/skynet,icetoggle/skynet,ypengju/skynet_comment,sdgdsffdsfff/skynet,chuenlungwang/skynet,xjdrew/skynet,chuenlungwang/skynet,icetoggle/skynet,sdgdsffdsfff/skynet,pigparadise/skynet,ypengju/skynet_comment,bingo235/skynet,leezhongshan/skynet,zhouxiaoxiaoxujian/skynet,letmefly/skynet,korialuo/skynet,felixdae/skynet,fhaoquan/skynet,letmefly/skynet,chfg007/skynet,sanikoyes/skynet,codingabc/skynet,Markal128/skynet,xinjuncoding/skynet,cmingjian/skynet,your-gatsby/skynet,rainfiel/skynet,nightcj/mmo,kebo/skynet,sanikoyes/skynet,harryzeng/skynet,fztcjjl/skynet,xinjuncoding/skynet,wangjunwei01/skynet,pichina/skynet,MRunFoss/skynet,Markal128/skynet,nightcj/mmo,microcai/skynet,sundream/skynet,Zirpon/skynet,cuit-zhaxin/skynet,cloudwu/skynet,zhouxiaoxiaoxujian/skynet,MoZhonghua/skynet,KittyCookie/skynet,catinred2/skynet,jxlczjp77/skynet,microcai/skynet,great90/skynet,fztcjjl/skynet,zhangshiqian1214/skynet,KAndQ/skynet,zhangshiqian1214/skynet,firedtoad/skynet,cdd990/skynet,zzh442856860/skynet,hongling0/skynet,iskygame/skynet,QuiQiJingFeng/skynet,xinjuncoding/skynet,felixdae/skynet,jiuaiwo1314/skynet,lynx-seu/skynet,longmian/skynet,JiessieDawn/skynet,catinred2/skynet,wangjunwei01/skynet,lawnight/skynet,javachengwc/skynet,wangyi0226/skynet,kebo/skynet,QuiQiJingFeng/skynet,cmingjian/skynet,cloudwu/skynet,kebo/skynet,dymx101/skynet,zhouxiaoxiaoxujian/skynet,xcjmine/skynet,cmingjian/skynet,lynx-seu/skynet,jxlczjp77/skynet,zhoukk/skynet,ludi1991/skynet,gitfancode/skynet,javachengwc/skynet,catinred2/skynet,cuit-zhaxin/skynet,xcjmine/skynet,ag6ag/skynet,bttscut/skynet,liuxuezhan/skynet,czlc/skynet,liuxuezhan/skynet,korialuo/skynet,jxlczjp77/skynet,yunGit/skynet,JiessieDawn/skynet,ypengju/skynet_comment,harryzeng/skynet,rainfiel/skynet,helling34/skynet,asanosoyokaze/skynet,pigparadise/skynet,cuit-zhaxin/skynet,lawnight/skynet,ag6ag/skynet,samael65535/skynet,letmefly/skynet,JiessieDawn/skynet,zhangshiqian1214/skynet,Zirpon/skynet,jiuaiwo1314/skynet,hongling0/skynet,MRunFoss/skynet,Ding8222/skynet,fhaoquan/skynet,czlc/skynet,firedtoad/skynet,leezhongshan/skynet,letmefly/skynet,puXiaoyi/skynet,hongling0/skynet,bigrpg/skynet,pichina/skynet,liuxuezhan/skynet,puXiaoyi/skynet,pigparadise/skynet,wangyi0226/skynet,microcai/skynet,fztcjjl/skynet,helling34/skynet,korialuo/skynet,harryzeng/skynet,gitfancode/skynet,xcjmine/skynet,xjdrew/skynet,your-gatsby/skynet,chuenlungwang/skynet,kyle-wang/skynet,sdgdsffdsfff/skynet,yunGit/skynet,vizewang/skynet,MoZhonghua/skynet,lynx-seu/skynet,bigrpg/skynet,bingo235/skynet,LiangMa/skynet,puXiaoyi/skynet,rainfiel/skynet,great90/skynet,leezhongshan/skynet,iskygame/skynet,pichina/skynet,sundream/skynet,samael65535/skynet,zhangshiqian1214/skynet,kyle-wang/skynet,u20024804/skynet,u20024804/skynet,zhoukk/skynet,cdd990/skynet,wangjunwei01/skynet,yunGit/skynet,your-gatsby/skynet,dymx101/skynet,samael65535/skynet,fhaoquan/skynet,zhoukk/skynet,boyuegame/skynet,ilylia/skynet,asanosoyokaze/skynet,kyle-wang/skynet,KittyCookie/skynet,MRunFoss/skynet,ludi1991/skynet,ilylia/skynet,KAndQ/skynet,dymx101/skynet,ludi1991/skynet,cpascal/skynet
|
868f4fd64db26aa9d579b56de0043bb9749bcec7
|
tests/modules/tap.lua
|
tests/modules/tap.lua
|
local uv = require('uv')
local utils = require('utils')
local stdin = utils.stdin
local stdout = utils.stdout
local stderr = utils.stderr
local colorize = utils.colorize
-- Capture output from global print and prefix with two spaces
local print = _G.print
_G.print = function (...)
local n = select('#', ...)
local arguments = {...}
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
local text = table.concat(arguments, "\t")
text = " " .. string.gsub(text, "\n", "\n ")
print(text)
end
local tests = {};
local function run()
local passed = 0
if #tests < 1 then
error("No tests specified!")
end
print("1.." .. #tests)
for i = 1, #tests do
local test = tests[i]
local cwd = uv.cwd()
print("\n# Starting Test: " .. colorize("highlight", test.name))
local pass, err = xpcall(function ()
local expected = 0
local function expect(fn, count)
expected = expected + (count or 1)
return function (...)
expected = expected - 1
local ret = fn(...)
collectgarbage()
return ret
end
end
test.fn(expect)
collectgarbage()
uv.run()
collectgarbage()
if expected > 0 then
error("Missing " .. expected .. " expected call" .. (expected == 1 and "" or "s"))
elseif expected < 0 then
error("Found " .. -expected .. " unexpected call" .. (expected == -1 and "" or "s"))
end
collectgarbage()
local unclosed = 0
uv.walk(function (handle)
if handle == stdout or handle == stderr or handle == stdin then return end
unclosed = unclosed + 1
print("UNCLOSED", handle)
end)
if unclosed > 0 then
error(unclosed .. " unclosed handle" .. (unclosed == 1 and "" or "s"))
end
if uv.cwd() ~= cwd then
error("Test moved cwd from " .. cwd .. " to " .. uv.cwd())
end
collectgarbage()
end, debug.traceback)
-- Flush out any more opened handles
uv.run()
uv.walk(function (handle)
if handle == stdout or handle == stderr or handle == stdin then return end
uv.close(handle)
end)
uv.run()
uv.chdir(cwd)
if pass then
print("ok " .. i .. " " .. colorize("success", test.name))
passed = passed + 1
else
_G.print(colorize("err", err))
print("not ok " .. i .. " " .. colorize("failure", test.name))
end
end
local failed = #tests - passed
if failed == 0 then
print("# All tests passed")
else
print("#" .. failed .. " failed test" .. (failed == 1 and "" or "s"))
end
-- Close all then handles, including stdout
uv.walk(uv.close)
uv.run()
os.exit(-failed)
end
local single = true
local prefix
local function tap(suite)
if type(suite) == "function" then
-- Pass in suite directly for single mode
suite(function (name, fn)
if prefix then
name = prefix .. ' - ' .. name
end
tests[#tests + 1] = {
name = name,
fn = fn
}
end)
prefix = nil
elseif type(suite) == "string" then
prefix = suite
single = false
else
-- Or pass in false to collect several runs of tests
-- And then pass in true in a later call to flush tests queue.
single = suite
end
if single then run() end
end
return tap
|
local uv = require('uv')
local utils = require('utils')
local colorize = utils.colorize
-- Capture output from global print and prefix with two spaces
local print = _G.print
_G.print = function (...)
local n = select('#', ...)
local arguments = {...}
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
local text = table.concat(arguments, "\t")
text = " " .. string.gsub(text, "\n", "\n ")
print(text)
end
local tests = {};
local function run()
local passed = 0
if #tests < 1 then
error("No tests specified!")
end
print("1.." .. #tests)
for i = 1, #tests do
local test = tests[i]
local cwd = uv.cwd()
local preexisting = {}
uv.walk(function (handle)
preexisting[handle] = true
end)
print("\n# Starting Test: " .. colorize("highlight", test.name))
local pass, err = xpcall(function ()
local expected = 0
local function expect(fn, count)
expected = expected + (count or 1)
return function (...)
expected = expected - 1
local ret = fn(...)
collectgarbage()
return ret
end
end
test.fn(expect)
collectgarbage()
uv.run()
collectgarbage()
if expected > 0 then
error("Missing " .. expected .. " expected call" .. (expected == 1 and "" or "s"))
elseif expected < 0 then
error("Found " .. -expected .. " unexpected call" .. (expected == -1 and "" or "s"))
end
collectgarbage()
local unclosed = 0
uv.walk(function (handle)
if preexisting[handle] then return end
unclosed = unclosed + 1
print("UNCLOSED", handle)
end)
if unclosed > 0 then
error(unclosed .. " unclosed handle" .. (unclosed == 1 and "" or "s"))
end
if uv.cwd() ~= cwd then
error("Test moved cwd from " .. cwd .. " to " .. uv.cwd())
end
collectgarbage()
end, debug.traceback)
-- Flush out any more opened handles
uv.run()
uv.walk(function (handle)
if preexisting[handle] then return end
uv.close(handle)
end)
uv.run()
uv.chdir(cwd)
if pass then
print("ok " .. i .. " " .. colorize("success", test.name))
passed = passed + 1
else
_G.print(colorize("err", err))
print("not ok " .. i .. " " .. colorize("failure", test.name))
end
end
local failed = #tests - passed
if failed == 0 then
print("# All tests passed")
else
print("#" .. failed .. " failed test" .. (failed == 1 and "" or "s"))
end
-- Close all then handles, including stdout
uv.walk(uv.close)
uv.run()
os.exit(-failed)
end
local single = true
local prefix
local function tap(suite)
if type(suite) == "function" then
-- Pass in suite directly for single mode
suite(function (name, fn)
if prefix then
name = prefix .. ' - ' .. name
end
tests[#tests + 1] = {
name = name,
fn = fn
}
end)
prefix = nil
elseif type(suite) == "string" then
prefix = suite
single = false
else
-- Or pass in false to collect several runs of tests
-- And then pass in true in a later call to flush tests queue.
single = suite
end
if single then run() end
end
return tap
|
Fix test library to ignore any and all pre-existing handles
|
Fix test library to ignore any and all pre-existing handles
|
Lua
|
apache-2.0
|
DBarney/luvit,zhaozg/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,kaustavha/luvit,rjeli/luvit,bsn069/luvit,kaustavha/luvit,luvit/luvit,rjeli/luvit,DBarney/luvit,bsn069/luvit,luvit/luvit,zhaozg/luvit,kaustavha/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream
|
028e9a14904206b52cf09ded22c85ef2e4d962af
|
scripts/tundra/util.lua
|
scripts/tundra/util.lua
|
local _tostring = tostring
module(..., package.seeall)
function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
table.foreach(value, function(i, v)
if (tonumber(i) ~= i) then
table.insert(auxTable, i)
else
table.insert(auxTable, tostring(i))
end
end)
table.sort(auxTable)
str = str..'{'
local separator = ""
local entry = ""
table.foreachi (auxTable, function (i, fieldName)
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = fieldName.." = "..tostring(rawget(value, fieldName))
end
str = str..separator..entry
separator = ", "
end)
str = str..'}'
end
return str
end
function map(t, fn)
local result = {}
for idx = 1, #t do
result[idx] = fn(t[idx])
end
return result
end
function mapnil(table, fn)
if not table then
return nil
else
return map(table, fn)
end
end
function get_named_arg(tab, name, context)
local v = tab[name]
if v then
return v
else
if context then
error(context .. ": argument " .. name .. " must be specified", 3)
else
error("argument " .. name .. " must be specified", 3)
end
end
end
function parse_cmdline(args, blueprint)
local index, max = 2, #args
local options, targets = {}, {}
local lookup = {}
for _, opt in ipairs(blueprint) do
if opt.Short then
lookup[opt.Short] = opt
end
if opt.Long then
lookup[opt.Long] = opt
end
end
while index <= max do
local s = args[index]
local key = nil
if s:sub(1, 2) == '--' then
key = s:sub(3)
elseif s:sub(1, 1) == '-' then
key = s:sub(2)
else
table.insert(targets, s)
end
if key then
local opt = lookup[key]
if not opt then
return nil, nil, "Unknown option " .. s
end
if opt.HasValue then
local val = args[index+1]
if val then
options[opt.Name] = val
index = index + 1
else
return nil, nil, "Missing value for option "..s
end
else
local v = options[opt.Name] or 0
options[opt.Name] = v + 1
end
end
index = index + 1
end
return options, targets
end
function clone_table(t)
local r = {}
for k, v in pairs(t) do
r[k] = v
end
return r
end
function clone_array(t)
local r = {}
for k, v in ipairs(t) do
r[k] = v
end
return r
end
function merge_arrays(...)
local result = {}
local count = #...
for i = 1, count do
local tab = select(i, ...)
if tab then
for _, v in ipairs(tab) do
result[#result + 1] = v
end
end
end
return result
end
function merge_arrays_2(a, b)
if a and b then
return merge_arrays(a, b)
elseif a then
return a
elseif b then
return b
else
return {}
end
end
function matches_any(str, patterns)
for _, pattern in ipairs(patterns) do
if str:match(pattern) then
return true
end
end
return false
end
function return_nil()
end
function nil_pairs(t)
if t then
return next, t
else
return return_nil
end
end
function nil_ipairs(t)
if t then
return ipairs(t)
else
return return_nil
end
end
function clear_table(tab)
local key, val = next(tab)
while key do
tab[key] = nil
key, val = next(tab, key)
end
return tab
end
function filter_in_place(tab, predicate)
local i, limit = 1, #tab
while i <= limit do
if not predicate(tab[i]) then
table.remove(tab, i)
limit = limit - 1
else
i = i + 1
end
end
return tab
end
function append_table(result, items)
local offset = #result
for i = 1, #items do
result[offset + i] = items[i]
end
return result
end
|
local _tostring = tostring
module(..., package.seeall)
function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
for k, v in pairs(value) do
auxTable[#auxTable + 1] = k
end
table.sort(auxTable, function (a, b) return _tostring(a) < _tostring(b) end)
str = str..'{'
local separator = ""
local entry = ""
for index, fieldName in ipairs(auxTable) do
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = tostring(fieldName) .. " = " .. tostring(rawget(value, fieldName))
end
str = str..separator..entry
separator = ", "
end
str = str..'}'
end
return str
end
function map(t, fn)
local result = {}
for idx = 1, #t do
result[idx] = fn(t[idx])
end
return result
end
function mapnil(table, fn)
if not table then
return nil
else
return map(table, fn)
end
end
function get_named_arg(tab, name, context)
local v = tab[name]
if v then
return v
else
if context then
error(context .. ": argument " .. name .. " must be specified", 3)
else
error("argument " .. name .. " must be specified", 3)
end
end
end
function parse_cmdline(args, blueprint)
local index, max = 2, #args
local options, targets = {}, {}
local lookup = {}
for _, opt in ipairs(blueprint) do
if opt.Short then
lookup[opt.Short] = opt
end
if opt.Long then
lookup[opt.Long] = opt
end
end
while index <= max do
local s = args[index]
local key = nil
if s:sub(1, 2) == '--' then
key = s:sub(3)
elseif s:sub(1, 1) == '-' then
key = s:sub(2)
else
table.insert(targets, s)
end
if key then
local opt = lookup[key]
if not opt then
return nil, nil, "Unknown option " .. s
end
if opt.HasValue then
local val = args[index+1]
if val then
options[opt.Name] = val
index = index + 1
else
return nil, nil, "Missing value for option "..s
end
else
local v = options[opt.Name] or 0
options[opt.Name] = v + 1
end
end
index = index + 1
end
return options, targets
end
function clone_table(t)
local r = {}
for k, v in pairs(t) do
r[k] = v
end
return r
end
function clone_array(t)
local r = {}
for k, v in ipairs(t) do
r[k] = v
end
return r
end
function merge_arrays(...)
local result = {}
local count = #...
for i = 1, count do
local tab = select(i, ...)
if tab then
for _, v in ipairs(tab) do
result[#result + 1] = v
end
end
end
return result
end
function merge_arrays_2(a, b)
if a and b then
return merge_arrays(a, b)
elseif a then
return a
elseif b then
return b
else
return {}
end
end
function matches_any(str, patterns)
for _, pattern in ipairs(patterns) do
if str:match(pattern) then
return true
end
end
return false
end
function return_nil()
end
function nil_pairs(t)
if t then
return next, t
else
return return_nil
end
end
function nil_ipairs(t)
if t then
return ipairs(t)
else
return return_nil
end
end
function clear_table(tab)
local key, val = next(tab)
while key do
tab[key] = nil
key, val = next(tab, key)
end
return tab
end
function filter_in_place(tab, predicate)
local i, limit = 1, #tab
while i <= limit do
if not predicate(tab[i]) then
table.remove(tab, i)
limit = limit - 1
else
i = i + 1
end
end
return tab
end
function append_table(result, items)
local offset = #result
for i = 1, #items do
result[offset + i] = items[i]
end
return result
end
|
Fixed tostring() for table keys.
|
Fixed tostring() for table keys.
|
Lua
|
mit
|
deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra
|
ffd70ceb68eb2146e939b4e4e3a15fa48bb12adc
|
share/lua/meta/art/01_musicbrainz.lua
|
share/lua/meta/art/01_musicbrainz.lua
|
--[[
Gets an artwork from amazon
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Return the artwork
function fetch_art()
local query
local meta = vlc.item:metas()
if meta["artist"] and meta["album"] then
query = "http://musicbrainz.org/ws/1/release/?type=xml&artist="..vlc.strings.encode_uri_component(meta["artist"]).."&title="..vlc.strings.encode_uri_component(meta["album"])
else
return nil
end
local l = vlc.object.libvlc()
local t = vlc.var.get( l, "musicbrainz-previousdate" )
if t ~= nil then
if t + 1000000. > vlc.misc.mdate() then
vlc.msg.warn( "We must wait 1 second between requests unless we want to be blacklisted from the musicbrainz server." )
vlc.misc.mwait( t + 1000000. )
end
vlc.var.set( l, "musicbrainz-previousdate", vlc.misc.mdate() )
else
vlc.var.create( l, "musicbrainz-previousdate", vlc.misc.mdate() )
end
l = nil
vlc.msg.dbg( query )
local s = vlc.stream( query )
local page = s:read( 65653 )
-- FIXME: multiple results may be available
_,_,asin = string.find( page, "<asin>(.-)</asin>" )
if asin then
return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg"
else
return nil
end
end
|
--[[
Gets an artwork from amazon
$Id$
Copyright © 2007-2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function try_query(query)
local l = vlc.object.libvlc()
local t = vlc.var.get( l, "musicbrainz-previousdate" )
if t ~= nil then
if t + 1000000. > vlc.misc.mdate() then
vlc.msg.warn( "We must wait 1 second between requests unless we want to be blacklisted from the musicbrainz server." )
vlc.misc.mwait( t + 1000000. )
end
vlc.var.set( l, "musicbrainz-previousdate", vlc.misc.mdate() )
else
vlc.var.create( l, "musicbrainz-previousdate", vlc.misc.mdate() )
end
l = nil
vlc.msg.dbg( query )
local s = vlc.stream( query )
local page = s:read( 65653 )
-- FIXME: multiple results may be available
_,_,asin = string.find( page, "<asin>(.-)</asin>" )
if asin then
return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg"
else
return nil
end
end
-- Return the artwork
function fetch_art()
local meta = vlc.item:metas()
if not (meta["artist"] and meta["album"]) then
return nil
end
local query1 = "http://musicbrainz.org/ws/1/release/?type=xml&artist="..vlc.strings.encode_uri_component(meta["artist"]).."&title="..vlc.strings.encode_uri_component(meta["album"])
local query2 = "http://musicbrainz.org/ws/1/release/?type=xml&query=artist:"..vlc.strings.encode_uri_component(meta["artist"]).." AND "..vlc.strings.encode_uri_component(meta["album"])
return try_query(query1) or try_query(query2)
end
|
Try a second musicbrainz query if the first one failed. This allows for fuzzier matches (like not taking spaces into account in 1980 - 1990 for example) but still doesn't fix issues with minor spelling errors.
|
Try a second musicbrainz query if the first one failed. This allows for fuzzier matches (like not taking spaces into account in 1980 - 1990 for example) but still doesn't fix issues with minor spelling errors.
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc
|
d3e2a391a6cd9814887093b05e926c3d8d6fea2f
|
pages/community/guilds/invite/post.lua
|
pages/community/guilds/invite/post.lua
|
require "guild"
function post()
if not session:isLogged() then
http:redirect("/")
return
end
local guild = db:singleQuery("SELECT name, ownerid, id FROM guilds WHERE name = ?", http.postValues["guild-name"])
if guild == nil then
http:redirect("/")
return
end
local invite = db:singleQuery("SELECT id FROM players WHERE name = ?", http.postValues["invite-name"])
if invite == nil then
session:setFlash("validationError", "Character not found")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
return
end
if db:singleQuery("SELECT guild_id FROM guild_membership WHERE player_id = ?", invite.id) ~= nil then
session:setFlash("validationError", "Character already on a guild")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
return
end
if not isGuildOwner(session:loggedAccount().ID, guild) then
http:redirect("/")
return
end
db:execute("INSERT INTO guild_invites (player_id, guild_id) VALUES (?, ?)", invite.id, guild.id)
session:setFlash("success", "Invitation sent")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
end
|
require "guild"
function post()
if not session:isLogged() then
http:redirect("/")
return
end
local guild = db:singleQuery("SELECT name, ownerid, id FROM guilds WHERE name = ?", http.postValues["guild-name"])
if guild == nil then
http:redirect("/")
return
end
local invite = db:singleQuery("SELECT id FROM players WHERE name = ?", http.postValues["invite-name"])
if invite == nil then
session:setFlash("validationError", "Character not found")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
return
end
if db:singleQuery("SELECT guild_id FROM guild_membership WHERE player_id = ?", invite.id) ~= nil then
session:setFlash("validationError", "Character already on a guild")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
return
end
if db:singleQuery("SELECT 1 FROM guild_invites WHERE player_id = ? AND guild_id = ?", invite.id, guild.id) ~= nil then
session:setFlash("validationError", "Character already invited")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
return
end
if not isGuildOwner(session:loggedAccount().ID, guild) then
http:redirect("/")
return
end
db:execute("INSERT INTO guild_invites (player_id, guild_id) VALUES (?, ?)", invite.id, guild.id)
session:setFlash("success", "Invitation sent")
http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
end
|
Fix guild invite
|
Fix guild invite
|
Lua
|
mit
|
Raggaer/castro,Raggaer/castro,Raggaer/castro
|
4efa27916f19dc6a862f37004cf733903f66aa82
|
modules/admin-core/luasrc/tools/webadmin.lua
|
modules/admin-core/luasrc/tools/webadmin.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
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.tools.webadmin", package.seeall)
require("luci.model.uci")
require("luci.sys")
require("luci.ip")
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
function date_format(secs)
local suff = {"min", "h", "d"}
local mins = 0
local hour = 0
local days = 0
if secs > 60 then
mins = math.floor(secs / 60)
secs = secs % 60
end
if mins > 60 then
hour = math.floor(mins / 60)
mins = mins % 60
end
if hour > 24 then
days = math.floor(hour / 24)
hour = hour % 24
end
if days > 0 then
return string.format("%dd %02dh %02dmin %02ds", days, hour, mins, secs)
else
return string.format("%02dh %02dmin %02ds", hour, mins, secs)
end
end
function network_get_addresses(net)
luci.model.uci.load_state("network")
local addr = {}
local ipv4 = luci.model.uci.get("network", net, "ipaddr")
local mav4 = luci.model.uci.get("network", net, "netmask")
local ipv6 = luci.model.uci.get("network", net, "ip6addr")
if ipv4 and mav4 then
ipv4 = luci.ip.IPv4(ipv4, mav4)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if ipv6 then
table.insert(addr, ipv6)
end
luci.model.uci.foreach("network", "alias",
function (section)
if section.interface == net then
if section.ipaddr and section.netmask then
local ipv4 = luci.ip.IPv4(section.ipaddr, section.netmask)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if section.ip6addr then
table.insert(addr, section.ip6addr)
end
end
end
)
return addr
end
function cbi_add_networks(field)
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function cbi_add_knownips(field)
for i, dataset in ipairs(luci.sys.net.arptable()) do
field:value(dataset["IP address"])
end
end
function network_get_zones(net)
if not luci.model.uci.load_state("firewall") then
return nil
end
local zones = {}
luci.model.uci.foreach("firewall", "zone",
function (section)
local znet = section.network or section.name
if luci.util.contains(luci.util.split(znet, " "), net) then
table.insert(zones, section.name)
end
end
)
return zones
end
function firewall_find_zone(name)
local find
luci.model.uci.foreach("firewall", "zone",
function (section)
if section.name == name then
find = section[".name"]
end
end
)
return find
end
function iface_get_network(iface)
luci.model.uci.load_state("network")
local net
luci.model.uci.foreach("network", "interface",
function (section)
local ifname = luci.model.uci.get(
"network", section[".name"], "ifname"
)
if iface == ifname then
net = section[".name"]
end
end
)
return net
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
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.tools.webadmin", package.seeall)
require("luci.model.uci")
require("luci.sys")
require("luci.ip")
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
function date_format(secs)
local suff = {"min", "h", "d"}
local mins = 0
local hour = 0
local days = 0
secs = math.floor(tonumber(secs))
if secs > 60 then
mins = math.floor(secs / 60)
secs = secs % 60
end
if mins > 60 then
hour = math.floor(mins / 60)
mins = mins % 60
end
if hour > 24 then
days = math.floor(hour / 24)
hour = hour % 24
end
if days > 0 then
return string.format("%dd %02dh %02dmin %02ds", days, hour, mins, secs)
else
return string.format("%02dh %02dmin %02ds", hour, mins, secs)
end
end
function network_get_addresses(net)
luci.model.uci.load_state("network")
local addr = {}
local ipv4 = luci.model.uci.get("network", net, "ipaddr")
local mav4 = luci.model.uci.get("network", net, "netmask")
local ipv6 = luci.model.uci.get("network", net, "ip6addr")
if ipv4 and mav4 then
ipv4 = luci.ip.IPv4(ipv4, mav4)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if ipv6 then
table.insert(addr, ipv6)
end
luci.model.uci.foreach("network", "alias",
function (section)
if section.interface == net then
if section.ipaddr and section.netmask then
local ipv4 = luci.ip.IPv4(section.ipaddr, section.netmask)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if section.ip6addr then
table.insert(addr, section.ip6addr)
end
end
end
)
return addr
end
function cbi_add_networks(field)
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function cbi_add_knownips(field)
for i, dataset in ipairs(luci.sys.net.arptable()) do
field:value(dataset["IP address"])
end
end
function network_get_zones(net)
if not luci.model.uci.load_state("firewall") then
return nil
end
local zones = {}
luci.model.uci.foreach("firewall", "zone",
function (section)
local znet = section.network or section.name
if luci.util.contains(luci.util.split(znet, " "), net) then
table.insert(zones, section.name)
end
end
)
return zones
end
function firewall_find_zone(name)
local find
luci.model.uci.foreach("firewall", "zone",
function (section)
if section.name == name then
find = section[".name"]
end
end
)
return find
end
function iface_get_network(iface)
luci.model.uci.load_state("network")
local net
luci.model.uci.foreach("network", "interface",
function (section)
local ifname = luci.model.uci.get(
"network", section[".name"], "ifname"
)
if iface == ifname then
net = section[".name"]
end
end
)
return net
end
|
Add missing number conversion (fixed #108)
|
Add missing number conversion (fixed #108)
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
|
b041f730df970ab3f68d0a8739b8ec6d3bb24445
|
epgp_Events.lua
|
epgp_Events.lua
|
-------------------------------------------------------------------------------
-- Event Handlers for tracking a raid
-------------------------------------------------------------------------------
-- CHAT_MSG_LOOT parsing
-- returns receiver, count, itemlink
local EPGP_LOOT_ITEM = "^(%S+) receives loot: (.+)%.$"
local EPGP_LOOT_ITEM_MULTIPLE = "^(%S+) receives loot: (.+)x(%d+)%.$"
local EPGP_LOOT_ITEM_SELF = "^You receive loot: (.+)%.$"
local EPGP_LOOT_ITEM_SELF_MULTIPLE = "^You receive loot: (.+)x(%d+)%.$"
function EPGP:ParseLootMsg(msg)
-- Variable names
-- r: reciever, i: itemlink, c: count
local _, _, r, i = string.find(msg, EPGP_LOOT_ITEM)
if (r and i) then return r, 1, i end
local _, _, r, i, c = string.find(msg, EPGP_LOOT_ITEM_MULTIPLE)
if (r and i and c) then return r, c, i end
local _, _, i = string.find(msg, EPGP_LOOT_ITEM_SELF)
if (i) then return UnitName("player"), 1, i end
local _, _, i, c = string.find(msg, EPGP_LOOT_ITEM_SELF_MULTIPLE)
if (i and c) then return UnitName("player"), c, i end
assert(false, "Unable to parse CHAT_MSG_LOOT message!")
end
function EPGP:CHAT_MSG_LOOT(msg)
local receiver, count, itemlink = self:ParseLootMsg(msg)
self:Debug("Player: [%s] Count: [%d] Loot: [%s]", receiver, count, itemlink)
self:EventLogAdd_LOOT(self:GetOrLastEventLog(), receiver, count, itemlink)
end
-- CHAT_MSG_COMBAT_HOSTILE_DEATH parsing
-- returns dead_mob
--
-- Message can be of two forms:
-- 1. "Greater Duskbat dies."
-- 2. "You have slain Greater Duskbat."
-- We only care about the first since we always get it. The second one we
-- get it in addition to the first if we did the killing blow.
local EPGP_UNIT_DIES_OTHER = "^(.+) dies%.$"
function EPGP:ParseHostileDeath(msg)
local _, _, dead_mob = string.find(msg, EPGP_UNIT_DIES_OTHER)
return dead_mob
end
function EPGP:CHAT_MSG_COMBAT_HOSTILE_DEATH(msg)
local dead_mob = self:ParseHostileDeath(msg)
if (not dead_mob) then return end
local mob_value = self:GetBossEP(dead_mob)
if (mob_value) then
self:Debug("Boss kill: %s value: %d", dead_mob, mob_value)
self:EventLogAdd_BOSSKILL(
self:GetLastEventLog(), dead_mob, self:GetCurrentRoster())
else
self:Debug(string.format("Trash kill: %s", dead_mob))
end
end
function EPGP:ZONE_CHANGED_NEW_AREA()
self.current_zone = GetRealZoneText()
if (self.db.profile.zones[self.current_zone]) then
self:Debug("Tracked zone: [%s]", self.current_zone)
else
self:Debug("Not tracked zone: [%s]", self.current_zone)
end
end
function EPGP:RAID_ROSTER_UPDATE()
self.raid_leader = IsReadLeader()
self:Reconfigure()
end
function EPGP:PARTY_MEMBERS_CHANGED()
self.raid_leader = IsRaidLeader()
self:Reconfigure()
end
|
-------------------------------------------------------------------------------
-- Event Handlers for tracking a raid
-------------------------------------------------------------------------------
-- CHAT_MSG_LOOT parsing
-- returns receiver, count, itemlink
local EPGP_LOOT_ITEM = "^(%S+) receives loot: (.+)%.$"
local EPGP_LOOT_ITEM_MULTIPLE = "^(%S+) receives loot: (.+)x(%d+)%.$"
local EPGP_LOOT_ITEM_SELF = "^You receive loot: (.+)%.$"
local EPGP_LOOT_ITEM_SELF_MULTIPLE = "^You receive loot: (.+)x(%d+)%.$"
function EPGP:ParseLootMsg(msg)
-- Variable names
-- r: reciever, i: itemlink, c: count
local _, _, r, i = string.find(msg, EPGP_LOOT_ITEM)
if (r and i) then return r, 1, i end
local _, _, r, i, c = string.find(msg, EPGP_LOOT_ITEM_MULTIPLE)
if (r and i and c) then return r, c, i end
local _, _, i = string.find(msg, EPGP_LOOT_ITEM_SELF)
if (i) then return UnitName("player"), 1, i end
local _, _, i, c = string.find(msg, EPGP_LOOT_ITEM_SELF_MULTIPLE)
if (i and c) then return UnitName("player"), c, i end
self:DEBUG("Ignored CHAT_MSG_LOOT message: %s", msg)
return nil, nil, nil
end
function EPGP:CHAT_MSG_LOOT(msg)
local receiver, count, itemlink = self:ParseLootMsg(msg)
if (receiver and count and itemlink) then
self:Debug("Player: [%s] Count: [%d] Loot: [%s]", receiver, count, itemlink)
self:EventLogAdd_LOOT(self:GetLastEventLog(), receiver, count, itemlink)
end
end
-- CHAT_MSG_COMBAT_HOSTILE_DEATH parsing
-- returns dead_mob
--
-- Message can be of two forms:
-- 1. "Greater Duskbat dies."
-- 2. "You have slain Greater Duskbat."
-- We only care about the first since we always get it. The second one we
-- get it in addition to the first if we did the killing blow.
local EPGP_UNIT_DIES_OTHER = "^(.+) dies%.$"
function EPGP:ParseHostileDeath(msg)
local _, _, dead_mob = string.find(msg, EPGP_UNIT_DIES_OTHER)
return dead_mob
end
function EPGP:CHAT_MSG_COMBAT_HOSTILE_DEATH(msg)
local dead_mob = self:ParseHostileDeath(msg)
if (not dead_mob) then return end
local mob_value = self:GetBossEP(dead_mob)
if (mob_value) then
self:Debug("Boss kill: %s value: %d", dead_mob, mob_value)
self:EventLogAdd_BOSSKILL(
self:GetLastEventLog(), dead_mob, self:GetCurrentRoster())
else
self:Debug(string.format("Trash kill: %s", dead_mob))
end
end
function EPGP:ZONE_CHANGED_NEW_AREA()
self.current_zone = GetRealZoneText()
if (self.db.profile.zones[self.current_zone]) then
self:Debug("Tracked zone: [%s]", self.current_zone)
else
self:Debug("Not tracked zone: [%s]", self.current_zone)
end
end
function EPGP:RAID_ROSTER_UPDATE()
self.raid_leader = IsReadLeader()
self:Reconfigure()
end
function EPGP:PARTY_MEMBERS_CHANGED()
self.raid_leader = IsRaidLeader()
self:Reconfigure()
end
|
Fix bug in parsing and logging loot.
|
Fix bug in parsing and logging loot.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp
|
d84e87e0c8b900c659e06b58c065846fb1d5b4c2
|
ZeroGrad.lua
|
ZeroGrad.lua
|
local ZeroGrad, parent = torch.class("nn.ZeroGrad", "nn.Module")
local function recursiveZero(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = recursiveZero(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = t1 or t2.new()
t1:resizeAs(t2):zero()
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function ZeroGrad:updateOutput(input)
self.output:set(input)
return self.output
end
-- the gradient is simply zeroed.
-- useful when you don't want to backpropgate through certain paths.
function ZeroGrad:updateGradInput(input, gradOutput)
self.gradInput = recursiveZero(self.gradInput, gradOutput)
end
|
local ZeroGrad, parent
if nn.ZeroGrad then -- prevent name conflicts with rnn
ZeroGrad, parent = nn.ZeroGrad, nn.Module
else
ZeroGrad, parent = torch.class('nn.ZeroGrad', 'nn.Module')
end
local function recursiveZero(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = recursiveZero(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = t1 or t2.new()
t1:resizeAs(t2):zero()
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function ZeroGrad:updateOutput(input)
self.output:set(input)
return self.output
end
-- the gradient is simply zeroed.
-- useful when you don't want to backpropgate through certain paths.
function ZeroGrad:updateGradInput(input, gradOutput)
self.gradInput = recursiveZero(self.gradInput, gradOutput)
end
|
fix dependency bug
|
fix dependency bug
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
38faabb4db2fc127bc67bd9052e7d16f1bf4a64e
|
vrp/client/survival.lua
|
vrp/client/survival.lua
|
-- api
function tvRP.varyHealth(variation)
local ped = GetPlayerPed(-1)
local n = math.floor(GetEntityHealth(ped)+variation)
SetEntityHealth(ped,n)
end
function tvRP.getHealth()
return GetEntityHealth(GetPlayerPed(-1))
end
function tvRP.setHealth(health)
local n = math.floor(health)
SetEntityHealth(GetPlayerPed(-1),n)
end
function tvRP.setFriendlyFire(flag)
NetworkSetFriendlyFireOption(flag)
SetCanAttackFriendly(GetPlayerPed(-1), flag, flag)
end
function tvRP.setPolice(flag)
local player = PlayerId()
SetPoliceIgnorePlayer(player, not flag)
SetDispatchCopsForPlayer(player, flag)
end
-- impact thirst and hunger when the player is running (every 5 seconds)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5000)
if IsPlayerPlaying(PlayerId()) then
local ped = GetPlayerPed(-1)
-- variations for one minute
local vthirst = 0
local vhunger = 0
-- on foot, increase thirst/hunger in function of velocity
if IsPedOnFoot(ped) then
local factor = math.min(tvRP.getSpeed(),10)
vthirst = vthirst+1*factor
vhunger = vhunger+0.5*factor
end
-- in melee combat, increase
if IsPedInMeleeCombat(ped) then
vthirst = vthirst+10
vhunger = vhunger+5
end
-- injured, hurt, increase
if IsPedHurt(ped) or IsPedInjured(ped) then
vthirst = vthirst+2
vhunger = vhunger+1
end
-- do variation
if vthirst ~= 0 then
vRPserver.varyThirst({vthirst/12.0})
end
if vhunger ~= 0 then
vRPserver.varyHunger({vhunger/12.0})
end
end
end
end)
-- coma system
local in_coma = false
local coma_health = cfg.coma_threshold
local coma_decrease_delay = math.floor(cfg.coma_duration*60000/(cfg.coma_threshold-100))
Citizen.CreateThread(function() -- coma thread
while true do
local ped = GetPlayerPed(-1)
Citizen.Wait(0)
if GetEntityHealth(ped) <= cfg.coma_threshold then
if not in_coma then -- go to coma state
in_coma = true
tvRP.setRagdoll(true)
coma_health = cfg.coma_threshold -- init coma health
end
-- stabilize health
SetEntityHealth(ped, coma_health)
else
if in_coma then
in_coma = false
tvRP.setRagdoll(false)
end
end
end
end)
Citizen.CreateThread(function() -- coma decrease thread
while true do
Citizen.Wait(coma_decrease_delay)
coma_health = coma_health-1
end
end)
function tvRP.isInComa()
return in_coma
end
|
-- api
function tvRP.varyHealth(variation)
local ped = GetPlayerPed(-1)
local n = math.floor(GetEntityHealth(ped)+variation)
SetEntityHealth(ped,n)
end
function tvRP.getHealth()
return GetEntityHealth(GetPlayerPed(-1))
end
function tvRP.setHealth(health)
local n = math.floor(health)
SetEntityHealth(GetPlayerPed(-1),n)
end
function tvRP.setFriendlyFire(flag)
NetworkSetFriendlyFireOption(flag)
SetCanAttackFriendly(GetPlayerPed(-1), flag, flag)
end
function tvRP.setPolice(flag)
local player = PlayerId()
SetPoliceIgnorePlayer(player, not flag)
SetDispatchCopsForPlayer(player, flag)
end
-- impact thirst and hunger when the player is running (every 5 seconds)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5000)
if IsPlayerPlaying(PlayerId()) then
local ped = GetPlayerPed(-1)
-- variations for one minute
local vthirst = 0
local vhunger = 0
-- on foot, increase thirst/hunger in function of velocity
if IsPedOnFoot(ped) then
local factor = math.min(tvRP.getSpeed(),10)
vthirst = vthirst+1*factor
vhunger = vhunger+0.5*factor
end
-- in melee combat, increase
if IsPedInMeleeCombat(ped) then
vthirst = vthirst+10
vhunger = vhunger+5
end
-- injured, hurt, increase
if IsPedHurt(ped) or IsPedInjured(ped) then
vthirst = vthirst+2
vhunger = vhunger+1
end
-- do variation
if vthirst ~= 0 then
vRPserver.varyThirst({vthirst/12.0})
end
if vhunger ~= 0 then
vRPserver.varyHunger({vhunger/12.0})
end
end
end
end)
-- coma system
local in_coma = false
local coma_health = cfg.coma_threshold
local coma_decrease_delay = math.floor(cfg.coma_duration*60000/(cfg.coma_threshold-100))
Citizen.CreateThread(function() -- coma thread
while true do
local ped = GetPlayerPed(-1)
Citizen.Wait(0)
if GetEntityHealth(ped) <= cfg.coma_threshold then
if not in_coma then -- go to coma state
in_coma = true
tvRP.setRagdoll(true)
coma_health = GetEntityHealth(ped)
end
-- stabilize health
SetEntityHealth(ped, coma_health)
else
if in_coma then
in_coma = false
tvRP.setRagdoll(false)
end
end
end
end)
Citizen.CreateThread(function() -- coma decrease thread
while true do
Citizen.Wait(coma_decrease_delay)
coma_health = coma_health-1
end
end)
function tvRP.isInComa()
return in_coma
end
|
Fix restart coma duration on respawn
|
Fix restart coma duration on respawn
|
Lua
|
mit
|
ENDrain/vRP-plusplus,ImagicTheCat/vRP,ENDrain/vRP-plusplus,ENDrain/vRP-plusplus,ImagicTheCat/vRP
|
a306cdfbbe5e4231ee918b21248930048ae4fcb1
|
plugins/mod_posix.lua
|
plugins/mod_posix.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local want_pposix_version = "0.3.1";
local pposix = assert(require "util.pposix");
if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end
local signal = select(2, pcall(require, "util.signal"));
if type(signal) == "string" then
module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
end
local logger_set = require "util.logger".setwriter;
local prosody = _G.prosody;
module.host = "*"; -- we're a global module
-- Allow switching away from root, some people like strange ports.
module:add_event_hook("server-started", function ()
local uid = module:get_option("setuid");
local gid = module:get_option("setgid");
if gid then
local success, msg = pposix.setgid(gid);
if success then
module:log("debug", "Changed group to "..gid.." successfully.");
else
module:log("error", "Failed to change group to "..gid..". Error: "..msg);
prosody.shutdown("Failed to change group to "..gid);
end
end
if uid then
local success, msg = pposix.setuid(uid);
if success then
module:log("debug", "Changed user to "..uid.." successfully.");
else
module:log("error", "Failed to change user to "..uid..". Error: "..msg);
prosody.shutdown("Failed to change user to "..uid);
end
end
end);
-- Don't even think about it!
module:add_event_hook("server-starting", function ()
local suid = module:get_option("setuid");
if not suid or suid == 0 or suid == "root" then
if pposix.getuid() == 0 and not module:get_option("run_as_root") then
module:log("error", "Danger, Will Robinson! Prosody doesn't need to be run as root, so don't do it!");
module:log("error", "For more information on running Prosody as root, see http://prosody.im/doc/root");
prosody.shutdown("Refusing to run as root");
end
end
end);
local pidfile_written;
local function remove_pidfile()
if pidfile_written then
os.remove(pidfile_written);
pidfile_written = nil;
end
end
local function write_pidfile()
if pidfile_written then
remove_pidfile();
end
local pidfile = module:get_option("pidfile");
if pidfile then
local pf, err = io.open(pidfile, "w+");
if not pf then
module:log("error", "Couldn't write pidfile; %s", err);
else
pf:write(tostring(pposix.getpid()));
pf:close();
pidfile_written = pidfile;
end
end
end
local syslog_opened
function syslog_sink_maker(config)
if not syslog_opened then
pposix.syslog_open("prosody");
syslog_opened = true;
end
local syslog, format = pposix.syslog_log, string.format;
return function (name, level, message, ...)
if ... then
syslog(level, format(message, ...));
else
syslog(level, message);
end
end;
end
require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker);
local daemonize = module:get_option("daemonize");
if daemonize == nil then
local no_daemonize = module:get_option("no_daemonize"); --COMPAT w/ 0.5
daemonize = not no_daemonize;
if no_daemonize ~= nil then
module:log("warn", "The 'no_daemonize' option is now replaced by 'daemonize'");
module:log("warn", "Update your config from 'no_daemonize = %s' to 'daemonize = %s'", tostring(no_daemonize), tostring(daemonize));
end
end
if daemonize then
local function daemonize_server()
local ok, ret = pposix.daemonize();
if not ok then
module:log("error", "Failed to daemonize: %s", ret);
elseif ret and ret > 0 then
os.exit(0);
else
module:log("info", "Successfully daemonized to PID %d", pposix.getpid());
write_pidfile();
end
end
module:add_event_hook("server-starting", daemonize_server);
else
-- Not going to daemonize, so write the pid of this process
write_pidfile();
end
module:add_event_hook("server-stopped", remove_pidfile);
-- Set signal handlers
if signal.signal then
signal.signal("SIGTERM", function ()
module:log("warn", "Received SIGTERM");
signal.signal("SIGTERM", function () end); -- Fixes us getting into some kind of loop
prosody.unlock_globals();
prosody.shutdown("Received SIGTERM");
prosody.lock_globals();
end);
signal.signal("SIGHUP", function ()
module:log("info", "Received SIGHUP");
prosody.reload_config();
prosody.reopen_logfiles();
end);
signal.signal("SIGINT", function ()
module:log("info", "Received SIGINT");
signal.signal("SIGINT", function () end); -- Fix to not loop
prosody.unlock_globals();
prosody.shutdown("Received SIGINT");
prosody.lock_globals();
end);
end
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local want_pposix_version = "0.3.1";
local pposix = assert(require "util.pposix");
if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end
local signal = select(2, pcall(require, "util.signal"));
if type(signal) == "string" then
module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
end
local logger_set = require "util.logger".setwriter;
local prosody = _G.prosody;
module.host = "*"; -- we're a global module
-- Allow switching away from root, some people like strange ports.
module:add_event_hook("server-started", function ()
local uid = module:get_option("setuid");
local gid = module:get_option("setgid");
if gid then
local success, msg = pposix.setgid(gid);
if success then
module:log("debug", "Changed group to "..gid.." successfully.");
else
module:log("error", "Failed to change group to "..gid..". Error: "..msg);
prosody.shutdown("Failed to change group to "..gid);
end
end
if uid then
local success, msg = pposix.setuid(uid);
if success then
module:log("debug", "Changed user to "..uid.." successfully.");
else
module:log("error", "Failed to change user to "..uid..". Error: "..msg);
prosody.shutdown("Failed to change user to "..uid);
end
end
end);
-- Don't even think about it!
module:add_event_hook("server-starting", function ()
local suid = module:get_option("setuid");
if not suid or suid == 0 or suid == "root" then
if pposix.getuid() == 0 and not module:get_option("run_as_root") then
module:log("error", "Danger, Will Robinson! Prosody doesn't need to be run as root, so don't do it!");
module:log("error", "For more information on running Prosody as root, see http://prosody.im/doc/root");
prosody.shutdown("Refusing to run as root");
end
end
end);
local pidfile_written;
local function remove_pidfile()
if pidfile_written then
os.remove(pidfile_written);
pidfile_written = nil;
end
end
local function write_pidfile()
if pidfile_written then
remove_pidfile();
end
local pidfile = module:get_option("pidfile");
if pidfile then
local pf, err = io.open(pidfile, "w+");
if not pf then
module:log("error", "Couldn't write pidfile; %s", err);
else
pf:write(tostring(pposix.getpid()));
pf:close();
pidfile_written = pidfile;
end
end
end
local syslog_opened
function syslog_sink_maker(config)
if not syslog_opened then
pposix.syslog_open("prosody");
syslog_opened = true;
end
local syslog, format = pposix.syslog_log, string.format;
return function (name, level, message, ...)
if ... then
syslog(level, format(message, ...));
else
syslog(level, message);
end
end;
end
require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker);
local daemonize = module:get_option("daemonize");
if daemonize == nil then
local no_daemonize = module:get_option("no_daemonize"); --COMPAT w/ 0.5
daemonize = not no_daemonize;
if no_daemonize ~= nil then
module:log("warn", "The 'no_daemonize' option is now replaced by 'daemonize'");
module:log("warn", "Update your config from 'no_daemonize = %s' to 'daemonize = %s'", tostring(no_daemonize), tostring(daemonize));
end
end
if daemonize then
local function daemonize_server()
local ok, ret = pposix.daemonize();
if not ok then
module:log("error", "Failed to daemonize: %s", ret);
elseif ret and ret > 0 then
os.exit(0);
else
module:log("info", "Successfully daemonized to PID %d", pposix.getpid());
write_pidfile();
end
end
module:add_event_hook("server-starting", daemonize_server);
else
-- Not going to daemonize, so write the pid of this process
write_pidfile();
end
module:add_event_hook("server-stopped", remove_pidfile);
-- Set signal handlers
if signal.signal then
signal.signal("SIGTERM", function ()
module:log("warn", "Received SIGTERM");
prosody.unlock_globals();
prosody.shutdown("Received SIGTERM");
prosody.lock_globals();
end);
signal.signal("SIGHUP", function ()
module:log("info", "Received SIGHUP");
prosody.reload_config();
prosody.reopen_logfiles();
end);
signal.signal("SIGINT", function ()
module:log("info", "Received SIGINT");
prosody.unlock_globals();
prosody.shutdown("Received SIGINT");
prosody.lock_globals();
end);
end
|
mod_posix: Remove the lines added to work around the util.signal loop bug
|
mod_posix: Remove the lines added to work around the util.signal loop bug
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2ede85b706f13b6f48d673de91cd05eac8faba00
|
handlers.lua
|
handlers.lua
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
if message:sub(1,1) == "\001" then
local space = message:find(" ") or #message
o:invoke("OnCTCP", parsePrefix(prefix), channel, message:sub(2, space-1):upper(), message:sub(space+1,#message-1))
else
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
--disabled, better to always track everything instead of having it have an empty user with just an "access" field
--also it is broken a bit anyway
--[[handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end]]
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
if user and o.channels[target].users[user] then o.channels[target].users[user].access.op = add end
elseif c == "h" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.halfop = add end
elseif c == "v" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.voice = add end
elseif c == "b" or c == "q" then
table.remove(optList, 1)
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
if message:sub(1,1) == "\001" then
local space = message:find(" ") or #message
o:invoke("OnCTCP", parsePrefix(prefix), channel, message:sub(2, space-1):upper(), message:sub(space+1,#message-1))
else
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick and not o.channels[channel] then
o.channels[channel] = {users = {}}
end
o.channels[channel].users[user.nick] = user
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
if not o.channels[channel] then
o.channels[channel] = {users = {}}
end
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
--disabled, better to always track everything instead of having it have an empty user with just an "access" field
--also it is broken a bit anyway
--[[handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end]]
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
if user and o.channels[target].users[user] then o.channels[target].users[user].access.op = add end
elseif c == "h" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.halfop = add end
elseif c == "v" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.voice = add end
elseif c == "b" or c == "q" then
table.remove(optList, 1)
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
fix crash on startup (seems to be when WHO response happens before the channel is joined)
|
fix crash on startup (seems to be when WHO response happens before the channel is joined)
|
Lua
|
mit
|
wolfy1339/LuaIRC
|
3524ce46d44cf587b7ed6004980b598e6ea85c8e
|
Resources/Scripts/Tests/JaggedList.lua
|
Resources/Scripts/Tests/JaggedList.lua
|
function ObjectIterator(list)
local function jaggedObjectListOterator(list, index)
if index[2] == nil then
index[1] = next(list, index[1])
if index[1] == nil then
return nil, nil
end
end
local i, k = next(list[index[1]], index[2])
index[2] = i
return index, k
end
return jaggedObjectListOterator, list, {nil, nil}
end
list = {
{1, 2, 3, 4},
{5, 6, 7},
{8, 9, 10, 11, 12, 13, 14},
{15},
{16, 17, 18},
{19, 20},
}
for a, b in ObjectIterator(list) do
if b ~= nil then
print(b)
end
end
function key(k)
if k == "escape" then
mode_manager.switch("Xsera/MainMenu")
end
end
function render()
graphics.begin_frame()
graphics.end_frame()
end
|
__idmt = {
__lt = function(a, b)
if a[1] == b[1] then
if a[2] == nil then print(debug.traceback("A")) end
if b[2] == nil then print(debug.traceback("B")) end
return a[2] < b[2]
else
return a[1] < b[1]
end
end;
__le = function(a, b)
if a[1] == b[1] then
return a[2] <= b[2]
else
return a[1] <= b[1]
end
end;
__eq = function(a, b)
return a[1] == b[1] and a[2] == b[2]
end;
__tostring = function(a)
return (a[1] or "nil") .. ", " .. (a[2] or "nil")
end;
}
function ObjectIterator(list)
local function jaggedListIterator(list, index)
if index[2] == nil then
index[1] = next(list, index[1])
if index[1] == nil then
return nil, nil
end
end
local i, k = next(list[index[1]], index[2])
index[2] = i
if index[2] == nil then
return jaggedListIterator(list, index)
end
return index, k
end
local nlt = {nil, nil}
setmetatable(nlt, __idmt)
return jaggedListIterator, list, nlt
end
list = {
{1, 2, 3, 4},
{5, 6, 7},
{8, 9, 10, 11, 12, 13, 14},
{15},
{16, 17, 18},
{19, 20},
}
for a, b in ObjectIterator(list) do
if b ~= nil then
print(a,": ", b)
end
end
function key(k)
if k == "escape" then
mode_manager.switch("Xsera/MainMenu")
end
end
function render()
graphics.begin_frame()
graphics.end_frame()
end
|
Fixes to the test.
|
Fixes to the test.
Signed-off-by: Scott McClaugherty <[email protected]>
|
Lua
|
mit
|
adam000/xsera,prophile/xsera,prophile/xsera,prophile/xsera,adam000/xsera,adam000/xsera,adam000/xsera,prophile/xsera,prophile/xsera
|
f7d878b6bbae17291eee4b66380f654864f03e3a
|
regress/readdir-errno.lua
|
regress/readdir-errno.lua
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua -r5.2 "$0" "$@"
]]
require"regress".export".*"
local unix = require"unix"
local tmpdir = check(mkdtemp())
local nofile = 256
for i=1,nofile do
local path = string.format("%s/%02x-%s", tmpdir, i - 1, tmpnonce())
check(io.open(path, "w+"))
end
info("created %d files in %s", nofile, tmpdir)
local n = 0
for name in check(unix.opendir(tmpdir)):files"name" do
if name ~= "." and name ~= ".." then
n = n + 1
end
end
check(n == nofile, "expected to see %d files, but only saw %d", nofile, n)
info("found all %d files in %s", nofile, tmpdir)
local function tryfail(how)
unix.chmod(tmpdir, "u+rwx") -- undo any previous chmod
local dir = check(unix.opendir(tmpdir))
how(dir)
repeat
local name, why, error = unix.readdir(dir, "name")
if name then
how(dir, name)
elseif error then
return error
end
until not name
dir:close()
end -- tryfail
local function dofail(t)
for _, how in ipairs(t) do
info("%s", how.text)
local error = tryfail(how.func)
if error then
return error
end
end
end -- dofail
local goterror = dofail{
{
text = "testing readdir_r error by changing file permissions during read",
func = function (dir, name)
if name then
check(unix.chmod(dir, "0000"), "unable to chmod")
end
end
},
{
text = "testing readdir_r error by changing file permissions before read",
func = function (dir, name)
if not name then
check(unix.chmod(dir, "0000"), "unable to chmod")
end
end
},
{
text = "testing readdir_r error by duping over descriptor during read",
func = function (dir, name)
if name then
check(unix.dup2(check(io.tmpfile()), dir), "unable to dup2")
end
end
},
{
text = "testing readdir_r error by duping over descriptor before read",
func = function (dir, name)
if not name then
check(unix.dup2(check(io.tmpfile()), dir), "unable to dup2")
end
end
},
}
check(goterror, "unable to induce readdir_r error")
info("induced readdir_r error: %s", unix.strerror(goterror))
say"OK"
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua -r5.2 "$0" "$@"
]]
require"regress".export".*"
local unix = require"unix"
local tmpdir = check(mkdtemp())
local nofile = 256
for i=1,nofile do
local path = string.format("%s/%02x-%s", tmpdir, i - 1, tmpnonce())
check(io.open(path, "w+"))
end
info("created %d files in %s", nofile, tmpdir)
local n = 0
for name in check(unix.opendir(tmpdir)):files"name" do
if name ~= "." and name ~= ".." then
n = n + 1
end
end
check(n == nofile, "expected to see %d files, but only saw %d", nofile, n)
info("found all %d files in %s", nofile, tmpdir)
local function tryfail(how)
unix.chmod(tmpdir, "u+rwx") -- undo any previous chmod
local dir = check(unix.opendir(tmpdir))
how(dir)
repeat
local name, why, error = unix.readdir(dir, "name")
if name then
how(dir, name)
elseif error then
return error
end
until not name
dir:close()
end -- tryfail
local function dofail(t)
for _, how in ipairs(t) do
info("%s", how.text)
local error = tryfail(how.func)
if error then
return error
end
end
end -- dofail
local goterror = dofail{
{
text = "testing readdir_r error by changing file permissions during read",
func = function (dir, name)
if name then
check(unix.chmod(dir, "0000"), "unable to chmod")
end
end
},
{
text = "testing readdir_r error by changing file permissions before read",
func = function (dir, name)
if not name then
check(unix.chmod(dir, "0000"), "unable to chmod")
end
end
},
{
text = "testing readdir_r error by duping over descriptor during read",
func = function (dir, name)
if name then
local fh = check(io.tmpfile())
check(unix.dup2(fh, dir), "unable to dup2")
fh:close()
end
end
},
{
text = "testing readdir_r error by duping over descriptor before read",
func = function (dir, name)
if not name then
local fh = check(io.tmpfile())
check(unix.dup2(fh, dir), "unable to dup2")
fh:close()
end
end
},
}
check(goterror, "unable to induce readdir_r error")
info("induced readdir_r error: %s", unix.strerror(goterror))
say"OK"
|
fix readdir-errno regressin test
|
fix readdir-errno regressin test
|
Lua
|
mit
|
wahern/lunix,Redfoxmoon3/lunix,wahern/lunix,Redfoxmoon3/lunix
|
efe8584781f172e21463c4ce74eab8a66cf077aa
|
scripts/format.lua
|
scripts/format.lua
|
-- Get the Gerrit base URL from the given change URL.
local function get_gerrit_base_url(change_url)
return string.sub(change_url, 1, #change_url - string.find(string.reverse(change_url), "/"))
end
-- Get a URL for a Gerrit query.
local function get_query_url(base_url, query, ...)
return string.format("%s/q/%s", base_url, string.format(query, ...))
end
-- Format a link.
local function format_link(text, target)
return string.format("[%s](%s)", text, target)
end
-- Format a link to a Gerrit query.
local function format_query_link(base_url, text, query, ...)
return format_link(text, get_query_url(base_url, query, ...))
end
-- Format a link to a user.
local function format_user(base_url, user, role)
return format_query_link(
base_url,
user.name or user.email,
"%s:%s+status:open",
role, user.email
)
end
-- Format a change's subject.
local function format_change_subject(change)
return format_link(change.subject, change.url)
end
-- Format a change's project.
local function format_change_project(base_url, change)
local result = format_query_link(
base_url,
change.project,
"project:%s+status:open",
change.project
)
if change.branch ~= "master" then
result = result .. ", branch:" .. change.branch
end
if change.topic then
result = result .. ", topic:" .. format_query_link(
base_url,
change.topic,
"topic:%s+status:open",
change.topic
)
end
return result
end
local APPROVAL_ICONS = {
["WaitForVerification"] = {[-1] = "⏳"},
["Code-Review"] = {[-2] = "👎", [-1] = "🤷", [1] = "👌", [2] = "👍"},
["Verified"] = {[-1] = "❌", [1] = "✔"},
-- fallback
["*"] = {[-2] = "👎", [-1] = "🙅", [1] = "🙆", [2] = "👍"},
}
local function get_approval_icon(type, value, old_value)
if value == 0 then
if old_value ~= 0 then
return "📝"
else
return nil
end
end
type_icons = APPROVAL_ICONS[type] or APPROVAL_ICONS["*"]
return type_icons[value]
end
local function format_approval(approval)
local approval_value = tonumber(approval.value)
local old_approval_value = tonumber(approval.old_value or "0")
local icon = get_approval_icon(approval.type, approval_value, old_approval_value)
local sign = ""
if approval_value > 0 then
sign = "+"
end
if icon then
icon = icon .. " "
else
icon = ""
end
return string.format("%s%s%s (%s)", icon, sign, approval_value, approval.type)
end
-- return an iterator over the lines in the given string
local function lines_iter(s)
return string.gmatch(s, "[^\r\n]+")
end
local function format_comment(comment, is_human)
local lines = {}
for line in lines_iter(comment) do
if is_human and not line:match "^Patch Set" and not line:match "%(%d+ comments?%)" then
table.insert(lines, "> " .. line)
elseif string.match(line, "FAILURE") then
table.insert(lines, "> " .. line)
end
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n")
end
end
local function format_inline_comment(base_url, change, patchset, comment)
local lines = {}
for line in lines_iter(comment.message) do
if #lines == 0 then
local url = string.format(
"%s/#/c/%s/%s/%s@%s",
base_url,
change.number,
patchset.number,
comment.file,
comment.line
)
table.insert(
lines,
string.format(
"> [Line %s](%s) by %s: %s",
comment.line,
url,
format_user(base_url, comment.reviewer, "reviewer"),
line
)
)
else
table.insert(lines, "> " .. line)
end
end
return table.concat(lines, "\n")
end
local function format_inline_comments(base_url, change, patchset)
local lines = {}
local comments = patchset.comments or {}
table.sort(comments, function (c1, c2) return c1.file < c2.file end)
local file
for _i, comment in ipairs(comments) do
if comment.file ~= file then
file = comment.file
table.insert(lines, string.format("`%s`", file))
end
table.insert(lines, format_inline_comment(base_url, change, patchset, comment))
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n") .. "\n"
end
end
-- Filter and format messages
-- return nil to filter the message
function format_comment_added(event, is_human)
local change = event.change
local patchset = event.patchSet
local base_url = get_gerrit_base_url(change.url)
local msg = format_change_subject(change) .. " (" .. format_change_project(base_url, change) .. ")"
local formatted_approvals = {}
for _i, approval in ipairs(event.approvals) do
local formatted_approval = format_approval(approval)
if formatted_approval then
table.insert(formatted_approvals, formatted_approval)
end
end
if #formatted_approvals > 0 then
msg = msg .. " " .. table.concat(formatted_approvals, ", ")
elseif not (is_human and patchset.comments and #patchset.comments > 0) then
-- TODO: messages without approvals should still be formatted since they
-- can be comment responses. This should be handled at a higher level.
-- Keep this here for now to prevent spamming.
return
end
msg = msg .. " from " .. format_user(base_url, event.author, "reviewer")
msg = msg .. (format_comment(event.comment, is_human) or "")
msg = msg .. (format_inline_comments(base_url, change, patchset) or "")
return msg
end
function format_reviewer_added(event)
local change = event.change
local base_url = get_gerrit_base_url(change.url)
return string.format(
"%s (%s) by %s 👓 Added as reviewer",
format_change_subject(change),
format_change_project(base_url, change),
format_user(base_url, change.owner, "owner")
)
end
|
-- Get the Gerrit base URL from the given change URL.
local function get_gerrit_base_url(change_url)
return string.sub(change_url, 1, #change_url - string.find(string.reverse(change_url), "/"))
end
-- Get a URL for a Gerrit query.
local function get_query_url(base_url, query, ...)
return string.format("%s/q/%s", base_url, string.format(query, ...))
end
-- Format a link.
local function format_link(text, target)
return string.format("[%s](%s)", text, target)
end
-- Format a link to a Gerrit query.
local function format_query_link(base_url, text, query, ...)
return format_link(text, get_query_url(base_url, query, ...))
end
-- Format a link to a user.
local function format_user(base_url, user, role)
return format_query_link(
base_url,
user.name or user.email,
"%s:%s+status:open",
role, user.email
)
end
-- Format a change's subject.
local function format_change_subject(change)
return format_link(change.subject, change.url)
end
-- Format a change's project.
local function format_change_project(base_url, change)
local result = format_query_link(
base_url,
change.project,
"project:%s+status:open",
change.project
)
if change.branch ~= "master" then
result = result .. ", branch:" .. change.branch
end
if change.topic then
result = result .. ", topic:" .. format_query_link(
base_url,
change.topic,
"topic:%s+status:open",
change.topic
)
end
return result
end
local APPROVAL_ICONS = {
["WaitForVerification"] = {[-1] = "⏳"},
["Code-Review"] = {[-2] = "👎", [-1] = "🤷", [1] = "👌", [2] = "👍"},
["Verified"] = {[-1] = "❌", [1] = "✔"},
-- fallback
["*"] = {[-2] = "👎", [-1] = "🙅", [1] = "🙆", [2] = "👍"},
}
local function get_approval_icon(type, value, old_value)
if value == 0 then
if old_value ~= 0 then
return "📝"
else
return nil
end
end
type_icons = APPROVAL_ICONS[type] or APPROVAL_ICONS["*"]
return type_icons[value]
end
local function format_approval(approval)
local approval_value = tonumber(approval.value) or 0
local old_approval_value = tonumber(approval.oldValue) or 0
if old_approval_value == approval_value then
return nil
end
local icon = get_approval_icon(approval.type, approval_value, old_approval_value)
local sign = ""
if approval_value > 0 then
sign = "+"
end
if icon then
icon = icon .. " "
else
icon = ""
end
return string.format("%s%s%s (%s)", icon, sign, approval_value, approval.type)
end
-- return an iterator over the lines in the given string
local function lines_iter(s)
return string.gmatch(s, "[^\r\n]+")
end
local function format_comment(comment, is_human)
local lines = {}
for line in lines_iter(comment) do
if is_human and not line:match "^Patch Set" and not line:match "%(%d+ comments?%)" then
table.insert(lines, "> " .. line)
elseif string.match(line, "FAILURE") then
table.insert(lines, "> " .. line)
end
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n")
end
end
local function format_inline_comment(base_url, change, patchset, comment)
local lines = {}
for line in lines_iter(comment.message) do
if #lines == 0 then
local url = string.format(
"%s/#/c/%s/%s/%s@%s",
base_url,
change.number,
patchset.number,
comment.file,
comment.line
)
table.insert(
lines,
string.format(
"> [Line %s](%s) by %s: %s",
comment.line,
url,
format_user(base_url, comment.reviewer, "reviewer"),
line
)
)
else
table.insert(lines, "> " .. line)
end
end
return table.concat(lines, "\n")
end
local function format_inline_comments(base_url, change, patchset)
local lines = {}
local comments = patchset.comments or {}
table.sort(comments, function (c1, c2) return c1.file < c2.file end)
local file
for _i, comment in ipairs(comments) do
if comment.file ~= file then
file = comment.file
table.insert(lines, string.format("`%s`", file))
end
table.insert(lines, format_inline_comment(base_url, change, patchset, comment))
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n") .. "\n"
end
end
-- Filter and format messages
-- return nil to filter the message
function format_comment_added(event, is_human)
local change = event.change
local patchset = event.patchSet
local base_url = get_gerrit_base_url(change.url)
local msg = format_change_subject(change) .. " (" .. format_change_project(base_url, change) .. ")"
local formatted_approvals = {}
table.sort(event.approvals, function(a1, a2) return a1.type < a2.type end)
for _i, approval in ipairs(event.approvals) do
local formatted_approval = format_approval(approval)
if formatted_approval then
table.insert(formatted_approvals, formatted_approval)
end
end
if #formatted_approvals > 0 then
msg = msg .. " " .. table.concat(formatted_approvals, ", ")
elseif not (is_human and patchset.comments and #patchset.comments > 0) then
-- TODO: messages without approvals should still be formatted since they
-- can be comment responses. This should be handled at a higher level.
-- Keep this here for now to prevent spamming.
return
end
msg = msg .. " from " .. format_user(base_url, event.author, "reviewer")
msg = msg .. (format_comment(event.comment, is_human) or "")
msg = msg .. (format_inline_comments(base_url, change, patchset) or "")
return msg
end
function format_reviewer_added(event)
local change = event.change
local base_url = get_gerrit_base_url(change.url)
return string.format(
"%s (%s) by %s 👓 Added as reviewer",
format_change_subject(change),
format_change_project(base_url, change),
format_user(base_url, change.owner, "owner")
)
end
|
improve approvals formatting
|
improve approvals formatting
* fix handling old values
* don't show labels that didn't change
* sort labels by type
|
Lua
|
apache-2.0
|
boxdot/gerritbot-rs,boxdot/gerritbot-rs,boxdot/gerritbot-rs
|
4f58b097785c5cf9384bdc44a9f8324a22422e7a
|
site/api/mbox.lua
|
site/api/mbox.lua
|
--[[
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.
]]--
-- This is mbox.lua - a script for generating mbox archives
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local aaa = require 'lib/aaa'
local user = require 'lib/user'
local cross = require 'lib/cross'
local days = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31
}
function leapYear(year)
if (year % 4 == 0) then
if (year%100 == 0)then
if (year %400 == 0) then
return true
end
else
return true
end
return false
end
end
function handle(r)
r.content_type = "application/mbox"
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d
if m == 2 and leapYear(y) then
d = 29
else
d = days[m]
end
-- fetch all results from the list (up to 20k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
if not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts("From \n")
r:puts(doc.source)
r:puts("\n")
end
end
end
end
return cross.OK
end
cross.start(handle)
|
--[[
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.
]]--
-- This is mbox.lua - a script for generating mbox archives
local elastic = require 'lib/elastic'
local cross = require 'lib/cross'
local days = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31
}
function leapYear(year)
if (year % 4 == 0) then
if (year%100 == 0)then
if (year %400 == 0) then
return true
end
else
return true
end
return false
end
end
function handle(r)
r.content_type = "application/mbox"
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d
if m == 2 and leapYear(y) then
d = 29
else
d = days[m]
end
-- fetch all results from the list (up to 10k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
if not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts("From \n")
r:puts(doc.source)
r:puts("\n")
end
end
end
end
return cross.OK
end
cross.start(handle)
|
Unused requires; fix comment
|
Unused requires; fix comment
|
Lua
|
apache-2.0
|
jimjag/ponymail,quenda/ponymail,quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,jimjag/ponymail,Humbedooh/ponymail,quenda/ponymail,jimjag/ponymail
|
97ae2d892811d4d56ce051ebca59082c074682be
|
gjk.lua
|
gjk.lua
|
--[[
Copyright (c) 2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local _PACKAGE = (...):match("^(.+)%.[^%.]+")
local vector = require(_PACKAGE .. '.vector-light')
local function support(shape_a, shape_b, dx, dy)
local x,y = shape_a:support(dx,dy)
return vector.sub(x,y, shape_b:support(-dx, -dy))
end
-- returns closest edge to the origin
local function closest_edge(simplex)
local e = {dist = math.huge}
local i = #simplex-1
for k = 1,#simplex-1,2 do
local ax,ay = simplex[i], simplex[i+1]
local bx,by = simplex[k], simplex[k+1]
i = k
local ex,ey = vector.perpendicular(bx-ax, by-ay)
local nx,ny = vector.normalize(ex,ey)
local d = vector.dot(ax,ay, nx,ny)
if d < e.dist then
e.dist = d
e.nx, e.ny = nx, ny
e.i = k
end
end
return e
end
local function EPA(shape_a, shape_b, simplex)
-- make sure simplex is oriented counter clockwise
local cx,cy, bx,by, ax,ay = unpack(simplex)
if vector.dot(ax-bx,ay-by, cx-bx,cy-by) < 0 then
simplex[1],simplex[2] = ax,ay
simplex[5],simplex[6] = cx,cy
end
-- the expanding polytype algorithm
local last_diff_dist = math.huge
while true do
local e = closest_edge(simplex)
local px,py = support(shape_a, shape_b, e.nx, e.ny)
local d = vector.dot(px,py, e.nx, e.ny)
local diff_dist = d - e.dist
if diff_dist < 1e-6 or last_diff_dist - diff_dist < 1e-10 then
return -d*e.nx, -d*e.ny
end
last_diff_dist = diff_dist
-- simplex = {..., simplex[e.i-1], px, py, simplex[e.i]
table.insert(simplex, e.i, py)
table.insert(simplex, e.i, px)
end
end
-- : : origin must be in plane between A and B
-- B o------o A since A is the furthest point on the MD
-- : : in direction of the origin.
local function do_line(simplex)
local bx,by, ax,ay = unpack(simplex)
local abx,aby = bx-ax, by-ay
local dx,dy = vector.perpendicular(abx,aby)
if vector.dot(dx,dy, -ax,-ay) < 0 then
dx,dy = -dx,-dy
end
return simplex, dx,dy
end
-- B .'
-- o-._ 1
-- | `-. .' The origin can only be in regions 1, 3 or 4:
-- | 4 o A 2 A lies on the edge of the MD and we came
-- | _.-' '. from left of BC.
-- o-' 3
-- C '.
local function do_triangle(simplex)
local cx,cy, bx,by, ax,ay = unpack(simplex)
local aox,aoy = -ax,-ay
local abx,aby = bx-ax, by-ay
local acx,acy = cx-ax, cy-ay
-- test region 1
local dx,dy = vector.perpendicular(abx,aby)
if vector.dot(dx,dy, acx,acy) > 0 then
dx,dy = -dx,-dy
end
if vector.dot(dx,dy, aox,aoy) > 0 then
-- simplex = {bx,by, ax,ay}
simplex[1], simplex[2] = bx,by
simplex[3], simplex[4] = ax,ay
simplex[5], simplex[6] = nil, nil
return simplex, dx,dy
end
-- test region 3
dx,dy = vector.perpendicular(acx,acy)
if vector.dot(dx,dy, abx,aby) > 0 then
dx,dy = -dx,-dy
end
if vector.dot(dx,dy, aox, aoy) > 0 then
-- simplex = {cx,cy, ax,ay}
simplex[3], simplex[4] = ax,ay
simplex[5], simplex[6] = nil, nil
return simplex, dx,dy
end
-- must be in region 4
return simplex
end
local function GJK(shape_a, shape_b)
local ax,ay = support(shape_a, shape_b, 1,0)
if ax == 0 and ay == 0 then
-- only true if shape_a and shape_b are touching in a vertex, e.g.
-- .--- .---.
-- | A | .-. | B | support(A, 1,0) = x
-- '---x---. or : A :x---' support(B, -1,0) = x
-- | B | `-' => support(A,B,1,0) = x - x = 0
-- '---'
-- Since CircleShape:support(dx,dy) normalizes dx,dy we have to opt
-- out or the algorithm blows up. In accordance to the cases below
-- choose to judge this situation as not colliding.
return false
end
local simplex = {ax,ay}
local n = 2
local dx,dy = -ax,-ay
-- first iteration: line case
ax,ay = support(shape_a, shape_b, dx,dy)
if vector.dot(ax,ay, dx,dy) <= 0 then
return false
end
simplex[n+1], simplex[n+2] = ax,ay
simplex, dx, dy = do_line(simplex, dx, dy)
n = 4
-- all other iterations must be the triangle case
while true do
ax,ay = support(shape_a, shape_b, dx,dy)
if vector.dot(ax,ay, dx,dy) <= 0 then
return false
end
simplex[n+1], simplex[n+2] = ax,ay
simplex, dx, dy = do_triangle(simplex, dx,dy)
n = #simplex
if n == 6 then
return true, EPA(shape_a, shape_b, simplex)
end
end
end
return GJK
|
--[[
Copyright (c) 2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local _PACKAGE = (...):match("^(.+)%.[^%.]+")
local vector = require(_PACKAGE .. '.vector-light')
local huge, abs = math.huge, math.abs
local function support(shape_a, shape_b, dx, dy)
local x,y = shape_a:support(dx,dy)
return vector.sub(x,y, shape_b:support(-dx, -dy))
end
-- returns closest edge to the origin
local function closest_edge(simplex)
local e = {dist = huge}
local i = #simplex-1
for k = 1,#simplex-1,2 do
local ax,ay = simplex[i], simplex[i+1]
local bx,by = simplex[k], simplex[k+1]
i = k
local ex,ey = vector.perpendicular(bx-ax, by-ay)
local nx,ny = vector.normalize(ex,ey)
local d = vector.dot(ax,ay, nx,ny)
if d < e.dist then
e.dist = d
e.nx, e.ny = nx, ny
e.i = k
end
end
return e
end
local function EPA(shape_a, shape_b, simplex)
-- make sure simplex is oriented counter clockwise
local cx,cy, bx,by, ax,ay = unpack(simplex)
if vector.dot(ax-bx,ay-by, cx-bx,cy-by) < 0 then
simplex[1],simplex[2] = ax,ay
simplex[5],simplex[6] = cx,cy
end
-- the expanding polytype algorithm
local last_diff_dist = huge
while true do
local e = closest_edge(simplex)
local px,py = support(shape_a, shape_b, e.nx, e.ny)
local d = vector.dot(px,py, e.nx, e.ny)
local diff_dist = d - e.dist
if diff_dist < 1e-6 or abs(last_diff_dist - diff_dist) < 1e-10 then
return -d*e.nx, -d*e.ny
end
last_diff_dist = diff_dist
-- simplex = {..., simplex[e.i-1], px, py, simplex[e.i]
table.insert(simplex, e.i, py)
table.insert(simplex, e.i, px)
end
end
-- : : origin must be in plane between A and B
-- B o------o A since A is the furthest point on the MD
-- : : in direction of the origin.
local function do_line(simplex)
local bx,by, ax,ay = unpack(simplex)
local abx,aby = bx-ax, by-ay
local dx,dy = vector.perpendicular(abx,aby)
if vector.dot(dx,dy, -ax,-ay) < 0 then
dx,dy = -dx,-dy
end
return simplex, dx,dy
end
-- B .'
-- o-._ 1
-- | `-. .' The origin can only be in regions 1, 3 or 4:
-- | 4 o A 2 A lies on the edge of the MD and we came
-- | _.-' '. from left of BC.
-- o-' 3
-- C '.
local function do_triangle(simplex)
local cx,cy, bx,by, ax,ay = unpack(simplex)
local aox,aoy = -ax,-ay
local abx,aby = bx-ax, by-ay
local acx,acy = cx-ax, cy-ay
-- test region 1
local dx,dy = vector.perpendicular(abx,aby)
if vector.dot(dx,dy, acx,acy) > 0 then
dx,dy = -dx,-dy
end
if vector.dot(dx,dy, aox,aoy) > 0 then
-- simplex = {bx,by, ax,ay}
simplex[1], simplex[2] = bx,by
simplex[3], simplex[4] = ax,ay
simplex[5], simplex[6] = nil, nil
return simplex, dx,dy
end
-- test region 3
dx,dy = vector.perpendicular(acx,acy)
if vector.dot(dx,dy, abx,aby) > 0 then
dx,dy = -dx,-dy
end
if vector.dot(dx,dy, aox, aoy) > 0 then
-- simplex = {cx,cy, ax,ay}
simplex[3], simplex[4] = ax,ay
simplex[5], simplex[6] = nil, nil
return simplex, dx,dy
end
-- must be in region 4
return simplex
end
local function GJK(shape_a, shape_b)
local ax,ay = support(shape_a, shape_b, 1,0)
if ax == 0 and ay == 0 then
-- only true if shape_a and shape_b are touching in a vertex, e.g.
-- .--- .---.
-- | A | .-. | B | support(A, 1,0) = x
-- '---x---. or : A :x---' support(B, -1,0) = x
-- | B | `-' => support(A,B,1,0) = x - x = 0
-- '---'
-- Since CircleShape:support(dx,dy) normalizes dx,dy we have to opt
-- out or the algorithm blows up. In accordance to the cases below
-- choose to judge this situation as not colliding.
return false
end
local simplex = {ax,ay}
local n = 2
local dx,dy = -ax,-ay
-- first iteration: line case
ax,ay = support(shape_a, shape_b, dx,dy)
if vector.dot(ax,ay, dx,dy) <= 0 then
return false
end
simplex[n+1], simplex[n+2] = ax,ay
simplex, dx, dy = do_line(simplex, dx, dy)
n = 4
-- all other iterations must be the triangle case
while true do
ax,ay = support(shape_a, shape_b, dx,dy)
if vector.dot(ax,ay, dx,dy) <= 0 then
return false
end
simplex[n+1], simplex[n+2] = ax,ay
simplex, dx, dy = do_triangle(simplex, dx,dy)
n = #simplex
if n == 6 then
return true, EPA(shape_a, shape_b, simplex)
end
end
end
return GJK
|
Fix commit adfe9a9a breaking EPA.
|
Fix commit adfe9a9a breaking EPA.
|
Lua
|
mit
|
aswyk/botrot
|
2794f6a99bd4057e9439c0e08b0ad9134f89a077
|
src/core/link.lua
|
src/core/link.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local debug = _G.developer_debug
local shm = require("core.shm")
local ffi = require("ffi")
local C = ffi.C
local packet = require("core.packet")
require("core.packet_h")
local counter = require("core.counter")
require("core.counter_h")
require("core.link_h")
local link_t = ffi.typeof("struct link")
local band = require("bit").band
local size = C.LINK_RING_SIZE -- NB: Huge slow-down if this is not local
max = C.LINK_MAX_PACKETS
local provided_counters = {
"dtime", "rxpackets", "rxbytes", "txpackets", "txbytes", "txdrop"
}
function new (name)
local r = ffi.new(link_t)
for _, c in ipairs(provided_counters) do
r.stats[c] = counter.create("links/"..name.."/"..c..".counter")
end
counter.set(r.stats.dtime, C.get_unix_time())
return r
end
function free (r, name)
for _, c in ipairs(provided_counters) do
counter.delete("links/"..name.."/"..c..".counter")
end
shm.unlink("links/"..name)
end
function receive (r)
-- if debug then assert(not empty(r), "receive on empty link") end
local p = r.packets[r.read]
r.read = band(r.read + 1, size - 1)
counter.add(r.stats.rxpackets)
counter.add(r.stats.rxbytes, p.length)
return p
end
function front (r)
return (r.read ~= r.write) and r.packets[r.read] or nil
end
function transmit (r, p)
-- assert(p)
if full(r) then
counter.add(r.stats.txdrop)
packet.free(p)
else
r.packets[r.write] = p
r.write = band(r.write + 1, size - 1)
counter.add(r.stats.txpackets)
counter.add(r.stats.txbytes, p.length)
end
end
-- Return true if the ring is empty.
function empty (r)
return r.read == r.write
end
-- Return true if the ring is full.
function full (r)
return band(r.write + 1, size - 1) == r.read
end
-- Return the number of packets that are ready for read.
function nreadable (r)
if r.read > r.write then
return r.write + size - r.read
else
return r.write - r.read
end
end
function nwritable (r)
return max - nreadable(r)
end
function stats (r)
local stats = {}
for _, c in ipairs(provided_counters) do
stats[c] = tonumber(counter.read(r.stats[c]))
end
return stats
end
function selftest ()
print("selftest: link")
local r = new("test")
local p = packet.allocate()
assert(counter.read(r.stats.txpackets) == 0 and empty(r) == true and full(r) == false)
assert(nreadable(r) == 0)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == 1 and empty(r) == false and full(r) == false)
for i = 1, max-2 do
transmit(r, p)
end
assert(counter.read(r.stats.txpackets) == max-1 and empty(r) == false and full(r) == false)
assert(nreadable(r) == counter.read(r.stats.txpackets))
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and empty(r) == false and full(r) == true)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and counter.read(r.stats.txdrop) == 1)
assert(not empty(r) and full(r))
while not empty(r) do
receive(r)
end
assert(counter.read(r.stats.rxpackets) == max)
link.free(r, "test")
print("selftest OK")
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local debug = _G.developer_debug
local shm = require("core.shm")
local ffi = require("ffi")
local C = ffi.C
local packet = require("core.packet")
require("core.packet_h")
local counter = require("core.counter")
require("core.counter_h")
require("core.link_h")
local link_t = ffi.typeof("struct link")
local band = require("bit").band
local size = C.LINK_RING_SIZE -- NB: Huge slow-down if this is not local
max = C.LINK_MAX_PACKETS
local provided_counters = {
"dtime", "rxpackets", "rxbytes", "txpackets", "txbytes", "txdrop"
}
function new (name)
local r = ffi.new(link_t)
for _, c in ipairs(provided_counters) do
r.stats[c] = counter.create("links/"..name.."/"..c..".counter")
end
counter.set(r.stats.dtime, C.get_unix_time())
return r
end
function free (r, name)
while not empty(r) do
packet.free(receive(r))
end
for _, c in ipairs(provided_counters) do
counter.delete("links/"..name.."/"..c..".counter")
end
shm.unlink("links/"..name)
end
function receive (r)
-- if debug then assert(not empty(r), "receive on empty link") end
local p = r.packets[r.read]
r.read = band(r.read + 1, size - 1)
counter.add(r.stats.rxpackets)
counter.add(r.stats.rxbytes, p.length)
return p
end
function front (r)
return (r.read ~= r.write) and r.packets[r.read] or nil
end
function transmit (r, p)
-- assert(p)
if full(r) then
counter.add(r.stats.txdrop)
packet.free(p)
else
r.packets[r.write] = p
r.write = band(r.write + 1, size - 1)
counter.add(r.stats.txpackets)
counter.add(r.stats.txbytes, p.length)
end
end
-- Return true if the ring is empty.
function empty (r)
return r.read == r.write
end
-- Return true if the ring is full.
function full (r)
return band(r.write + 1, size - 1) == r.read
end
-- Return the number of packets that are ready for read.
function nreadable (r)
if r.read > r.write then
return r.write + size - r.read
else
return r.write - r.read
end
end
function nwritable (r)
return max - nreadable(r)
end
function stats (r)
local stats = {}
for _, c in ipairs(provided_counters) do
stats[c] = tonumber(counter.read(r.stats[c]))
end
return stats
end
function selftest ()
print("selftest: link")
local r = new("test")
local p = packet.allocate()
assert(counter.read(r.stats.txpackets) == 0 and empty(r) == true and full(r) == false)
assert(nreadable(r) == 0)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == 1 and empty(r) == false and full(r) == false)
for i = 1, max-2 do
transmit(r, p)
end
assert(counter.read(r.stats.txpackets) == max-1 and empty(r) == false and full(r) == false)
assert(nreadable(r) == counter.read(r.stats.txpackets))
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and empty(r) == false and full(r) == true)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and counter.read(r.stats.txdrop) == 1)
assert(not empty(r) and full(r))
while not empty(r) do
receive(r)
end
assert(counter.read(r.stats.rxpackets) == max)
link.free(r, "test")
print("selftest OK")
end
|
core.link: free any packets left in link when freeing link
|
core.link: free any packets left in link when freeing link
Due to how the engine works, the case that a link is non-empty between
breaths is rare (specifically, it should only occur when an app pushes
to a “slow” output interface). That’s probably why this went unnoticed
until now. I don’t even have a case that triggers this bug, it just came
to me.
|
Lua
|
apache-2.0
|
Igalia/snabb,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,eugeneia/snabb,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabbswitch,dpino/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,dpino/snabb,eugeneia/snabb,eugeneia/snabbswitch,snabbco/snabb,snabbco/snabb,SnabbCo/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabb,dpino/snabbswitch,Igalia/snabb,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,dpino/snabb,dpino/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,dpino/snabb
|
ed63b2a1b158a0837edad1dc6111f37e27cc66b9
|
helper.lua
|
helper.lua
|
-- Helper Module
--
local setup = require "setup"
local dbmodule = require "dbmodule"
local config = require "config"
scriptdb = config.scriptdb
local helper = {}
helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search by Name of Script (s)", "Search by Category (c)", "Create script.db backup (b)", "Exit (q)"}
helper.searchMenu ={ "Search by Name (s)", "Main Menu (b)", "Exit (q)"}
function helper.banner()
banner=[[
_ _ _____ _____ _
| \ | |/ ___|| ___| | |
| \| |\ `--. | |__ __ _ _ __ ___ | |__
| . ` | `--. \| __| / _` || '__| / __|| '_ \
| |\ |/\__/ /| |___ | (_| || | | (__ | | | |
\_| \_/\____/ \____/ \__,_||_| \___||_| |_|
]]
return banner
end
function getScirptDesc( nse )
io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (q) ')
local option = io.read("*n")
if nse[option] then
print("\n")
local file = config.scriptsPath..nse[option]
local lines = lines_from(file)
for k,v in pairs(lines) do
local i = string.find(v, "license")
if not i then
print('\27[96m'..v..'\27[0m')
else
getScirptDesc(nse)
end
end
elseif option == "q" then
hepler.searchConsole()
else
helper.Main()
end
end
function resultList(nse)
if #nse > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#nse.."\n")
for k,v in ipairs(nse) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScirptDesc(nse)
else
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nNot Results Found\n")
io.write("Do you want search again? [y/n]: ")
local action = io.read()
if action == 'y' then
hepler.searchConsole()
else
helper.Main()
end
end
function helper.menu(menulist)
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
for key,value in ipairs(menulist) do
print(key.." "..value)
end
return menulist
end
function hepler.searchConsole()
io.write('\nnsearch> ')
local command = io.read()
if command == "help" or command == nil then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("name : search by script's name ")
print("exit : close the console")
print("back : returns to the main menu")
print("\n Usage name:http")
hepler.searchConsole()
elseif string.find(command,"name:") then
string = command:gsub("name:","")
os.execute("clear")
dbmodule.findScript(string,helper.banner())
elseif string.find(command,"exit") then
os.exit()
elseif string.find(command,"back") then
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
else
print("bad string")
hepler.searchConsole()
end
end
function searchMenu()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "3" then
os.exit()
elseif action == "b" or action == "2" then
os.execute( "clear" )
helper.menu(helper.mainMenu)
helper.Main()
elseif action == "s" or action == "1" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute()
end
end
function helper.Main()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "6" then
os.exit()
elseif action == "i" or action == "2" then
os.execute( "clear" )
setup.install(helper.banner())
elseif action == "s" or action == "3" then
os.execute( "clear" )
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
elseif action == "b" or action == "4" then
setup.createBackup(helper.banner())
os.execute( "clear" )
helper.menu(mainMenu)
helper.Main()
else
os.exit()
end
end
return helper
|
-- Helper Module
--
local setup = require "setup"
local dbmodule = require "dbmodule"
local config = require "config"
scriptdb = config.scriptdb
local helper = {}
helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search by Name of Script (s)", "Search by Category (c)", "Create script.db backup (b)", "Exit (q)"}
helper.searchMenu ={ "Search by Name (s)", "Main Menu (b)", "Exit (q)"}
function helper.banner()
banner=[[
_ _ _____ _____ _
| \ | |/ ___|| ___| | |
| \| |\ `--. | |__ __ _ _ __ ___ | |__
| . ` | `--. \| __| / _` || '__| / __|| '_ \
| |\ |/\__/ /| |___ | (_| || | | (__ | | | |
\_| \_/\____/ \____/ \__,_||_| \___||_| |_|
]]
return banner
end
function getScirptDesc( nse )
io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (0) ')
local option = io.read("*n")
if nse[option] then
print("\n")
local file = config.scriptsPath..nse[option]
local lines = lines_from(file)
for k,v in pairs(lines) do
local i = string.find(v, "license")
if not i then
print('\27[96m'..v..'\27[0m')
else
getScirptDesc(nse)
end
end
elseif option == 0 then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
function resultList(nse)
if #nse > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#nse.."\n")
for k,v in ipairs(nse) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScirptDesc(nse)
else
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nNot Results Found\n")
io.write("Do you want search again? [y/n]: ")
local action = io.read()
if action == 'y' then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
end
function helper.menu(menulist)
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
for key,value in ipairs(menulist) do
print(key.." "..value)
end
return menulist
end
function helper.searchConsole()
io.write('\nnsearch> ')
local command = io.read()
if command == "help" or command == nil then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("name : search by script's name ")
print("exit : close the console")
print("back : returns to the main menu")
print("\n Usage name:http")
helper.searchConsole()
elseif string.find(command,"name:") then
string = command:gsub("name:","")
os.execute("clear")
resultList(dbmodule.findScript(string,helper.banner()))
elseif string.find(command,"exit") then
os.exit()
elseif string.find(command,"back") then
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
else
helper.searchConsole()
end
end
function searchMenu()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "3" then
os.exit()
elseif action == "b" or action == "2" then
os.execute( "clear" )
helper.menu(helper.mainMenu)
helper.Main()
elseif action == "s" or action == "1" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute()
end
end
function helper.Main()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "6" then
os.exit()
elseif action == "i" or action == "2" then
os.execute( "clear" )
setup.install(helper.banner())
elseif action == "s" or action == "3" then
os.execute( "clear" )
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
elseif action == "b" or action == "4" then
setup.createBackup(helper.banner())
os.execute( "clear" )
helper.menu(mainMenu)
helper.Main()
else
os.exit()
end
end
return helper
|
fixing call functions
|
fixing call functions
|
Lua
|
apache-2.0
|
JKO/nsearch,JKO/nsearch
|
9f3030d04618a29f0f97c1cb491425ab85283e05
|
src/soul.lua
|
src/soul.lua
|
local soul = {}
local conversation = require("conversation")
local utils = require("utils")
local lfs = require("lfs")
commands = {}
for file in lfs.dir("commands") do
local command = file:match("^(.+).lua")
if (command) then
local path = "commands." .. command
package.loaded[path] = nil
local status, ret = pcall(require, path)
if (status) then
commands[command] = ret
logger:info("loaded " .. path)
else
logger:error(ret)
end
end
end
soul.onMessageReceive = function(msg)
msg.text = msg.text:gsub("@" .. bot.info.username, "")
msg.chat.id = math.floor(msg.chat.id)
msg.from.id = math.floor(msg.from.id)
if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then
return true
end
if os.time() - msg.date > config.ignore then
return true
end
for k, v in pairs(commands) do
if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then
if v.limit then
if v.limit.disable then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, the command is disabled.",
reply_to_message_id = msg.message_id
}
elseif v.limit.master and msg.from.username ~= config.master then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, permission denied.",
reply_to_message_id = msg.message_id
}
elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then
return commands.help.func(msg, k)
end
end
return v.func(msg)
end
end
for keyword, reply in pairs(conversation) do
local match = false
if type(keyword) == "string" then
match = msg.text:find(keyword)
elseif type(keyword) == "table" then
for i = 1, #keyword do
match = match or msg.text:find(keyword[i])
end
if keyword.reply and not msg.reply_to_message then
match = false
end
elseif type(keyword) == "function" then
match = keyword(msg.text)
end
if match then
local ans, rep
if type(reply) == "string" then
ans = reply
elseif type(reply) == "table" then
ans = utils.rand(table.unpack(reply))
if reply.reply then
rep = msg.message_id
elseif reply.reply_to_reply and msg.reply_to_message then
rep = msg.reply_to_message.message_id
end
elseif type(reply) == "function" then
ans = tostring(reply())
end
if ans:find("^sticker#%S-$") then
return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep)
elseif ans:find("^document#%S-$") then
return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep)
else
return bot.sendMessage(msg.chat.id, ans, reply.type or "Markdown", nil, nil, rep)
end
end
end
end
soul.onEditedMessageReceive = function (msg)
-- process
end
soul.onLeftChatMembersReceive = function (msg)
end
soul.onNewChatMembersReceive = function (msg)
end
soul.onPhotoReceive = function(msg)
-- process
end
soul.onAudioReceive = function (msg)
-- process
end
soul.onVideoReceive = function (msg)
-- process
end
soul.onDocumentReceive = function (msg)
-- process
end
soul.onGameReceive = function (msg)
-- process
end
soul.onStickerReceive = function (msg)
end
soul.onVideoNoteReceive = function (msg)
end
soul.onContactReceive = function (msg)
end
soul.onLocationReceive = function (msg)
end
setmetatable(soul, {
__index = function(t, key)
logger:warn("called undefined processer " .. key)
return (function() return false end)
end
})
return soul
|
local soul = {}
local conversation = require("conversation")
local utils = require("utils")
local lfs = require("lfs")
commands = {}
for file in lfs.dir("commands") do
local command = file:match("^(.+).lua")
if (command) then
local path = "commands." .. command
package.loaded[path] = nil
local status, ret = pcall(require, path)
if (status) then
commands[command] = ret
logger:info("loaded " .. path)
else
logger:error(ret)
end
end
end
soul.onMessageReceive = function(msg)
msg.text = msg.text:gsub("@" .. bot.info.username, "")
msg.chat.id = math.floor(msg.chat.id)
msg.from.id = math.floor(msg.from.id)
if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then
return true
end
if os.time() - msg.date > config.ignore then
return true
end
for k, v in pairs(commands) do
if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then
if v.limit then
if v.limit.disable then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, the command is disabled.",
reply_to_message_id = msg.message_id
}
elseif v.limit.master and msg.from.username ~= config.master then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, permission denied.",
reply_to_message_id = msg.message_id
}
elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then
return commands.help.func(msg, k)
end
end
return v.func(msg)
end
end
for keyword, reply in pairs(conversation) do
local match = false
if type(keyword) == "string" then
match = msg.text:find(keyword)
elseif type(keyword) == "table" then
for i = 1, #keyword do
match = match or msg.text:find(keyword[i])
end
if keyword.reply and not msg.reply_to_message then
match = false
end
elseif type(keyword) == "function" then
match = keyword(msg.text)
end
if match then
local ans, rep, rep_type = "Markdown"
if type(reply) == "string" then
ans = reply
elseif type(reply) == "table" then
ans = utils.rand(table.unpack(reply))
if reply.reply then
rep = msg.message_id
elseif reply.reply_to_reply and msg.reply_to_message then
rep = msg.reply_to_message.message_id
end
if reply.type then
rep_type = reply.type
end
elseif type(reply) == "function" then
ans = tostring(reply())
end
if ans:find("^sticker#%S-$") then
return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep)
elseif ans:find("^document#%S-$") then
return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep)
else
return bot.sendMessage{
chat_id = msg.chat.id,
text = ans,
parse_mode = rep_type,
reply_to_message_id = rep
}
end
end
end
end
soul.onEditedMessageReceive = function (msg)
-- process
end
soul.onLeftChatMembersReceive = function (msg)
end
soul.onNewChatMembersReceive = function (msg)
end
soul.onPhotoReceive = function(msg)
-- process
end
soul.onAudioReceive = function (msg)
-- process
end
soul.onVideoReceive = function (msg)
-- process
end
soul.onDocumentReceive = function (msg)
-- process
end
soul.onGameReceive = function (msg)
-- process
end
soul.onStickerReceive = function (msg)
end
soul.onVideoNoteReceive = function (msg)
end
soul.onContactReceive = function (msg)
end
soul.onLocationReceive = function (msg)
end
setmetatable(soul, {
__index = function(t, key)
logger:warn("called undefined processer " .. key)
return (function() return false end)
end
})
return soul
|
fix: indexed nil value in conversation
|
fix: indexed nil value in conversation
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
1304dbc73cb92e6d9c6df7890ca37220c00d43d5
|
core/configmanager.lua
|
core/configmanager.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, format =
setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, string.format;
local eventmanager = require "core.eventmanager";
module "configmanager"
local parsers = {};
local config = { ["*"] = { core = {} } };
local global_config = config["*"];
-- When host not found, use global
setmetatable(config, { __index = function () return global_config; end});
local host_mt = { __index = global_config };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(global_config, section_name);
if not section then return nil; end
return section[k];
end
};
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
function set(host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f, err = io.open(filename);
if f then
local ok, err = parsers[format].load(f:read("*a"), filename);
f:close();
if ok then
eventmanager.fire_event("config-reloaded", { filename = filename, format = format });
end
return ok, "parser", err;
end
return f, "file", err;
end
if not format then
return nil, "file", "no parser specified";
else
return nil, "file", "no parser for "..(format);
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- _M needed to avoid name clash with local 'parsers'
function _M.parsers()
local p = {};
for format in pairs(parsers) do
table.insert(p, format);
end
return p;
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data, filename)
local env;
-- The ' = true' are needed so as not to set off __newindex when we assign the functions below
env = setmetatable({ Host = true; host = true; Component = true, component = true,
Include = true, include = true, RunScript = dofile }, { __index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(env.__currenthost or "*", "core", k, v);
end});
rawset(env, "__currenthost", "*") -- Default is global
function env.Host(name)
if rawget(config, name) and rawget(config[name].core, "component_module") then
error(format("Host %q clashes with previously defined %s Component %q, for services use a sub-domain like conference.%s",
name, config[name].core.component_module:gsub("^%a+$", { component = "external", muc = "MUC"}), name, name), 0);
end
rawset(env, "__currenthost", name);
-- Needs at least one setting to logically exist :)
set(name or "*", "core", "defined", true);
end
env.host = env.Host;
function env.Component(name)
if rawget(config, name) and rawget(config[name].core, "defined") and not rawget(config[name].core, "component_module") then
error(format("Component %q clashes with previously defined Host %q, for services use a sub-domain like conference.%s",
name, name, name), 0);
end
set(name, "core", "component_module", "component");
-- Don't load the global modules by default
set(name, "core", "load_global_modules", false);
rawset(env, "__currenthost", name);
return function (module)
if type(module) == "string" then
set(name, "core", "component_module", module);
end
end
end
env.component = env.Component;
function env.Include(file)
local f, err = io.open(file);
if f then
local data = f:read("*a");
local ok, err = parsers.lua.load(data, file);
if not ok then error(err:gsub("%[string.-%]", file), 0); end
end
if not f then error("Error loading included "..file..": "..err, 0); end
return f, err;
end
env.include = env.Include;
local chunk, err = loadstring(data, "@"..filename);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return true;
end
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, format =
setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, string.format;
local eventmanager = require "core.eventmanager";
module "configmanager"
local parsers = {};
local config = { ["*"] = { core = {} } };
local global_config = config["*"];
-- When host not found, use global
setmetatable(config, { __index = function () return global_config; end});
local host_mt = { __index = global_config };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(global_config, section_name);
if not section then return nil; end
return section[k];
end
};
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
function set(host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f, err = io.open(filename);
if f then
local ok, err = parsers[format].load(f:read("*a"), filename);
f:close();
if ok then
eventmanager.fire_event("config-reloaded", { filename = filename, format = format });
end
return ok, "parser", err;
end
return f, "file", err;
end
if not format then
return nil, "file", "no parser specified";
else
return nil, "file", "no parser for "..(format);
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- _M needed to avoid name clash with local 'parsers'
function _M.parsers()
local p = {};
for format in pairs(parsers) do
table.insert(p, format);
end
return p;
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data, filename)
local env;
-- The ' = true' are needed so as not to set off __newindex when we assign the functions below
env = setmetatable({
Host = true; host = true; Component = true, component = true,
Include = true, include = true, RunScript = dofile }, {
__index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(env.__currenthost or "*", "core", k, v);
end
});
rawset(env, "__currenthost", "*") -- Default is global
function env.Host(name)
if rawget(config, name) and rawget(config[name].core, "component_module") then
error(format("Host %q clashes with previously defined %s Component %q, for services use a sub-domain like conference.%s",
name, config[name].core.component_module:gsub("^%a+$", { component = "external", muc = "MUC"}), name, name), 0);
end
rawset(env, "__currenthost", name);
-- Needs at least one setting to logically exist :)
set(name or "*", "core", "defined", true);
end
env.host = env.Host;
function env.Component(name)
if rawget(config, name) and rawget(config[name].core, "defined") and not rawget(config[name].core, "component_module") then
error(format("Component %q clashes with previously defined Host %q, for services use a sub-domain like conference.%s",
name, name, name), 0);
end
set(name, "core", "component_module", "component");
-- Don't load the global modules by default
set(name, "core", "load_global_modules", false);
rawset(env, "__currenthost", name);
return function (module)
if type(module) == "string" then
set(name, "core", "component_module", module);
end
end
end
env.component = env.Component;
function env.Include(file)
local f, err = io.open(file);
if f then
local data = f:read("*a");
local ok, err = parsers.lua.load(data, file);
if not ok then error(err:gsub("%[string.-%]", file), 0); end
end
if not f then error("Error loading included "..file..": "..err, 0); end
return f, err;
end
env.include = env.Include;
local chunk, err = loadstring(data, "@"..filename);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return true;
end
end
return _M;
|
configmanager: Fix very wacky indentation
|
configmanager: Fix very wacky indentation
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.