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
|
---|---|---|---|---|---|---|---|---|---|
783efb134e31c08e56668f3730aa8fb78a704e4c
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[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$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
s:option(Value, "log_size", nil, "kiB").optional = true
s:option(Value, "log_ip").optional = true
s:option(Value, "conloglevel").optional = true
s:option(Value, "cronloglevel").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[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$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached", "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
s:option(Value, "log_size", nil, "kiB").optional = true
s:option(Value, "log_ip").optional = true
s:option(Value, "conloglevel").optional = true
s:option(Value, "cronloglevel").optional = true
return m
|
modules/admin-full: fix udata vs. string in system.lua model
|
modules/admin-full: fix udata vs. string in system.lua model
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5148 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
stephank/luci,gwlim/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,freifunk-gluon/luci,projectbismark/luci-bismark,ch3n2k/luci,gwlim/luci,vhpham80/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,stephank/luci,gwlim/luci,Canaan-Creative/luci,8devices/carambola2-luci,saraedum/luci-packages-old,jschmidlapp/luci,yeewang/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,phi-psi/luci,ch3n2k/luci,ch3n2k/luci,phi-psi/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,vhpham80/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,vhpham80/luci,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,stephank/luci,vhpham80/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ch3n2k/luci,jschmidlapp/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,Flexibity/luci,jschmidlapp/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,freifunk-gluon/luci,freifunk-gluon/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,phi-psi/luci,gwlim/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,stephank/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,freifunk-gluon/luci,yeewang/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,vhpham80/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,8devices/carambola2-luci,Flexibity/luci,phi-psi/luci,Flexibity/luci,gwlim/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci
|
a2142308fbee3c74171e08dde6e50c6c1edc2821
|
.config/nvim/lua/config/dap.lua
|
.config/nvim/lua/config/dap.lua
|
local dap_ui = require("dapui")
local dap_python = require("dap-python")
local dap_mappings = require("mappings.dap")
local M = {}
function M.setup()
dap_ui.setup({
icons = { expanded = "", collapsed = "" },
sidebar = {
elements = {
{
id = "scopes",
size = 0.50,
},
{ id = "watches", size = 0.10 },
{ id = "breakpoints", size = 0.20 },
{ id = "stacks", size = 0.20 },
},
width = 50,
},
})
dap_python.setup()
vim.fn.sign_define(
"DapBreakpoint",
{ text = " ", texthl = "LspDiagnosticsSignError", numhl = "LspDiagnosticsSignError" }
)
vim.fn.sign_define(
"DapBreakpointRejected",
{ text = " ", texthl = "LspDiagnosticsSignError", numhl = "LspDiagnosticsSignError" }
)
vim.fn.sign_define(
"DapLogPoint",
{ text = " ", texthl = "LspDiagnosticsSignInformation", numhl = "LspDiagnosticsSignInformation" }
)
vim.fn.sign_define(
"DapStopped",
{ text = " ", texthl = "LspDiagnosticsSignWarning", numhl = "LspDiagnosticsSignWarning" }
)
vim.g.dap_virtual_text = true
dap_mappings.enable_mappings()
end
return M
|
local dap_ui = require("dapui")
local dap_python = require("dap-python")
-- Needs to be /virtual_text and not .virtual_text because of caching.
-- Modifying any property will not work if it's a dot (.) because the source
-- uses slash (/) and therefore has a different table.
local dap_virtual_text = require("nvim-dap-virtual-text/virtual_text")
local dap_mappings = require("mappings.dap")
local M = {}
function M.setup()
dap_ui.setup({
icons = { expanded = "", collapsed = "" },
sidebar = {
elements = {
{
id = "scopes",
size = 0.50,
},
{ id = "watches", size = 0.10 },
{ id = "breakpoints", size = 0.20 },
{ id = "stacks", size = 0.20 },
},
width = 50,
},
})
dap_python.setup()
vim.fn.sign_define(
"DapBreakpoint",
{ text = " ", texthl = "LspDiagnosticsSignError", numhl = "LspDiagnosticsSignError" }
)
vim.fn.sign_define(
"DapBreakpointRejected",
{ text = " ", texthl = "LspDiagnosticsSignError", numhl = "LspDiagnosticsSignError" }
)
vim.fn.sign_define(
"DapLogPoint",
{ text = " ", texthl = "LspDiagnosticsSignInformation", numhl = "LspDiagnosticsSignInformation" }
)
vim.fn.sign_define(
"DapStopped",
{ text = " ", texthl = "LspDiagnosticsSignWarning", numhl = "LspDiagnosticsSignWarning" }
)
vim.g.dap_virtual_text = true
-- Set the prefix for the virtual text
dap_virtual_text.text_prefix = " ‣ "
dap_virtual_text.error_prefix = " ‣ "
dap_virtual_text.info_prefix = " ‣ "
dap_mappings.enable_mappings()
end
return M
|
Set prefix for DAP virtual text
|
Set prefix for DAP virtual text
It's hacky because it's not exposed as a config, but that's good enough.
|
Lua
|
mit
|
jungomi/dotfiles
|
b3cf141095ae963cd2c46d05b854e8bd66369e14
|
etc/Far3/Profile/Macros/scripts/Editor.BlockIndent.lua
|
etc/Far3/Profile/Macros/scripts/Editor.BlockIndent.lua
|
-- http://forum.farmanager.com/viewtopic.php?f=15&t=7703
-- http://evil-programmers.googlecode.com/svn/trunk/BlockIndent/BlockIndent.lua
--[[
Block Indent for Far Manager
Version: 2.1
Copyright (C) 2001 Alex Yaroslavsky
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Features:
- Right or Left Indentation of the selected block (or the current line) by
a tab or a space.
- Each line in the block is indented relatively to its own position with no
respect to other lines in the block.
- Tab indentation as in Borland Turbo IDE, text is indented to the nearest
tab position and not just by tab size.
- Works correctly with any editor settings (expand tabs or not, inserts real
tabs).
--]]
local Indent = function (IndentByTabSize, Forward)
local F = far.Flags
local ei = editor.GetInfo(nil);
local IndentSize = IndentByTabSize and ei.TabSize or 1
local IndentStr = IndentByTabSize and "\t" or " "
local line = ei.CurLine;
local loop = false
if ei.BlockType ~= F.BTYPE_NONE then
local s = editor.GetString()
if s.SelStart ~= 0 then
loop = true;
line = ei.BlockStartLine;
end
end
editor.UndoRedo(nil, F.EUR_BEGIN)
repeat
editor.SetPosition(nil, line, 1, 0, 0, 1, ei.Overtype)
-- patch 2.7 at http://forum.farmanager.com/viewtopic.php?p=125167#p125167
-- local s = editor.GetString(nil, 0, 0)
local s = editor.GetString(nil, line, 0)
if not s or (loop and ((s.SelStart == 0) or (s.SelEnd ~= -1 and s.SelStart > s.SelEnd))) then
break
end
local j = s.StringText:find("[^ \t]")
if j and (j>1 or Forward) then
local TabPos = editor.RealToTab(nil, nil, j) - 1
local x = math.floor(TabPos/IndentSize)
if ((TabPos%IndentSize) == 0) and not Forward then
x = x - 1
end
x = Forward and x + 1 or x
-- patch 2.7 at http://forum.farmanager.com/viewtopic.php?p=125167#p125167
-- editor.SetString(nil, nil, s.StringText:sub(j), s.StringEOL)
-- for i=1,x,1 do editor.InsertText(nil,IndentStr) end
editor.SetString(nil, nil, IndentStr:rep(x)..s.StringText:sub(j), s.StringEOL)
end
line = line + 1
-- http://forum.farmanager.com/viewtopic.php?p=125170#p125170
loop = ei.TotalLines >= line
until not loop
editor.SetPosition(nil, ei.CurLine, ei.CurPos, 0, ei.TopScreenLine, ei.LeftPos, ei.Overtype)
editor.UndoRedo(nil, F.EUR_END)
end
Macro {
area = "Editor";
key = "ShiftTab";
flags = "DisableOutput";
description = "Editor: Indent right by tab size";
action = function()
Indent(true, true)
end;
}
Macro {
area = "Editor";
key = "ShiftBS";
flags = "DisableOutput";
description = "Editor: Indent left by tab size";
action = function()
Indent(true, false)
end;
}
NoMacro {
area = "Editor";
key = "";
flags = "DisableOutput";
description = "Editor: Indent right by space";
action = function()
Indent(false, true)
end;
}
NoMacro {
area = "Editor";
key = "";
flags = "DisableOutput";
description = "Editor: Indent left by space";
action = function()
Indent(false, false)
end;
}
|
-- http://forum.farmanager.com/viewtopic.php?f=15&t=7703
-- http://evil-programmers.googlecode.com/svn/trunk/BlockIndent/BlockIndent.lua
--[[
Block Indent for Far Manager
Version: 2.1
Copyright (C) 2001 Alex Yaroslavsky
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Features:
- Right or Left Indentation of the selected block (or the current line) by
a tab or a space.
- Each line in the block is indented relatively to its own position with no
respect to other lines in the block.
- Tab indentation as in Borland Turbo IDE, text is indented to the nearest
tab position and not just by tab size.
- Works correctly with any editor settings (expand tabs or not, inserts real
tabs).
--]]
local Indent = function (IndentByTabSize, Forward)
local F = far.Flags
local ei = editor.GetInfo(nil);
local IndentSize = IndentByTabSize and ei.TabSize or 1
local IndentStr = IndentByTabSize and "\t" or " "
local line = ei.CurLine;
local loop = false
if ei.BlockType ~= F.BTYPE_NONE then
local s = editor.GetString()
if s.SelStart ~= 0 then
loop = true;
line = ei.BlockStartLine;
end
end
editor.UndoRedo(nil, F.EUR_BEGIN)
repeat
editor.SetPosition(nil, line, 1, 0, 0, 1, ei.Overtype)
-- patch 2.7 at http://forum.farmanager.com/viewtopic.php?p=125167#p125167
-- local s = editor.GetString(nil, 0, 0)
local s = editor.GetString(nil, line, 0)
if not s or (loop and ((s.SelStart == 0) or (s.SelEnd ~= -1 and s.SelStart > s.SelEnd))) then
break
end
local j = s.StringText:find("[^ \t]")
if j and (j>1 or Forward) then
local TabPos = editor.RealToTab(nil, nil, j) - 1
local x = math.floor(TabPos/IndentSize)
if ((TabPos%IndentSize) == 0) and not Forward then
x = x - 1
end
x = Forward and x + 1 or x
-- patch 2.7 at http://forum.farmanager.com/viewtopic.php?p=125167#p125167
-- editor.SetString(nil, nil, s.StringText:sub(j), s.StringEOL)
-- for i=1,x,1 do editor.InsertText(nil,IndentStr) end
editor.SetString(nil, nil, IndentStr:rep(x)..s.StringText:sub(j), s.StringEOL)
end
line = line + 1
-- http://forum.farmanager.com/viewtopic.php?p=125170#p125170
loop = ei.TotalLines >= line
until not loop
editor.SetPosition(nil, ei.CurLine, ei.CurPos, 0, ei.TopScreenLine, ei.LeftPos, ei.Overtype)
editor.UndoRedo(nil, F.EUR_END)
end
-- patch for Far 3.0 build 4444
-- comment or remove unsupported flags = "DisableOutput"
-- http://forum.farmanager.com/viewtopic.php?p=133237#p133237
Macro {
area = "Editor";
key = "ShiftTab";
--flags = "DisableOutput";
description = "Editor: Indent right by tab size";
action = function()
Indent(true, true)
end;
}
Macro {
area = "Editor";
key = "ShiftBS";
--flags = "DisableOutput";
description = "Editor: Indent left by tab size";
action = function()
Indent(true, false)
end;
}
NoMacro {
area = "Editor";
key = "";
--flags = "DisableOutput";
description = "Editor: Indent right by space";
action = function()
Indent(false, true)
end;
}
NoMacro {
area = "Editor";
key = "";
--flags = "DisableOutput";
description = "Editor: Indent left by space";
action = function()
Indent(false, false)
end;
}
|
fix error with unsupported flag in lua macros
|
fix error with unsupported flag in lua macros
|
Lua
|
mit
|
ildar-shaimordanov/tea-set
|
cf505d476219f84844161f86a4a6547f39142793
|
src/cosy/backend/redis.test.lua
|
src/cosy/backend/redis.test.lua
|
require "busted"
local assert = require "luassert"
local Platform = require "cosy.platform"
Platform.logger.enabled = false
local Configuration = require "cosy.configuration"
Configuration.data.password.time = 0.001
Configuration.data.password.min_size = 5
local Backend = require "cosy.backend.redis"
describe ("Redis backend", function ()
local session
setup (function ()
Backend.pool [1] = require "fakeredis" .new ()
Backend.pool [1].transaction = function (client, opt, f)
return f (client)
end
Backend.pool [1].multi = function () end
Backend.pool [1]:hset ("/username", "metadata", Platform.json.encode {
type = "user",
locale = "en",
})
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
session = setmetatable ({}, Backend)
end)
before_each (function()
Configuration:reload ()
end)
describe ("'authenticate' method", function ()
it ("requires a string username", function ()
assert.has.error (function ()
session:authenticate {
username = 123456,
password = "password",
}
end)
end)
it ("requires a username with a minimum size", function ()
Configuration.data.username.min_size = 5
assert.has.error (function ()
session:authenticate {
username = "1234",
password = "password",
}
end)
end)
it ("requires a username with a maximum size", function ()
Configuration.data.username.max_size = 5
assert.has.error (function ()
session:authenticate {
username = "123456",
password = "password",
}
end)
end)
it ("requires a username containing only alphanumerical characters", function ()
assert.has.error (function ()
session:authenticate {
username = "abc!def",
password = "password",
}
end)
end)
it ("does not authenticate non-existing username", function ()
assert.has.error (function ()
session:authenticate {
username = "missing",
password = "password",
}
end)
end)
it ("does not authenticate an erroneous username/password", function ()
assert.has.error (function ()
session:authenticate {
username = "username",
password = "erroneous",
}
end)
end)
it ("does a password with a minimum size", function ()
Configuration.data.password.min_size = 5
assert.has.error (function ()
session:authenticate {
username = "username",
password = "1234",
}
end)
end)
it ("does a password with a maximum size", function ()
Configuration.data.password.max_size = 5
assert.has.error (function ()
session:authenticate {
username = "username",
password = "123456",
}
end)
end)
it ("authenticates a valid username/password", function ()
Configuration.data.password.min_size = #"password"
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.are.equal (session.username, "username")
end)
it ("rehashes password if necessary", function ()
Configuration.data.password.min_size = #"password"
Platform.password.rounds = 4
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
Platform.password.rounds = 5
local s = spy.on (Platform.password, "hash")
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.spy (s).was_called ()
end)
it ("does not rehash password unless necessary", function ()
Configuration.data.password.min_size = #"password"
Platform.password.rounds = 5
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
Platform.password.rounds = 5
local s = spy.on (Platform.password, "hash")
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.spy (s).was_not_called ()
end)
it ("sets the session locale", function ()
Configuration.data.password.min_size = #"password"
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.are.equal (session.locale, "en")
end)
end)
--[[
describe ("'create_user' method", function ()
it ("does not create an existing user", function ()
assert.has.error (function ()
Backend:create_user {
username = "username",
password = "password",
}
end)
end)
it ("creates a valid user", function ()
assert.has.no.error (function ()
Backend:create_user {
username = "myself",
password = "password",
}
end)
end)
end)
--]]
end)
|
require "busted"
local assert = require "luassert"
local Platform = require "cosy.platform"
Platform.logger.enabled = false
local Configuration = require "cosy.configuration"
Configuration.data.password.time = 0.001
Configuration.data.password.min_size = 5
local Backend = require "cosy.backend.redis"
describe ("Redis backend", function ()
local session
setup (function ()
Backend.pool [1] = require "fakeredis" .new ()
Backend.pool [1].transaction = function (client, opt, f)
return f (client)
end
Backend.pool [1].multi = function () end
Backend.pool [1]:hset ("/username", "metadata", Platform.json.encode {
type = "user",
locale = "en",
})
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
session = setmetatable ({}, Backend)
end)
before_each (function()
Configuration:reload ()
Configuration.data.username.min_size = 2
Configuration.data.username.max_size = 10
Configuration.data.password.min_size = 2
Configuration.data.password.max_size = 10
end)
describe ("authenticate method", function ()
it ("requires a string username", function ()
assert.has.error (function ()
session:authenticate {
username = 123456,
password = "password",
}
end)
end)
it ("requires a username with a minimum size", function ()
assert.has.error (function ()
session:authenticate {
username = "1",
password = "password",
}
end)
end)
it ("requires a username with a maximum size", function ()
Configuration.data.username.max_size = 5
assert.has.error (function ()
session:authenticate {
username = "1234567890",
password = "password",
}
end)
end)
it ("requires a username containing only alphanumerical characters", function ()
assert.has.error (function ()
session:authenticate {
username = "abc!def",
password = "password",
}
end)
end)
it ("does not authenticate a non-existing username", function ()
assert.has.error (function ()
session:authenticate {
username = "missing",
password = "password",
}
end)
end)
it ("does not authenticate a non-user", function ()
Backend.pool [1]:hset ("/something", "metadata", Platform.json.encode {
type = "other",
locale = "en",
})
Backend.pool [1]:hset ("/something", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
assert.has.error (function ()
session:authenticate {
username = "something",
password = "password",
}
end)
end)
it ("does not authenticate an erroneous username/password", function ()
assert.has.error (function ()
session:authenticate {
username = "username",
password = "erroneous",
}
end)
end)
it ("requires a password with a minimum size", function ()
assert.has.error (function ()
session:authenticate {
username = "username",
password = "1",
}
end)
end)
it ("requires a password with a maximum size", function ()
assert.has.error (function ()
session:authenticate {
username = "username",
password = "1234567890",
}
end)
end)
it ("authenticates a valid username/password", function ()
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.are.equal (session.username, "username")
end)
it ("rehashes password if necessary", function ()
Platform.password.rounds = 4
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
Platform.password.rounds = 5
local s = spy.on (Platform.password, "hash")
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.spy (s).was_called ()
end)
it ("does not rehash password unless necessary", function ()
Platform.password.rounds = 5
Backend.pool [1]:hset ("/username", "secrets", Platform.json.encode {
password = Platform.password.hash "password",
})
Platform.password.rounds = 5
local s = spy.on (Platform.password, "hash")
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.spy (s).was_not_called ()
end)
it ("sets the session locale", function ()
assert.has.no.error (function ()
session:authenticate {
username = "username",
password = "password",
}
end)
assert.are.equal (session.locale, "en")
end)
end)
--[[
describe ("'create_user' method", function ()
it ("does not create an existing user", function ()
assert.has.error (function ()
Backend:create_user {
username = "username",
password = "password",
}
end)
end)
it ("creates a valid user", function ()
assert.has.no.error (function ()
Backend:create_user {
username = "myself",
password = "password",
}
end)
end)
end)
--]]
end)
|
Fix tests of redis backend.
|
Fix tests of redis backend.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
fbbd8f855e4af092018a6b5c060b1e82a3714ef7
|
cpaste.lua
|
cpaste.lua
|
-- CPaste, micro pastebin running on Carbon
print("Morning, Ladies and Gentlemen, CPaste here.")
-- Settings:
ret = dofile("settings.lua")
-- Actual Code:
srv.Use(mw.Logger()) -- Activate logger.
srv.GET("/:id", mw.new(function() -- Main Retrieval of Pastes.
local id = params("id") -- Get ID
if #id ~= 8 then
content("No such paste.", 404, "text/plain")
else
local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis
if err ~= nil then error(err) end
local res,err = con.Cmd("get", "cpaste:"..id).String() -- Get cpaste:<ID>
if err ~= nil then error(err) end
local cpastemdata, err = con.Cmd("get", "cpastemdata:"..id).String()
if err ~= nil then error(err) end
if res == "<nil>" then
content(doctype()(
tag"head"(
tag"title" "CPaste"
),
tag"body"(
"No such paste."
)
))
else
if cpastemdata == "plain" then
content(res, 200, "text/plain")
else
content(res)
end
end
con.Close()
end
end, {redis_addr=ret.redis}))
srv.GET("/", mw.echo(ret.mainpage)) -- Main page.
srv.POST("/", mw.new(function() -- Putting up pastes
local data = form("f")
if not data then
data = form("c")
end
local plain = true
if not form("html") then
plain = false
end
if not data then
if #data <= maxpastesize then
math.randomseed(unixtime())
local id = ""
local stringtable={}
for i=1,8 do
local n = math.random(48, 122)
if (n < 58 or n > 64) and (n < 91 or n > 96) then
id = id .. string.char(n)
else
id = id .. string.char(math.random(97, 122))
end
end
local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis
if err ~= nil then error(err) end
local r, err = con.Cmd("set", "cpaste:"..id, data) -- Set cpaste:<randomid> to data
if err ~= nil then error(err) end
local r, err = con.Cmd("set", "cpastemdata:"..id, plain and "plain" or "html") -- Set cpastemdate:<randomid> to the metadata
if err ~= nil then error(err) end
local r, err = con.Cmd("expire", "cpaste:"..id, expiretime) -- Make it expire
if err ~= nil then error(err) end
local r, err = con.Cmd("expire", "cpastemdata:"..id, expiretime) -- Make it expire
if err ~= nil then error(err) end
con.Close()
content(url..id.."\n", 200, "text/plain")
else
content("Content too big. Max is "..tostring(maxpastesize).." Bytes, given "..tostring(#data).." Bytes.", 400, "text/plain")
end
else
content("No content given.", 400, "text/plain")
end
end, {url=ret.url, expiretime=ret.expiresecs, redis_addr=ret.redis, maxpastesize=ret.maxpastesize}))
|
-- CPaste, micro pastebin running on Carbon
print("Morning, Ladies and Gentlemen, CPaste here.")
-- Settings:
ret = dofile("settings.lua")
-- Actual Code:
srv.Use(mw.Logger()) -- Activate logger.
srv.GET("/:id", mw.new(function() -- Main Retrieval of Pastes.
local id = params("id") -- Get ID
if #id ~= 8 then
content("No such paste.", 404, "text/plain")
else
local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis
if err ~= nil then error(err) end
local res,err = con.Cmd("get", "cpaste:"..id).String() -- Get cpaste:<ID>
if err ~= nil then error(err) end
local cpastemdata, err = con.Cmd("get", "cpastemdata:"..id).String()
if err ~= nil then error(err) end
if res == "<nil>" then
content(doctype()(
tag"head"(
tag"title" "CPaste"
),
tag"body"(
"No such paste."
)
))
else
if cpastemdata == "plain" then
content(res, 200, "text/plain")
else
content(res)
end
end
con.Close()
end
end, {redis_addr=ret.redis}))
srv.GET("/", mw.echo(ret.mainpage)) -- Main page.
srv.POST("/", mw.new(function() -- Putting up pastes
local data = form("f") or form("c")
local plain = form("html") and false or true
if data then
if #data <= maxpastesize then
math.randomseed(unixtime())
local id = ""
local stringtable={}
for i=1,8 do
local n = math.random(48, 122)
if (n < 58 or n > 64) and (n < 91 or n > 96) then
id = id .. string.char(n)
else
id = id .. string.char(math.random(97, 122))
end
end
local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis
if err ~= nil then error(err) end
local r, err = con.Cmd("set", "cpaste:"..id, data) -- Set cpaste:<randomid> to data
if err ~= nil then error(err) end
local r, err = con.Cmd("set", "cpastemdata:"..id, plain and "plain" or "html") -- Set cpastemdate:<randomid> to the metadata
if err ~= nil then error(err) end
local r, err = con.Cmd("expire", "cpaste:"..id, expiretime) -- Make it expire
if err ~= nil then error(err) end
local r, err = con.Cmd("expire", "cpastemdata:"..id, expiretime) -- Make it expire
if err ~= nil then error(err) end
con.Close()
content(url..id.."\n", 200, "text/plain")
else
content("Content too big. Max is "..tostring(maxpastesize).." Bytes, given "..tostring(#data).." Bytes.", 400, "text/plain")
end
else
content("No content given.", 400, "text/plain")
end
end, {url=ret.url, expiretime=ret.expiresecs, redis_addr=ret.redis, maxpastesize=ret.maxpastesize}))
|
Some fixes
|
Some fixes
|
Lua
|
mit
|
carbonsrv/cpaste,vifino/cpaste
|
49fdced670748dbd453a1c9fe1941d4676e3d368
|
RiriTamanegi/simplejutsu.lua
|
RiriTamanegi/simplejutsu.lua
|
local prefix = 'znbja_' -- global prefix for classes and IDs
local arg = {...}
local function array(tab)
return tab and setmetatable(tab,table) or setmetatable({},table)
end
-- Add some functions to table to be used as a special metatable
function table:map(func)
local arr = array{}
for i=1, #self do
arr:insert(func(self[i]))
end
return self
end
function table:insertArray(arr)
for i=1, #arr do
self:insert(arr[i])
end
return self
end
--- Create the HAML renderer
local haml = require 'haml'
local hamlOptions = {format = 'html5'}
local engine = haml.new(hamlOptions)
local function renderHAML(file,vars)
engine:render_file(file,vars)
end
function table:renderHAML(file)
return renderHAML(file,self)
end
--- Some of the 'renderers' don't support file arguments, and I needed to read Some
-- basic text files into strings anyways, so why not?
local function readFull(file)
local err
local file,string
file,err = io.open(file)
assert(file,err)
string,err = file:read('*a')
assert(string,err)
file:close()
return string
end
--- YAML renderer
local yaml = require 'yaml'
local function loadYAML(file)
local tab,err = yaml.load(readFull(file))
assert(tab,err)
return array(tab)
end
-- Applies the global prefix to classes and IDs
local function prefixer(string)
return prefix..string
end
string.prefix = prefixer -- allow the :prefix chainable
-- Allows the automatic creation of unique IDs for elements of similar natures
local iterateID
do
local tracker = {}
iterateID = function(class)
tracker[class] = tracker[class] and tracker[class]+1 or 0
return ('%s%i'):format(class,tracker[class]):prefix()
end
end
--- The actual full rendering logic
-- @document will be table.concat'd at the end of this all.
local document = array{}
local options = loadYAML('info.yaml')
for i=1, #arg do
document:insertArray(
loadYAML(arg[i]):map(function(options)
options.ID = iterateID('jutsu')
return options:renderHAML('haml/jutsu.haml')
end)
)
end
local output = document:concat('\n')
local file = io.open('jutsuoutput.html','w')
file:write(output)
file:close()
|
local prefix = 'znbja_' -- global prefix for classes and IDs
local arg = {'jutsu/Passive/Clan.yaml'}
local function array(tab)
return tab and setmetatable(tab,table) or setmetatable({},table)
end
-- Add some functions to table to be used as a special metatable
function table:map(func)
local arr = array{}
for i=1, #self do
arr:insert(func(self[i]))
end
return self
end
function table:insertArray(arr)
for i=1, #arr do
self:insert(arr[i])
end
return self
end
--- Create the HAML renderer
local haml = require 'haml'
local hamlOptions = {format = 'html5'}
local engine = haml.new(hamlOptions)
local function renderHAML(file,vars)
engine:render_file(file,vars)
end
--- Some of the 'renderers' don't support file arguments, and I needed to read Some
-- basic text files into strings anyways, so why not?
local function readFull(file)
local err
local file,string
file,err = io.open(file)
assert(file,err)
string,err = file:read('*a')
assert(string,err)
file:close()
return string
end
--- YAML renderer
local yaml = require 'yaml'
local function loadYAML(file)
local tab,err = yaml.load(readFull(file))
assert(tab,err)
return array(tab)
end
-- Applies the global prefix to classes and IDs
local function prefixer(string)
return prefix..string
end
string.prefix = prefixer -- allow the :prefix chainable
-- Allows the automatic creation of unique IDs for elements of similar natures
local iterateID
do
local tracker = {}
iterateID = function(class)
tracker[class] = tracker[class] and tracker[class]+1 or 0
return ('%s%i'):format(class,tracker[class]):prefix()
end
end
--- The actual full rendering logic
-- @document will be table.concat'd at the end of this all.
local document = array{}
for i=1, #arg do
document:insertArray(
loadYAML(arg[i]):map(function(options)
options.ID = iterateID('jutsu')
return renderHAML('haml/jutsu.haml',options)
end)
)
end
local output = document:concat('\n')
local handle = io.open('jutsuoutput.html','w')
handle:write(output)
handle:close()
|
Squash some bugs
|
Squash some bugs
|
Lua
|
unlicense
|
Zee1234/HTML-CSS
|
b7f3c0829808efd302f396610374037f0c9a88c1
|
src/cosy/proxy/remember_path.lua
|
src/cosy/proxy/remember_path.lua
|
local proxy = require "cosy.util.proxy"
local copy = require "cosy.util.shallow_copy"
local tags = require "cosy.util.tags"
local PATH = tags.PATH
local remember_path = proxy {}
local forward = remember_path.__index
local path = proxy {}
function path.__concat (lhs, rhs)
local result = copy (lhs)
result [#result + 1] = rhs
return path (result)
end
function remember_path:__index (key)
if not rawget (self, PATH) then
rawset (self, PATH, path { self })
return self [key]
end
local result = forward (self, key)
if type (result) ~= "table" then
return result
end
local p = self [PATH] .. key
rawset (result, PATH, p)
return result
end
return remember_path
|
local proxy = require "cosy.util.proxy"
local copy = require "cosy.util.shallow_copy"
local tags = require "cosy.util.tags"
local PATH = tags.PATH
local IS_VOLATILE = tags.IS_VOLATILE
local remember_path = proxy {}
local forward = remember_path.__index
local path = proxy {}
function path.__concat (lhs, rhs)
local result = copy (lhs)
result [#result + 1] = rhs
return path (result)
end
function remember_path:__index (key)
if not rawget (self, PATH) then
rawset (self, PATH, path { self })
return self [key]
end
local volatile = rawget (self, IS_VOLATILE) or (type (key) == "table" and key [IS_VOLATILE])
local result = forward (self, key)
if type (result) ~= "table" then
return result
end
local p = self [PATH] .. key
rawset (result, PATH, p)
rawset (result, IS_VOLATILE, volatile)
return result
end
return remember_path
|
Fix the volatile detection.
|
Fix the volatile detection.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
19e72e4e0672292c9fd853e21c4953e32023a479
|
lua/String.lua
|
lua/String.lua
|
local squote = "'"
local dquote = '"'
-- escape "sequences"
local escapeSequences = {
a = '\a',
b = '\b',
f = '\f',
r = '\r',
n = '\n',
t = '\t',
v = '\v',
['"'] = '"',
["'"] = "'",
['\\'] = '\\'
}
local pads = {
z = "\\z",
x = "\\x",
['0'] = '\\0',
['1'] = '\\1',
['2'] = '\\2',
['3'] = '\\3',
['4'] = '\\4',
['5'] = '\\5',
['6'] = '\\6',
['7'] = '\\7',
['8'] = '\\8',
['9'] = '\\9'
}
setmetatable(pads, {
__index = function(t,k)
return "\\v" .. k .. "/"
end
})
local findpairs
do
--[[
local function _findnext_util(a, b, ...)
return b, coroutine.yield(a, b, ...)
end
local function _findnext(stringandpattern, index)
while true do
index = _findnext_util(string.find(stringandpattern[1], stringandpattern[2], index + 1))
end
end
function findpairs(string, pattern)
return coroutine.wrap(_findnext), {string, pattern}, 0
end
--]]
-- [[
-- alternate (stateless) findpairs (untested)
local function _findnext(stringandpattern, index)
-- only branch if index = 0
if index > 0 then
-- this should always give a match,
-- as we're starting from the same index as the returned match
local x,y = string.find(stringandpattern[1], stringandpattern[2], index)
return string.find(stringandpattern[1], stringandpattern[2], y+1)
else
return string.find(stringandpattern[1], stringandpattern[2], index + 1)
end
end
function findpairs(string, pattern)
return _findnext, {string, pattern}, 0
end
--]]
end
-- Parse a string like it's a Lua 5.2 string.
local function parseString52(s)
-- "validate" string
local startChar = string.sub(s,1,1)
assert(startChar==squote or startChar==dquote, "not a string")
assert(string.sub(s, -1, -1) == startChar, "unfinished string")
-- remove quotes
local str = string.sub(s, 2, -2)
-- TODO check for unescaped quotes
-- replace "normal" escapes with a padded escape
str = string.gsub(str, "\\(.)", function(c)
-- swap startChar with some invalid escape
if c == startChar then
c = "m"
-- swap the invalid escape with startChar
elseif c == "m" then
c = startChar
end
return pads[c]
end)
-- check for a padded escape for startChar - remember this is actually our invalid escape
assert(not string.find(str, "\\v" .. startChar .. "/"), "invalid escape sequence near '\\m'")
-- then check for non-escaped startChar
assert(not string.find(str, startChar), "unfinished string")
-- pad 1-digit numerical escapes
str = string.gsub(str, "\\([0-9])[^0-9]", "\\00%1")
-- pad 2-digit numerical escapes
str = string.gsub(str, "\\([0-9][0-9])[^0-9]", "\\0%1")
local t = {}
local i = 1
local last = 1
-- split on \z
for from, to in findpairs(str, "\\z") do
t[i] = string.sub(str, last, from - 1)
last = to+1
i = i + 1
end
t[i] = string.sub(str, last)
-- parse results
local nt = {}
for x,y in ipairs(t) do
nt[x] = string.gsub(y, "\\(([vx0-9])((.).))",
function(a,b,c,d)
if b == "v" then
return escapeSequences[d] or (d == "m" and startChar or assert(false, "invalid escape sequence near '\\" .. d .. "'"))
elseif b == "x" then
local n = tonumber(c, 16)
assert(n, "hexadecimal digit expected near '\\x" .. c .. "'")
return string.char(n)
else
local n = tonumber(a)
assert(n < 256, "decimal escape too large near '\\" .. a .. "'")
return string.char(n)
end
end)
if x > 1 then
-- handle \z
nt[x] = string.gsub(nt[x], "^[%s]*", "")
end
end
-- merge
return table.concat(nt, "")
end
-- "tests"
-- TODO add more
-- also add automatic checks
-- syntax error in Lua 5.0 :/ uncomment to enable
--[[
if _VERSION == "Lua 5.2" and not ... then
local t = {
[=["\""]=],
[=["""]=],
[=["v""]=],
[=[""/"]=],
[=["\v"/"]=],
[=["\m"]=]
}
for _, str in ipairs(t) do
local s, m = pcall(parseString52, str)
io.write(tostring(s and m or "nil"))
io.write(tostring(s and "" or ("\t" .. m)) .. "\n")
s, m = load("return " .. str, "@/home/soniex2/git/github/Stuff/lua/String.lua:")
io.write(tostring(s and s()))
io.write(tostring(m and "\t"..m or "") .. "\n")
end
elseif not ... then
print("Tests require Lua 5.2")
end
--]]
return {
parse52 = parseString52,
findpairs = findpairs,
}
|
local squote = "'"
local dquote = '"'
local function chartopad(c)
return string.format("\\%03d", string.byte(c))
end
local pads = {
z = "\\z",
x = "\\x",
['0'] = '\\0',
['1'] = '\\1',
['2'] = '\\2',
['3'] = '\\3',
['4'] = '\\4',
['5'] = '\\5',
['6'] = '\\6',
['7'] = '\\7',
['8'] = '\\8',
['9'] = '\\9',
-- remap escape sequences
a = chartopad('\a'),
b = chartopad('\b'),
f = chartopad('\f'),
r = chartopad('\r'),
n = chartopad('\n'),
t = chartopad('\t'),
v = chartopad('\v'),
['"'] = chartopad('\"'),
["'"] = chartopad('\''),
['\\'] = chartopad('\\')
}
local numbers = {
['0'] = true,
['1'] = true,
['2'] = true,
['3'] = true,
['4'] = true,
['5'] = true,
['6'] = true,
['7'] = true,
['8'] = true,
['9'] = true
}
setmetatable(pads, {
__index = function(t,k) error("invalid escape sequence near '\\" .. k .. "'", 3) end
})
local findpairs
do
local function _findnext(flags, index)
-- only branch if index = 0
if index > 0 then
-- this should always give a match,
-- as we're starting from the same index as the returned match
-- TODO: test %f >.>
local x,y = string.find(flags[1], flags[2], index, flags[3])
return string.find(flags[1], flags[2], y+1, flags[3])
else
return string.find(flags[1], flags[2], index + 1, flags[3])
end
end
function findpairs(str, pat, raw)
return _findnext, {str, pat, raw}, 0
end
end
-- Parse a string like it's a Lua 5.2 string.
local function parseString52(s)
-- "validate" string
local startChar = string.sub(s,1,1)
assert(startChar==squote or startChar==dquote, "not a string")
assert(string.sub(s, -1, -1) == startChar, "unfinished string")
-- remove quotes
local str = string.sub(s, 2, -2)
-- replace "normal" escapes with a padded escape
str = string.gsub(str, "\\(.)", pads)
-- check for non-escaped startChar
assert(not string.find(str, startChar), "unfinished string")
-- pad numerical escapes
str = string.gsub(str, "\\([0-9])(.?)(.?)", function(a, b, c)
local x = a
-- swap b and c if #b == 0; this is to avoid UB:
-- _in theory_ `c` could match but not `b`, this solves
-- that problem. uncomment if you know what you're doing.
if #b == 0 then b, c = c, b end
if numbers[b] then
x, b = x .. b, ""
if numbers[c] then
x, c = x .. c, ""
end
end
local temp1 = ("0"):rep(3 - #x)
return "\\" .. temp1 .. x .. b .. c
end)
local t = {}
local i = 1
local last = 1
-- split on \z
-- we can look for "\z" directly because we already escaped everything else
for from, to in findpairs(str, "\\z", true) do
t[i] = string.sub(str, last, from - 1)
last = to+1
i = i + 1
end
t[i] = string.sub(str, last)
-- parse results
local nt = {}
for x,y in ipairs(t) do
nt[x] = string.gsub(y, "\\(([x0-9])((.).))",
function(a,b,c,d)
if b ~= "x" then
local n = tonumber(a)
assert(n < 256, "decimal escape too large near '\\" .. a .. "'")
return string.char(n)
else
local n = tonumber(c, 16)
assert(n, "hexadecimal digit expected near '\\x" .. c .. "'")
return string.char(n)
end
end)
if x > 1 then
-- handle \z
nt[x] = string.gsub(nt[x], "^[%s]*", "")
end
end
-- merge
return table.concat(nt, "")
end
-- "tests"
-- TODO add more
-- also add automatic checks
if _VERSION == "Lua 5.2" and not ... then
local t = {
[=["\""]=],
[=["""]=],
[=["v""]=],
[=[""/"]=],
[=["\v"/"]=],
[=["\m"]=],
[=["\32"]=],
}
for _, str in ipairs(t) do
local s, m = pcall(parseString52, str)
io.write(tostring(s and m or "nil"))
io.write(tostring(s and "" or ("\t" .. m)) .. "\n")
s, m = load("return " .. str, "@/home/soniex2/git/github/Stuff/lua/String.lua:")
io.write(tostring(s and s()))
io.write(tostring(m and "\t"..m or "") .. "\n")
end
elseif not ... then
print("Tests require Lua 5.2")
end
return {
parse52 = parseString52,
findpairs = findpairs,
}
|
Fix bugs and screw 5.0 compat
|
Fix bugs and screw 5.0 compat
|
Lua
|
mit
|
SoniEx2/Stuff,SoniEx2/Stuff
|
bb47bcc126e501d4f04dd42f7ddc7b93efe67aa8
|
mod_admin_web/admin_web/mod_admin_web.lua
|
mod_admin_web/admin_web/mod_admin_web.lua
|
-- Copyright (C) 2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- <session xmlns="http://prosody.im/streams/c2s" jid="[email protected]/brussels">
-- <encrypted/>
-- <compressed/>
-- </session>
-- <session xmlns="http://prosody.im/streams/s2s" jid="example.com">
-- <encrypted/>
-- <compressed/>
-- <in/> / <out/>
-- </session>
local stanza = require "util.stanza";
local uuid_generate = require "util.uuid".generate;
local httpserver = require "net.httpserver";
local lfs = require "lfs";
local open = io.open;
local stat = lfs.attributes;
local host = module:get_host();
local service = config.get("*", "core", "webadmin_pubsub_host") or ("pubsub." .. host);
local http_base = (prosody.paths.plugins or "./plugins/") .. "admin_web/www_files";
local xmlns_c2s_session = "http://prosody.im/streams/c2s";
local xmlns_s2s_session = "http://prosody.im/streams/s2s";
local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" };
local response_403 = { status = "403 Forbidden", body = "<h1>Forbidden</h1>You don't have permission to view the contents of this directory :(" };
local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
local mime_map = {
html = "text/html";
xml = "text/xml";
js = "text/javascript";
css = "text/css";
};
local idmap = {};
function add_client(session)
local name = session.full_jid;
local id = idmap[name];
if not id then
id = uuid_generate();
idmap[name] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_c2s_session, jid = name}):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_c2s_session, service, id, item);
module:log("debug", "Added client " .. name);
end
function del_client(session)
local name = session.full_jid;
local id = idmap[name];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_c2s_session, service, id, notifier);
end
end
function add_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if not id then
id = uuid_generate();
idmap[name.."_"..type] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_s2s_session, jid = name})
:tag(type):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_s2s_session, service, id, item);
module:log("debug", "Added host " .. name .. " s2s" .. type);
end
function del_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_s2s_session, service, id, notifier);
end
end
local function preprocess_path(path)
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
function serve_file(path)
local full_path = http_base..path;
if stat(full_path, "mode") == "directory" then
if stat(full_path.."/index.html", "mode") == "file" then
return serve_file(path.."/index.html");
end
return response_403;
end
local f, err = open(full_path, "rb");
if not f then return response_404; end
local data = f:read("*a");
data = data:gsub("%%PUBSUBHOST%%", service);
f:close();
if not data then
return response_403;
end
local ext = path:match("%.([^.]*)$");
local mime = mime_map[ext]; -- Content-Type should be nil when not known
return {
headers = { ["Content-Type"] = mime; };
body = data;
};
end
local function handle_file_request(method, body, request)
local path = preprocess_path(request.url.path);
if not path then return response_400; end
path = path:gsub("^/[^/]+", ""); -- Strip /admin/
return serve_file(path);
end
function module.load()
local host_session = prosody.hosts[host];
local http_conf = config.get("*", "core", "webadmin_http_ports");
httpserver.new_from_config(http_conf, handle_file_request, { base = "admin" });
end
module:hook("server-started", function ()
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_s2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_s2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_s2s_session .. ": " .. tostring(errmsg));
end
end
for remotehost, session in pairs(host_session.s2sout) do
if session.type ~= "s2sout_unauthed" then
add_host(session, "out");
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host then
add_host(session, "in");
end
end
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_c2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_c2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_c2s_session .. ": " .. tostring(errmsg));
end
end
for username, user in pairs(host_session.sessions or {}) do
for resource, session in pairs(user.sessions or {}) do
add_client(session);
end
end
end);
module:hook("resource-bind", function(event)
add_client(event.session);
end);
module:hook("resource-unbind", function(event)
del_client(event.session);
end);
module:hook("s2sout-established", function(event)
add_host(event.session, "out");
end);
module:hook("s2sin-established", function(event)
add_host(event.session, "in");
end);
module:hook("s2sout-destroyed", function(event)
del_host(event.session, "out");
end);
module:hook("s2sin-destroyed", function(event)
del_host(event.session, "in");
end);
|
-- Copyright (C) 2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- <session xmlns="http://prosody.im/streams/c2s" jid="[email protected]/brussels">
-- <encrypted/>
-- <compressed/>
-- </session>
-- <session xmlns="http://prosody.im/streams/s2s" jid="example.com">
-- <encrypted/>
-- <compressed/>
-- <in/> / <out/>
-- </session>
local stanza = require "util.stanza";
local uuid_generate = require "util.uuid".generate;
local httpserver = require "net.httpserver";
local lfs = require "lfs";
local open = io.open;
local stat = lfs.attributes;
local host = module:get_host();
local service = config.get("*", "core", "webadmin_pubsub_host") or ("pubsub." .. host);
local http_base = (prosody.paths.plugins or "./plugins/") .. "admin_web/www_files";
local xmlns_c2s_session = "http://prosody.im/streams/c2s";
local xmlns_s2s_session = "http://prosody.im/streams/s2s";
local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" };
local response_403 = { status = "403 Forbidden", body = "<h1>Forbidden</h1>You don't have permission to view the contents of this directory :(" };
local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
local mime_map = {
html = "text/html";
xml = "text/xml";
js = "text/javascript";
css = "text/css";
};
local idmap = {};
function add_client(session)
local name = session.full_jid;
local id = idmap[name];
if not id then
id = uuid_generate();
idmap[name] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_c2s_session, jid = name}):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_c2s_session, service, id, item);
module:log("debug", "Added client " .. name);
end
function del_client(session)
local name = session.full_jid;
local id = idmap[name];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_c2s_session, service, id, notifier);
end
end
function add_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if not id then
id = uuid_generate();
idmap[name.."_"..type] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_s2s_session, jid = name})
:tag(type):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_s2s_session, service, id, item);
module:log("debug", "Added host " .. name .. " s2s" .. type);
end
function del_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_s2s_session, service, id, notifier);
end
end
local function preprocess_path(path)
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
function serve_file(path)
local full_path = http_base..path;
if stat(full_path, "mode") == "directory" then
if stat(full_path.."/index.html", "mode") == "file" then
return serve_file(path.."/index.html");
end
return response_403;
end
local f, err = open(full_path, "rb");
if not f then return response_404; end
local data = f:read("*a");
data = data:gsub("%%PUBSUBHOST%%", service);
f:close();
if not data then
return response_403;
end
local ext = path:match("%.([^.]*)$");
local mime = mime_map[ext]; -- Content-Type should be nil when not known
return {
headers = { ["Content-Type"] = mime; };
body = data;
};
end
local function handle_file_request(method, body, request)
local path = preprocess_path(request.url.path);
if not path then return response_400; end
path = path:gsub("^/[^/]+", ""); -- Strip /admin/
return serve_file(path);
end
function module.load()
local http_conf = config.get("*", "core", "webadmin_http_ports");
httpserver.new_from_config(http_conf, handle_file_request, { base = "admin" });
end
prosody.events.add_handler("server-started", function ()
local host_session = prosody.hosts[host];
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_s2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_s2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_s2s_session .. ": " .. tostring(errmsg));
end
end
for remotehost, session in pairs(host_session.s2sout) do
if session.type ~= "s2sout_unauthed" then
add_host(session, "out");
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host then
add_host(session, "in");
end
end
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_c2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_c2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_c2s_session .. ": " .. tostring(errmsg));
end
end
for username, user in pairs(host_session.sessions or {}) do
for resource, session in pairs(user.sessions or {}) do
add_client(session);
end
end
end);
module:hook("resource-bind", function(event)
add_client(event.session);
end);
module:hook("resource-unbind", function(event)
del_client(event.session);
end);
module:hook("s2sout-established", function(event)
add_host(event.session, "out");
end);
module:hook("s2sin-established", function(event)
add_host(event.session, "in");
end);
module:hook("s2sout-destroyed", function(event)
del_host(event.session, "out");
end);
module:hook("s2sin-destroyed", function(event)
del_host(event.session, "in");
end);
|
mod_admin_web: Fix initialisation code, undeclared variable and wrong event scope
|
mod_admin_web: Fix initialisation code, undeclared variable and wrong event scope
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
b6a7261bec9014169465984fffa4fa60f6b4995b
|
cookbooks/neovim/files/nvim/lua/plugins.lua
|
cookbooks/neovim/files/nvim/lua/plugins.lua
|
-- Packer.nvim bootstrapping
-- see https://github.com/wbthomason/packer.nvim#bootstrapping
-- TODO: Move to ~/.config/nvim/lua/init.lua
local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
-- Plugins
local packer = require('packer')
packer.init {
display = {
open_fn = require('packer.util').float,
},
}
return packer.startup(function(use)
-- lua plugins
use {
{ 'wbthomason/packer.nvim' },
{
'neovim/nvim-lspconfig',
requires = {
'nvim-lua/lsp-status.nvim',
'hrsh7th/cmp-nvim-lsp',
},
config = function()
require('lsp')
end
},
{
'hrsh7th/nvim-cmp',
requires = {
'neovim/nvim-lspconfig',
'hrsh7th/cmp-buffer',
'hrsh7th/cmp-nvim-lua',
'hrsh7th/cmp-nvim-lsp',
'hrsh7th/cmp-path',
},
config = function()
local cmp = require('cmp')
cmp.setup {
mapping = cmp.mapping.preset.insert({}),
sources = {
{ name = 'buffer' },
{ name = 'nvim_lua' },
{ name = 'nvim_lsp' },
{ name = 'path' },
},
}
end,
},
{
'folke/which-key.nvim',
-- TODO: Lazy loading
-- cmd = { 'WhichKey' },
-- keys = { '<leader>', '<Space>' },
config = function()
local wk = require('which-key')
wk.setup({ triggers = { '<leader>' } })
wk.register({
G = {
name = '+git',
g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' },
o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' },
},
l = {
name = '+lsp',
r = { vim.lsp.buf.references, 'references' },
d = { '<cmd>Trouble<CR>', 'diagnostics' },
f = { function() vim.lsp.buf.format({ async = true }) end, 'format' },
},
f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' },
b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' },
g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' },
p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' },
n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' },
P = {
name = '+packer',
u = { '<cmd>PackerUpdate<CR>', 'update' },
s = { '<cmd>PackerSync<CR>', 'sync' },
i = { '<cmd>PackerInstall<CR>', 'install' },
c = { '<cmd>PackerCompile<CR>', 'compile' },
},
},
{ prefix = '<leader>' })
end
},
{
'lewis6991/gitsigns.nvim',
tag = 'release',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require('gitsigns').setup {
signs = {
-- default: text = '_'
delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' },
},
current_line_blame = true,
}
end
},
{
'nvim-lualine/lualine.nvim',
requires = {
{ 'kyazdani42/nvim-web-devicons', opt = true },
'nvim-lua/lsp-status.nvim',
'projekt0n/github-nvim-theme',
},
config = function()
local lsp_status = require('lsp-status')
require('lualine').setup{
options = {
theme = 'auto',
globalstatus = true,
},
sections = {
lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' },
},
}
end
},
{
'folke/trouble.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
config = function()
require('trouble').setup {
auto_close = true,
}
end
},
{
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
},
{
'nvim-telescope/telescope.nvim',
cmd = { 'Telescope' },
requires = {
'nvim-lua/popup.nvim',
'nvim-lua/plenary.nvim',
'nvim-telescope/telescope-ghq.nvim',
},
config = function()
local telescope = require('telescope')
telescope.load_extension('ghq')
telescope.setup {
defaults = {
mappings = {
i = {
-- see https://github.com/nvim-telescope/telescope.nvim/issues/499
["<C-u>"] = false,
},
},
},
}
end,
},
{
'akinsho/bufferline.nvim',
tag = '*',
requires = {
'kyazdani42/nvim-web-devicons',
},
config = function()
require('bufferline').setup {
options = {
separator_style = 'thin',
diagnostics = "nvim_lsp",
},
}
end,
},
{
'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
config = function()
require('nvim-treesitter.configs').setup {
highlight = {
enable = true,
},
}
end,
},
{
'projekt0n/github-nvim-theme',
config = function()
require('github-theme').setup {
theme_style = 'dark_default',
transparent = true,
}
end,
}
}
-- vimscript plugins
use {
{ 'tpope/vim-fugitive' },
{ 'tpope/vim-endwise' },
{ 'tpope/vim-surround' },
{ 'hashivim/vim-terraform', ft = 'terraform' },
{ 'tmux-plugins/vim-tmux', ft = 'tmux' },
{ 'cespare/vim-toml' },
{ 'dag/vim-fish' },
{
'tyru/caw.vim',
keys = { '<C-k>' },
config = function()
vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {})
end
},
{
'scrooloose/nerdtree',
cmd = { 'NERDTreeFind', 'NERDTreeToggle' },
keys = { '<F2>', '<F3>' },
setup = function()
vim.g.NERDTreeChDirMode = 0
vim.g.NERDTreeShowHidden = 1
vim.g.NERDTreeWinSize = 30
end,
config = function()
vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true })
end
},
{
'tyru/open-browser-github.vim',
requires = { 'tyru/open-browser.vim', opt = true },
cmd = {
'OpenGithubFile',
'OpenGithubIssue',
'OpenGithubPullReq',
'OpenGithubProject',
'OpenGithubCommit'
},
setup = function()
vim.g.openbrowser_github_url_exists_check = 'ignore'
end
},
{ 'towolf/vim-helm' },
}
end)
|
-- Packer.nvim bootstrapping
-- see https://github.com/wbthomason/packer.nvim#bootstrapping
-- TODO: Move to ~/.config/nvim/lua/init.lua
local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
-- Plugins
local packer = require('packer')
packer.init {
display = {
open_fn = require('packer.util').float,
},
}
return packer.startup(function(use)
-- lua plugins
use {
{ 'wbthomason/packer.nvim' },
{
'neovim/nvim-lspconfig',
requires = {
'nvim-lua/lsp-status.nvim',
'hrsh7th/cmp-nvim-lsp',
},
config = function()
require('lsp')
end
},
{
'hrsh7th/nvim-cmp',
requires = {
'neovim/nvim-lspconfig',
'hrsh7th/cmp-buffer',
'hrsh7th/cmp-nvim-lua',
'hrsh7th/cmp-nvim-lsp',
'hrsh7th/cmp-path',
},
config = function()
local cmp = require('cmp')
cmp.setup {
mapping = cmp.mapping.preset.insert({}),
sources = {
{ name = 'buffer' },
{ name = 'nvim_lua' },
{ name = 'nvim_lsp' },
{ name = 'path' },
},
}
end,
},
{
'folke/which-key.nvim',
-- TODO: Lazy loading
-- cmd = { 'WhichKey' },
-- keys = { '<leader>', '<Space>' },
config = function()
local wk = require('which-key')
wk.setup({ triggers = { '<leader>' } })
wk.register({
G = {
name = '+git',
g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' },
o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' },
},
l = {
name = '+lsp',
r = { vim.lsp.buf.references, 'references' },
d = { '<cmd>Trouble<CR>', 'diagnostics' },
f = { function() vim.lsp.buf.format({ async = true }) end, 'format' },
},
f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' },
b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' },
g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' },
p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' },
n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' },
P = {
name = '+packer',
u = { '<cmd>PackerUpdate<CR>', 'update' },
s = { '<cmd>PackerSync<CR>', 'sync' },
i = { '<cmd>PackerInstall<CR>', 'install' },
c = { '<cmd>PackerCompile<CR>', 'compile' },
},
},
{ prefix = '<leader>' })
end
},
{
'lewis6991/gitsigns.nvim',
tag = 'release',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require('gitsigns').setup {
signs = {
-- default: text = '_'
delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' },
},
current_line_blame = true,
}
end
},
{
'nvim-lualine/lualine.nvim',
requires = {
{ 'kyazdani42/nvim-web-devicons', opt = true },
'nvim-lua/lsp-status.nvim',
'projekt0n/github-nvim-theme',
},
config = function()
local lsp_status = require('lsp-status')
require('lualine').setup{
options = {
theme = 'auto',
globalstatus = true,
},
sections = {
lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' },
},
}
end
},
{
'folke/trouble.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
config = function()
require('trouble').setup {
auto_close = true,
}
end
},
{
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
},
{
'nvim-telescope/telescope.nvim',
cmd = { 'Telescope' },
requires = {
'nvim-lua/popup.nvim',
'nvim-lua/plenary.nvim',
'nvim-telescope/telescope-ghq.nvim',
},
config = function()
local telescope = require('telescope')
telescope.load_extension('ghq')
telescope.setup {
defaults = {
mappings = {
i = {
-- see https://github.com/nvim-telescope/telescope.nvim/issues/499
["<C-u>"] = false,
},
},
},
}
end,
},
{
'akinsho/bufferline.nvim',
tag = '*',
requires = {
'kyazdani42/nvim-web-devicons',
},
config = function()
require('bufferline').setup {
options = {
separator_style = 'thin',
diagnostics = "nvim_lsp",
},
}
end,
},
{
'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
config = function()
require('nvim-treesitter.configs').setup {
highlight = {
enable = true,
},
}
end,
},
{
'projekt0n/github-nvim-theme',
config = function()
require('github-theme').setup {
theme_style = 'dark_default',
transparent = true,
}
end,
}
}
-- vimscript plugins
use {
{ 'tpope/vim-fugitive' },
{ 'tpope/vim-endwise' },
{ 'tpope/vim-surround' },
{ 'hashivim/vim-terraform', ft = 'terraform' },
{ 'tmux-plugins/vim-tmux', ft = 'tmux' },
{ 'cespare/vim-toml' },
{ 'dag/vim-fish' },
{
'tyru/caw.vim',
keys = { '<C-k>' },
config = function()
vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {})
end
},
{
'scrooloose/nerdtree',
cmd = { 'NERDTreeFind', 'NERDTreeToggle' },
keys = { '<F2>', '<F3>' },
setup = function()
vim.g.NERDTreeChDirMode = 0
vim.g.NERDTreeShowHidden = 1
vim.g.NERDTreeWinSize = 30
end,
config = function()
vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true })
end
},
{
'tyru/open-browser-github.vim',
requires = {
{
'tyru/open-browser.vim',
cmd = {
'OpenGithubFile',
'OpenGithubIssue',
'OpenGithubPullReq',
'OpenGithubProject',
'OpenGithubCommit',
}
},
},
cmd = {
'OpenGithubFile',
'OpenGithubIssue',
'OpenGithubPullReq',
'OpenGithubProject',
'OpenGithubCommit',
},
setup = function()
vim.g.openbrowser_github_url_exists_check = 'ignore'
end
},
{ 'towolf/vim-helm' },
}
end)
|
Fix lazyloading for open-browser.vim
|
Fix lazyloading for open-browser.vim
|
Lua
|
mit
|
tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles
|
6b69c65fe69b58ae796352d18b564642bfb29bee
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached"), "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
modules/freifunk: fix same problem
|
modules/freifunk: fix same problem
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci
|
a48897ded6e1bdbaa163ea71963bb35ae76a2d37
|
lua/entities/gmod_wire_expression2/core/timer.lua
|
lua/entities/gmod_wire_expression2/core/timer.lua
|
/******************************************************************************\
Timer support
\******************************************************************************/
local timerid = 0
local function Execute(self, name)
self.data.timer.runner = name
self.data['timer'].timers[name] = nil
if(self.entity and self.entity.Execute) then
self.entity:Execute()
end
if !self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
end
self.data.timer.runner = nil
end
local function AddTimer(self, name, delay)
if delay < 10 then delay = 10 end
if self.data.timer.runner == name then
timer.Adjust("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
timer.Start("e2_" .. self.data['timer'].timerid .. "_" .. name)
elseif !self.data['timer'].timers[name] then
timer.Create("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
end
self.data['timer'].timers[name] = true
end
local function RemoveTimer(self, name)
if self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
self.data['timer'].timers[name] = nil
end
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data['timer'] = {}
self.data['timer'].timerid = timerid
self.data['timer'].timers = {}
timerid = timerid + 1
end)
registerCallback("destruct", function(self)
for name,_ in pairs(self.data['timer'].timers) do
RemoveTimer(self, name)
end
end)
/******************************************************************************/
__e2setcost(20)
e2function void interval(rv1)
AddTimer(self, "interval", rv1)
end
e2function void timer(string rv1, rv2)
AddTimer(self, rv1, rv2)
end
__e2setcost(5)
e2function void stoptimer(string rv1)
RemoveTimer(self, rv1)
end
__e2setcost(1)
e2function number clk()
if self.data.timer.runner == "interval"
then return 1 else return 0 end
end
e2function number clk(string rv1)
if self.data.timer.runner == rv1
then return 1 else return 0 end
end
e2function string clkName()
return self.data.timer.runner or ""
end
e2function array getTimers()
local ret = {}
local i = 0
for name,_ in pairs( self.data.timer.timers ) do
i = i + 1
ret[i] = name
end
self.prf = self.prf + i * 5
return ret
end
e2function void stopAllTimers()
for name,_ in pairs(self.data.timer.timers) do
self.prf = self.prf + 5
RemoveTimer(self,name)
end
end
/******************************************************************************/
e2function number curtime()
return CurTime()
end
e2function number realtime()
return RealTime()
end
e2function number systime()
return SysTime()
end
-----------------------------------------------------------------------------------
local function luaDateToE2Table( time, utc )
local ret = {n={},ntypes={},s={},stypes={},size=0}
local time = os.date((utc and "!" or "") .. "*t",time)
if not time then return ret end -- this happens if you give it a negative time
for k,v in pairs( time ) do
if k == "isdst" then
ret.s.isdst = (v and 1 or 0)
ret.stypes.isdst = "n"
else
ret.s[k] = v
ret.stypes[k] = "n"
end
ret.size = ret.size + 1
end
return ret
end
__e2setcost(10)
-- Returns the server's current time formatted neatly in a table
e2function table date()
return luaDateToE2Table()
end
-- Returns the specified time formatted neatly in a table
e2function table date( time )
return luaDateToE2Table(time)
end
-- Returns the server's current time formatted neatly in a table using UTC
e2function table dateUTC()
return luaDateToE2Table(nil,true)
end
-- Returns the specified time formatted neatly in a table using UTC
e2function table dateUTC( time )
return luaDateToE2Table(time,true)
end
-- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it
-- It's essentially the same as the date function above
e2function number time(string component)
local ostime = os.date("!*t")
local ret = ostime[component]
return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst
end
-----------------------------------------------------------------------------------
__e2setcost(2)
-- Returns the time in seconds
e2function number time()
return os.time()
end
-- Attempts to construct the time from the data in the given table (same as lua's os.time)
-- The table structure must be the same as in the above date functions
-- If any values are missing or of the wrong type, that value is ignored (it will be nil)
local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true}
e2function number time(table data)
local args = {}
for k,v in pairs( data.s ) do
if data.stypes[k] ~= "n" or not validkeys[k] then continue end
if k == "isdst" then
args.isdst = (v == 1)
else
args[k] = v
end
end
return os.time( args )
end
|
/******************************************************************************\
Timer support
\******************************************************************************/
local timerid = 0
local function Execute(self, name)
self.data.timer.runner = name
self.data['timer'].timers[name] = nil
if(self.entity and self.entity.Execute) then
self.entity:Execute()
end
if !self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
end
self.data.timer.runner = nil
end
local function AddTimer(self, name, delay)
if delay < 10 then delay = 10 end
local timerName = "e2_" .. self.data.timer.timerid .. "_" .. name
if self.data.timer.runner == name and timer.Exists(timerName) then
timer.Adjust(timerName, delay / 1000, 2, function()
Execute(self, name)
end)
timer.Start(timerName)
elseif !self.data['timer'].timers[name] then
timer.Create(timerName, delay / 1000, 2, function()
Execute(self, name)
end)
end
self.data['timer'].timers[name] = true
end
local function RemoveTimer(self, name)
if self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
self.data['timer'].timers[name] = nil
end
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data['timer'] = {}
self.data['timer'].timerid = timerid
self.data['timer'].timers = {}
timerid = timerid + 1
end)
registerCallback("destruct", function(self)
for name,_ in pairs(self.data['timer'].timers) do
RemoveTimer(self, name)
end
end)
/******************************************************************************/
__e2setcost(20)
e2function void interval(rv1)
AddTimer(self, "interval", rv1)
end
e2function void timer(string rv1, rv2)
AddTimer(self, rv1, rv2)
end
__e2setcost(5)
e2function void stoptimer(string rv1)
RemoveTimer(self, rv1)
end
__e2setcost(1)
e2function number clk()
if self.data.timer.runner == "interval"
then return 1 else return 0 end
end
e2function number clk(string rv1)
if self.data.timer.runner == rv1
then return 1 else return 0 end
end
e2function string clkName()
return self.data.timer.runner or ""
end
e2function array getTimers()
local ret = {}
local i = 0
for name,_ in pairs( self.data.timer.timers ) do
i = i + 1
ret[i] = name
end
self.prf = self.prf + i * 5
return ret
end
e2function void stopAllTimers()
for name,_ in pairs(self.data.timer.timers) do
self.prf = self.prf + 5
RemoveTimer(self,name)
end
end
/******************************************************************************/
e2function number curtime()
return CurTime()
end
e2function number realtime()
return RealTime()
end
e2function number systime()
return SysTime()
end
-----------------------------------------------------------------------------------
local function luaDateToE2Table( time, utc )
local ret = {n={},ntypes={},s={},stypes={},size=0}
local time = os.date((utc and "!" or "") .. "*t",time)
if not time then return ret end -- this happens if you give it a negative time
for k,v in pairs( time ) do
if k == "isdst" then
ret.s.isdst = (v and 1 or 0)
ret.stypes.isdst = "n"
else
ret.s[k] = v
ret.stypes[k] = "n"
end
ret.size = ret.size + 1
end
return ret
end
__e2setcost(10)
-- Returns the server's current time formatted neatly in a table
e2function table date()
return luaDateToE2Table()
end
-- Returns the specified time formatted neatly in a table
e2function table date( time )
return luaDateToE2Table(time)
end
-- Returns the server's current time formatted neatly in a table using UTC
e2function table dateUTC()
return luaDateToE2Table(nil,true)
end
-- Returns the specified time formatted neatly in a table using UTC
e2function table dateUTC( time )
return luaDateToE2Table(time,true)
end
-- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it
-- It's essentially the same as the date function above
e2function number time(string component)
local ostime = os.date("!*t")
local ret = ostime[component]
return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst
end
-----------------------------------------------------------------------------------
__e2setcost(2)
-- Returns the time in seconds
e2function number time()
return os.time()
end
-- Attempts to construct the time from the data in the given table (same as lua's os.time)
-- The table structure must be the same as in the above date functions
-- If any values are missing or of the wrong type, that value is ignored (it will be nil)
local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true}
e2function number time(table data)
local args = {}
for k,v in pairs( data.s ) do
if data.stypes[k] ~= "n" or not validkeys[k] then continue end
if k == "isdst" then
args.isdst = (v == 1)
else
args[k] = v
end
end
return os.time( args )
end
|
Fix stopping and starting timer within it's own callback
|
Fix stopping and starting timer within it's own callback
|
Lua
|
apache-2.0
|
garrysmodlua/wire,sammyt291/wire,thegrb93/wire,dvdvideo1234/wire,wiremod/wire,NezzKryptic/Wire,Grocel/wire
|
d596515f0df6d1f7de045d4c4f724e7f24d094e4
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local port = module:get_option("reg_servlet_port") or 9280;
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config({ port = port }, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then port = 9443; end
require "net.httpserver".new_from_config({ port = port; ssl = { key = ssl_key, certificate = ssl_cert }; }, handle_req, { base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
377679bfc578fbc2e62f626e580c9f057415b888
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { target = connect_host, port = connect_port };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_hosts = host_session.srv_hosts;
if not (srv_choice and srv_choice.answer and srv_choice.answer.secure) then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { answer = { secure = true }, { target = connect_host, port = connect_port } };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
0b10ae66a3e6af514d97fd54e376cbfafa767329
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
if not dns_lookup.types or not dns_lookup.types.TLSA then
module:log("error", "No TLSA support available, DANE will not be supported");
return
end
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = host_session.from_host and idna_to_ascii(host_session.from_host);
if not name then return end
host_session.dane = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
local n = #answer
if n == 0 then if cb then return cb(a,b,c,e); end return end
if n == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_hosts = host_session.srv_hosts;
if not ( srv_hosts and srv_hosts.answer and srv_hosts.answer.secure ) then return end
local srv_choice = srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
if not dns_lookup.types or not dns_lookup.types.TLSA then
module:log("error", "No TLSA support available, DANE will not be supported");
return
end
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = host_session.from_host and idna_to_ascii(host_session.from_host);
if not name then return end
host_session.dane = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
local n = #answer
if n == 0 then if cb then return cb(a,b,c,e); end return end
if n == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_hosts = host_session.srv_hosts;
if not ( srv_hosts and srv_hosts.answer and srv_hosts.answer.secure ) then return end
local srv_choice = srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
local host_session = event.origin;
host_session.log("debug", "Pausing connection until DANE lookup is completed");
host_session.conn:pause()
local function resume()
module:log("eebug", "Resuming connection");
host_session.conn:resume()
end
if not dane_lookup(host_session, resume) then
resume();
end
end, 10);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
mod_s2s_auth_dane: Pause s2sin while doing SRV and TLSA lookups, fixes race condition (Can haz util.async plz)
|
mod_s2s_auth_dane: Pause s2sin while doing SRV and TLSA lookups, fixes race condition (Can haz util.async plz)
|
Lua
|
mit
|
crunchuser/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,prosody-modules/import,either1/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,prosody-modules/import,prosody-modules/import,amenophis1er/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules
|
e8a99110abbae47ee07dc2f3439c4e90e6790c1f
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
require "luci.sys"
require "luci.tools.webadmin"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return string.format("%X", routes6[section].metric)
end
end
return f, m, r
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
Fix display of v6 Routing metric on Freifunk status pages
|
Fix display of v6 Routing metric on Freifunk status pages
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3891 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
vhpham80/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,jschmidlapp/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,stephank/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,phi-psi/luci,jschmidlapp/luci,projectbismark/luci-bismark,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,Flexibity/luci,stephank/luci,vhpham80/luci,Flexibity/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,ThingMesh/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,Canaan-Creative/luci,8devices/carambola2-luci,alxhh/piratenluci,saraedum/luci-packages-old,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,freifunk-gluon/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,stephank/luci,zwhfly/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,alxhh/piratenluci,alxhh/piratenluci,gwlim/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,Flexibity/luci,vhpham80/luci,gwlim/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,yeewang/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,Flexibity/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,gwlim/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,freifunk-gluon/luci,alxhh/piratenluci,ch3n2k/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,8devices/carambola2-luci,projectbismark/luci-bismark,Flexibity/luci,alxhh/piratenluci,jschmidlapp/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,alxhh/piratenluci,gwlim/luci,phi-psi/luci,eugenesan/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ch3n2k/luci,projectbismark/luci-bismark,ch3n2k/luci,stephank/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci
|
25e48b20a8b41e5c5d9d110d7a0e6be54f337232
|
src_trunk/resources/job-system/trucker/s_trucker_job.lua
|
src_trunk/resources/job-system/trucker/s_trucker_job.lua
|
function giveTruckingMoney(wage)
exports.global:givePlayerSafeMoney(source, wage)
end
addEvent("giveTruckingMoney", true)
addEventHandler("giveTruckingMoney", getRootElement(), giveTruckingMoney)
function respawnTruck(vehicle)
removePedFromVehicle(source, vehicle)
respawnVehicle(vehicle)
setElementData(vehicle, "locked", 0, false)
setVehicleLocked(vehicle, false)
setElementVelocity(vehicle,0,0,0)
end
addEvent("respawnTruck", true)
addEventHandler("respawnTruck", getRootElement(), respawnTruck)
local truck = { [414] = true }
function checkTruckingEnterVehicle(thePlayer, seat)
if getElementData(source, "owner") == -2 and getElementData(source, "faction") == -1 and seat == 0 and truck[getElementModel(source)] and getElementData(source,"job") == 1 and getElementData(thePlayer,"job") == 1 then
triggerClientEvent("startTruckJob", thePlayer)
end
end
addEventHandler("onVehicleEnter", getRootElement(), checkTruckingEnterVehicle)
|
function giveTruckingMoney(wage)
exports.global:givePlayerSafeMoney(source, wage)
end
addEvent("giveTruckingMoney", true)
addEventHandler("giveTruckingMoney", getRootElement(), giveTruckingMoney)
function respawnTruck(vehicle)
removePedFromVehicle(source, vehicle)
respawnVehicle(vehicle)
setElementData(vehicle, "locked", 0, false)
setVehicleLocked(vehicle, false)
setElementVelocity(vehicle,0,0,0)
end
addEvent("respawnTruck", true)
addEventHandler("respawnTruck", getRootElement(), respawnTruck)
local truck = { [414] = true }
function checkTruckingEnterVehicle(thePlayer, seat)
outputDebugString(tostring(getElementData(source, "owner")))
outputDebugString(tostring(getElementData(source, "faction")))
outputDebugString(tostring(getElementData(source,"job")))
outputDebugString(tostring(getElementData(thePlayer,"job")))
if getElementData(source, "owner") == -2 and getElementData(source, "faction") == -1 and seat == 0 and truck[getElementModel(source)] and getElementData(source,"job") == 1 and getElementData(thePlayer,"job") == 1 then
triggerClientEvent(thePlayer, "startTruckJob", thePlayer)
end
end
addEventHandler("onVehicleEnter", getRootElement(), checkTruckingEnterVehicle)
|
Fixed trucker job pt 1
|
Fixed trucker job pt 1
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@917 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
58749afc728c28ba93bb7764408404a699fafc28
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[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$
]]--
m = Map("dhcp", "Dnsmasq")
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s:option(Flag, "domainneeded")
s:option(Flag, "authoritative")
s:option(Flag, "boguspriv")
s:option(Flag, "filterwin2k")
s:option(Flag, "localise_queries")
s:option(Value, "local")
s:option(Value, "domain")
s:option(Flag, "expandhosts")
s:option(Flag, "nonegcache")
s:option(Flag, "readethers")
s:option(Value, "leasefile")
s:option(Value, "resolvfile")
s:option(Flag, "nohosts").optional = true
s:option(Flag, "strictorder").optional = true
s:option(Flag, "logqueries").optional = true
s:option(Flag, "noresolv").optional = true
s:option(Value, "dnsforwardmax").optional = true
s:option(Value, "port").optional = true
s:option(Value, "ednspacket_max").optional = true
s:option(Value, "dhcpleasemax").optional = true
s:option(Value, "addnhosts").optional = true
s:option(Value, "queryport").optional = true
s:option(Flag, "enable_tftp").optional = true
s:option(Value, "tftp_root").optional = true
s:option(Value, "dhcp_boot").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[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$
]]--
m = Map("dhcp", "Dnsmasq",
translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" ..
"\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " ..
"firewalls"))
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s.addremove = false
s:option(Flag, "domainneeded",
translate("Domain required"),
translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " ..
"<abbr title=\"Domain Name System\">DNS</abbr>-Name"))
s:option(Flag, "authoritative",
translate("Authoritative"),
translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr> in the local network"))
s:option(Flag, "boguspriv",
translate("Filter private"),
translate("Don't forward reverse lookups for local networks"))
s:option(Flag, "filterwin2k",
translate("Filter useless"),
translate("filter useless <abbr title=\"Domain Name System\">DNS</abbr>-queries of " ..
"Windows-systems"))
s:option(Flag, "localise_queries",
translate("Localise queries"),
translate("localises the hostname depending on its subnet"))
s:option(Value, "local",
translate("Local Server"))
s:option(Value, "domain",
translate("Local Domain"))
s:option(Flag, "expandhosts",
translate("Expand Hosts"),
translate("adds domain names to hostentries in the resolv file"))
s:option(Flag, "nonegcache",
translate("don't cache unknown"),
translate("prevents caching of negative <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"replies"))
s:option(Flag, "readethers",
translate("Use <code>/etc/ethers</code>"),
translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " ..
"Configuration Protocol\">DHCP</abbr>-Server"))
s:option(Value, "leasefile",
translate("Leasefile"),
translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr>-leases will be stored"))
s:option(Value, "resolvfile",
translate("Resolvfile"),
translate("local <abbr title=\"Domain Name System\">DNS</abbr> file"))
s:option(Flag, "nohosts",
translate("Ignore <code>/etc/hosts</code>")).optional = true
s:option(Flag, "strictorder",
translate("Strict order"),
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server will be queried in the " ..
"order of the resolvfile")).optional = true
s:option(Flag, "logqueries",
translate("Log queries")).optional = true
s:option(Flag, "noresolv",
translate("Ignore resolve file")).optional = true
s:option(Value, "dnsforwardmax",
translate("concurrent queries")).optional = true
s:option(Value, "port",
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Port")).optional = true
s:option(Value, "ednspacket_max",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Extension Mechanisms for " ..
"Domain Name System\">EDNS0</abbr> paket size")).optional = true
s:option(Value, "dhcpleasemax",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Dynamic Host Configuration " ..
"Protocol\">DHCP</abbr>-Leases")).optional = true
s:option(Value, "addnhosts",
translate("additional hostfile")).optional = true
s:option(Value, "queryport",
translate("query port")).optional = true
s:option(Flag, "enable_tftp",
translate("Enable TFTP-Server")).optional = true
s:option(Value, "tftp_root",
translate("TFTP-Server Root")).optional = true
s:option(Value, "dhcp_boot",
translate("Network Boot Image")).optional = true
return m
|
modules/admin-full: fix dnsmasq page
|
modules/admin-full: fix dnsmasq page
|
Lua
|
apache-2.0
|
remakeelectric/luci,nwf/openwrt-luci,openwrt/luci,thess/OpenWrt-luci,fkooman/luci,Hostle/luci,keyidadi/luci,oyido/luci,NeoRaider/luci,MinFu/luci,sujeet14108/luci,tcatm/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,Noltari/luci,lcf258/openwrtcn,marcel-sch/luci,Sakura-Winkey/LuCI,NeoRaider/luci,forward619/luci,slayerrensky/luci,artynet/luci,slayerrensky/luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,MinFu/luci,chris5560/openwrt-luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,RedSnake64/openwrt-luci-packages,cshore/luci,daofeng2015/luci,maxrio/luci981213,deepak78/new-luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,dismantl/luci-0.12,openwrt/luci,lbthomsen/openwrt-luci,oyido/luci,chris5560/openwrt-luci,david-xiao/luci,sujeet14108/luci,jorgifumi/luci,maxrio/luci981213,deepak78/new-luci,taiha/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,keyidadi/luci,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,palmettos/test,Kyklas/luci-proto-hso,rogerpueyo/luci,dwmw2/luci,palmettos/cnLuCI,kuoruan/lede-luci,florian-shellfire/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,marcel-sch/luci,joaofvieira/luci,fkooman/luci,LuttyYang/luci,artynet/luci,obsy/luci,harveyhu2012/luci,RuiChen1113/luci,palmettos/test,forward619/luci,mumuqz/luci,shangjiyu/luci-with-extra,oneru/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,RuiChen1113/luci,wongsyrone/luci-1,urueedi/luci,nmav/luci,jchuang1977/luci-1,oyido/luci,jlopenwrtluci/luci,kuoruan/luci,deepak78/new-luci,maxrio/luci981213,dismantl/luci-0.12,sujeet14108/luci,dismantl/luci-0.12,aa65535/luci,lcf258/openwrtcn,obsy/luci,kuoruan/lede-luci,981213/luci-1,LuttyYang/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,cshore/luci,artynet/luci,hnyman/luci,openwrt/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,Hostle/luci,joaofvieira/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,fkooman/luci,lbthomsen/openwrt-luci,slayerrensky/luci,mumuqz/luci,david-xiao/luci,openwrt/luci,aa65535/luci,artynet/luci,tcatm/luci,mumuqz/luci,urueedi/luci,keyidadi/luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,oyido/luci,chris5560/openwrt-luci,schidler/ionic-luci,ff94315/luci-1,teslamint/luci,obsy/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,opentechinstitute/luci,NeoRaider/luci,obsy/luci,david-xiao/luci,oyido/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,urueedi/luci,slayerrensky/luci,jchuang1977/luci-1,opentechinstitute/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,shangjiyu/luci-with-extra,jorgifumi/luci,lcf258/openwrtcn,zhaoxx063/luci,Wedmer/luci,bittorf/luci,jchuang1977/luci-1,cshore/luci,RuiChen1113/luci,zhaoxx063/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,NeoRaider/luci,florian-shellfire/luci,maxrio/luci981213,tobiaswaldvogel/luci,ff94315/luci-1,teslamint/luci,cshore/luci,nmav/luci,nmav/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,slayerrensky/luci,taiha/luci,forward619/luci,remakeelectric/luci,keyidadi/luci,thesabbir/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,maxrio/luci981213,bright-things/ionic-luci,thess/OpenWrt-luci,daofeng2015/luci,Wedmer/luci,openwrt/luci,jorgifumi/luci,david-xiao/luci,nwf/openwrt-luci,keyidadi/luci,florian-shellfire/luci,sujeet14108/luci,ff94315/luci-1,NeoRaider/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,forward619/luci,forward619/luci,Noltari/luci,urueedi/luci,thesabbir/luci,jchuang1977/luci-1,thess/OpenWrt-luci,Sakura-Winkey/LuCI,thesabbir/luci,bittorf/luci,shangjiyu/luci-with-extra,dwmw2/luci,taiha/luci,981213/luci-1,deepak78/new-luci,kuoruan/luci,LuttyYang/luci,bright-things/ionic-luci,teslamint/luci,florian-shellfire/luci,Noltari/luci,forward619/luci,hnyman/luci,MinFu/luci,hnyman/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,dwmw2/luci,harveyhu2012/luci,bright-things/ionic-luci,Hostle/luci,palmettos/test,dwmw2/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,981213/luci-1,openwrt/luci,Noltari/luci,marcel-sch/luci,Noltari/luci,bittorf/luci,oneru/luci,ollie27/openwrt_luci,palmettos/test,openwrt-es/openwrt-luci,Hostle/luci,MinFu/luci,maxrio/luci981213,hnyman/luci,fkooman/luci,joaofvieira/luci,981213/luci-1,zhaoxx063/luci,jchuang1977/luci-1,cappiewu/luci,bittorf/luci,joaofvieira/luci,taiha/luci,mumuqz/luci,sujeet14108/luci,artynet/luci,ff94315/luci-1,oneru/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,jchuang1977/luci-1,ff94315/luci-1,oneru/luci,deepak78/new-luci,oneru/luci,sujeet14108/luci,LuttyYang/luci,bright-things/ionic-luci,male-puppies/luci,Sakura-Winkey/LuCI,981213/luci-1,daofeng2015/luci,MinFu/luci,nmav/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,daofeng2015/luci,thess/OpenWrt-luci,taiha/luci,male-puppies/luci,shangjiyu/luci-with-extra,thesabbir/luci,zhaoxx063/luci,hnyman/luci,keyidadi/luci,daofeng2015/luci,cappiewu/luci,kuoruan/lede-luci,palmettos/test,thesabbir/luci,aa65535/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,wongsyrone/luci-1,Hostle/luci,Wedmer/luci,teslamint/luci,oneru/luci,maxrio/luci981213,artynet/luci,cshore/luci,rogerpueyo/luci,ff94315/luci-1,artynet/luci,bittorf/luci,palmettos/test,dismantl/luci-0.12,tobiaswaldvogel/luci,daofeng2015/luci,male-puppies/luci,forward619/luci,bright-things/ionic-luci,bright-things/ionic-luci,Noltari/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,aa65535/luci,obsy/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,palmettos/test,cshore/luci,jlopenwrtluci/luci,david-xiao/luci,tcatm/luci,palmettos/cnLuCI,david-xiao/luci,Kyklas/luci-proto-hso,marcel-sch/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,kuoruan/luci,aa65535/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,chris5560/openwrt-luci,rogerpueyo/luci,tobiaswaldvogel/luci,cappiewu/luci,lcf258/openwrtcn,schidler/ionic-luci,harveyhu2012/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,joaofvieira/luci,kuoruan/luci,tcatm/luci,joaofvieira/luci,dwmw2/luci,hnyman/luci,jorgifumi/luci,harveyhu2012/luci,lcf258/openwrtcn,nmav/luci,oyido/luci,thesabbir/luci,nmav/luci,obsy/luci,nmav/luci,tcatm/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,nmav/luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,kuoruan/lede-luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,RuiChen1113/luci,LuttyYang/luci,RuiChen1113/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,teslamint/luci,teslamint/luci,forward619/luci,remakeelectric/luci,keyidadi/luci,981213/luci-1,cappiewu/luci,hnyman/luci,fkooman/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,marcel-sch/luci,david-xiao/luci,lcf258/openwrtcn,rogerpueyo/luci,male-puppies/luci,taiha/luci,RuiChen1113/luci,marcel-sch/luci,maxrio/luci981213,MinFu/luci,jlopenwrtluci/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,obsy/luci,artynet/luci,mumuqz/luci,lbthomsen/openwrt-luci,deepak78/new-luci,florian-shellfire/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,LuttyYang/luci,bittorf/luci,palmettos/test,palmettos/cnLuCI,chris5560/openwrt-luci,tcatm/luci,Kyklas/luci-proto-hso,sujeet14108/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,slayerrensky/luci,Wedmer/luci,wongsyrone/luci-1,tcatm/luci,aa65535/luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,obsy/luci,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,schidler/ionic-luci,marcel-sch/luci,lcf258/openwrtcn,taiha/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,male-puppies/luci,schidler/ionic-luci,taiha/luci,opentechinstitute/luci,florian-shellfire/luci,wongsyrone/luci-1,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,oyido/luci,teslamint/luci,thesabbir/luci,slayerrensky/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,remakeelectric/luci,fkooman/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,nmav/luci,artynet/luci,rogerpueyo/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,opentechinstitute/luci,dwmw2/luci,zhaoxx063/luci,openwrt/luci,chris5560/openwrt-luci,remakeelectric/luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,kuoruan/luci,jorgifumi/luci,Noltari/luci,schidler/ionic-luci,chris5560/openwrt-luci,remakeelectric/luci,wongsyrone/luci-1,thess/OpenWrt-luci,deepak78/new-luci,florian-shellfire/luci,bittorf/luci,chris5560/openwrt-luci,zhaoxx063/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,openwrt-es/openwrt-luci,Wedmer/luci,schidler/ionic-luci,Wedmer/luci,aa65535/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,jorgifumi/luci,dwmw2/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,Hostle/luci,urueedi/luci,kuoruan/lede-luci,urueedi/luci,NeoRaider/luci,ff94315/luci-1,mumuqz/luci,palmettos/cnLuCI,oneru/luci,cshore/luci,fkooman/luci,harveyhu2012/luci,remakeelectric/luci,marcel-sch/luci,cappiewu/luci,male-puppies/luci,NeoRaider/luci,mumuqz/luci,oneru/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,jorgifumi/luci,cappiewu/luci,kuoruan/luci,wongsyrone/luci-1,remakeelectric/luci,dwmw2/luci,wongsyrone/luci-1,kuoruan/lede-luci,oyido/luci,rogerpueyo/luci,fkooman/luci,cappiewu/luci,dismantl/luci-0.12,kuoruan/lede-luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,MinFu/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,hnyman/luci,thess/OpenWrt-luci,Hostle/luci,nwf/openwrt-luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,keyidadi/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,nwf/openwrt-luci,daofeng2015/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci
|
0650de4cd010d5d780dc255ef4f9d9503e76b553
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached"), "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
modules/freifunk: fix same problem
|
modules/freifunk: fix same problem
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5150 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
c45a4613ce40f939b52c2ccd883712ff30d54dcc
|
xmake/core/sandbox/modules/import/lib/detect/cache.lua
|
xmake/core/sandbox/modules/import/lib/detect/cache.lua
|
--!The Make-like Build Utility based on 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.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file cache.lua
--
-- define module
local sandbox_lib_detect_cache = sandbox_lib_detect_cache or {}
-- load modules
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")
local cache = require("project/cache")
local project = require("project/project")
local sandbox = require("sandbox/sandbox")
local raise = require("sandbox/modules/raise")
-- get detect cache instance
function sandbox_lib_detect_cache._instance()
-- get it
local detectcache = sandbox_lib_detect_cache._INSTANCE or cache(utils.ifelse(os.isfile(project.file()), "local.detect", "memory.detect"))
sandbox_lib_detect_cache._INSTANCE = detectcache
-- ok?
return detectcache
end
-- load detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
--
function sandbox_lib_detect_cache.load(name)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- attempt to get result from cache first
return detectcache:get(name) or {}
end
-- save detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
-- @param info the cache info
--
function sandbox_lib_detect_cache.save(name, info)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- save cache info
detectcache:set(name, info)
detectcache:flush()
end
-- clear detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
--
function sandbox_lib_detect_cache.clear(name)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- clear cache info
if name then
detectcache:set(name, {})
else
detectcache:clear()
end
detectcache:flush()
end
-- return module
return sandbox_lib_detect_cache
|
--!The Make-like Build Utility based on 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.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file cache.lua
--
-- define module
local sandbox_lib_detect_cache = sandbox_lib_detect_cache or {}
-- load modules
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")
local cache = require("project/cache")
local project = require("project/project")
local sandbox = require("sandbox/sandbox")
local raise = require("sandbox/modules/raise")
-- get detect cache instance
function sandbox_lib_detect_cache._instance()
-- get it
local detectcache = sandbox_lib_detect_cache._INSTANCE or cache(utils.ifelse(os.isfile(project.file()), "local.detect", "memory.detect"))
sandbox_lib_detect_cache._INSTANCE = detectcache
-- ok?
return detectcache
end
-- load detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
--
function sandbox_lib_detect_cache.load(name)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- attempt to get result from cache first
local cacheinfo = detectcache:get(name)
if cacheinfo == nil then
cacheinfo = {}
detectcache:set(name, cacheinfo)
end
-- ok?
return cacheinfo
end
-- save detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
-- @param info the cache info
--
function sandbox_lib_detect_cache.save(name, info)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- save cache info
detectcache:set(name, info)
detectcache:flush()
end
-- clear detect cache
--
-- @param name the cache name. .e.g find_program, find_programver, ..
--
function sandbox_lib_detect_cache.clear(name)
-- get detect cache
local detectcache = sandbox_lib_detect_cache._instance()
-- clear cache info
if name then
detectcache:set(name, {})
else
detectcache:clear()
end
detectcache:flush()
end
-- return module
return sandbox_lib_detect_cache
|
fix detect cache bug
|
fix detect cache bug
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
8c93ac8ea3f90546208ce9b3d94db39b2fa7b003
|
npc/base/talk.lua
|
npc/base/talk.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/>.
]]
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
local common = require("base.common")
local messages = require("base.messages")
local class = require("base.class")
local baseNPC = require("npc.base.basic")
local processorList = require("npc.base.responses")
local tools = require("npc.base.tools")
local consequence = require("npc.base.consequence.consequence")
local condition = require("npc.base.condition.condition")
local talkNPC = class(function(self, rootNPC)
if rootNPC == nil or not rootNPC:is_a(baseNPC) then
return
end
self["_parent"] = rootNPC
self["_entry"] = nil
self["_cycleText"] = nil
self["_state"] = 0
self["_saidNumber"] = nil
self["_nextCycleText"] = -1
end)
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = messages.Messages()
self._parent:addCycle(self)
end
self._cycleText:addMessage(germanText, englishText)
end
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return
end
if (self._entry == nil) then
self._parent:addRecvText(self)
self._entry = {}
end
newEntry:setParent(self)
table.insert(self._entry, newEntry)
end
function talkNPC:receiveText(npcChar, texttype, player, text)
local result = false
for _, entry in pairs(self._entry) do
if entry:checkEntry(npcChar, texttype, player, text) then
entry:execute(npcChar, player)
result = true
return true
end
end
return result
end
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(6000, 9000) --10 to 15 minutes
local german, english = self._cycleText:getRandomMessage()
local textTypeDe, textDe = tools.get_text_and_talktype(german)
local textTypeEn, textEn = tools.get_text_and_talktype(english)
npcChar:talk(textTypeDe, textDe, textEn)
else
self._nextCycleText = self._nextCycleText - counter
end
return self._nextCycleText
end
local talkNPCEntry = class(function(self)
self["_trigger"] = {}
self["_conditions"] = {}
self["_responses"] = {}
self["_responseProcessors"] = {}
self["_responsesCount"] = 0
self["_consequences"] = {}
self["_parent"] = nil
end)
function talkNPCEntry:addTrigger(text)
if text == nil or type(text) ~= "string" then
return
end
text = string.lower(text)
text = string.gsub(text,'([ ]+)',' .*') -- replace all spaces by " .*"
table.insert(self._trigger, text)
end
function talkNPCEntry:setParent(npc)
for _, value in pairs(self._conditions) do
value:setNPC(npc)
end
for _, value in pairs(self._consequences) do
value:setNPC(npc)
end
self._parent = npc
end
function talkNPCEntry:addCondition(c)
if c == nil or not c:is_a(condition.condition) then
return
end
table.insert(self._conditions, c)
if (self._parent ~= nil) then
c:setNPC(self._parent)
end
end
function talkNPCEntry:addResponse(text)
if text == nil or type(text) ~= "string" then
return
end
table.insert(self._responses, text)
self._responsesCount = self._responsesCount + 1
for _, processor in pairs(processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {}
end
table.insert(self._responseProcessors[self._responsesCount], processor)
end
end
end
function talkNPCEntry:addConsequence(c)
if c == nil or not c:is_a(consequence.consequence) then
return
end
table.insert(self._consequences, c)
if (self._parent ~= nil) then
c:setNPC(self._parent)
end
end
function talkNPCEntry:checkEntry(npcChar, texttype, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern)
self._saidNumber = number
if a ~= nil then
local conditionsResult = true
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, texttype, player) then
conditionsResult = false
break
end
end
if conditionsResult then
return true
end
end
end
end
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount)
local responseText = self._responses[selectedResponse]
local responseProcessors = self._responseProcessors[selectedResponse]
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText)
end
end
local textType, text = tools.get_text_and_talktype(responseText)
npcChar:talk(textType, text)
end
for _, consequence in pairs(self._consequences) do
if consequence then
consequence:perform(npcChar, player)
end
end
end
talkNPC["talkNPCEntry"] = talkNPCEntry
return talkNPC
|
--[[
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/>.
]]
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
local common = require("base.common")
local messages = require("base.messages")
local class = require("base.class")
local baseNPC = require("npc.base.basic")
local processorList = require("npc.base.responses")
local tools = require("npc.base.tools")
local consequence = require("npc.base.consequence.consequence")
local condition = require("npc.base.condition.condition")
local talkNPC = class(function(self, rootNPC)
if rootNPC == nil or not rootNPC:is_a(baseNPC) then
return
end
self["_parent"] = rootNPC
self["_entry"] = nil
self["_cycleText"] = nil
self["_state"] = 0
self["_saidNumber"] = nil
self["_nextCycleText"] = -1
end)
local talkNPCEntry = class(function(self)
self["_trigger"] = {}
self["_conditions"] = {}
self["_responses"] = {}
self["_responseProcessors"] = {}
self["_responsesCount"] = 0
self["_consequences"] = {}
self["_parent"] = nil
end)
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = messages.Messages()
self._parent:addCycle(self)
end
self._cycleText:addMessage(germanText, englishText)
end
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return
end
if (self._entry == nil) then
self._parent:addRecvText(self)
self._entry = {}
end
newEntry:setParent(self)
table.insert(self._entry, newEntry)
end
function talkNPC:receiveText(npcChar, texttype, player, text)
local result = false
for _, entry in pairs(self._entry) do
if entry:checkEntry(npcChar, texttype, player, text) then
entry:execute(npcChar, player)
result = true
return true
end
end
return result
end
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(6000, 9000) --10 to 15 minutes
local german, english = self._cycleText:getRandomMessage()
local textTypeDe, textDe = tools.get_text_and_talktype(german)
local textTypeEn, textEn = tools.get_text_and_talktype(english)
npcChar:talk(textTypeDe, textDe, textEn)
else
self._nextCycleText = self._nextCycleText - counter
end
return self._nextCycleText
end
function talkNPCEntry:addTrigger(text)
if text == nil or type(text) ~= "string" then
return
end
text = string.lower(text)
text = string.gsub(text,'([ ]+)',' .*') -- replace all spaces by " .*"
table.insert(self._trigger, text)
end
function talkNPCEntry:setParent(npc)
for _, value in pairs(self._conditions) do
value:setNPC(npc)
end
for _, value in pairs(self._consequences) do
value:setNPC(npc)
end
self._parent = npc
end
function talkNPCEntry:addCondition(c)
if c == nil or not c:is_a(condition) then
return
end
table.insert(self._conditions, c)
if (self._parent ~= nil) then
c:setNPC(self._parent)
end
end
function talkNPCEntry:addResponse(text)
if text == nil or type(text) ~= "string" then
return
end
table.insert(self._responses, text)
self._responsesCount = self._responsesCount + 1
for _, processor in pairs(processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {}
end
table.insert(self._responseProcessors[self._responsesCount], processor)
end
end
end
function talkNPCEntry:addConsequence(c)
if c == nil or not c:is_a(consequence) then
return
end
table.insert(self._consequences, c)
if (self._parent ~= nil) then
c:setNPC(self._parent)
end
end
function talkNPCEntry:checkEntry(npcChar, texttype, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern)
self._saidNumber = number
if a ~= nil then
local conditionsResult = true
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, texttype, player) then
conditionsResult = false
break
end
end
if conditionsResult then
return true
end
end
end
end
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount)
local responseText = self._responses[selectedResponse]
local responseProcessors = self._responseProcessors[selectedResponse]
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText)
end
end
local textType, text = tools.get_text_and_talktype(responseText)
npcChar:talk(textType, text)
end
for _, consequence in pairs(self._consequences) do
if consequence then
consequence:perform(npcChar, player)
end
end
end
talkNPC["talkNPCEntry"] = talkNPCEntry
return talkNPC
|
Fix easyNPC talk
|
Fix easyNPC talk
* Define talkNPCEntry before using it
* Use correct tables for condition and consequence classes
|
Lua
|
agpl-3.0
|
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
|
09220a941f3df746140b3a526bc3ac4405e55716
|
Shilke2D/Core/Juggler.lua
|
Shilke2D/Core/Juggler.lua
|
--[[---
A Juggler animates objects implementing IAnimatable interface.
A juggler is a simple object. It does no more than
saving a list of objects implementing "IAnimatable" and advancing
their time if it is told to do so (by calling its own "advanceTime"
method). When an animation is completed, it throws it away.
You can create juggler objects yourself, just as well. That way,
you can group your game into logical components that handle their
animations independently. All you have to do is call the "advanceTime"
method on your custom juggler once per frame.
Moreover the Juggler implements itself the IAnimatable interface,
so a Juggler can be add to another Juggler.
--]]
Juggler = class(nil,IAnimatable)
---Used internally to handle pending operation scheduled while "playing"
local Pending = {
ADD = 0,
REMOVE = 1
}
function Juggler:init()
self.animatedObjs = {}
self.pendingList ={}
self.playing = false
self.paused = false
end
--[[---
Used to pause the current juggler execution.
When a juggler is paused also the execution of all the managed IAnimatable objects is paused
@param paused true/false to enable/disable the pause status
@return nil
--]]
function Juggler:setPause(paused)
self.paused = paused
end
--[[---
Return the current juggler pause state.
@return bool if the juggler is currently in pause
--]]
function Juggler:isPaused()
return self.paused
end
--[[---
Advances the time of all the objects added to the juggler.
After the animation phase is done, it checks for queued add/remove
operations and executes them in the same request order.
@param deltaTime millisec elapsed since last call
--]]
function Juggler:advanceTime(deltaTime)
if self.paused then
return
end
self.playing = true
for _,v in ipairs(self.animatedObjs) do
v:advanceTime(deltaTime)
end
self.playing = false
if #self.pendingList > 0 then
for _,v in ipairs(self.pendingList) do
if v.action == Pending.ADD then
self:add(v.obj)
elseif v.action == Pending.REMOVE then
self:remove(v.obj)
else
error("illegal operation: "..v.action)
end
end
table.clear(self.pendingList)
end
end
--[[---
Add an IAnimatable object to the juggler.
If the juggler is playing (in advanceTime) the add is queued, if not
the obj is added immediatly. If it's an eventDispatcher, the
juggler register itself as a listener for the REMOVE_FROM_JUGGLER
@param obj An object that implement the IAnimatable interface
--]]
function Juggler:add(obj)
--assert(obj:implements(IAnimatable), debug.getinfo(1,"n").name ..
-- " obj doesn't implement IAnimatable")
if self.playing then
table.insert(self.pendingList,{
action = Pending.ADD,
obj = obj
})
return
end
if table.find(self.animatedObjs,obj) == 0 then
table.insert(self.animatedObjs,obj)
if obj:is_a(EventDispatcher) then
obj:addEventListener(Event.REMOVE_FROM_JUGGLER,
Juggler.onRemoveEvent,self)
end
end
end
--[[---
Remove an object from the juggler.
If the juggler is playing (in advanceTime) the remove is queued,
if not the obj is removed immediatly. If it's an eventDispatcher,
the juggler deregister itself as listener for the REMOVE_FROM_JUGGLER
--]]
function Juggler:remove(obj)
if self.playing then
table.insert(self.pendingList,{
action = Pending.REMOVE,
obj = obj
})
return
end
if table.removeObj(self.animatedObjs,obj) then
if obj:is_a(EventDispatcher) then
obj:removeEventListener(Event.REMOVE_FROM_JUGGLER,
Juggler.onRemoveEvent,self)
end
end
end
--[[---
Internal function.
Called when a listened obj dispatch an Event.REMOVE_FROM_JUGGLER event
--]]
function Juggler:onRemoveEvent(event)
self:remove(event.sender)
end
--[[---
Remove all the objects from the juggler.
If the juggler is playing (advaceTime) the removal of the objects will take place during the next frame
--]]
function Juggler:clear()
--stop all the pending add operation
for i = #self.pendingList,1,-1 do
local a = self.pendingList[i]
if a.action == Pending.ADD then
self.pendingList[i] = nil
end
end
--request for remove all the other objects
for _,v in ipairs(self.animatedObjs) do
self:remove(v)
end
-- the real clear will be done at next frame, whene all the 'pending remove' will be completed
end
|
--[[---
A Juggler animates objects implementing IAnimatable interface.
A juggler is a simple object. It does no more than
saving a list of objects implementing "IAnimatable" and advancing
their time if it is told to do so (by calling its own "advanceTime"
method). When an animation is completed, it throws it away.
You can create juggler objects yourself, just as well. That way,
you can group your game into logical components that handle their
animations independently. All you have to do is call the "advanceTime"
method on your custom juggler once per frame.
Moreover the Juggler implements itself the IAnimatable interface,
so a Juggler can be add to another Juggler.
--]]
Juggler = class(nil,IAnimatable)
---Used internally to handle pending operation scheduled while "playing"
local Pending = {ADD = 0, REMOVE = 1, REMOVE_ALL = 2}
local ACTION, OBJ = 1, 2
function Juggler:init()
self.animatedObjs = {}
self.pendingList ={}
self.playing = false
self.paused = false
end
function Juggler:dispose()
self:clear()
end
--[[---
Used to pause the current juggler execution.
When a juggler is paused also the execution of all the managed IAnimatable objects is paused
@param paused true/false to enable/disable the pause status
@return nil
--]]
function Juggler:setPause(paused)
self.paused = paused
end
--[[---
Return the current juggler pause state.
@return bool if the juggler is currently in pause
--]]
function Juggler:isPaused()
return self.paused
end
--[[---
Advances the time of all the objects added to the juggler.
After the animation phase is done, it checks for queued add/remove
operations and executes them in the same request order.
@param deltaTime millisec elapsed since last call
--]]
function Juggler:advanceTime(deltaTime)
if self.paused then
return
end
self.playing = true
for _,obj in ipairs(self.animatedObjs) do
obj:advanceTime(deltaTime)
end
self.playing = false
if #self.pendingList > 0 then
for _,v in ipairs(self.pendingList) do
local action, obj = v[ACTION], v[OBJ]
if action == Pending.ADD then
self:add(obj)
elseif action == Pending.REMOVE then
self:remove(obj)
elseif action == Pending.REMOVE_ALL then
self:clear()
else
error("illegal operation: " .. action)
end
end
table.clear(self.pendingList)
end
end
--[[---
Internal function.
Called when a listened obj dispatch an Event.REMOVE_FROM_JUGGLER event
--]]
function Juggler:onRemoveEvent(event)
self:remove(event.sender)
end
--[[---
Add an IAnimatable object to the juggler.
If the juggler is playing (in advanceTime) the add is queued, if not
the obj is added immediatly. If it's an eventDispatcher, the
juggler register itself as a listener for the REMOVE_FROM_JUGGLER
@param obj An object that implement the IAnimatable interface
--]]
function Juggler:add(obj)
if self.playing then
table.insert(self.pendingList, {Pending.ADD, obj})
return
end
if table.find(self.animatedObjs,obj) == 0 then
table.insert(self.animatedObjs,obj)
if obj:is_a(EventDispatcher) then
obj:addEventListener(Event.REMOVE_FROM_JUGGLER, Juggler.onRemoveEvent,self)
end
end
end
--[[---
Remove an object from the juggler.
If the juggler is playing (in advanceTime) the remove is queued,
if not the obj is removed immediatly. If it's an eventDispatcher,
the juggler deregister itself as listener for the REMOVE_FROM_JUGGLER
--]]
function Juggler:remove(obj)
if self.playing then
table.insert(self.pendingList, {Pending.REMOVE, obj})
return
end
if table.removeObj(self.animatedObjs,obj) then
if obj:is_a(EventDispatcher) then
obj:removeEventListener(Event.REMOVE_FROM_JUGGLER, Juggler.onRemoveEvent,self)
end
end
end
--[[---
Remove all the objects from the juggler.
If the juggler is playing (advaceTime) the removal of the objects will take place during the next frame
--]]
function Juggler:clear()
if self.playing then
--remove all the other pending operations because of the remove_all call
table.clear(self.pendingList)
table.insert(self.pendingList, {Pending.REMOVE_ALL})
return
end
for _,obj in ipairs(self.animatedObjs) do
if obj:is_a(EventDispatcher) then
obj:removeEventListener(Event.REMOVE_FROM_JUGGLER, Juggler.onRemoveEvent,self)
end
end
table.clear(self.animatedObjs)
end
|
Simplified logic / fix of juggler add/remove/clear
|
Simplified logic / fix of juggler add/remove/clear
- fixed clear logic
- simplified add/remove calls
|
Lua
|
mit
|
Shrike78/Shilke2D
|
9e08be7b28596b1f377df21b7aaf6a7ba65b71d3
|
lua_modules/http/httpserver.lua
|
lua_modules/http/httpserver.lua
|
------------------------------------------------------------------------------
-- HTTP server module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <[email protected]>
------------------------------------------------------------------------------
local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
local http
do
------------------------------------------------------------------------------
-- request methods
------------------------------------------------------------------------------
local make_req = function(conn, method, url)
return {
conn = conn,
method = method,
url = url,
}
end
------------------------------------------------------------------------------
-- response methods
------------------------------------------------------------------------------
local make_res = function(csend, cfini)
local send = function(self, data, status)
-- TODO: req.send should take care of response headers!
if self.send_header then
csend("HTTP/1.1 ")
csend(tostring(status or 200))
-- TODO: real HTTP status code/name table
csend(" OK\r\n")
-- we use chunked transfer encoding, to not deal with Content-Length:
-- response header
self:send_header("Transfer-Encoding", "chunked")
-- TODO: send standard response headers, such as Server:, Date:
end
if data then
-- NB: no headers allowed after response body started
if self.send_header then
self.send_header = nil
-- end response headers
csend("\r\n")
end
-- chunked transfer encoding
csend(("%X\r\n"):format(#data))
csend(data)
csend("\r\n")
end
end
local send_header = function(_, name, value)
-- NB: quite a naive implementation
csend(name)
csend(": ")
csend(value)
csend("\r\n")
end
-- finalize request, optionally sending data
local finish = function(self, data, status)
-- NB: res.send takes care of response headers
if data then
self:send(data, status)
end
-- finalize chunked transfer encoding
csend("0\r\n\r\n")
-- close connection
cfini()
end
--
local res = { }
res.send_header = send_header
res.send = send
res.finish = finish
return res
end
------------------------------------------------------------------------------
-- HTTP parser
------------------------------------------------------------------------------
local http_handler = function(handler)
return function(conn)
local csend = (require "fifosock").wrap(conn)
local req, res
local buf = ""
local method, url
local cfini = function()
conn:on("receive", nil)
conn:on("disconnection", nil)
csend(function()
conn:on("sent", nil)
conn:close()
end)
end
local ondisconnect = function(connection)
connection:on("sent", nil)
collectgarbage("collect")
end
-- header parser
local cnt_len = 0
local onheader = function(_, k, v)
-- TODO: look for Content-Type: header
-- to help parse body
-- parse content length to know body length
if k == "content-length" then
cnt_len = tonumber(v)
end
if k == "expect" and v == "100-continue" then
csend("HTTP/1.1 100 Continue\r\n")
end
-- delegate to request object
if req and req.onheader then
req:onheader(k, v)
end
end
-- body data handler
local body_len = 0
local ondata = function(_, chunk)
-- feed request data to request handler
if not req or not req.ondata then return end
req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length:
-- ondata(conn) is called
body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then
req:ondata()
end
end
local onreceive = function(connection, chunk)
-- merge chunks in buffer
if buf then
buf = buf .. chunk
else
buf = chunk
end
-- consume buffer line by line
while #buf > 0 do
-- extract line
local e = buf:find("\r\n", 1, true)
if not e then break end
local line = buf:sub(1, e - 1)
buf = buf:sub(e + 2)
-- method, url?
if not method then
do
local _
-- NB: just version 1.1 assumed
_, _, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
end
if method then
-- make request and response objects
req = make_req(connection, method, url)
res = make_res(csend, cfini)
end
-- spawn request handler
handler(req, res)
-- header line?
elseif #line > 0 then
-- parse header
local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
-- header seems ok?
if k then
k = k:lower()
onheader(connection, k, v)
end
-- headers end
else
-- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler
connection:on("receive", ondata)
-- NB: we feed the rest of the buffer as starting chunk of body
ondata(connection, buf)
-- buffer no longer needed
buf = nil
-- parser done
break
end
end
end
conn:on("receive", onreceive)
conn:on("disconnection", ondisconnect)
end
end
------------------------------------------------------------------------------
-- HTTP server
------------------------------------------------------------------------------
local srv
local createServer = function(port, handler)
-- NB: only one server at a time
if srv then srv:close() end
srv = net.createServer(net.TCP, 15)
-- listen
srv:listen(port, http_handler(handler))
return srv
end
------------------------------------------------------------------------------
-- HTTP server methods
------------------------------------------------------------------------------
http = {
createServer = createServer,
}
end
return http
|
------------------------------------------------------------------------------
-- HTTP server module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <[email protected]>
------------------------------------------------------------------------------
local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
local http
do
------------------------------------------------------------------------------
-- request methods
------------------------------------------------------------------------------
local make_req = function(conn, method, url)
return {
conn = conn,
method = method,
url = url,
}
end
------------------------------------------------------------------------------
-- response methods
------------------------------------------------------------------------------
local make_res = function(csend, cfini)
local send = function(self, data, status)
-- TODO: req.send should take care of response headers!
if self.send_header then
csend("HTTP/1.1 ")
csend(tostring(status or 200))
-- TODO: real HTTP status code/name table
csend(" OK\r\n")
-- we use chunked transfer encoding, to not deal with Content-Length:
-- response header
self:send_header("Transfer-Encoding", "chunked")
-- TODO: send standard response headers, such as Server:, Date:
end
if data then
-- NB: no headers allowed after response body started
if self.send_header then
self.send_header = nil
-- end response headers
csend("\r\n")
end
-- chunked transfer encoding
csend(("%X\r\n"):format(#data))
csend(data)
csend("\r\n")
end
end
local send_header = function(_, name, value)
-- NB: quite a naive implementation
csend(name)
csend(": ")
csend(value)
csend("\r\n")
end
-- finalize request, optionally sending data
local finish = function(self, data, status)
-- NB: res.send takes care of response headers
if data then
self:send(data, status)
end
-- finalize chunked transfer encoding
csend("0\r\n\r\n")
-- close connection
cfini()
end
--
local res = { }
res.send_header = send_header
res.send = send
res.finish = finish
return res
end
------------------------------------------------------------------------------
-- HTTP parser
------------------------------------------------------------------------------
local http_handler = function(handler)
return function(conn)
local csend = (require "fifosock").wrap(conn)
local req, res
local buf = ""
local method, url
local ondisconnect = function(connection)
connection:on("receive", nil)
connection:on("disconnection", nil)
connection:on("sent", nil)
collectgarbage("collect")
end
local cfini = function()
csend(function()
conn:on("sent", nil)
conn:close()
ondisconnect(conn)
end)
end
-- header parser
local cnt_len = 0
local onheader = function(_, k, v)
-- TODO: look for Content-Type: header
-- to help parse body
-- parse content length to know body length
if k == "content-length" then
cnt_len = tonumber(v)
end
if k == "expect" and v == "100-continue" then
csend("HTTP/1.1 100 Continue\r\n")
end
-- delegate to request object
if req and req.onheader then
req:onheader(k, v)
end
end
-- body data handler
local body_len = 0
local ondata = function(_, chunk)
-- feed request data to request handler
if not req or not req.ondata then return end
req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length:
-- ondata(conn) is called
body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then
req:ondata()
end
end
local onreceive = function(connection, chunk)
-- merge chunks in buffer
if buf then
buf = buf .. chunk
else
buf = chunk
end
-- consume buffer line by line
while #buf > 0 do
-- extract line
local e = buf:find("\r\n", 1, true)
if not e then break end
local line = buf:sub(1, e - 1)
buf = buf:sub(e + 2)
-- method, url?
if not method then
do
local _
-- NB: just version 1.1 assumed
_, _, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
end
if method then
-- make request and response objects
req = make_req(connection, method, url)
res = make_res(csend, cfini)
end
-- spawn request handler
handler(req, res)
-- header line?
elseif #line > 0 then
-- parse header
local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
-- header seems ok?
if k then
k = k:lower()
onheader(connection, k, v)
end
-- headers end
else
-- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler
connection:on("receive", ondata)
-- NB: we feed the rest of the buffer as starting chunk of body
ondata(connection, buf)
-- buffer no longer needed
buf = nil
-- parser done
break
end
end
end
conn:on("receive", onreceive)
conn:on("disconnection", ondisconnect)
end
end
------------------------------------------------------------------------------
-- HTTP server
------------------------------------------------------------------------------
local srv
local createServer = function(port, handler)
-- NB: only one server at a time
if srv then srv:close() end
srv = net.createServer(net.TCP, 15)
-- listen
srv:listen(port, http_handler(handler))
return srv
end
------------------------------------------------------------------------------
-- HTTP server methods
------------------------------------------------------------------------------
http = {
createServer = createServer,
}
end
return http
|
httpserver: fix memory leak
|
httpserver: fix memory leak
There was a memory leak related to not dropping all references to
fifosock's ssend.
|
Lua
|
mit
|
HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,vsky279/nodemcu-firmware,FelixPe/nodemcu-firmware,vsky279/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,vsky279/nodemcu-firmware,eku/nodemcu-firmware,nodemcu/nodemcu-firmware,HEYAHONG/nodemcu-firmware,FelixPe/nodemcu-firmware,FelixPe/nodemcu-firmware,nodemcu/nodemcu-firmware,vsky279/nodemcu-firmware,nodemcu/nodemcu-firmware,FelixPe/nodemcu-firmware,FelixPe/nodemcu-firmware,vsky279/nodemcu-firmware
|
2715eb54306984d24cd31dcb6e809232572cbe32
|
modules/lua/commands.lua
|
modules/lua/commands.lua
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Commands for the lua module.
module('_m.lua.commands', package.seeall)
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
buffer:begin_undo_action()
buffer:line_end() buffer:new_line()
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num - 1)
for _, patt in ipairs(control_structure_patterns) do
if line:match(patt) then
local indent = buffer.line_indentation[line_num - 1]
buffer:add_text( patt:match('repeat') and '\nuntil' or '\nend' )
buffer.line_indentation[line_num + 1] = indent
buffer.line_indentation[line_num] = indent + buffer.indent
buffer:line_up() buffer:line_end()
break
end
end
buffer:end_undo_action()
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local buffer = buffer
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
local f = io.open(path)
if f then f:close() textadept.io.open(path) break end
end
end
---
-- Executes the current file.
function run()
local buffer = buffer
local cmd = 'lua "'..buffer.filename..'" 2>&1'
local p = io.popen(cmd)
local out = p:read('*all')
p:close()
textadept.print('> '..cmd..'\n'..out)
end
-- Lua-specific key commands.
local keys = _G.keys
if type(keys) == 'table' then
local m_editing = _m.textadept.editing
keys.lua = {
al = { textadept.io.open, _HOME..'/modules/lua/init.lua' },
ac = {
g = { goto_required }
},
['s\n'] = { try_to_autocomplete_end },
cq = { m_editing.block_comment, '--~' },
cg = { run },
['('] = { function()
buffer.word_chars =
'_.:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
m_editing.show_call_tip(_m.lua.api, true)
buffer:set_chars_default()
return false
end },
}
end
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Commands for the lua module.
module('_m.lua.commands', package.seeall)
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
buffer:begin_undo_action()
buffer:line_end() buffer:new_line()
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num - 1)
for _, patt in ipairs(control_structure_patterns) do
if line:match(patt) then
local indent = buffer.line_indentation[line_num - 1]
buffer:add_text( patt:match('repeat') and '\nuntil' or '\nend' )
buffer.line_indentation[line_num + 1] = indent
buffer.line_indentation[line_num] = indent + buffer.indent
buffer:line_up() buffer:line_end()
break
end
end
buffer:end_undo_action()
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local buffer = buffer
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
if not file then return end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
local f = io.open(path)
if f then f:close() textadept.io.open(path) break end
end
end
---
-- Executes the current file.
function run()
local buffer = buffer
local cmd = 'lua "'..buffer.filename..'" 2>&1'
local p = io.popen(cmd)
local out = p:read('*all')
p:close()
textadept.print('> '..cmd..'\n'..out)
end
-- Lua-specific key commands.
local keys = _G.keys
if type(keys) == 'table' then
local m_editing = _m.textadept.editing
keys.lua = {
al = { textadept.io.open, _HOME..'/modules/lua/init.lua' },
ac = {
g = { goto_required }
},
['s\n'] = { try_to_autocomplete_end },
cq = { m_editing.block_comment, '--~' },
cg = { run },
['('] = { function()
buffer.word_chars =
'_.:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
m_editing.show_call_tip(_m.lua.api, true)
buffer:set_chars_default()
return false
end },
}
end
|
Fix bug when file is not matched in modules/lua/commands.lua.
|
Fix bug when file is not matched in modules/lua/commands.lua.
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
1ff4e26aa81819ae5d72476b8b47300a7ae74333
|
core/xmlhandlers.lua
|
core/xmlhandlers.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.
--
require "util.stanza"
local st = stanza;
local tostring = tostring;
local pairs = pairs;
local ipairs = ipairs;
local type = type;
local print = print;
local format = string.format;
local m_random = math.random;
local t_insert = table.insert;
local t_remove = table.remove;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local sm_destroy_session = import("core.sessionmanager", "destroy_session");
local default_log = require "util.logger".init("xmlhandlers");
local error = error;
module "xmlhandlers"
local ns_prefixes = {
["http://www.w3.org/XML/1998/namespace"] = "xml";
}
function init_xmlhandlers(session, stream_callbacks)
local ns_stack = { "" };
local curr_ns, name = "";
local curr_tag;
local chardata = {};
local xml_handlers = {};
local log = session.log or default_log;
local cb_streamopened = stream_callbacks.streamopened;
local cb_streamclosed = stream_callbacks.streamclosed;
local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end;
local cb_handlestanza = stream_callbacks.handlestanza;
local stream_tag = stream_callbacks.stream_tag;
local stream_default_ns = stream_callbacks.default_ns;
local stanza
function xml_handlers:StartElement(tagname, attr)
if stanza and #chardata > 0 then
-- We have some character data in the buffer
stanza:text(t_concat(chardata));
chardata = {};
end
local curr_ns,name = tagname:match("^(.+)|([^%|]+)$");
if curr_ns ~= stream_default_ns then
attr.xmlns = curr_ns;
end
-- FIXME !!!!!
for i, k in ipairs(attr) do
if type(k) == "string" then
local ns, nm = k:match("^([^|]+)|?([^|]-)$")
if ns and nm then
ns = ns_prefixes[ns];
if ns then
attr[ns..":"..nm] = attr[k];
attr[i] = ns..":"..nm;
attr[k] = nil;
end
end
end
end
if not stanza then --if we are not currently inside a stanza
if session.notopen then
if tagname == stream_tag then
if cb_streamopened then
cb_streamopened(session, attr);
end
else
-- Garbage before stream?
cb_error(session, "no-stream");
end
return;
end
if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
cb_error(session, "invalid-top-level-element");
end
stanza = st.stanza(name, attr);
curr_tag = stanza;
else -- we are inside a stanza, so add a tag
attr.xmlns = nil;
if curr_ns ~= stream_default_ns then
attr.xmlns = curr_ns;
end
stanza:tag(name, attr);
end
end
function xml_handlers:CharacterData(data)
if stanza then
t_insert(chardata, data);
end
end
function xml_handlers:EndElement(tagname)
curr_ns,name = tagname:match("^(.+)|([^%|]+)$");
if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
if tagname == stream_tag then
if cb_streamclosed then
cb_streamclosed(session);
end
return;
elseif name == "error" then
cb_error(session, "stream-error", stanza);
else
cb_error(session, "parse-error", "unexpected-element-close", name);
end
end
if stanza then
if #chardata > 0 then
-- We have some character data in the buffer
stanza:text(t_concat(chardata));
chardata = {};
end
-- Complete stanza
if #stanza.last_add == 0 then
cb_handlestanza(session, stanza);
stanza = nil;
else
stanza:up();
end
end
end
return xml_handlers;
end
return init_xmlhandlers;
|
-- 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.
--
require "util.stanza"
local st = stanza;
local tostring = tostring;
local pairs = pairs;
local ipairs = ipairs;
local type = type;
local print = print;
local format = string.format;
local m_random = math.random;
local t_insert = table.insert;
local t_remove = table.remove;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local sm_destroy_session = import("core.sessionmanager", "destroy_session");
local default_log = require "util.logger".init("xmlhandlers");
local error = error;
module "xmlhandlers"
local ns_prefixes = {
["http://www.w3.org/XML/1998/namespace"] = "xml";
}
function init_xmlhandlers(session, stream_callbacks)
local ns_stack = { "" };
local curr_ns, name = "";
local curr_tag;
local chardata = {};
local xml_handlers = {};
local log = session.log or default_log;
local cb_streamopened = stream_callbacks.streamopened;
local cb_streamclosed = stream_callbacks.streamclosed;
local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end;
local cb_handlestanza = stream_callbacks.handlestanza;
local stream_tag = stream_callbacks.stream_tag;
local stream_default_ns = stream_callbacks.default_ns;
local stanza
function xml_handlers:StartElement(tagname, attr)
if stanza and #chardata > 0 then
-- We have some character data in the buffer
stanza:text(t_concat(chardata));
chardata = {};
end
local curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
if not name then
curr_ns, name = "", curr_ns;
end
if curr_ns ~= stream_default_ns then
attr.xmlns = curr_ns;
end
-- FIXME !!!!!
for i, k in ipairs(attr) do
if type(k) == "string" then
local ns, nm = k:match("^([^|]+)|?([^|]-)$")
if ns and nm then
ns = ns_prefixes[ns];
if ns then
attr[ns..":"..nm] = attr[k];
attr[i] = ns..":"..nm;
attr[k] = nil;
end
end
end
end
if not stanza then --if we are not currently inside a stanza
if session.notopen then
if tagname == stream_tag then
if cb_streamopened then
cb_streamopened(session, attr);
end
else
-- Garbage before stream?
cb_error(session, "no-stream");
end
return;
end
if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
cb_error(session, "invalid-top-level-element");
end
stanza = st.stanza(name, attr);
curr_tag = stanza;
else -- we are inside a stanza, so add a tag
attr.xmlns = nil;
if curr_ns ~= stream_default_ns then
attr.xmlns = curr_ns;
end
stanza:tag(name, attr);
end
end
function xml_handlers:CharacterData(data)
if stanza then
t_insert(chardata, data);
end
end
function xml_handlers:EndElement(tagname)
curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
if not name then
curr_ns, name = "", curr_ns;
end
if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
if tagname == stream_tag then
if cb_streamclosed then
cb_streamclosed(session);
end
return;
elseif name == "error" then
cb_error(session, "stream-error", stanza);
else
cb_error(session, "parse-error", "unexpected-element-close", name);
end
end
if stanza then
if #chardata > 0 then
-- We have some character data in the buffer
stanza:text(t_concat(chardata));
chardata = {};
end
-- Complete stanza
if #stanza.last_add == 0 then
cb_handlestanza(session, stanza);
stanza = nil;
else
stanza:up();
end
end
end
return xml_handlers;
end
return init_xmlhandlers;
|
xmlhandlers: Fix tag pattern again for the default namespace
|
xmlhandlers: Fix tag pattern again for the default namespace
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
0d097bd44950e3439d7200a1f2c81a8d8c9e9b39
|
src/plugins/lua/trie.lua
|
src/plugins/lua/trie.lua
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]--
-- Trie is rspamd module designed to define and operate with suffix trie
local rspamd_logger = require "rspamd_logger"
local rspamd_trie = require "rspamd_trie"
local _ = require "fun"
local mime_trie
local raw_trie
-- here we store all patterns as text
local mime_patterns = {}
local raw_patterns = {}
-- here we store params for each pattern, so for each i = 1..n patterns[i]
-- should have corresponding params[i]
local mime_params = {}
local raw_params = {}
local function tries_callback(task)
local matched = {}
local function gen_trie_cb(raw)
local patterns = mime_patterns
local params = mime_params
if raw then
patterns = raw_patterns
params = raw_params
end
return function (idx, pos)
local param = params[idx]
local pattern = patterns[idx]
rspamd_logger.debugx("<%1> matched pattern %2 at pos %3",
task:get_message_id(), pattern, pos)
if params['multi'] or not matched[pattern] then
task:insert_result(params['symbol'], 1.0)
if not params['multi'] then
matched[pattern] = true
end
end
end
end
if mime_trie then
mime_trie:search_mime(task, gen_trie_cb(false))
end
if raw_trie then
raw_trie:search_rawmsg(task, gen_trie_cb(true))
end
end
local function process_single_pattern(pat, symbol, cf)
if pat then
if cf['raw'] then
table.insert(raw_patterns, pat)
table.insert(raw_params, {symbol=symbol, multi=multi})
else
table.insert(mime_patterns, pat)
table.insert(mime_params, {symbol=symbol, multi=multi})
end
end
end
local function process_trie_file(symbol, cf)
file = io.open(cf['file'])
if not file then
rspamd_logger.errx('Cannot open trie file %1', cf['file'])
else
if cf['binary'] then
rspamd_logger.errx('binary trie patterns are not implemented yet: %1',
cf['file'])
else
local multi = false
if cf['multi'] then multi = true end
for line in file:lines() do
local pat = string.match(line, '^([^#].*[^%s])%s*$')
process_single_pattern(pat, symbol, cf)
end
end
end
end
local function process_trie_conf(symbol, cf)
local raw = false
if type(cf) ~= 'table' then
rspamd_logger.errx('invalid value for symbol %1: "%2", expected table',
symbol, cf)
return
end
if cf['raw'] then raw = true end
if cf['file'] then
process_trie_file(symbol, cf)
elseif cf['patterns'] then
_.each(function(pat)
process_single_pattern(pat, symbol, cf)
end, cf['patterns'])
end
rspamd_config:register_virtual_symbol(symbol, 1.0)
end
local opts = rspamd_config:get_key("trie")
if opts then
for sym, opt in pairs(opts) do
process_trie_conf(sym, opt)
end
if #raw_patterns > 0 then
raw_trie = rspamd_trie.create(raw_patterns)
rspamd_logger.infox('registered raw search trie from %1 patterns', #raw_patterns)
end
if #mime_patterns > 0 then
mime_trie = rspamd_trie.create(mime_patterns)
rspamd_logger.infox('registered mime search trie from %1 patterns', #mime_patterns)
end
if mime_trie or raw_trie then
rspamd_config:register_callback_symbol('TRIE', 1.0, tries_callback)
else
rspamd_logger.err('no tries defined')
end
end
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]--
-- Trie is rspamd module designed to define and operate with suffix trie
local rspamd_logger = require "rspamd_logger"
local rspamd_trie = require "rspamd_trie"
local _ = require "fun"
local mime_trie
local raw_trie
-- here we store all patterns as text
local mime_patterns = {}
local raw_patterns = {}
-- here we store params for each pattern, so for each i = 1..n patterns[i]
-- should have corresponding params[i]
local mime_params = {}
local raw_params = {}
local function tries_callback(task)
local matched = {}
local function gen_trie_cb(raw)
local patterns = mime_patterns
local params = mime_params
if raw then
patterns = raw_patterns
params = raw_params
end
return function (idx, pos)
local param = params[idx]
local pattern = patterns[idx]
if param['multi'] or not matched[pattern] then
rspamd_logger.debugx("<%1> matched pattern %2 at pos %3",
task:get_message_id(), pattern, pos)
task:insert_result(param['symbol'], 1.0)
if not param['multi'] then
matched[pattern] = true
end
end
end
end
if mime_trie then
mime_trie:search_mime(task, gen_trie_cb(false))
end
if raw_trie then
raw_trie:search_rawmsg(task, gen_trie_cb(true))
end
end
local function process_single_pattern(pat, symbol, cf)
if pat then
local multi = false
if cf['multi'] then multi = true end
if cf['raw'] then
table.insert(raw_patterns, pat)
table.insert(raw_params, {symbol=symbol, multi=multi})
else
table.insert(mime_patterns, pat)
table.insert(mime_params, {symbol=symbol, multi=multi})
end
end
end
local function process_trie_file(symbol, cf)
file = io.open(cf['file'])
if not file then
rspamd_logger.errx('Cannot open trie file %1', cf['file'])
else
if cf['binary'] then
rspamd_logger.errx('binary trie patterns are not implemented yet: %1',
cf['file'])
else
for line in file:lines() do
local pat = string.match(line, '^([^#].*[^%s])%s*$')
process_single_pattern(pat, symbol, cf)
end
end
end
end
local function process_trie_conf(symbol, cf)
local raw = false
if type(cf) ~= 'table' then
rspamd_logger.errx('invalid value for symbol %1: "%2", expected table',
symbol, cf)
return
end
if cf['raw'] then raw = true end
if cf['file'] then
process_trie_file(symbol, cf)
elseif cf['patterns'] then
_.each(function(pat)
process_single_pattern(pat, symbol, cf)
end, cf['patterns'])
end
rspamd_config:register_virtual_symbol(symbol, 1.0)
end
local opts = rspamd_config:get_key("trie")
if opts then
for sym, opt in pairs(opts) do
process_trie_conf(sym, opt)
end
if #raw_patterns > 0 then
raw_trie = rspamd_trie.create(raw_patterns)
rspamd_logger.infox('registered raw search trie from %1 patterns', #raw_patterns)
end
if #mime_patterns > 0 then
mime_trie = rspamd_trie.create(mime_patterns)
rspamd_logger.infox('registered mime search trie from %1 patterns', #mime_patterns)
end
if mime_trie or raw_trie then
rspamd_config:register_callback_symbol('TRIE', 1.0, tries_callback)
else
rspamd_logger.err('no tries defined')
end
end
|
Fix trie plugin.
|
Fix trie plugin.
|
Lua
|
apache-2.0
|
andrejzverev/rspamd,amohanta/rspamd,awhitesong/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,dark-al/rspamd,andrejzverev/rspamd,awhitesong/rspamd,awhitesong/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,dark-al/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,amohanta/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,awhitesong/rspamd,AlexeySa/rspamd,dark-al/rspamd,amohanta/rspamd,dark-al/rspamd,amohanta/rspamd,minaevmike/rspamd,andrejzverev/rspamd
|
141402dd55fe346c6264066fc41716082ab76410
|
btCommandScripts/move.lua
|
btCommandScripts/move.lua
|
VFS.Include(LUAUI_DIRNAME .. "Widgets/BtCreator/debug_utils.lua", nil, VFS.RAW_FIRST)
local cmd = {}
cmd.targets = {}
cmd.n = 0
function cmd.run(unitIds, parameter)
cmd.indexOfComma = string.find(parameter, ",")
dx = parameter:sub(1, cmd.indexOfComma - 1)
dy = parameter:sub(cmd.indexOfComma + 1)
Spring.Echo("Lua MOVE command run, unitIds: " .. dump(unitIds) .. ", parameter: " .. parameter .. ", dx: " .. dx .. ", dy: " .. dy .. ", tick: "..cmd.n)
cmd.n = cmd.n + 1
done = true
x,y,z=0
for i = 1, #unitIds do
x, y, z = Spring.GetUnitPosition(unitIds[i])
tarX = x + dx
tarY = y + dy
Spring.Echo("tar X - " .. tarX .. " tar Y - " .. tarY)
if not cmd.targets[unitIds[i]] then
cmd.targets[unitIds[i]] = {tarX,tarY,z}
Spring.GiveOrderToUnit(unitIds[i], CMD.MOVE, cmd.targets[unitIds[i]], {})
end
Spring.Echo("AtX: " .. x .. ", TargetX: " .. cmd.targets[unitIds[i]][1] .. " AtY: " .. y .. ", TargetY: " .. cmd.targets[unitIds[i]][2])
if math.abs(x - cmd.targets[unitIds[i]][1]) > 10 or math.abs(y - cmd.targets[unitIds[i]][2]) > 10 then
done = false
end
end
if done then
cmd.reset() -- reusing the same object for all move commands, so need to reset on success (TODO - 1 object per command instance)
return "S"
else
return "R"
end
-- TODO implement failure (return "F")
end
function cmd.reset()
Spring.Echo("Lua command reset")
cmd.targets = {}
cmd.n = 0
end
return cmd
|
VFS.Include(LUAUI_DIRNAME .. "Widgets/BtCreator/debug_utils.lua", nil, VFS.RAW_FIRST)
local cmd = {}
cmd.targets = {}
cmd.n = 0
function cmd.run(unitIds, parameter)
cmd.indexOfComma = string.find(parameter, ",")
dx = parameter:sub(1, cmd.indexOfComma - 1)
dz = parameter:sub(cmd.indexOfComma + 1)
Spring.Echo("Lua MOVE command run, unitIds: " .. dump(unitIds) .. ", parameter: " .. parameter .. ", dx: " .. dx .. ", dz: " .. dz .. ", tick: "..cmd.n)
cmd.n = cmd.n + 1
done = true
x,y,z = 0,0,0
for i = 1, #unitIds do
x, y, z = Spring.GetUnitPosition(unitIds[i])
tarX = x + dx
tarZ = z + dz
if not cmd.targets[unitIds[i]] then
cmd.targets[unitIds[i]] = {tarX,y,tarZ}
Spring.GiveOrderToUnit(unitIds[i], CMD.MOVE, cmd.targets[unitIds[i]], {})
end
Spring.Echo("AtX: " .. x .. ", TargetX: " .. cmd.targets[unitIds[i]][1] .. " AtZ: " .. z .. ", TargetZ: " .. cmd.targets[unitIds[i]][2])
if math.abs(x - cmd.targets[unitIds[i]][1]) > 10 or math.abs(z - cmd.targets[unitIds[i]][3]) > 10 then
done = false
end
end
if done then
cmd.reset() -- reusing the same object for all move commands, so need to reset on success (TODO - 1 object per command instance)
return "S"
else
return "R"
end
-- TODO implement failure (return "F")
end
function cmd.reset()
Spring.Echo("Lua command reset")
cmd.targets = {}
cmd.n = 0
end
return cmd
|
Fixed move - replaced y coordinate with the correct z coord.
|
Fixed move - replaced y coordinate with the correct z coord.
|
Lua
|
mit
|
MartinFrancu/BETS
|
ca971227b88f004f6e4ecb0d2b3ac23086a97f5f
|
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 threadman = require("threadman")
local httpd = require("httpd")
local scanner = require("scanner")
local socket = require("socket")
print("[transitd]", "starting up...")
-- configure gateway functionality
if config.gateway.enabled == "yes" then
if config.cjdns.gatewaySupport == "yes" and config.cjdns.tunnelSupport == "yes" then
local network = require("network")
local interface, err = network.getIpv4TransitInterface()
if err then
error("Failed to determine IPv4 transit interface! Cannot start in gateway mode. ("..err..")")
end
if not interface then
error("Failed to determine IPv4 transit interface! Cannot start in gateway mode.")
end
if config.gateway.ipv6support == "yes" then
local interface, err = network.getIpv6TransitInterface()
if err then
error("Failed to determine IPv6 transit interface! Please disable ipv6support in the configuration file. ("..err..")")
end
if not interface then
error("Failed to determine IPv6 transit interface! Please disable ipv6support in the configuration file.")
end
end
local tunnel = require("cjdnstools.tunnel")
local result, err = tunnel.gatewaySetup()
if err then
error("Failed to set up cjdns tunnel gateway: "..err)
end
end
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"})
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
end
end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
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 threadman = require("threadman")
local httpd = require("httpd")
local scanner = require("scanner")
local socket = require("socket")
print("[transitd]", "starting up...")
-- configure gateway functionality
if config.gateway.enabled == "yes" then
if config.cjdns.gatewaySupport == "yes" and config.cjdns.tunnelSupport == "yes" then
local network = require("network")
local interface, err = network.getIpv4TransitInterface()
if err then
error("Failed to determine IPv4 transit interface! Cannot start in gateway mode. ("..err..")")
end
if not interface then
error("Failed to determine IPv4 transit interface! Cannot start in gateway mode.")
end
if config.gateway.ipv6support == "yes" then
local interface, err = network.getIpv6TransitInterface()
if err then
error("Failed to determine IPv6 transit interface! Please disable ipv6support in the configuration file. ("..err..")")
end
if not interface then
error("Failed to determine IPv6 transit interface! Please disable ipv6support in the configuration file.")
end
end
local tunnel = require("cjdnstools.tunnel")
local result, err = tunnel.gatewaySetup()
if err then
error("Failed to set up cjdns tunnel gateway: "..err)
end
end
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"})
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
end
end
if msg ~= nil and msg["type"] == "exit" then break end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
print("[transitd]", "exiting.")
os.exit(retval)
|
Fixed issue with main thread exit
|
Fixed issue with main thread exit
|
Lua
|
mit
|
transitd/transitd,pdxmeshnet/mnigs,transitd/transitd,pdxmeshnet/mnigs,transitd/transitd,intermesh-networks/transitd,intermesh-networks/transitd
|
fd15a24af928838c2d640b8c1162c98933d53cf4
|
core/hyphenator-liang.lua
|
core/hyphenator-liang.lua
|
local function addPattern(h, p)
local t = h.trie;
for char in p:gmatch('%D') do
if not(t[char]) then t[char] = {} end
t = t[char]
end
t["_"] = {};
local lastWasDigit = 0
for char in p:gmatch('.') do
if char:find("%d") then
lastWasDigit = 1
table.insert(t["_"], tonumber(char))
elseif lastWasDigit == 1 then
lastWasDigit = 0
else
table.insert(t["_"], 0)
end
end
end
function loadPatterns(h, language)
SILE.languageSupport.loadLanguage(language)
local languageset = SILE.hyphenator.languages[language];
if not (languageset) then
print("No patterns for language "..language)
return
end
for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end
if not languageset.exceptions then languageset.exceptions = {} end
for _,exc in pairs(languageset.exceptions) do
local k = exc:gsub("-", "")
h.exceptions[k] = { 0 }
for i in exc:gmatch(".") do table.insert(h.exceptions[k], i == "-" and 1 or 0) end
end
end
function _hyphenate(self, w)
if string.len(w) < self.minWord then return {w} end
local points = self.exceptions[w:lower()]
local word = {}
for i in w:gmatch(".") do table.insert(word, i) end
if not points then
points = SU.map(function()return 0 end, word)
local work = SU.map(string.lower, word)
table.insert(work, ".")
table.insert(work, 1, ".")
table.insert(points, 1, 0)
for i = 1, #work do
local t = self.trie
for j = i, #work do
if not t[work[j]] then break end
t = t[work[j]]
local p = t["_"]
if p then
for k = 1, #p do
if points[i+k - 2] and points[i+k -2] < p[k] then
points[i+k -2] = p[k]
end
end
end
end
end
-- Still inside the no-exceptions case
for i = 1,self.leftmin do points[i] = 0 end
for i = #points-self.rightmin,#points do points[i] = 0 end
end
local pieces = {""}
for i = 1,#word do
pieces[#pieces] = pieces[#pieces] .. word[i]
if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end
end
return pieces
end
SILE.hyphenator = {}
SILE.hyphenator.languages = {};
_hyphenators = {};
local hyphenateNode = function(n)
if not n:isNnode() or not n.text then return {n} end
if not _hyphenators[n.language] then
_hyphenators[n.language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[n.language], n.language)
end
local breaks = _hyphenate(_hyphenators[n.language],n.text);
if #breaks > 1 then
local newnodes = {}
for j, b in ipairs(breaks) do
if not(b=="") then
for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do
if nn:isNnode() then
nn.parent = n
table.insert(newnodes, nn)
end
end
if not (j == #breaks) then
d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes("-", n.options) })
d.parent = n
table.insert(newnodes, d)
--table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") }))
end
end
end
n.children = newnodes
n.hyphenated = false
n.done = false
return newnodes
end
return {n}
end
showHyphenationPoints = function (word, language)
language = language or "en"
if not _hyphenators[language] then
_hyphenators[language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[language], language)
end
return SU.concat(_hyphenate(_hyphenators[language], word), "-")
end
SILE.hyphenate = function (nodelist)
local newlist = {}
for i = 1,#nodelist do
local n = nodelist[i]
local newnodes = hyphenateNode(n)
for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end
end
return newlist
end
|
local function addPattern(h, p)
local t = h.trie;
bits = SU.splitUtf8(p)
for i = 1,#bits do char = bits[i]
if not char:find("%d") then
if not(t[char]) then t[char] = {} end
t = t[char]
end
end
t["_"] = {};
local lastWasDigit = 0
for i = 1,#bits do char = bits[i]
if char:find("%d") then
lastWasDigit = 1
table.insert(t["_"], tonumber(char))
elseif lastWasDigit == 1 then
lastWasDigit = 0
else
table.insert(t["_"], 0)
end
end
end
function loadPatterns(h, language)
SILE.languageSupport.loadLanguage(language)
local languageset = SILE.hyphenator.languages[language];
if not (languageset) then
print("No patterns for language "..language)
return
end
for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end
if not languageset.exceptions then languageset.exceptions = {} end
for _,exc in pairs(languageset.exceptions) do
local k = exc:gsub("-", "")
h.exceptions[k] = { 0 }
for i in exc:gmatch(".") do table.insert(h.exceptions[k], i == "-" and 1 or 0) end
end
end
function _hyphenate(self, w)
if string.len(w) < self.minWord then return {w} end
local points = self.exceptions[w:lower()]
local word = SU.splitUtf8(w)
if not points then
points = SU.map(function()return 0 end, word)
local work = SU.map(string.lower, word)
table.insert(work, ".")
table.insert(work, 1, ".")
table.insert(points, 1, 0)
for i = 1, #work do
local t = self.trie
for j = i, #work do
if not t[work[j]] then break end
t = t[work[j]]
local p = t["_"]
if p then
for k = 1, #p do
if points[i+k - 2] and points[i+k -2] < p[k] then
points[i+k -2] = p[k]
end
end
end
end
end
-- Still inside the no-exceptions case
for i = 1,self.leftmin do points[i] = 0 end
for i = #points-self.rightmin,#points do points[i] = 0 end
end
local pieces = {""}
for i = 1,#word do
pieces[#pieces] = pieces[#pieces] .. word[i]
if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end
end
return pieces
end
SILE.hyphenator = {}
SILE.hyphenator.languages = {};
_hyphenators = {};
local hyphenateNode = function(n)
if not n:isNnode() or not n.text then return {n} end
if not _hyphenators[n.language] then
_hyphenators[n.language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[n.language], n.language)
end
local breaks = _hyphenate(_hyphenators[n.language],n.text);
if #breaks > 1 then
local newnodes = {}
for j, b in ipairs(breaks) do
if not(b=="") then
for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do
if nn:isNnode() then
nn.parent = n
table.insert(newnodes, nn)
end
end
if not (j == #breaks) then
d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes("-", n.options) })
d.parent = n
table.insert(newnodes, d)
--table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") }))
end
end
end
n.children = newnodes
n.hyphenated = false
n.done = false
return newnodes
end
return {n}
end
showHyphenationPoints = function (word, language)
language = language or "en"
if not _hyphenators[language] then
_hyphenators[language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[language], language)
end
return SU.concat(_hyphenate(_hyphenators[language], word), "-")
end
SILE.hyphenate = function (nodelist)
local newlist = {}
for i = 1,#nodelist do
local n = nodelist[i]
local newnodes = hyphenateNode(n)
for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end
end
return newlist
end
|
UTF8-ify hyphenation. Fixes #195
|
UTF8-ify hyphenation. Fixes #195
|
Lua
|
mit
|
simoncozens/sile,neofob/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,alerque/sile,simoncozens/sile
|
bfed32e97be2782eb3f26e1e63d823d901f8a7ee
|
SorterMeter.lua
|
SorterMeter.lua
|
local A, L = unpack(select(2, ...))
local M = A.sorter:NewModule("SorterMeter")
A.sorter.meter = M
local tmp1 = {}
local format, ipairs, pairs, select, strsplit, tinsert, wipe = string.format, ipairs, pairs, select, strsplit, table.insert, wipe
M.snapshot = {}
local function loadSkada()
if not Skada.total or not Skada.total.players then
return "Skada", false
end
-- Skada strips the realm name.
-- For simplicity's sake, we do not attempt to handle cases where two
-- players with the same name from different realms are in the same raid.
local playerKeys = wipe(tmp1)
local name
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
name = select(1, strsplit("-", name, 2)) or name
playerKeys[name] = key
end
end
for _, p in pairs(Skada.total.players) do
if playerKeys[p.name] then
M.snapshot[playerKeys[p.name]] = (p.damage or 0) + (p.healing or 0)
end
end
return "Skada", true
end
local function loadRecount()
if not Recount.db2 or not Recount.db2.combatants or not Recount.db2.combatants[GetUnitName("player")] then
return "Recount", false
end
local playerKeys = wipe(tmp1)
local name, c
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
playerKeys[name] = key
c = Recount.db2.combatants[name]
if c and c.Fights and c.Fights.OverallData then
-- Recount stores healings and absorbs separately internally.
M.snapshot[key] = (c.Fights.OverallData.Damage or 0) + (c.Fights.OverallData.Healing or 0) + (c.Fights.OverallData.Absorbs or 0)
else
M.snapshot[key] = 0
end
end
end
-- Merge pet data
for _, c in pairs(Recount.db2.combatants) do
if c.type == "Pet" and c.Fights and c.Fights.OverallData and c.Owner and playerKeys[c.Owner] then
M.snapshot[playerKeys[c.Owner]] = M.snapshot[playerKeys[c.Owner]] + (c.Fights.OverallData.Damage or 0) + (c.Fights.OverallData.Healing or 0) + (c.Fights.OverallData.Absorbs or 0)
end
end
return "Recount", true
end
local function loadDetails()
-- Details has a different concept of what "overall" means. Trash and even
-- boss fights, except previous attempts on the current boss, are excluded by
-- default. So it's entirely possible that there is a current segment but no
-- overall segment. We check for both: some data is better than no data.
local found
local segments = wipe(tmp1)
tinsert(segments, "overall")
tinsert(segments, "current")
for _, segment in ipairs(segments) do
if not found and Details.GetActor and (Details:GetActor(segment, 1) or Details:GetActor(segment, 2)) then
found = true
local name, damage, healing
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
damage = Details:GetActor(segment, 1, name)
healing = Details:GetActor(segment, 2, name)
M.snapshot[key] = (damage and damage.total or 0) + (healing and healing.total or 0)
end
end
end
end
if not found then
return "Details", false
end
return "Details", true
end
local function calculateAverages()
local countDamage, totalDamage = 0, 0
local countHealing, totalHealing = 0, 0
for key, amount in pairs(M.snapshot) do
if keyIsDps(key) then
countDamage = countDamage + 1
totalDamage = totalDamage + amount
elseif keyIsHealer(key) then
countHealing = countHealing + 1
totalHealing = totalHealing + amount
end
end
M.snapshot["_averageDamage"] = (countDamage > 0) and (totalDamage / countDamage) or 0
M.snapshot["_averageHealing"] = (countHealing > 0) and (totalHealing / countHealing) or 0
end
function M:BuildSnapshot()
wipe(M.snapshot)
local addon, success
if Skada then
addon, success = loadSkada()
elseif Recount then
addon, success = loadRecount()
elseif Details then
addon, success = loadDetails()
else
A.console:Print(L["No supported damage/healing meter addon found."])
return
end
if success then
A.console:Print(format(L["Using damage/healing data from %s."], A.util:GetAddonNameAndVersion(addon)))
else
A.console:Print(format(L["There is currently no data available from %s."], A.util:GetAddonNameAndVersion(addon)))
end
calculateAverages()
end
|
local A, L = unpack(select(2, ...))
local M = A.sorter:NewModule("SorterMeter")
A.sorter.meter = M
local tmp1 = {}
local format, ipairs, pairs, select, strsplit, tinsert, wipe = string.format, ipairs, pairs, select, strsplit, table.insert, wipe
M.snapshot = {}
local function loadSkada()
if not Skada.total or not Skada.total.players then
return "Skada", false
end
-- Skada strips the realm name.
-- For simplicity's sake, we do not attempt to handle cases where two
-- players with the same name from different realms are in the same raid.
local playerKeys = wipe(tmp1)
local name
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
name = select(1, strsplit("-", name, 2)) or name
playerKeys[name] = key
end
end
for _, p in pairs(Skada.total.players) do
if playerKeys[p.name] then
M.snapshot[playerKeys[p.name]] = (p.damage or 0) + (p.healing or 0)
end
end
return "Skada", true
end
local function loadRecount()
if not Recount.db2 or not Recount.db2.combatants or not Recount.db2.combatants[GetUnitName("player")] then
return "Recount", false
end
local playerKeys = wipe(tmp1)
local name, c
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
playerKeys[name] = key
c = Recount.db2.combatants[name]
if c and c.Fights and c.Fights.OverallData then
-- Recount stores healings and absorbs separately internally.
M.snapshot[key] = (c.Fights.OverallData.Damage or 0) + (c.Fights.OverallData.Healing or 0) + (c.Fights.OverallData.Absorbs or 0)
else
M.snapshot[key] = 0
end
end
end
-- Merge pet data
for _, c in pairs(Recount.db2.combatants) do
if c.type == "Pet" and c.Fights and c.Fights.OverallData and c.Owner and playerKeys[c.Owner] then
M.snapshot[playerKeys[c.Owner]] = M.snapshot[playerKeys[c.Owner]] + (c.Fights.OverallData.Damage or 0) + (c.Fights.OverallData.Healing or 0) + (c.Fights.OverallData.Absorbs or 0)
end
end
return "Recount", true
end
local function loadDetails()
-- Details has a different concept of what "overall" means. Trash and even
-- boss fights, except previous attempts on the current boss, are excluded by
-- default. So it's entirely possible that there is a current segment but no
-- overall segment. We check for both: some data is better than no data.
local found
local segments = wipe(tmp1)
tinsert(segments, "overall")
tinsert(segments, "current")
for _, segment in ipairs(segments) do
if not found and Details.GetActor and (Details:GetActor(segment, 1) or Details:GetActor(segment, 2)) then
found = true
local name, damage, healing
for g = 1, 8 do
for key, _ in pairs(A.sorter.core.groups[g]) do
name = A.sorter.core:KeyGetName(key)
damage = Details:GetActor(segment, 1, name)
healing = Details:GetActor(segment, 2, name)
M.snapshot[key] = (damage and damage.total or 0) + (healing and healing.total or 0)
end
end
end
end
if not found then
return "Details", false
end
return "Details", true
end
local function calculateAverages()
local countDamage, totalDamage = 0, 0
local countHealing, totalHealing = 0, 0
for key, amount in pairs(M.snapshot) do
-- Ignore tanks.
if A.sorter.core:KeyIsDps(key) then
countDamage = countDamage + 1
totalDamage = totalDamage + amount
elseif A.sorter.core:KeyIsHealer(key) then
countHealing = countHealing + 1
totalHealing = totalHealing + amount
end
end
M.snapshot["_averageDamage"] = (countDamage > 0) and (totalDamage / countDamage) or 0
M.snapshot["_averageHealing"] = (countHealing > 0) and (totalHealing / countHealing) or 0
end
function M:BuildSnapshot()
wipe(M.snapshot)
local addon, success
if Skada then
addon, success = loadSkada()
elseif Recount then
addon, success = loadRecount()
elseif Details then
addon, success = loadDetails()
else
A.console:Print(L["No supported damage/healing meter addon found."])
return
end
if success then
A.console:Print(format(L["Using damage/healing data from %s."], A.util:GetAddonNameAndVersion(addon)))
else
A.console:Print(format(L["There is currently no data available from %s."], A.util:GetAddonNameAndVersion(addon)))
end
calculateAverages()
end
|
fix ref missed in refactoring
|
fix ref missed in refactoring
|
Lua
|
mit
|
bencvt/FixGroups
|
48ea4aab5cb6b9bb855a2cf91e4cb0c80fdbfeb3
|
emacs.lua
|
emacs.lua
|
local emacs = {}
local capture = function(isNote)
local key = ""
if isNote then
key = "\"z\"" -- key is a string associated with org-capture template
end
local currentApp = hs.window.focusedWindow();
local pid = "\"" .. currentApp:pid() .. "\" "
local title = "\"" .. currentApp:title() .. "\" "
local runStr = "/usr/local/bin/emacsclient" .. " -c -F '(quote (name . \"capture\"))'" .. " -e '(activate-capture-frame " .. pid .. title .. key .. " )'"
hs.timer.delayed.new(0.1, function() io.popen(runStr) end):start()
end
local bind = function(hotkeyModal, fsm)
hotkeyModal:bind ("", "c", function()
fsm:toIdle()
capture() end)
hotkeyModal:bind("", "z", function()
fsm:toIdle()
capture(true) -- note on currently clocked in
end)
end
-- don't remove - this is callable from Emacs
emacs.switchToApp = function(pid)
local app = hs.application.applicationForPID(pid)
if app then
app:activate()
end
end
-- don't remove - this is callable from Emacs
emacs.switchToAppAndPasteFromClipboard = function(pid)
local app = hs.application.applicationForPID(pid)
if app then
app:activate()
app:selectMenuItem({"Edit", "Paste"})
end
end
emacs.addState = function(modal)
modal.addState("emacs", {
init = function(self, fsm)
self.hotkeyModal = hs.hotkey.modal.new()
modal.displayModalText "c \tcapture\nz\tnote"
self.hotkeyModal:bind("","escape", function() fsm:toIdle() end)
self.hotkeyModal:bind({"cmd"}, "space", nil, function() fsm:toMain() end)
bind(self.hotkeyModal, fsm)
self.hotkeyModal:enter()
end})
end
emacs.editWithEmacs = function()
local currentApp = hs.window.focusedWindow():application()
hs.eventtap.keyStroke({"cmd"}, "a")
hs.eventtap.keyStroke({"cmd"}, "c")
local pid = "\"" .. currentApp:pid() .. "\" "
local title = "\"" .. currentApp:title() .. "\" "
local runStr = "/usr/local/bin/emacsclient" .. " -c -F '(quote (name . \"edit\"))'" .. " -e '(ag/edit-with-emacs" .. pid .. title .. " )'";
io.popen(runStr)
end
emacs.enableEditWithEmacs = function()
emacs.editWithEmacsKey =
emacs.editWithEmacsKey or hs.hotkey.new({"cmd", "ctrl"}, "o", nil, emacs.editWithEmacs)
emacs.editWithEmacsKey:enable()
end
emacs.disableEditWithEmacs = function()
emacs.editWithEmacsKey:disable()
end
-- whenever I connect to a different display my Emacs frame gets screwed. This is a temporary fix (until) I figure out Display Profiles feature
-- the relevant elisp function couldn be found here: https://github.com/agzam/dot-spacemacs/blob/master/layers/ag-general/funcs.el#L36
local function fixEmacsFrame()
io.popen("/usr/local/bin/emacsclient" .. " -e '(ag/fix-frame)'")
end
hs.screen.watcher.new(function()
hs.alert("Screen watcher")
fixEmacsFrame()
end):start()
hs.caffeinate.watcher.new(function(ev)
local mds = { hs.caffeinate.watcher.systemDidWake,
hs.caffeinate.watcher.screensDidUnlock,
hs.caffeinate.watcher.sessionDidBecomeActive }
hs.alert("caffeinate event " .. ev)
if hs.fnutils.contains(mds, ev) then
hs.timer.doAfter(0.1, fixEmacsFrame)
end
end):start()
return emacs
|
local emacs = {}
local capture = function(isNote)
local key = ""
if isNote then
key = "\"z\"" -- key is a string associated with org-capture template
end
local currentApp = hs.window.focusedWindow();
local pid = "\"" .. currentApp:pid() .. "\" "
local title = "\"" .. currentApp:title() .. "\" "
local runStr = "/usr/local/bin/emacsclient" .. " -c -F '(quote (name . \"capture\"))'" .. " -e '(activate-capture-frame " .. pid .. title .. key .. " )'"
hs.timer.delayed.new(0.1, function() io.popen(runStr) end):start()
end
local bind = function(hotkeyModal, fsm)
hotkeyModal:bind ("", "c", function()
fsm:toIdle()
capture() end)
hotkeyModal:bind("", "z", function()
fsm:toIdle()
capture(true) -- note on currently clocked in
end)
end
-- don't remove - this is callable from Emacs
emacs.switchToApp = function(pid)
local app = hs.application.applicationForPID(pid)
if app then
app:activate()
end
end
-- don't remove - this is callable from Emacs
emacs.switchToAppAndPasteFromClipboard = function(pid)
local app = hs.application.applicationForPID(pid)
if app then
app:activate()
app:selectMenuItem({"Edit", "Paste"})
end
end
emacs.addState = function(modal)
modal.addState("emacs", {
init = function(self, fsm)
self.hotkeyModal = hs.hotkey.modal.new()
modal.displayModalText "c \tcapture\nz\tnote"
self.hotkeyModal:bind("","escape", function() fsm:toIdle() end)
self.hotkeyModal:bind({"cmd"}, "space", nil, function() fsm:toMain() end)
bind(self.hotkeyModal, fsm)
self.hotkeyModal:enter()
end})
end
emacs.editWithEmacs = function()
local currentApp = hs.window.focusedWindow():application()
hs.eventtap.keyStroke({"cmd"}, "a")
hs.eventtap.keyStroke({"cmd"}, "c")
local pid = "\"" .. currentApp:pid() .. "\" "
local title = "\"" .. currentApp:title() .. "\" "
local runStr = "/usr/local/bin/emacsclient" .. " -c -F '(quote (name . \"edit\"))'" .. " -e '(ag/edit-with-emacs" .. pid .. title .. " )'";
io.popen(runStr)
end
emacs.enableEditWithEmacs = function()
emacs.editWithEmacsKey =
emacs.editWithEmacsKey or hs.hotkey.new({"cmd", "ctrl"}, "o", nil, emacs.editWithEmacs)
emacs.editWithEmacsKey:enable()
end
emacs.disableEditWithEmacs = function()
emacs.editWithEmacsKey:disable()
end
-- whenever I connect to a different display my Emacs frame gets screwed. This is a temporary fix (until) I figure out Display Profiles feature
-- you can find the relevant elisp function here: https://github.com/agzam/dot-spacemacs/blob/master/layers/ag-general/funcs.el#L36
local function fixEmacsFrame()
io.popen("/usr/local/bin/emacsclient" .. " -e '(ag/fix-frame)'")
end
hs.screen.watcher.newWithActiveScreen(function(isActiveScreenChanged)
if isActiveScreenChanged == nil then
hs.alert("Screen watcher")
fixEmacsFrame()
end
end):start()
return emacs
|
Fixes fixEmacsFrame
|
Fixes fixEmacsFrame
previously it wasn't working properly, with the latest Hammerspoon now it does
|
Lua
|
mit
|
agzam/spacehammer
|
21dbc41dc38f5e57f1d43be9320b3175d7b19c98
|
MMOCoreORB/bin/scripts/managers/jedi/village/phase1/fs_patrol.lua
|
MMOCoreORB/bin/scripts/managers/jedi/village/phase1/fs_patrol.lua
|
local Patrol = require("quest.tasks.patrol")
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
local VillageJediManagerCommon = require("managers.jedi.village.village_jedi_manager_common")
require("utils.helpers")
FsPatrol = Patrol:new {
-- Task properties
taskName = "FsPatrol",
-- Patrol properties
waypointName = "@quest/force_sensitive/fs_patrol:patrol_point",
numPoints = 8,
areaSize = 48,
originX = 5313,
originY = -4161,
forceSpawn = true,
enemyList = { "sith_shadow_mercenary", "sith_shadow_thug", "sith_shadow_pirate", "sith_shadow_outlaw" }
}
function FsPatrol:spawnEnemies(pPlayer, numEnemies, x, y)
writeData(SceneObject(pPlayer):getObjectID() .. self.taskName .. "numEnemies", numEnemies)
local playerID = SceneObject(pPlayer):getObjectID()
for i = 1, numEnemies, 1 do
local npcType
if (numEnemies < 3) then
npcType = getRandomNumber(1,2)
else
npcType = getRandomNumber(3,4)
end
local offsetX = getRandomNumber(-5, 5)
local offsetY = getRandomNumber(-5, 5)
local spawnX = x + offsetX
local spawnY = y + offsetY
local spawnZ = getTerrainHeight(pPlayer, spawnX, spawnY)
local pMobile = spawnMobile(SceneObject(pPlayer):getZoneName(), self.enemyList[npcType], 0, spawnX, spawnZ, spawnY, 0, 0)
if (pMobile ~= nil) then
createEvent(600 * 1000, self.taskName, "destroyMobile", pMobile)
writeData(SceneObject(pMobile):getObjectID() .. self.taskName .. "ownerID", playerID)
if (numEnemies <= 3) then
createObserver(OBJECTDESTRUCTION, self.taskName, "notifyKilledGoodTarget", pMobile)
else
createObserver(OBJECTDESTRUCTION, self.taskName, "notifyKilledBadTarget", pMobile)
end
end
end
end
function FsPatrol:destroyMobile(pMobile)
if (pMobile == nil) then
return
end
if (CreatureObject(pMobile):isInCombat()) then
createEvent(60 * 1000, self.taskName, "destroyMobile", pMobile)
return
end
deleteData(SceneObject(pMobile):getObjectID() .. self.taskName .. "ownerID")
SceneObject(pMobile):destroyObjectFromWorld()
end
function FsPatrol:notifyKilledGoodTarget(pVictim, pAttacker)
local ownerID = readData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
local numEnemies = readData(ownerID .. self.taskName .. "numEnemies")
numEnemies = numEnemies - 1
if (numEnemies <= 0) then
writeData(ownerID .. ":completedCurrentPoint", 1)
end
deleteData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
writeData(ownerID .. self.taskName .. "numEnemies", numEnemies)
return 1
end
function FsPatrol:notifyKilledBadTarget(pVictim, pAttacker)
local ownerID = readData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
if (SceneObject(pAttacker):getObjectID() == ownerID) then
CreatureObject(pAttacker):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_killed_dont_kill_npc")
self:failPatrol(pAttacker)
end
deleteData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
return 1
end
function FsPatrol:onPlayerKilled(pPlayer)
local completedCount = tonumber(QuestManager.getStoredVillageValue(pPlayer, "FsPatrolCompletedCount"))
local playerID = SceneObject(pPlayer):getObjectID()
if (completedCount >= 0 and completedCount < 20 and readData(playerID .. ":failedPatrol") ~= 1) then
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_death")
self:failPatrol(pPlayer)
end
end
function FsPatrol:onEnteredActiveArea(pPlayer, pActiveArea)
if (pPlayer == nil) then
return 0
end
local playerID = SceneObject(pPlayer):getObjectID()
if (readData(playerID .. ":completedCurrentPoint") == -1) then
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_previous_point")
self:failPatrol(pPlayer)
deleteData(playerID .. ":completedCurrentPoint")
return 1
end
local spawnChance = getRandomNumber(1,100)
if (spawnChance >= 70) then
writeData(playerID .. ":completedCurrentPoint", -1)
local numEnemies = getRandomNumber(1,3)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:small_group" .. numEnemies)
self:spawnEnemies(pPlayer, numEnemies, SceneObject(pActiveArea):getWorldPositionX(), SceneObject(pActiveArea):getWorldPositionY())
elseif (spawnChance >= 60 and spawnChance < 70) then
writeData(playerID .. ":completedCurrentPoint", 1)
local numEnemies = getRandomNumber(5,8)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:large_group" .. numEnemies)
self:spawnEnemies(pPlayer, numEnemies, SceneObject(pActiveArea):getWorldPositionX(), SceneObject(pActiveArea):getWorldPositionY())
else
writeData(playerID .. ":completedCurrentPoint", 1)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:no_objective")
end
return 1
end
function FsPatrol:resetFsPatrol(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
deleteData(playerID .. ":failedPatrol")
deleteData(playerID .. "completedCurrentPoint")
self:waypointCleanup(pCreature)
self:setupPatrolPoints(pCreature)
end
function FsPatrol:completeFsPatrol(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. "completedCurrentPoint")
self:finish(pCreature)
end
return FsPatrol
|
local Patrol = require("quest.tasks.patrol")
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
local VillageJediManagerCommon = require("managers.jedi.village.village_jedi_manager_common")
require("utils.helpers")
FsPatrol = Patrol:new {
-- Task properties
taskName = "FsPatrol",
-- Patrol properties
waypointName = "@quest/force_sensitive/fs_patrol:patrol_point",
numPoints = 8,
areaSize = 48,
originX = 5313,
originY = -4161,
forceSpawn = true,
enemyList = { "sith_shadow_mercenary", "sith_shadow_thug", "sith_shadow_pirate", "sith_shadow_outlaw" }
}
function FsPatrol:spawnEnemies(pPlayer, numEnemies, x, y)
writeData(SceneObject(pPlayer):getObjectID() .. self.taskName .. "numEnemies", numEnemies)
local playerID = SceneObject(pPlayer):getObjectID()
for i = 1, numEnemies, 1 do
local npcType
if (numEnemies < 3) then
npcType = getRandomNumber(1,2)
else
npcType = getRandomNumber(3,4)
end
local offsetX = getRandomNumber(-5, 5)
local offsetY = getRandomNumber(-5, 5)
local spawnX = x + offsetX
local spawnY = y + offsetY
local spawnZ = getTerrainHeight(pPlayer, spawnX, spawnY)
local pMobile = spawnMobile(SceneObject(pPlayer):getZoneName(), self.enemyList[npcType], 0, spawnX, spawnZ, spawnY, 0, 0)
if (pMobile ~= nil) then
createEvent(600 * 1000, self.taskName, "destroyMobile", pMobile)
writeData(SceneObject(pMobile):getObjectID() .. self.taskName .. "ownerID", playerID)
if (numEnemies <= 3) then
createObserver(OBJECTDESTRUCTION, self.taskName, "notifyKilledGoodTarget", pMobile)
else
createObserver(OBJECTDESTRUCTION, self.taskName, "notifyKilledBadTarget", pMobile)
end
end
end
end
function FsPatrol:destroyMobile(pMobile)
if (pMobile == nil) then
return
end
if (CreatureObject(pMobile):isInCombat()) then
createEvent(60 * 1000, self.taskName, "destroyMobile", pMobile)
return
end
deleteData(SceneObject(pMobile):getObjectID() .. self.taskName .. "ownerID")
SceneObject(pMobile):destroyObjectFromWorld()
end
function FsPatrol:notifyKilledGoodTarget(pVictim, pAttacker)
local ownerID = readData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
local numEnemies = readData(ownerID .. self.taskName .. "numEnemies")
numEnemies = numEnemies - 1
if (numEnemies <= 0) then
writeData(ownerID .. ":completedCurrentPoint", 1)
end
deleteData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
writeData(ownerID .. self.taskName .. "numEnemies", numEnemies)
return 1
end
function FsPatrol:notifyKilledBadTarget(pVictim, pAttacker)
local ownerID = readData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
if (SceneObject(pAttacker):getObjectID() == ownerID) then
CreatureObject(pAttacker):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_killed_dont_kill_npc")
self:failPatrol(pAttacker)
end
deleteData(SceneObject(pVictim):getObjectID() .. self.taskName .. "ownerID")
return 1
end
function FsPatrol:onPlayerKilled(pPlayer)
local completedCount = tonumber(QuestManager.getStoredVillageValue(pPlayer, "FsPatrolCompletedCount"))
local playerID = SceneObject(pPlayer):getObjectID()
if (completedCount >= 0 and completedCount < 20 and readData(playerID .. ":failedPatrol") ~= 1) then
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_death")
self:failPatrol(pPlayer)
end
end
function FsPatrol:onEnteredActiveArea(pPlayer, pActiveArea)
if (pPlayer == nil) then
return 0
end
local playerID = SceneObject(pPlayer):getObjectID()
if (readData(playerID .. ":completedCurrentPoint") == -1) then
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:failed_previous_point")
self:failPatrol(pPlayer)
deleteData(playerID .. ":completedCurrentPoint")
return 1
end
local spawnChance = getRandomNumber(1,100)
if (spawnChance >= 70) then
writeData(playerID .. ":completedCurrentPoint", -1)
local numEnemies = getRandomNumber(1,3)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:small_group" .. numEnemies)
self:spawnEnemies(pPlayer, numEnemies, SceneObject(pActiveArea):getWorldPositionX(), SceneObject(pActiveArea):getWorldPositionY())
elseif (spawnChance >= 60 and spawnChance < 70) then
writeData(playerID .. ":completedCurrentPoint", 1)
local numEnemies = getRandomNumber(5,8)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:large_group" .. numEnemies)
self:spawnEnemies(pPlayer, numEnemies, SceneObject(pActiveArea):getWorldPositionX(), SceneObject(pActiveArea):getWorldPositionY())
else
writeData(playerID .. ":completedCurrentPoint", 1)
CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_patrol:no_objective")
end
return 1
end
function FsPatrol:resetFsPatrol(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
deleteData(playerID .. ":failedPatrol")
deleteData(playerID .. "completedCurrentPoint")
self:waypointCleanup(pCreature)
self:setupPatrolPoints(pCreature)
end
function FsPatrol:completeFsPatrol(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. "completedCurrentPoint")
deleteData(playerID .. ":patrolWaypointsReached")
self:finish(pCreature)
end
return FsPatrol
|
[fixed] Sarguillo patrols failing after completing a previous patrol
|
[fixed] Sarguillo patrols failing after completing a previous patrol
Change-Id: I3d2389b6ae20aa57029e402cb27f4b7f03504d4a
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
eccc343b24c7f976a12229821b654261698dcfa2
|
extensions/urlevent/urlevent.lua
|
extensions/urlevent/urlevent.lua
|
--- === hs.urlevent ===
---
--- Allows Hammerspoon to respond to URLs
--- Hammerspoon is configured to react to URLs that start with `hammerspoon://` when they are opened by OS X.
--- This extension allows you to register callbacks for these URL events and their parameters, offering a flexible way to receive events from other applications.
---
--- You can also choose to make Hammerspoon the default for `http://` and `https://` URLs, which lets you route the URLs in your Lua code
---
--- Given a URL such as `hammerspoon://someEventToHandle?someParam=things&otherParam=stuff`, in the literal, RFC1808 sense of the URL, `someEventToHandle` is the hostname (or net_loc) of the URL, but given that these are not network resources, we consider `someEventToHandle` to be the name of the event. No path should be specified in the URL - it should consist purely of a hostname and, optionally, query parameters.
---
--- See also `hs.ipc` for a command line IPC mechanism that is likely more appropriate for shell scripts or command line use. Unlike `hs.ipc`, `hs.urlevent` is not able to return any data to its caller.
---
--- NOTE: If Hammerspoon is not running when a `hammerspoon://` URL is opened, Hammerspoon will be launched, but it will not react to the URL event. Nor will it react to any events until this extension is loaded and event callbacks have been bound.
--- NOTE: Any event which is received, for which no callback has been bound, will be logged to the Hammerspoon Console
--- NOTE: When you trigger a URL from another application, it is usually best to have the URL open in the background, if that option is available. Otherwise, OS X will activate Hammerspoon (i.e. give it focus), which makes URL events difficult to use for things like window management.
local log = require'hs.logger'.new('urlevent')
local urlevent = require "hs.liburlevent"
local callbacks = {}
--- hs.urlevent.httpCallback
--- Variable
--- A function that should handle http:// and https:// URL events
---
--- Notes:
--- * The function should handle four arguments:
--- * scheme - A string containing the URL scheme (i.e. "http")
--- * host - A string containing the host requested (e.g. "www.hammerspoon.org")
--- * params - A table containing the key/value pairs of all the URL parameters
--- * fullURL - A string containing the full, original URL
--- * senderPID - An integer containing the PID of the application that opened the URL, if available (otherwise -1)
urlevent.httpCallback = nil
--- hs.urlevent.mailtoCallback
--- Variable
--- A function that should handle mailto: URL events
---
--- Notes:
--- * The function should handle four arguments:
--- * scheme - A string containing the URL scheme (i.e. "http")
--- * host - A string containing the host requested (e.g. "www.hammerspoon.org")
--- * params - A table containing the key/value pairs of all the URL parameters
--- * fullURL - A string containing the full, original URL -- will be bla
--- * senderPID - An integer containing the PID of the application that opened the URL, if available (otherwise -1)
urlevent.mailtoCallback = nil
-- Set up our top-level callback and register it with the Objective C part of the extension
local function urlEventCallback(scheme, event, params, fullURL, senderPID)
local bundleID = hs.processInfo["bundleID"]
local hsScheme = string.lower(string.sub(bundleID, (string.find(bundleID, "%.[^%.]*$")) + 1))
if (scheme == "http" or scheme == "https" or scheme == "file") then
if not urlevent.httpCallback then
log.ef("Hammerspoon is configured for http(s):// URLs, but no http callback has been set")
else
local ok, err = xpcall(function() return urlevent.httpCallback(scheme, event, params, fullURL, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
elseif (scheme == "mailto") then
if not urlevent.mailtoCallback then
log.ef("Hammerspoon is configured for mailto URLs, but no mailtoCallback has been set")
else
local ok, err = xpcall(function() return urlevent.mailtoCallback(scheme, event, params, fullURL, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
elseif (scheme == hsScheme) then
if not event then
log.wf("Something called a " .. hsScheme .. ":// URL without an action")
return
end
if not callbacks[event] then
log.wf("Received hs.urlevent event with no registered callback:"..event)
else
local ok, err = xpcall(function() return callbacks[event](event, params, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
else
log.ef("Hammerspoon has been passed a %s URL, but does not know how to handle it", scheme)
end
end
urlevent.setCallback(urlEventCallback)
--- hs.urlevent.bind(eventName, callback)
--- Function
--- Registers a callback for a hammerspoon:// URL event
---
--- Parameters:
--- * eventName - A string containing the name of an event
--- * callback - A function that will be called when the specified event is received, or nil to remove an existing callback
---
--- Returns:
--- * None
---
--- Notes:
--- * The callback function should accept two parameters:
--- * eventName - A string containing the name of the event
--- * params - A table containing key/value string pairs containing any URL parameters that were specified in the URL
--- * senderPID - An integer containing the PID of the sending application, if available (otherwise -1)
--- * Given the URL `hammerspoon://doThingA?value=1` The event name is `doThingA` and the callback's `params` argument will be a table containing `{["value"] = "1"}`
function urlevent.bind(eventName, callback)
callbacks[eventName] = callback
end
--- hs.urlevent.openURL(url)
--- Function
--- Opens a URL with the default application
---
--- Parameters:
--- * url - A string containing a URL, which must contain a scheme and '://'
---
--- Returns:
--- * A boolean, true if the URL was opened successfully, otherwise false
function urlevent.openURL(url)
local c = string.find(url, "://")
if not c then
log.ef("hs.urlevent.openURL() called for a URL that lacks '://'")
return false
end
local scheme = string.sub(url, 0, c - 1)
local handler = urlevent.getDefaultHandler(scheme)
return urlevent.openURLWithBundle(url, handler)
end
return urlevent
|
--- === hs.urlevent ===
---
--- Allows Hammerspoon to respond to URLs
--- Hammerspoon is configured to react to URLs that start with `hammerspoon://` when they are opened by OS X.
--- This extension allows you to register callbacks for these URL events and their parameters, offering a flexible way to receive events from other applications.
---
--- You can also choose to make Hammerspoon the default for `http://` and `https://` URLs, which lets you route the URLs in your Lua code
---
--- Given a URL such as `hammerspoon://someEventToHandle?someParam=things&otherParam=stuff`, in the literal, RFC1808 sense of the URL, `someEventToHandle` is the hostname (or net_loc) of the URL, but given that these are not network resources, we consider `someEventToHandle` to be the name of the event. No path should be specified in the URL - it should consist purely of a hostname and, optionally, query parameters.
---
--- See also `hs.ipc` for a command line IPC mechanism that is likely more appropriate for shell scripts or command line use. Unlike `hs.ipc`, `hs.urlevent` is not able to return any data to its caller.
---
--- NOTE: If Hammerspoon is not running when a `hammerspoon://` URL is opened, Hammerspoon will be launched, but it will not react to the URL event. Nor will it react to any events until this extension is loaded and event callbacks have been bound.
--- NOTE: Any event which is received, for which no callback has been bound, will be logged to the Hammerspoon Console
--- NOTE: When you trigger a URL from another application, it is usually best to have the URL open in the background, if that option is available. Otherwise, OS X will activate Hammerspoon (i.e. give it focus), which makes URL events difficult to use for things like window management.
local log = require'hs.logger'.new('urlevent')
local urlevent = require "hs.liburlevent"
local callbacks = {}
--- hs.urlevent.httpCallback
--- Variable
--- A function that should handle http:// and https:// URL events
---
--- Notes:
--- * The function should handle four arguments:
--- * scheme - A string containing the URL scheme (i.e. "http")
--- * host - A string containing the host requested (e.g. "www.hammerspoon.org")
--- * params - A table containing the key/value pairs of all the URL parameters
--- * fullURL - A string containing the full, original URL
--- * senderPID - An integer containing the PID of the application that opened the URL, if available (otherwise -1)
urlevent.httpCallback = nil
--- hs.urlevent.mailtoCallback
--- Variable
--- A function that should handle mailto: URL events
---
--- Notes:
--- * The function should handle four arguments:
--- * scheme - A string containing the URI scheme (i.e. "mailto")
--- * host - A string containing the host requested (typically nil)
--- * params - A table containing the key/value pairs of all the URL parameters, typically empty
--- * fullURL - A string containing the full, original URI
--- * senderPID - An integer containing the PID of the application that opened the URI, if available (otherwise -1)
urlevent.mailtoCallback = nil
-- Set up our top-level callback and register it with the Objective C part of the extension
local function urlEventCallback(scheme, event, params, fullURL, senderPID)
local bundleID = hs.processInfo["bundleID"]
local hsScheme = string.lower(string.sub(bundleID, (string.find(bundleID, "%.[^%.]*$")) + 1))
if (scheme == "http" or scheme == "https" or scheme == "file") then
if not urlevent.httpCallback then
log.ef("Hammerspoon is configured for http(s):// URLs, but no http callback has been set")
else
local ok, err = xpcall(function() return urlevent.httpCallback(scheme, event, params, fullURL, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
elseif (scheme == "mailto") then
if not urlevent.mailtoCallback then
log.ef("Hammerspoon is configured for mailto URLs, but no mailtoCallback has been set")
else
local ok, err = xpcall(function() return urlevent.mailtoCallback(scheme, event, params, fullURL, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
elseif (scheme == hsScheme) then
if not event then
log.wf("Something called a " .. hsScheme .. ":// URL without an action")
return
end
if not callbacks[event] then
log.wf("Received hs.urlevent event with no registered callback:"..event)
else
local ok, err = xpcall(function() return callbacks[event](event, params, senderPID) end, debug.traceback)
if not ok then
hs.showError(err)
end
end
else
log.ef("Hammerspoon has been passed a %s URL, but does not know how to handle it", scheme)
end
end
urlevent.setCallback(urlEventCallback)
--- hs.urlevent.bind(eventName, callback)
--- Function
--- Registers a callback for a hammerspoon:// URL event
---
--- Parameters:
--- * eventName - A string containing the name of an event
--- * callback - A function that will be called when the specified event is received, or nil to remove an existing callback
---
--- Returns:
--- * None
---
--- Notes:
--- * The callback function should accept two parameters:
--- * eventName - A string containing the name of the event
--- * params - A table containing key/value string pairs containing any URL parameters that were specified in the URL
--- * senderPID - An integer containing the PID of the sending application, if available (otherwise -1)
--- * Given the URL `hammerspoon://doThingA?value=1` The event name is `doThingA` and the callback's `params` argument will be a table containing `{["value"] = "1"}`
function urlevent.bind(eventName, callback)
callbacks[eventName] = callback
end
--- hs.urlevent.openURL(url)
--- Function
--- Opens a URL with the default application
---
--- Parameters:
--- * url - A string containing a URL, which must contain a scheme and '://'
---
--- Returns:
--- * A boolean, true if the URL was opened successfully, otherwise false
function urlevent.openURL(url)
local c = string.find(url, "://")
if not c then
log.ef("hs.urlevent.openURL() called for a URL that lacks '://'")
return false
end
local scheme = string.sub(url, 0, c - 1)
local handler = urlevent.getDefaultHandler(scheme)
return urlevent.openURLWithBundle(url, handler)
end
return urlevent
|
Fix up the docstrings for hs.urlevent.mailtoCallback
|
Fix up the docstrings for hs.urlevent.mailtoCallback
|
Lua
|
mit
|
asmagill/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,asmagill/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon
|
c59e925d8e2919819b8dfe8e4969fac911b9be4a
|
mods/BeardLib-Editor/Classes/Map/Elements/navobstacleelement.lua
|
mods/BeardLib-Editor/Classes/Map/Elements/navobstacleelement.lua
|
EditorNavObstacle = EditorNavObstacle or class(MissionScriptEditor) --Currently broken
function EditorNavObstacle:create_element()
EditorNavObstacle.super.create_element(self)
self._element.class = "ElementNavObstacle"
self._element.values.obstacle_list = {}
self._element.values.operation = "add"
self._guis = {}
self._obstacle_units = {}
self._all_object_names = {}
end
function EditorNavObstacle:_build_panel()
self:_create_panel()
self:ComboCtrl("operation", {"add", "remove"}, {help = "Choose if you want to add or remove an obstacle"})
self:BuildUnitsManage("obstacle_list", {values_name = "Object", value_key = "object", key = "unit_id", orig = {unit_id = 0, object = ""}, combo_items_func = function(name, value)
--local objects = self:_get_objects_by_unit(value.unit)
--table.insert(objects, "")
return {} -- objects
end})
end
function EditorNavObstacle:_get_objects_by_unit(unit)
local all_object_names = {}
if unit then
local root_obj = unit:orientation_object()
all_object_names = {}
local tree_depth = 1
local _process_object_tree
function _process_object_tree(obj, depth)
local indented_name = BeardLibEditor.Utils:Unhash(obj:name(), "other") --:s()
for i = 1, depth do
indented_name = indented_name
end
table.insert(all_object_names, indented_name)
local children = obj:children()
for _, child in ipairs(children) do
_process_object_tree(child, depth + 1)
end
end
_process_object_tree(root_obj, 0)
end
return all_object_names
end
|
EditorNavObstacle = EditorNavObstacle or class(MissionScriptEditor) --Currently broken
function EditorNavObstacle:create_element()
EditorNavObstacle.super.create_element(self)
self._element.class = "ElementNavObstacle"
self._element.values.obstacle_list = {}
self._element.values.operation = "add"
self._guis = {}
self._obstacle_units = {}
self._all_object_names = {}
end
function EditorNavObstacle:_build_panel()
self:_create_panel()
self:ComboCtrl("operation", {"add", "remove"}, {help = "Choose if you want to add or remove an obstacle"})
self:BuildUnitsManage("obstacle_list", {values_name = "Object", value_key = "obj_name", key = "unit_id", orig = {unit_id = 0, obj_name = "", guis_id = 1}, combo_items_func = function(name, value)
-- get all obj idstrings and map them to unindented values
-- why the fuck is this function called collect it should be called map AAAA
local objects = table.collect(self:_get_objects_by_unit(value.unit), self._unindent_obj_name)
return objects
end})
end
function EditorNavObstacle:_get_objects_by_unit(unit)
local all_object_names = {}
if unit then
local root_obj = unit:orientation_object()
all_object_names = {}
local tree_depth = 1
local function _process_object_tree(obj, depth)
local indented_name = obj:name():s()
for i = 1, depth, 1 do
indented_name = "-" .. indented_name
end
table.insert(all_object_names, indented_name)
local children = obj:children()
for _, child in ipairs(children) do
_process_object_tree(child, depth + 1)
end
end
_process_object_tree(root_obj, 0)
end
return all_object_names
end
function EditorNavObstacle._unindent_obj_name(obj_name)
while string.sub(obj_name, 1, 1) == "-" do
obj_name = string.sub(obj_name, 2)
end
-- get rid of @ID(obj_name)@
return obj_name:match("@ID(.*)@")
end
|
Fixed #257
|
Fixed #257
|
Lua
|
mit
|
simon-wh/PAYDAY-2-BeardLib-Editor
|
e61e5baee780cde9af26c8c64133b124c053df70
|
src/plugins/lua/whitelist.lua
|
src/plugins/lua/whitelist.lua
|
-- Module that add symbols to those hosts or from domains that are contained in whitelist
local symbol_ip = nil
local symbol_from = nil
local r = nil
local h = nil -- radix tree and hash table
function check_whitelist (task)
if symbol_ip then
-- check client's ip
local ipn = task:get_from_ip_num()
if ipn then
local key = r:get_key(ipn)
if key then
task:insert_result( symbol_ip, 1)
end
end
end
if symbol_from then
-- check client's from domain
local from = task:get_from()
if from then
local from_addr = from[1]['addr']
if from_addr then
local _,_,domain = string.find(from_addr, '@(.+)>?$')
local key = h:get_key(domain)
if key then
task:insert_result(symbol_from, 1)
end
end
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('whitelist', 'symbol_ip', 'string')
rspamd_config:register_module_option('whitelist', 'symbol_from', 'string')
rspamd_config:register_module_option('whitelist', 'ip_whitelist', 'map')
rspamd_config:register_module_option('whitelist', 'from_whitelist', 'map')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('whitelist')
if opts then
if opts['symbol_ip'] or opts['symbol_from'] then
symbol_ip = opts['symbol_ip']
symbol_from = opts['symbol_from']
if symbol_ip then
if opts['ip_whitelist'] then
r = rspamd_config:add_radix_map (opts['ip_whitelist'])
else
-- No whitelist defined
symbol_ip = nil
end
end
if symbol_from then
if opts['from_whitelist'] then
h = rspamd_config:add_hash_map (opts['from_whitelist'])
else
-- No whitelist defined
symbol_from = nil
end
end
-- Register symbol's callback
if symbol_ip then
rspamd_config:register_symbol(symbol_ip, 1.0, 'check_whitelist')
elseif symbol_from then
rspamd_config:register_symbol(symbol_from, 1.0, 'check_whitelist')
end
end
end
|
-- Module that add symbols to those hosts or from domains that are contained in whitelist
local symbol_ip = nil
local symbol_from = nil
local r = nil
local h = nil -- radix tree and hash table
local function check_whitelist (task)
if symbol_ip then
-- check client's ip
local ipn = task:get_from_ip_num()
if ipn then
local key = r:get_key(ipn)
if key then
task:insert_result( symbol_ip, 1)
end
end
end
if symbol_from then
-- check client's from domain
local from = task:get_from()
if from then
local from_addr = from[1]['addr']
if from_addr then
local _,_,domain = string.find(from_addr, '@(.+)>?$')
local key = h:get_key(domain)
if key then
task:insert_result(symbol_from, 1)
end
end
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('whitelist', 'symbol_ip', 'string')
rspamd_config:register_module_option('whitelist', 'symbol_from', 'string')
rspamd_config:register_module_option('whitelist', 'ip_whitelist', 'map')
rspamd_config:register_module_option('whitelist', 'from_whitelist', 'map')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('whitelist')
if opts then
if opts['symbol_ip'] or opts['symbol_from'] then
local symbol_ip = opts['symbol_ip']
local symbol_from = opts['symbol_from']
if symbol_ip then
if opts['ip_whitelist'] then
r = rspamd_config:add_radix_map (opts['ip_whitelist'])
else
-- No whitelist defined
symbol_ip = nil
end
end
if symbol_from then
if opts['from_whitelist'] then
h = rspamd_config:add_hash_map (opts['from_whitelist'])
else
-- No whitelist defined
symbol_from = nil
end
end
-- Register symbol's callback
if symbol_ip or symbol_from then
rspamd_config:register_callback_symbol_priority('WHITELIST', 1.0, -1, check_whitelist)
if symbol_from then
rspamd_config:register_virtual_symbol(symbol_from, 1.0)
end
if symbol_ip then
rspamd_config:register_virtual_symbol(symbol_ip, 1.0)
end
end
end
end
|
Fix whitelist module.
|
Fix whitelist module.
|
Lua
|
apache-2.0
|
minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,awhitesong/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,dark-al/rspamd,awhitesong/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,amohanta/rspamd,AlexeySa/rspamd,awhitesong/rspamd,dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,dark-al/rspamd,amohanta/rspamd,AlexeySa/rspamd,dark-al/rspamd,amohanta/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,dark-al/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,awhitesong/rspamd,andrejzverev/rspamd
|
c2989af91bac22014b704a8101c7752442dfe7e8
|
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
|
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
|
includeFile("lok/blood_razor_berzerker.lua")
includeFile("lok/blood_razor_captain.lua")
includeFile("lok/blood_razor_cutthroat.lua")
includeFile("lok/blood_razor_destroyer.lua")
includeFile("lok/blood_razor_elite_pirate.lua")
includeFile("lok/blood_razor_guard.lua")
includeFile("lok/blood_razor_officer.lua")
includeFile("lok/blood_razor_scout.lua")
includeFile("lok/blood_razor_strong_pirate.lua")
includeFile("lok/blood_razor_weak_pirate.lua")
includeFile("lok/canyon_corsair_captain.lua")
includeFile("lok/canyon_corsair_cutthroat.lua")
includeFile("lok/canyon_corsair_destroyer.lua")
includeFile("lok/canyon_corsair_elite_pirate.lua")
includeFile("lok/canyon_corsair_guard.lua")
includeFile("lok/canyon_corsair_scout.lua")
includeFile("lok/canyon_corsair_strong_pirate.lua")
includeFile("lok/canyon_corsair_weak_pirate.lua")
includeFile("lok/cas_vankoo.lua")
includeFile("lok/crazed_gurk_destroyer.lua")
includeFile("lok/deadly_vesp.lua")
includeFile("lok/demolishing_snorbal_titan.lua")
includeFile("lok/desert_vesp.lua")
includeFile("lok/domesticated_gurnaset.lua")
includeFile("lok/domesticated_snorbal.lua")
includeFile("lok/droideka.lua")
includeFile("lok/dune_kimogila.lua")
includeFile("lok/elder_snorbal_female.lua")
includeFile("lok/elder_snorbal_male.lua")
includeFile("lok/elite_canyon_corsair.lua")
includeFile("lok/enraged_dune_kimogila.lua")
includeFile("lok/enraged_kimogila.lua")
includeFile("lok/female_langlatch.lua")
includeFile("lok/female_snorbal_calf.lua")
includeFile("lok/feral_gurk.lua")
includeFile("lok/ferocious_kusak.lua")
includeFile("lok/flit_bloodsucker.lua")
includeFile("lok/flit_harasser.lua")
includeFile("lok/flit.lua")
includeFile("lok/flit_youth.lua")
includeFile("lok/giant_dune_kimogila.lua")
includeFile("lok/giant_flit.lua")
includeFile("lok/giant_kimogila.lua")
includeFile("lok/giant_pharple.lua")
includeFile("lok/giant_spined_snake.lua")
includeFile("lok/gorge_vesp.lua")
includeFile("lok/gurk_gatherer.lua")
includeFile("lok/gurk.lua")
includeFile("lok/gurk_tracker.lua")
includeFile("lok/gurk_whelp.lua")
includeFile("lok/gurnaset_be.lua")
includeFile("lok/gurnaset_hatchling.lua")
includeFile("lok/gurnaset.lua")
includeFile("lok/imperial_deserter.lua")
includeFile("lok/jinkins.lua")
includeFile("lok/juvenile_langlatch.lua")
includeFile("lok/kimogila_be.lua")
includeFile("lok/kimogila_hatchling.lua")
includeFile("lok/kimogila.lua")
includeFile("lok/kole.lua")
includeFile("lok/kusak_be.lua")
includeFile("lok/kusak_hunter.lua")
includeFile("lok/kusak.lua")
includeFile("lok/kusak_mauler.lua")
includeFile("lok/kusak_pup.lua")
includeFile("lok/kusak_stalker.lua")
includeFile("lok/langlatch_be.lua")
includeFile("lok/langlatch_destroyer.lua")
includeFile("lok/langlatch_hatchling.lua")
includeFile("lok/langlatch_hunter.lua")
includeFile("lok/langlatch_marauder.lua")
includeFile("lok/lethargic_behemoth.lua")
includeFile("lok/loathsome_mangler.lua")
includeFile("lok/lowland_salt_mynock.lua")
includeFile("lok/male_langlatch.lua")
includeFile("lok/male_snorbal_calf.lua")
includeFile("lok/marooned_pirate_captain.lua")
includeFile("lok/marooned_pirate_engineer.lua")
includeFile("lok/marooned_pirate_first_mate.lua")
includeFile("lok/marooned_pirate.lua")
includeFile("lok/mature_snorbal_female.lua")
includeFile("lok/mature_snorbal_male.lua")
includeFile("lok/mercenary_commander.lua")
includeFile("lok/mercenary_destroyer.lua")
includeFile("lok/mercenary_elite.lua")
includeFile("lok/mercenary_messenger.lua")
includeFile("lok/mercenary_warlord.lua")
includeFile("lok/mercenary_weak.lua")
includeFile("lok/mountain_vesp_medium.lua")
includeFile("lok/nien_nunb.lua")
includeFile("lok/nym_guard_elite.lua")
includeFile("lok/nym_guard_strong.lua")
includeFile("lok/nym_guard_weak.lua")
includeFile("lok/nym.lua")
includeFile("lok/nym_bodyguard.lua")
includeFile("lok/nym_brawler.lua")
includeFile("lok/nym_destroyer.lua")
--includeFile("lok/nym_domesticated_gurk.lua")
--includeFile("lok/nym_droideka.lua")
includeFile("lok/nym_patrol_elite.lua")
includeFile("lok/nym_pirate_elite.lua")
includeFile("lok/nym_kusak_guardian.lua")
includeFile("lok/nym_patrol_strong.lua")
includeFile("lok/nym_patrol_weak.lua")
includeFile("lok/nym_pirate_strong.lua")
includeFile("lok/nym_pirate_weak.lua")
includeFile("lok/nym_surveyor.lua")
includeFile("lok/perlek.lua")
includeFile("lok/perlek_ravager.lua")
includeFile("lok/perlek_scavenger.lua")
includeFile("lok/pharple.lua")
includeFile("lok/reclusive_gurk_king.lua")
includeFile("lok/riverside_sulfur_mynok.lua")
includeFile("lok/runty_pharple.lua")
includeFile("lok/salt_mynock.lua")
includeFile("lok/sandy_spined_snake.lua")
includeFile("lok/shaggy_gurk_youth.lua")
includeFile("lok/sharptooth_langlatch.lua")
includeFile("lok/snorbal_be.lua")
includeFile("lok/snorbal.lua")
includeFile("lok/snorbal_matriarch.lua")
includeFile("lok/spined_snake.lua")
includeFile("lok/spined_snake_recluse.lua")
includeFile("lok/strong_mercenary.lua")
includeFile("lok/sulfer_pool_mynock.lua")
includeFile("lok/sulfur_lake_pirate.lua")
includeFile("lok/theme_park_rebel_bounty_hunter.lua")
includeFile("lok/theme_park_rebel_edycu.lua")
includeFile("lok/theme_park_rebel_engineer.lua")
includeFile("lok/theme_park_rebel_hyperdrive_seller.lua")
includeFile("lok/theme_park_rebel_pirate.lua")
includeFile("lok/theme_park_rebel_pirate_holocron.lua")
includeFile("lok/weak_mercenary.lua")
includeFile("lok/rifea_eicik.lua")
includeFile("lok/rorha_wahe.lua")
includeFile("lok/reggi_tirver.lua")
includeFile("lok/vixur_webb.lua")
includeFile("lok/ifoja_lico.lua")
includeFile("lok/evathm.lua")
includeFile("lok/bapibac.lua")
includeFile("lok/lok_herald_01.lua")
includeFile("lok/lok_herald_02.lua")
includeFile("lok/melo.lua")
includeFile("lok/idhak_ipath.lua")
includeFile("lok/ciwi_mosregri.lua")
|
includeFile("lok/blood_razor_berzerker.lua")
includeFile("lok/blood_razor_captain.lua")
includeFile("lok/blood_razor_cutthroat.lua")
includeFile("lok/blood_razor_destroyer.lua")
includeFile("lok/blood_razor_elite_pirate.lua")
includeFile("lok/blood_razor_guard.lua")
includeFile("lok/blood_razor_officer.lua")
includeFile("lok/blood_razor_scout.lua")
includeFile("lok/blood_razor_strong_pirate.lua")
includeFile("lok/blood_razor_weak_pirate.lua")
includeFile("lok/canyon_corsair_captain.lua")
includeFile("lok/canyon_corsair_cutthroat.lua")
includeFile("lok/canyon_corsair_destroyer.lua")
includeFile("lok/canyon_corsair_elite_pirate.lua")
includeFile("lok/canyon_corsair_guard.lua")
includeFile("lok/canyon_corsair_scout.lua")
includeFile("lok/canyon_corsair_strong_pirate.lua")
includeFile("lok/canyon_corsair_weak_pirate.lua")
includeFile("lok/cas_vankoo.lua")
includeFile("lok/crazed_gurk_destroyer.lua")
includeFile("lok/deadly_vesp.lua")
includeFile("lok/demolishing_snorbal_titan.lua")
includeFile("lok/desert_vesp.lua")
includeFile("lok/domesticated_gurnaset.lua")
includeFile("lok/domesticated_snorbal.lua")
includeFile("lok/droideka.lua")
includeFile("lok/dune_kimogila.lua")
includeFile("lok/elder_snorbal_female.lua")
includeFile("lok/elder_snorbal_male.lua")
includeFile("lok/elite_canyon_corsair.lua")
includeFile("lok/enraged_dune_kimogila.lua")
includeFile("lok/enraged_kimogila.lua")
includeFile("lok/female_langlatch.lua")
includeFile("lok/female_snorbal_calf.lua")
includeFile("lok/feral_gurk.lua")
includeFile("lok/ferocious_kusak.lua")
includeFile("lok/flit_bloodsucker.lua")
includeFile("lok/flit_harasser.lua")
includeFile("lok/flit.lua")
includeFile("lok/flit_youth.lua")
includeFile("lok/giant_dune_kimogila.lua")
includeFile("lok/giant_flit.lua")
includeFile("lok/giant_kimogila.lua")
includeFile("lok/giant_pharple.lua")
includeFile("lok/giant_spined_snake.lua")
includeFile("lok/gorge_vesp.lua")
includeFile("lok/gurk_gatherer.lua")
includeFile("lok/gurk.lua")
includeFile("lok/gurk_tracker.lua")
includeFile("lok/gurk_whelp.lua")
includeFile("lok/gurnaset_be.lua")
includeFile("lok/gurnaset_hatchling.lua")
includeFile("lok/gurnaset.lua")
includeFile("lok/imperial_deserter.lua")
includeFile("lok/jinkins.lua")
includeFile("lok/juvenile_langlatch.lua")
includeFile("lok/kimogila_be.lua")
includeFile("lok/kimogila_hatchling.lua")
includeFile("lok/kimogila.lua")
includeFile("lok/kole.lua")
includeFile("lok/kusak_be.lua")
includeFile("lok/kusak_hunter.lua")
includeFile("lok/kusak.lua")
includeFile("lok/kusak_mauler.lua")
includeFile("lok/kusak_pup.lua")
includeFile("lok/kusak_stalker.lua")
includeFile("lok/langlatch_be.lua")
includeFile("lok/langlatch_destroyer.lua")
includeFile("lok/langlatch_hatchling.lua")
includeFile("lok/langlatch_hunter.lua")
includeFile("lok/langlatch_marauder.lua")
includeFile("lok/lethargic_behemoth.lua")
includeFile("lok/loathsome_mangler.lua")
includeFile("lok/lowland_salt_mynock.lua")
includeFile("lok/male_langlatch.lua")
includeFile("lok/male_snorbal_calf.lua")
includeFile("lok/marooned_pirate_captain.lua")
includeFile("lok/marooned_pirate_engineer.lua")
includeFile("lok/marooned_pirate_first_mate.lua")
includeFile("lok/marooned_pirate.lua")
includeFile("lok/mature_snorbal_female.lua")
includeFile("lok/mature_snorbal_male.lua")
includeFile("lok/mercenary_commander.lua")
includeFile("lok/mercenary_destroyer.lua")
includeFile("lok/mercenary_elite.lua")
includeFile("lok/mercenary_messenger.lua")
includeFile("lok/mercenary_warlord.lua")
includeFile("lok/mercenary_weak.lua")
includeFile("lok/mountain_vesp_medium.lua")
includeFile("lok/nien_nunb.lua")
includeFile("lok/nym_guard_elite.lua")
includeFile("lok/nym_guard_strong.lua")
includeFile("lok/nym_guard_weak.lua")
includeFile("lok/nym.lua")
includeFile("lok/nym_bodyguard.lua")
includeFile("lok/nym_brawler.lua")
includeFile("lok/nym_destroyer.lua")
--includeFile("lok/nym_domesticated_gurk.lua")
--includeFile("lok/nym_droideka.lua")
includeFile("lok/nym_patrol_elite.lua")
includeFile("lok/nym_pirate_elite.lua")
includeFile("lok/nym_kusak_guardian.lua")
includeFile("lok/nym_patrol_strong.lua")
includeFile("lok/nym_patrol_weak.lua")
includeFile("lok/nym_pirate_strong.lua")
includeFile("lok/nym_pirate_weak.lua")
includeFile("lok/nym_surveyor.lua")
includeFile("lok/perlek.lua")
includeFile("lok/perlek_ravager.lua")
includeFile("lok/perlek_scavenger.lua")
includeFile("lok/pharple.lua")
includeFile("lok/reclusive_gurk_king.lua")
includeFile("lok/riverside_sulfur_mynok.lua")
includeFile("lok/runty_pharple.lua")
includeFile("lok/salt_mynock.lua")
includeFile("lok/sandy_spined_snake.lua")
includeFile("lok/shaggy_gurk_youth.lua")
includeFile("lok/sharptooth_langlatch.lua")
includeFile("lok/snorbal_be.lua")
includeFile("lok/snorbal.lua")
includeFile("lok/snorbal_matriarch.lua")
includeFile("lok/spined_snake.lua")
includeFile("lok/spined_snake_recluse.lua")
includeFile("lok/strong_mercenary.lua")
includeFile("lok/sulfer_pool_mynock.lua")
includeFile("lok/sulfur_lake_pirate.lua")
includeFile("lok/theme_park_rebel_bounty_hunter.lua")
includeFile("lok/theme_park_rebel_edycu.lua")
includeFile("lok/theme_park_rebel_engineer.lua")
includeFile("lok/theme_park_rebel_hyperdrive_seller.lua")
includeFile("lok/theme_park_rebel_nym_contact.lua")
includeFile("lok/theme_park_rebel_pirate.lua")
includeFile("lok/theme_park_rebel_pirate_holocron.lua")
includeFile("lok/weak_mercenary.lua")
includeFile("lok/rifea_eicik.lua")
includeFile("lok/rorha_wahe.lua")
includeFile("lok/reggi_tirver.lua")
includeFile("lok/vixur_webb.lua")
includeFile("lok/ifoja_lico.lua")
includeFile("lok/evathm.lua")
includeFile("lok/bapibac.lua")
includeFile("lok/lok_herald_01.lua")
includeFile("lok/lok_herald_02.lua")
includeFile("lok/melo.lua")
includeFile("lok/idhak_ipath.lua")
includeFile("lok/ciwi_mosregri.lua")
|
(unstable) [fixed] missing npc template for rebel theme park.
|
(unstable) [fixed] missing npc template for rebel theme park.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5938 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
a39f51e4c5072cea222be88e3f65d570b26447ea
|
wyx/map/World.lua
|
wyx/map/World.lua
|
local Class = require 'lib.hump.class'
local Dungeon = getClass 'wyx.map.Dungeon'
local EntityRegistry = getClass 'wyx.entity.EntityRegistry'
local HeroEntityFactory = getClass 'wyx.entity.HeroEntityFactory'
local PrimeEntityChangedEvent = getClass 'wyx.event.PrimeEntityChangedEvent'
local message = getClass 'wyx.component.message'
-- World
--
local World = Class{name='World',
function(self)
-- places can be dungeons, outdoor areas, towns, etc
self._places = {}
self._heroFactory = HeroEntityFactory()
self._eregistry = EntityRegistry()
end
}
-- destructor
function World:destroy()
self._heroFactory:destroy()
self._heroFactory = nil
for k in pairs(self._places) do
self._places[k]:destroy()
self._places[k] = nil
end
self._primeEntity = nil
self._loadstate = nil
self._eregistry:destroy()
self._eregistry = nil
self._places = nil
self._curPlace = nil
self._lastPlace = nil
end
-- generate the world
function World:generate()
if self._loadstate then
self._eregistry:setState(self._loadstate.eregistry)
self:_loadHero()
for name,place in pairs(self._loadstate.places) do
if place.class == 'Dungeon' then
local dungeon = Dungeon(name)
dungeon:setState(place)
dungeon:regenerate()
self:addPlace(dungeon)
end
end
self._curPlace = self._loadstate.curPlace
self._lastPlace = self._loadstate.lastPlace
self._loadstate = nil
else
local dungeon = Dungeon('Lonely Dungeon')
dungeon:generateLevel(1)
self:addPlace(dungeon)
end
local place = self:getCurrentPlace()
local level = place:getCurrentLevel()
if self._primeEntity then
level:addEntity(self._primeEntity)
local x, y = level:getRandomPortalPosition()
local entity = self._eregistry:get(self._primeEntity)
entity:send(message('SET_POSITION'), x, y, x, y)
end
level:notifyEntitiesLoaded()
end
function World:_loadHero()
if self._loadstate then
local id = self._loadstate.primeEntity
info = self._eregistry:getEntityLoadState(id)
local newID = self._heroFactory:createEntity(info)
self._heroFactory:registerEntity(newID)
self._eregistry:setDuplicateID(id, newID)
self:setPrimeEntity(newID)
end
end
function World:createHero(info)
local id = self._heroFactory:createEntity(info)
self._heroFactory:registerEntity(id)
self:setPrimeEntity(id)
end
function World:getPrimeEntity() return self._primeEntity end
function World:setPrimeEntity(id)
local old = self._primeEntity
self._primeEntity = id
local PIC = getClass 'wyx.component.PlayerInputComponent'
local input = PIC()
self._heroFactory:setInputComponent(self._primeEntity, input)
local entity = self._eregistry:get(self._primeEntity)
local TimeComponent = getClass 'wyx.component.TimeComponent'
local timeComps = entity:getComponentsByClass(TimeComponent)
if timeComps and #timeComps > 0 then
TimeSystem:setFirst(timeComps[1])
entity:send(message('TIME_AUTO'), false)
end
entity:send(message('CONTAINER_RESIZE'), 10)
GameEvents:push(PrimeEntityChangedEvent(self._primeEntity))
return old
end
function World:addPlace(place)
local name = place:getName()
self._places[name] = place
self._curPlace = self._curPlace or name
end
-- return the current place
function World:getCurrentPlace() return self._places[self._curPlace] end
-- return the given place
function World:getPlace(name) return self._places[name] end
-- switch to the given place
function World:setPlace(name)
verify('string', name)
assert(self._places[name], 'No such place: %s', place)
self._lastPlace = self._curPlace
self._curPlace = name
end
-- return the entity registry
function World:getEntityRegistry() return self._eregistry end
-- save the world (forget the cheerleader)
function World:getState()
local state = {}
state.places = {}
state.curPlace = self._curPlace
state.lastPlace = self._lastPlace
state.primeEntity = self._primeEntity
state.eregistry = self._eregistry:getState()
for name, place in pairs(self._places) do
state.places[name] = place:getState()
end
return state
end
-- load the world
function World:setState(state) self._loadstate = state end
-- the class
return World
|
local Class = require 'lib.hump.class'
local Dungeon = getClass 'wyx.map.Dungeon'
local EntityRegistry = getClass 'wyx.entity.EntityRegistry'
local HeroEntityFactory = getClass 'wyx.entity.HeroEntityFactory'
local PrimeEntityChangedEvent = getClass 'wyx.event.PrimeEntityChangedEvent'
local message = getClass 'wyx.component.message'
local property = require 'wyx.component.property'
-- World
--
local World = Class{name='World',
function(self)
-- places can be dungeons, outdoor areas, towns, etc
self._places = {}
self._heroFactory = HeroEntityFactory()
self._eregistry = EntityRegistry()
end
}
-- destructor
function World:destroy()
self._heroFactory:destroy()
self._heroFactory = nil
for k in pairs(self._places) do
self._places[k]:destroy()
self._places[k] = nil
end
self._primeEntity = nil
self._loadstate = nil
self._eregistry:destroy()
self._eregistry = nil
self._places = nil
self._curPlace = nil
self._lastPlace = nil
end
-- generate the world
function World:generate()
if self._loadstate then
self._eregistry:setState(self._loadstate.eregistry)
self:_loadHero()
for name,place in pairs(self._loadstate.places) do
if place.class == 'Dungeon' then
local dungeon = Dungeon(name)
dungeon:setState(place)
dungeon:regenerate()
self:addPlace(dungeon)
end
end
self._curPlace = self._loadstate.curPlace
self._lastPlace = self._loadstate.lastPlace
else
local dungeon = Dungeon('Lonely Dungeon')
dungeon:generateLevel(1)
self:addPlace(dungeon)
end
local place = self:getCurrentPlace()
local level = place:getCurrentLevel()
if self._primeEntity then
level:addEntity(self._primeEntity)
local entity = self._eregistry:get(self._primeEntity)
local x, y
if self._loadstate then
local pos = entity:query(property('Position'))
x, y = pos[1], pos[2]
else
x, y = level:getRandomPortalPosition()
end
entity:send(message('SET_POSITION'), x, y, x, y)
end
level:notifyEntitiesLoaded()
self._loadstate = nil
end
function World:_loadHero()
if self._loadstate then
local id = self._loadstate.primeEntity
info = self._eregistry:getEntityLoadState(id)
local newID = self._heroFactory:createEntity(info)
self._heroFactory:registerEntity(newID)
self._eregistry:setDuplicateID(id, newID)
self:setPrimeEntity(newID)
end
end
function World:createHero(info)
local id = self._heroFactory:createEntity(info)
self._heroFactory:registerEntity(id)
self:setPrimeEntity(id)
end
function World:getPrimeEntity() return self._primeEntity end
function World:setPrimeEntity(id)
local old = self._primeEntity
self._primeEntity = id
local PIC = getClass 'wyx.component.PlayerInputComponent'
local input = PIC()
self._heroFactory:setInputComponent(self._primeEntity, input)
local entity = self._eregistry:get(self._primeEntity)
local TimeComponent = getClass 'wyx.component.TimeComponent'
local timeComps = entity:getComponentsByClass(TimeComponent)
if timeComps and #timeComps > 0 then
TimeSystem:setFirst(timeComps[1])
entity:send(message('TIME_AUTO'), false)
end
entity:send(message('CONTAINER_RESIZE'), 10)
GameEvents:push(PrimeEntityChangedEvent(self._primeEntity))
return old
end
function World:addPlace(place)
local name = place:getName()
self._places[name] = place
self._curPlace = self._curPlace or name
end
-- return the current place
function World:getCurrentPlace() return self._places[self._curPlace] end
-- return the given place
function World:getPlace(name) return self._places[name] end
-- switch to the given place
function World:setPlace(name)
verify('string', name)
assert(self._places[name], 'No such place: %s', place)
self._lastPlace = self._curPlace
self._curPlace = name
end
-- return the entity registry
function World:getEntityRegistry() return self._eregistry end
-- save the world (forget the cheerleader)
function World:getState()
local state = {}
state.places = {}
state.curPlace = self._curPlace
state.lastPlace = self._lastPlace
state.primeEntity = self._primeEntity
state.eregistry = self._eregistry:getState()
for name, place in pairs(self._places) do
state.places[name] = place:getState()
end
return state
end
-- load the world
function World:setState(state) self._loadstate = state end
-- the class
return World
|
fix hero position not being loaded
|
fix hero position not being loaded
|
Lua
|
mit
|
scottcs/wyx
|
04808d991f01ab40a1cc75d6e42c3c53a5d9b30d
|
interface/configenv/flow/mode.lua
|
interface/configenv/flow/mode.lua
|
local function _update_delay_one(self)
self.updatePacket = self._update_packet
self._update_packet = nil
end
local _single_index, _alt_index = 0, 0
local _valid_modes = {
none = true, -- setting this makes validation easier (see option.test)
single = function(dv, pkt)
dv[_single_index + 1]:update()
dv:applyAll(pkt)
_single_index = incAndWrap(_single_index, dv.count) -- luacheck: globals incAndWrap
end,
alternating = function(dv, pkt)
dv[_alt_index + 1]:updateApply(pkt)
_alt_index = incAndWrap(_alt_index, dv.count) -- luacheck: globals incAndWrap
end,
random = function(dv, pkt)
local index = math.random(dv.count)
dv[index]:update()
dv:applyAll(pkt)
end,
random_alt = function(dv, pkt)
local index = math.random(dv.count)
dv[index]:updateApply(pkt)
end,
all = function(dv, pkt)
dv:updateApplyAll(pkt)
end,
}
local _modelist = {}
for i in pairs(_valid_modes) do
table.insert(_modelist, i)
end
local option = {}
option.formatString = {}
for _,v in ipairs(_modelist) do
table.insert(option.formatString, v)
end
option.formatString = "<" .. table.concat(option.formatString, "|") .. ">"
option.helpString = "Change how dynamic fields are updated. (default = single)"
-- TODO add value documentation
function option.parse(self, mode)
if #self.packet.dynvars == 0 or mode == "none" then
return -- packets will not change
end
-- Don't change the first packet
self.updatePacket = _update_delay_one
mode = type(mode) == "string" and _valid_modes[string.lower(mode)]
self._update_packet = mode or _valid_modes.single
end
function option.validate() end
function option.test(self, error, mode)
local t = type(mode)
if t == "string" then
error:assert(#self.packet.dynvars > 0, 4, "Option 'mode': Value set, but no dynvars in associated packet.")
if not _valid_modes[string.lower(mode)] then
error(4, "Option 'mode': Invalid value %q. Can be one of %s.",
mode, table.concat(_modelist, ", "))
return false
end
else
error(4, "Option 'mode': Invalid argument. String expected, got %s.", t)
return false
end
return true
end
return option
|
local flow
local function _update_delay_one()
flow.updatePacket = flow._update_packet
flow._update_packet = nil
end
-- closures are ok because the script is reinstanced per slave-thread
local _single_index, _alt_index = 0, 0
local _valid_modes = {
none = true, -- setting this makes validation easier (see option.test)
single = function(dv, pkt)
dv[_single_index + 1]:update()
dv:applyAll(pkt)
_single_index = incAndWrap(_single_index, dv.count) -- luacheck: globals incAndWrap
end,
alternating = function(dv, pkt)
dv[_alt_index + 1]:updateApply(pkt)
_alt_index = incAndWrap(_alt_index, dv.count) -- luacheck: globals incAndWrap
end,
random = function(dv, pkt)
local index = math.random(dv.count)
dv[index]:update()
dv:applyAll(pkt)
end,
random_alt = function(dv, pkt)
local index = math.random(dv.count)
dv[index]:updateApply(pkt)
end,
all = function(dv, pkt)
dv:updateApplyAll(pkt)
end,
}
local _modelist = {}
for i in pairs(_valid_modes) do
table.insert(_modelist, i)
end
local option = {}
option.formatString = {}
for _,v in ipairs(_modelist) do
table.insert(option.formatString, v)
end
option.formatString = "<" .. table.concat(option.formatString, "|") .. ">"
option.helpString = "Change how dynamic fields are updated. (default = single)"
-- TODO add value documentation
function option.parse(self, mode)
if #self.packet.dynvars == 0 or mode == "none" then
return -- packets will not change
end
-- Don't change the first packet
flow = self
self.updatePacket = _update_delay_one
mode = type(mode) == "string" and _valid_modes[string.lower(mode)]
self._update_packet = mode or _valid_modes.single
end
function option.validate() end
function option.test(self, error, mode)
local t = type(mode)
if t == "string" then
error:assert(#self.packet.dynvars > 0, 4, "Option 'mode': Value set, but no dynvars in associated packet.")
if not _valid_modes[string.lower(mode)] then
error(4, "Option 'mode': Invalid value %q. Can be one of %s.",
mode, table.concat(_modelist, ", "))
return false
end
else
error(4, "Option 'mode': Invalid argument. String expected, got %s.", t)
return false
end
return true
end
return option
|
Fixed modes never activating.
|
Fixed modes never activating.
|
Lua
|
mit
|
dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,emmericp/MoonGen,scholzd/MoonGen
|
568c9e16c2bdbd0b836515f2031939e37cfd363e
|
ssbase/gamemode/sv_profiles.lua
|
ssbase/gamemode/sv_profiles.lua
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"}
local update_filter = {"id", "steamId", "rank", "avatarUrl"}
SS.Profiles = {}
-- Check if the player has a valid avatar url stored in the database, if not fetch it.
function PLAYER_META:CheckAvatar()
if self.profile and (!self.profile.avatar or string.Trim(self.profile.avatarUrl) == "" )then
http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64,
function(body)
if self and self:IsValid() then
body = util.JSONToTable(body)
DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatarfull.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'")
end
end,
function(error)
Error("[AVATAR FETCH FAILED] ".. error)
end
)
end
end
function PLAYER_META:CreateProfile()
if(self:IsBot()) then return end
local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "")
local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')"
DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end)
end
function PLAYER_META:ProfileLoad()
if(self:IsBot()) then return end
MsgN("[PROFILE] Loading ", self)
local steamid = self:SteamID()
SS.Profiles[steamid] = {}
self:ChatPrint("Loading your profile")
if DB_DEVS then self:ProfileLoaded() return end
timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end)
DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'",
function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end,
function()
if self and self:IsValid() then
self.ProfileFailed = true
self:ChatPrint("We failed to load your profile, trying again in 60 seconds.")
timer.Simple(60, function()
if self and self:IsValid() then
self:ProfileLoad()
end
end )
end
end)
end
function PLAYER_META:ProfileLoaded(res)
local steamid = self:SteamID()
if res and res[1] then
if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end
self.profile = res[1]
MsgN("[PROFILE] Loaded ", self)
self:SetRank(self.profile.rank)
self:SetMoney(self.profile.money)
self:SetExp(self.profile.exp)
self:SetStoreItems(self.profile.store)
self:SetEquipped(self.profile.equipped)
self:NetworkOwnedItem()
if !self:HasMoney(0) then
self:SetMoney(0)
self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!")
end
self:ChatPrint("Your profile has been loaded")
elseif res and !res[1] then
self:ChatPrint("No profile detected, creating one for you.")
self:CreateProfile()
return
else
self.profile = {}
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
self:SetRank(DB_DEVS and 100 or 0)
self:SetMoney(100)
self:SetExp(1)
self:SetStoreItems("")
self:SetEquipped("")
self:ChatPrint("We had problems loading your profile and have created a temporary one for you.")
end
self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil
self.playtimeStart = os.time()
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
SS.Profiles[self:SteamID()] = self.profile
self:CheckAvatar()
timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function()
if self and self:IsValid() then
self.profile.lastLoginTimestamp = os.time()
self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
self:ProfileSave()
else
timer.Destroy(steamid.."_ProfileUpdate")
end
end )
hook.Run("PlayerSetModel", self)
self:SetNetworkedBool("ss_profileloaded", true)
end
/* Sync Profile with database */
function PLAYER_META:ProfileSave()
if(self:IsBot()) then return end
local profile = SS.Profiles[self:SteamID()]
profile.money = self.money
profile.exp = self.exp
profile.playtime = profile.playtime+(os.time()-self.playtimeStart)
profile.store = util.TableToJSON(self.storeItems)
profile.equipped = util.TableToJSON(self.storeEquipped)
self.playtimeStart = os.time()
local Query = "UPDATE users SET "
local first = true
for k,v in pairs(profile) do
if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these.
if first then
Query = Query..k.."='"..v.."'"
first = false
else
Query = Query..", "..k.."='"..v.."'"
end
end
Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'"
DB_Query(Query)
end
function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this
if(self:IsBot()) then return end
if !SERVER then return end
DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" )
end
--------------------------------------------------
--
--------------------------------------------------
function PLAYER_META:SetStoreItems(data)
if (!data or data == "" or data == "[]") then
self.storeItems = {}
else
self.storeItems = util.JSONToTable(data)
end
end
--------------------------------------------------
--
--------------------------------------------------
function PLAYER_META:SetEquipped(data)
if (!data or data == "" or data == "[]") then
self.storeEquipped = {}
for i = 1, SS.STORE.SLOT.MAXIMUM do
self.storeEquipped[i] = {}
end
else
self.storeEquipped = util.JSONToTable(data)
end
end
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"}
local update_filter = {"id", "steamId", "rank", "avatarUrl"}
SS.Profiles = {}
-- Check if the player has a valid avatar url stored in the database, if not fetch it.
function PLAYER_META:CheckAvatar()
if self.profile and (!self.profile.avatarUrl or string.Trim(self.profile.avatarUrl) == "" or string.sub(self.profile.avatarURL, string.len(self.profile.avatarURL)-9, string.len(self.profile.avatarURL)) == "_full.jpg") then
http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64,
function(body)
if self and self:IsValid() then
body = util.JSONToTable(body)
DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatarfull.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'")
self:ChatPrint("AVATAR DEBUG: "..body.response.players[1].avatarfull)
end
end,
function(error)
Error("[AVATAR FETCH FAILED] ".. error)
end
)
end
end
function PLAYER_META:CreateProfile()
if(self:IsBot()) then return end
local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "")
local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')"
DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end)
end
function PLAYER_META:ProfileLoad()
if(self:IsBot()) then return end
MsgN("[PROFILE] Loading ", self)
local steamid = self:SteamID()
SS.Profiles[steamid] = {}
self:ChatPrint("Loading your profile")
if DB_DEVS then self:ProfileLoaded() return end
timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end)
DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'",
function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end,
function()
if self and self:IsValid() then
self.ProfileFailed = true
self:ChatPrint("We failed to load your profile, trying again in 60 seconds.")
timer.Simple(60, function()
if self and self:IsValid() then
self:ProfileLoad()
end
end )
end
end)
end
function PLAYER_META:ProfileLoaded(res)
local steamid = self:SteamID()
if res and res[1] then
if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end
self.profile = res[1]
MsgN("[PROFILE] Loaded ", self)
self:SetRank(self.profile.rank)
self:SetMoney(self.profile.money)
self:SetExp(self.profile.exp)
self:SetStoreItems(self.profile.store)
self:SetEquipped(self.profile.equipped)
self:NetworkOwnedItem()
if !self:HasMoney(0) then
self:SetMoney(0)
self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!")
end
self:ChatPrint("Your profile has been loaded")
elseif res and !res[1] then
self:ChatPrint("No profile detected, creating one for you.")
self:CreateProfile()
return
else
self.profile = {}
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
self:SetRank(DB_DEVS and 100 or 0)
self:SetMoney(100)
self:SetExp(1)
self:SetStoreItems("")
self:SetEquipped("")
self:ChatPrint("We had problems loading your profile and have created a temporary one for you.")
end
self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil
self.playtimeStart = os.time()
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
SS.Profiles[self:SteamID()] = self.profile
self:CheckAvatar()
timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function()
if self and self:IsValid() then
self.profile.lastLoginTimestamp = os.time()
self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
self:ProfileSave()
else
timer.Destroy(steamid.."_ProfileUpdate")
end
end )
hook.Run("PlayerSetModel", self)
self:SetNetworkedBool("ss_profileloaded", true)
end
/* Sync Profile with database */
function PLAYER_META:ProfileSave()
if(self:IsBot()) then return end
local profile = SS.Profiles[self:SteamID()]
profile.money = self.money
profile.exp = self.exp
profile.playtime = profile.playtime+(os.time()-self.playtimeStart)
profile.store = util.TableToJSON(self.storeItems)
profile.equipped = util.TableToJSON(self.storeEquipped)
self.playtimeStart = os.time()
local Query = "UPDATE users SET "
local first = true
for k,v in pairs(profile) do
if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these.
if first then
Query = Query..k.."='"..v.."'"
first = false
else
Query = Query..", "..k.."='"..v.."'"
end
end
Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'"
DB_Query(Query)
end
function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this
if(self:IsBot()) then return end
if !SERVER then return end
DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" )
end
--------------------------------------------------
--
--------------------------------------------------
function PLAYER_META:SetStoreItems(data)
if (!data or data == "" or data == "[]") then
self.storeItems = {}
else
self.storeItems = util.JSONToTable(data)
end
end
--------------------------------------------------
--
--------------------------------------------------
function PLAYER_META:SetEquipped(data)
if (!data or data == "" or data == "[]") then
self.storeEquipped = {}
for i = 1, SS.STORE.SLOT.MAXIMUM do
self.storeEquipped[i] = {}
end
else
self.storeEquipped = util.JSONToTable(data)
end
end
|
A fix/debug for avatar updating
|
A fix/debug for avatar updating
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
91e1f02c9889d0ca16a02225520c652c2d6acaba
|
mock/common/ScriptedBehaviour.lua
|
mock/common/ScriptedBehaviour.lua
|
module 'mock'
--------------------------------------------------------------------
CLASS: ScriptedBehaviour ( Behaviour )
:MODEL{
Field 'script' :asset( 'com_script' ) :getset( 'Script' );
}
registerComponent( 'ScriptedBehaviour', ScriptedBehaviour )
function ScriptedBehaviour:__init()
self.scriptPath = false
self.delegate = false
self.dataInstance = false
end
function ScriptedBehaviour:getScript()
return self.scriptPath
end
function ScriptedBehaviour:setScript( path )
self.scriptPath = path
self:updateComponentScript()
end
function ScriptedBehaviour:updateComponentScript()
local path = self.scriptPath
local scriptObj = loadAsset( path )
local delegate, dataInstance
if scriptObj then
delegate, dataInstance = scriptObj:buildInstance( self )
end
local prevInstance = self.dataInstance
self.delegate = delegate or false
self.dataInstance = dataInstance or false
if prevInstance and dataInstance then
_cloneObject( prevInstance, dataInstance )
end
end
function ScriptedBehaviour:onStart( ent )
--Update delegate
local delegate = self.delegate
if delegate then
--insert global variables
delegate.entity = ent
-- delegate.scene = ent:getScene()
local onStart = delegate.onStart
if onStart then onStart() end
self.onThread = delegate.onThread
local onMsg = delegate.onMsg
if onMsg then
self.msgListener = onMsg
ent:addMsgListener( self.msgListener )
end
if delegate.onUpdate then
ent.scene:addUpdateListener( self )
end
end
return Behaviour.onStart( self, ent )
end
function ScriptedBehaviour:onUpdate( dt )
return self.delegate.onUpdate( dt )
end
function ScriptedBehaviour:onDetach( ent )
if self.delegate then
local onDetach = self.delegate.onDetach
if onDetach then onDetach( ent ) end
if self.msgListener then
ent:removeMsgListener( self.msgListener )
end
ent.scene:removeUpdateListener( self )
end
end
function ScriptedBehaviour:installInputListener( option )
return installInputListener( self.delegate, option )
end
function ScriptedBehaviour:uninstallInputListener()
return uninstallInputListener( self.delegate )
end
function ScriptedBehaviour:__serialize( objMap )
local dataInstance = self.dataInstance
if not dataInstance then return end
return _serializeObject( dataInstance, objMap )
end
function ScriptedBehaviour:__deserialize( data, objMap, namespace )
if not data then return end
local dataInstance = self.dataInstance
if not dataInstance then return end
return _deserializeObject( dataInstance, data, objMap, namespace )
end
function ScriptedBehaviour:__clone( src, objMap )
local dataInstance = self.dataInstance
if not dataInstance then return end
return _cloneObject( src, dataInstance, objMap )
end
|
module 'mock'
--------------------------------------------------------------------
CLASS: ScriptedBehaviour ( Behaviour )
:MODEL{
Field 'script' :asset( 'com_script' ) :getset( 'Script' );
}
registerComponent( 'ScriptedBehaviour', ScriptedBehaviour )
function ScriptedBehaviour:__init()
self.scriptPath = false
self.delegate = false
self.dataInstance = false
end
function ScriptedBehaviour:getScript()
return self.scriptPath
end
function ScriptedBehaviour:setScript( path )
self.scriptPath = path
self:updateComponentScript()
end
function ScriptedBehaviour:updateComponentScript()
local path = self.scriptPath
local scriptObj = loadAsset( path )
local delegate, dataInstance
if scriptObj then
delegate, dataInstance = scriptObj:buildInstance( self )
end
local prevInstance = self.dataInstance
self.delegate = delegate or false
self.dataInstance = dataInstance or false
if prevInstance and dataInstance then
_cloneObject( prevInstance, dataInstance )
end
self:updateMsgListener()
end
function ScriptedBehaviour:updateMsgListener()
local ent = self:getEntity()
if not ent then return end
if self.msgListener then
ent:removeMsgListener( self.msgListener )
self.msgListener = false
end
local delegate = self.delegate
if delegate then
local onMsg = delegate.onMsg
if onMsg then
self.msgListener = onMsg
ent:addMsgListener( self.msgListener )
end
end
end
function ScriptedBehaviour:onAttach( ent )
ScriptedBehaviour.__super.onAttach( self, ent )
self:updateMsgListener()
end
function ScriptedBehaviour:onStart( ent )
--Update delegate
local delegate = self.delegate
if delegate then
--insert global variables
delegate.entity = ent
-- delegate.scene = ent:getScene()
local onStart = delegate.onStart
if onStart then onStart() end
self.onThread = delegate.onThread
if delegate.onUpdate then
ent.scene:addUpdateListener( self )
end
end
return Behaviour.onStart( self, ent )
end
function ScriptedBehaviour:onUpdate( dt )
return self.delegate.onUpdate( dt )
end
function ScriptedBehaviour:onDetach( ent )
if self.delegate then
local onDetach = self.delegate.onDetach
if onDetach then onDetach( ent ) end
if self.msgListener then
ent:removeMsgListener( self.msgListener )
end
ent.scene:removeUpdateListener( self )
end
end
function ScriptedBehaviour:installInputListener( option )
return installInputListener( self.delegate, option )
end
function ScriptedBehaviour:uninstallInputListener()
return uninstallInputListener( self.delegate )
end
function ScriptedBehaviour:__serialize( objMap )
local dataInstance = self.dataInstance
if not dataInstance then return end
return _serializeObject( dataInstance, objMap )
end
function ScriptedBehaviour:__deserialize( data, objMap, namespace )
if not data then return end
local dataInstance = self.dataInstance
if not dataInstance then return end
return _deserializeObject( dataInstance, data, objMap, namespace )
end
function ScriptedBehaviour:__clone( src, objMap )
local dataInstance = self.dataInstance
if not dataInstance then return end
return _cloneObject( src, dataInstance, objMap )
end
|
fixed - ScriptBehaviours msgListener
|
fixed - ScriptBehaviours msgListener
|
Lua
|
mit
|
tommo/mock
|
9c7f2a13a556bb359ca940ea33c511f56921cd1d
|
lua/entities/gmod_wire_value.lua
|
lua/entities/gmod_wire_value.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Value"
ENT.WireDebugName = "Value"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Outputs = Wire_CreateOutputs(self, { "Out" })
end
local types_lookup = {
NORMAL = 0,
ANGLE = Angle(0,0,0),
VECTOR = Vector(0,0,0),
VECTOR2 = {0,0},
VECTOR4 = {0,0,0,0},
STRING = "",
}
function ENT:SetupLegacy( values )
local new = {}
for k,v in pairs( values ) do
local tp, val = string.match( v, "^ *([^: ]+) *:(.*)$" )
tp = string.upper(tp or "NORMAL")
if types_lookup[tp] then
new[#new+1] = { DataType = tp, Value = val or v }
end
end
self.LegacyOutputs = true
self:Setup( new )
end
local tonumber = tonumber
local parsers = {}
function parsers.NORMAL( val )
return tonumber(val)
end
function parsers.VECTOR ( val )
local x,y,z = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) and tonumber(y) then
return Vector(tonumber(x),tonumber(y),tonumber(z))
end
end
function parsers.VECTOR2( val )
local x, y = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) then return {tonumber(x), tonumber(y)} end
end
function parsers.VECTOR4( val )
local x, y, z, w = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) and tonumber(y) and tonumber(w) then
return {tonumber(x),tonumber(y),tonumber(z),tonumber(w)}
end
end
function parsers.ANGLE( val )
local p,y,r = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(p) and tonumber(y) and tonumber(r) then
return Angle(tonumber(p),tonumber(y),tonumber(r))
end
end
function parsers.STRING( val )
return tostring( val )
end
function ENT:ParseValue( value, tp )
if parsers[tp] then
local ret = parsers[tp]( value )
if ret then
return ret
else
WireLib.AddNotify( self:GetPlayer(), "Constant Value: Unable to parse value '" .. tostring(value) .. "' as type '" .. tp .. "'.", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
return types_lookup[tp]
end
end
end
function ENT:Setup( valuesin )
if not valuesin then return end
local _, val = next( valuesin )
if not val then
WireLib.AddNotify( self:GetPlayer(), "Constant Value: No values found!", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
elseif not istable( val ) then -- old dupe
self:SetupLegacy( valuesin )
else
self.value = valuesin -- Wirelink/Duplicator Info
local names = {}
local types = {}
local values = {}
local descs = {}
for k,v in pairs(valuesin) do
v.DataType = string.upper( v.DataType )
if v.DataType == "NUMBER" then v.DataType = "NORMAL" end
if types_lookup[string.upper( v.DataType )] ~= nil then
names[k] = tostring( k )
types[k] = string.upper( v.DataType )
values[k] = self:ParseValue( v.Value, string.upper( v.DataType ) )
descs[k] = values[k] ~= nil and v.Value or "*ERROR*"
else
WireLib.AddNotify( self:GetPlayer(), "Constant Value: Invalid type '" .. string.upper( v.DataType ) .. "' specified.", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
names[k] = tostring( k )
types[k] = "STRING"
values[k] = "INVALID TYPE SPECIFIED"
descs[k] = "*ERROR*"
end
end
if self.LegacyOutputs then
-- Gmod12 Constant Values will have outputs like Value1, Value2...
-- To avoid breaking old dupes, we'll use those names if we're created from an old dupe
for k,v in pairs(names) do
names[k] = "Value"..v
end
end
-- this is where storing the values as strings comes in: they are the descriptions for the inputs.
WireLib.AdjustSpecialOutputs(self, names, types, descs )
local txt = {}
for k,v in pairs(valuesin) do
txt[#txt+1] = string.format( "%s [%s]: %s",names[k],types[k],descs[k])
WireLib.TriggerOutput( self, names[k], values[k] )
end
self:SetOverlayText(table.concat( txt, "\n" ))
end
end
function ENT:ReadCell( Address )
return self.value[Address+1]
end
duplicator.RegisterEntityClass("gmod_wire_value", WireLib.MakeWireEnt, "Data", "value")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Value"
ENT.WireDebugName = "Value"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Outputs = Wire_CreateOutputs(self, { "Out" })
end
local types_lookup = {
NORMAL = 0,
ANGLE = Angle(0,0,0),
VECTOR = Vector(0,0,0),
VECTOR2 = {0,0},
VECTOR4 = {0,0,0,0},
STRING = "",
}
function ENT:SetupLegacy( values )
local new = {}
for k,v in pairs( values ) do
local tp, val = string.match( v, "^ *([^: ]+) *:(.*)$" )
tp = string.upper(tp or "NORMAL")
if types_lookup[tp] then
new[#new+1] = { DataType = tp, Value = val or v }
end
end
self.LegacyOutputs = true
self:Setup( new )
end
local tonumber = tonumber
local parsers = {}
function parsers.NORMAL( val )
return tonumber(val)
end
function parsers.VECTOR ( val )
local x,y,z = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) and tonumber(y) then
return Vector(tonumber(x),tonumber(y),tonumber(z))
end
end
function parsers.VECTOR2( val )
local x, y = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) then return {tonumber(x), tonumber(y)} end
end
function parsers.VECTOR4( val )
local x, y, z, w = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(x) and tonumber(y) and tonumber(y) and tonumber(w) then
return {tonumber(x),tonumber(y),tonumber(z),tonumber(w)}
end
end
function parsers.ANGLE( val )
local p,y,r = string.match( val, "^ *([^%s,]+) *, *([^%s,]+) *, *([^%s,]+) *$" )
if tonumber(p) and tonumber(y) and tonumber(r) then
return Angle(tonumber(p),tonumber(y),tonumber(r))
end
end
function parsers.STRING( val )
return tostring( val )
end
function ENT:ParseValue( value, tp )
if parsers[tp] then
local ret = parsers[tp]( value )
if ret then
return ret
else
WireLib.AddNotify( self:GetPlayer(), "Constant Value: Unable to parse value '" .. tostring(value) .. "' as type '" .. tp .. "'.", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
return types_lookup[tp]
end
end
end
function ENT:Setup( valuesin )
if not valuesin then return end
local _, val = next( valuesin )
if not val then
WireLib.AddNotify( self:GetPlayer(), "Constant Value: No values found!", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
elseif not istable( val ) then -- old dupe
self:SetupLegacy( valuesin )
else
self.value = valuesin -- Wirelink/Duplicator Info
local names = {}
local types = {}
local values = {}
local descs = {}
for k,v in pairs(valuesin) do
v.DataType = string.upper( v.DataType )
if v.DataType == "NUMBER" then v.DataType = "NORMAL" end
if types_lookup[string.upper( v.DataType )] ~= nil then
names[k] = tostring( k )
types[k] = string.upper( v.DataType )
values[k] = self:ParseValue( v.Value, string.upper( v.DataType ) )
descs[k] = values[k] ~= nil and v.Value or "*ERROR*"
else
WireLib.AddNotify( self:GetPlayer(), "Constant Value: Invalid type '" .. string.upper( v.DataType ) .. "' specified.", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
names[k] = tostring( k )
types[k] = "STRING"
values[k] = "INVALID TYPE SPECIFIED"
descs[k] = "*ERROR*"
end
end
if self.LegacyOutputs then
-- Gmod12 Constant Values will have outputs like Value1, Value2...
-- To avoid breaking old dupes, we'll use those names if we're created from an old dupe
for k,v in pairs(names) do
names[k] = "Value"..v
end
end
-- this is where storing the values as strings comes in: they are the descriptions for the inputs.
WireLib.AdjustSpecialOutputs(self, names, types, descs )
local txt = {}
for k,v in pairs(valuesin) do
txt[#txt+1] = string.format( "%s [%s]: %s",names[k],types[k],descs[k])
WireLib.TriggerOutput( self, names[k], values[k] )
end
self:SetOverlayText(table.concat( txt, "\n" ))
self.types = types
self.values = values
end
end
function ENT:ReadCell( Address )
local tp = self.types[Address+1]
-- we can only retrieve numbers here, unfortunately.
-- This is because the ReadCell function assumes that things like vectors and strings store one of their values per cell,
-- which the constant value does not. While this could be worked around, it's just not worth the effort imo, and it'd just be confusing to use
-- If you need to get other types, you'll need to use E2's "Wlk[OutputName,OutputType]" index syntax instead
if tp == "NORMAL" then
return self.values[Address+1]
end
return 0
end
duplicator.RegisterEntityClass("gmod_wire_value", WireLib.MakeWireEnt, "Data", "value")
|
fixed hi-speed for constant value
|
fixed hi-speed for constant value
Fixes #844
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,CaptainPRICE/wire,mms92/wire,dvdvideo1234/wire,bigdogmat/wire,thegrb93/wire,immibis/wiremod,wiremod/wire,garrysmodlua/wire,Python1320/wire,NezzKryptic/Wire,rafradek/wire,mitterdoo/wire,Grocel/wire,sammyt291/wire,notcake/wire
|
e5c0583dac00d684f01acf31ea83281c4c599ec0
|
lua/starfall/libs_sh/vectors.lua
|
lua/starfall/libs_sh/vectors.lua
|
SF.Vectors = {}
--- Vector type
-- @shared
local vec_methods, vec_metamethods = SF.Typedef( "Vector" )
local wrap, unwrap = SF.CreateWrapper( vec_metamethods, true, false, debug.getregistry().Vector )
SF.DefaultEnvironment.Vector = function ( ... )
return wrap( Vector( ... ) )
end
SF.Vectors.Wrap = wrap
SF.Vectors.Unwrap = unwrap
SF.Vectors.Methods = vec_methods
SF.Vectors.Metatable = vec_metamethods
--- __newindex metamethod
function vec_metamethods.__newindex ( t, k, v )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
end
elseif k == "x" or k =="y" or k == "z" then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
else
rawset( t, k, v )
end
end
local _p = vec_metamethods.__index
--- __index metamethod
function vec_metamethods.__index ( t, k )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
return unwrap( t )[ k ]
end
else
if k == "x" or k =="y" or k == "z" then
return unwrap( t )[ k ]
end
end
return _p[ k ]
end
--- tostring metamethod
-- @return string representing the vector.
function vec_metamethods:__tostring ()
return unwrap( self ):__tostring()
end
--- multiplication metamethod
-- @param n Scalar to multiply against vector
-- @return Scaled vector.
function vec_metamethods:__mul ( n )
SF.CheckType( n, "number" )
return wrap( unwrap( self ):__mul( n ) )
end
--- add metamethod
-- @param v Vector to add
-- @return Resultant vector after addition operation.
function vec_metamethods:__add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__add( unwrap( v ) ) )
end
--- sub metamethod
-- @param v Vector to subtract
-- @return Resultant vector after subtraction operation.
function vec_metamethods:__sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__sub( unwrap( v ) ) )
end
--- unary minus metamethod
-- @returns negated vector.
function vec_metamethods:__unm ()
return wrap( unwrap( self ):__unm() )
end
--- equivalence metamethod
-- @returns bool if both sides are equal.
function vec_metamethods:__eq ( ... )
return SF.Sanitize( unwrap( self ):__eq( SF.Unsanitize( ... ) ) )
end
--- Add vector - Modifies self.
-- @param v Vector to add
-- @return nil
function vec_methods:add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Add( unwrap( v ) )
end
--- Get the vector's angle.
-- @return Angle
function vec_methods:getAngle ()
return SF.WrapObject( unwrap( self ):Angle() )
end
--- Returns the Angle between two vectors.
-- @param v Second Vector
-- @return Angle
function vec_methods:getAngleEx ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return SF.WrapObject( unwrap( self ):AngleEx( unwrap( v ) ) )
end
--- Calculates the cross product of the 2 vectors, creates a unique perpendicular vector to both input vectors.
-- @param v Second Vector
-- @return Vector
function vec_methods:cross ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):Cross( unwrap( v ) ) )
end
--- Returns the pythagorean distance between the vector and the other vector.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistance ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Distance( unwrap( v ) )
end
--- Returns the squared distance of 2 vectors, this is faster Vector:getDistance as calculating the square root is an expensive process.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistanceSqr ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):DistToSqr( unwrap( v ) )
end
--- Dot product is the cosine of the angle between both vectors multiplied by their lengths. A.B = ||A||||B||cosA.
-- @param v Second Vector
-- @return Number
function vec_methods:dot ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Dot( unwrap( v ) )
end
--- Returns a new vector with the same direction by length of 1.
-- @return Vector Normalised
function vec_methods:getNormalized ()
return wrap( unwrap( self ):GetNormalized() )
end
--- Is this vector and v equal within tolerance t.
-- @param v Second Vector
-- @param t Tolerance number.
-- @return bool True/False.
function vec_methods:isEqualTol ( v, t )
SF.CheckType( v, SF.Types[ "Vector" ] )
SF.CheckType( t, "number" )
return unwrap( self ):IsEqualTol( unwrap( v ), t )
end
--- Are all fields zero.
-- @return bool True/False
function vec_methods:isZero ()
return unwrap( self ):IsZero()
end
--- Get the vector's Length.
-- @return number Length.
function vec_methods:getLength ()
return unwrap( self ):Length()
end
--- Get the vector's length squared ( Saves computation by skipping the square root ).
-- @return number length squared.
function vec_methods:getLengthSqr ()
return unwrap( self ):LengthSqr()
end
--- Returns the length of the vector in two dimensions, without the Z axis.
-- @return number length
function vec_methods:getLength2D ()
return unwrap( self ):Length2D()
end
--- Returns the length squared of the vector in two dimensions, without the Z axis. ( Saves computation by skipping the square root )
-- @return number length squared.
function vec_methods:getLength2DSqr ()
return unwrap( self ):Length2DSqr()
end
--- Scalar Multiplication of the vector. Self-Modifies.
-- @param n Scalar to multiply with.
-- @return nil
function vec_methods:mul ( n )
SF.CheckType( n, "number" )
unwrap( self ):Mul( n )
end
--- Set's all vector fields to 0.
-- @return nil
function vec_methods:setZero ()
unwrap( self ):Zero()
end
--- Normalise the vector, same direction, length 0. Self-Modifies.
-- @return nil
function vec_methods:normalize ()
unwrap( self ):Normalize()
end
--- Rotate the vector by Angle a. Self-Modifies.
-- @param a Angle to rotate by.
-- @return nil.
function vec_methods:rotate ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
unwrap( self ):Rotate( SF.UnwrapObject( a ) )
end
--- Copies the values from the second vector to the first vector. Self-Modifies.
-- @param v Second Vector
-- @return nil
function vec_methods:set ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Set( unwrap( v ) )
end
--- Subtract v from this Vector. Self-Modifies.
-- @param v Second Vector.
-- @return nil
function vec_methods:sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Sub( unwrap( v ) )
end
--- Translates the vectors position into 2D user screen coordinates. Self-Modifies.
-- @return nil
function vec_methods:toScreen ()
return unwrap( self ):ToScreen()
end
--- Returns whenever the given vector is in a box created by the 2 other vectors.
-- @param v1 Vector used to define AABox
-- @param v2 Second Vector to define AABox
-- @return bool True/False.
function vec_methods:withinAABox ( v1, v2 )
SF.CheckType( v1, SF.Types[ "Vector" ] )
SF.CheckType( v2, SF.Types[ "Vector" ] )
return unwrap( self ):WithinAABox( unwrap( v1 ), unwrap( v2 ) )
end
|
SF.Vectors = {}
--- Vector type
-- @shared
local vec_methods, vec_metamethods = SF.Typedef( "Vector" )
local wrap, unwrap = SF.CreateWrapper( vec_metamethods, true, false, debug.getregistry().Vector )
SF.DefaultEnvironment.Vector = function ( ... )
return wrap( Vector( ... ) )
end
SF.Vectors.Wrap = wrap
SF.Vectors.Unwrap = unwrap
SF.Vectors.Methods = vec_methods
SF.Vectors.Metatable = vec_metamethods
--- __newindex metamethod
function vec_metamethods.__newindex ( t, k, v )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
end
elseif k == "x" or k =="y" or k == "z" then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
else
rawset( t, k, v )
end
end
local _p = vec_metamethods.__index
--- __index metamethod
function vec_metamethods.__index ( t, k )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
return unwrap( t )[ k ]
end
else
if k == "x" or k =="y" or k == "z" then
return unwrap( t )[ k ]
end
end
return _p[ k ]
end
--- tostring metamethod
-- @return string representing the vector.
function vec_metamethods:__tostring ()
return unwrap( self ):__tostring()
end
--- multiplication metamethod
-- @param n Scalar to multiply against vector
-- @return Scaled vector.
function vec_metamethods:__mul ( n )
SF.CheckType( n, "number" )
return wrap( unwrap( self ):__mul( n ) )
end
--- division metamethod
-- @param n Scalar to divide the Vector by
-- @return Scaled vector.
function vec_metamethods:__div ( n )
SF.CheckType( n, "number" )
return SF.WrapObject( unwrap( self ):__div( n ) )
end
--- add metamethod
-- @param v Vector to add
-- @return Resultant vector after addition operation.
function vec_metamethods:__add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__add( unwrap( v ) ) )
end
--- sub metamethod
-- @param v Vector to subtract
-- @return Resultant vector after subtraction operation.
function vec_metamethods:__sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__sub( unwrap( v ) ) )
end
--- unary minus metamethod
-- @returns negated vector.
function vec_metamethods:__unm ()
return wrap( unwrap( self ):__unm() )
end
--- equivalence metamethod
-- @returns bool if both sides are equal.
function vec_metamethods:__eq ( ... )
return SF.Sanitize( unwrap( self ):__eq( SF.Unsanitize( ... ) ) )
end
--- Add vector - Modifies self.
-- @param v Vector to add
-- @return nil
function vec_methods:add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Add( unwrap( v ) )
end
--- Get the vector's angle.
-- @return Angle
function vec_methods:getAngle ()
return SF.WrapObject( unwrap( self ):Angle() )
end
--- Returns the Angle between two vectors.
-- @param v Second Vector
-- @return Angle
function vec_methods:getAngleEx ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return SF.WrapObject( unwrap( self ):AngleEx( unwrap( v ) ) )
end
--- Calculates the cross product of the 2 vectors, creates a unique perpendicular vector to both input vectors.
-- @param v Second Vector
-- @return Vector
function vec_methods:cross ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):Cross( unwrap( v ) ) )
end
--- Returns the pythagorean distance between the vector and the other vector.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistance ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Distance( unwrap( v ) )
end
--- Returns the squared distance of 2 vectors, this is faster Vector:getDistance as calculating the square root is an expensive process.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistanceSqr ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):DistToSqr( unwrap( v ) )
end
--- Dot product is the cosine of the angle between both vectors multiplied by their lengths. A.B = ||A||||B||cosA.
-- @param v Second Vector
-- @return Number
function vec_methods:dot ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Dot( unwrap( v ) )
end
--- Returns a new vector with the same direction by length of 1.
-- @return Vector Normalised
function vec_methods:getNormalized ()
return wrap( unwrap( self ):GetNormalized() )
end
--- Is this vector and v equal within tolerance t.
-- @param v Second Vector
-- @param t Tolerance number.
-- @return bool True/False.
function vec_methods:isEqualTol ( v, t )
SF.CheckType( v, SF.Types[ "Vector" ] )
SF.CheckType( t, "number" )
return unwrap( self ):IsEqualTol( unwrap( v ), t )
end
--- Are all fields zero.
-- @return bool True/False
function vec_methods:isZero ()
return unwrap( self ):IsZero()
end
--- Get the vector's Length.
-- @return number Length.
function vec_methods:getLength ()
return unwrap( self ):Length()
end
--- Get the vector's length squared ( Saves computation by skipping the square root ).
-- @return number length squared.
function vec_methods:getLengthSqr ()
return unwrap( self ):LengthSqr()
end
--- Returns the length of the vector in two dimensions, without the Z axis.
-- @return number length
function vec_methods:getLength2D ()
return unwrap( self ):Length2D()
end
--- Returns the length squared of the vector in two dimensions, without the Z axis. ( Saves computation by skipping the square root )
-- @return number length squared.
function vec_methods:getLength2DSqr ()
return unwrap( self ):Length2DSqr()
end
--- Scalar Multiplication of the vector. Self-Modifies.
-- @param n Scalar to multiply with.
-- @return nil
function vec_methods:mul ( n )
SF.CheckType( n, "number" )
unwrap( self ):Mul( n )
end
--- Set's all vector fields to 0.
-- @return nil
function vec_methods:setZero ()
unwrap( self ):Zero()
end
--- Normalise the vector, same direction, length 0. Self-Modifies.
-- @return nil
function vec_methods:normalize ()
unwrap( self ):Normalize()
end
--- Rotate the vector by Angle a. Self-Modifies.
-- @param a Angle to rotate by.
-- @return nil.
function vec_methods:rotate ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
unwrap( self ):Rotate( SF.UnwrapObject( a ) )
end
--- Copies the values from the second vector to the first vector. Self-Modifies.
-- @param v Second Vector
-- @return nil
function vec_methods:set ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Set( unwrap( v ) )
end
--- Subtract v from this Vector. Self-Modifies.
-- @param v Second Vector.
-- @return nil
function vec_methods:sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Sub( unwrap( v ) )
end
--- Translates the vectors position into 2D user screen coordinates. Self-Modifies.
-- @return nil
function vec_methods:toScreen ()
return unwrap( self ):ToScreen()
end
--- Returns whenever the given vector is in a box created by the 2 other vectors.
-- @param v1 Vector used to define AABox
-- @param v2 Second Vector to define AABox
-- @return bool True/False.
function vec_methods:withinAABox ( v1, v2 )
SF.CheckType( v1, SF.Types[ "Vector" ] )
SF.CheckType( v2, SF.Types[ "Vector" ] )
return unwrap( self ):WithinAABox( unwrap( v1 ), unwrap( v2 ) )
end
|
Added v / n. __div metamethod to vectors.
|
Added v / n. __div metamethod to vectors.
Fixes #216
|
Lua
|
bsd-3-clause
|
Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall
|
c5535717e3a8081dbbd39a57c6845a9b04b0d863
|
deps/process.lua
|
deps/process.lua
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/process"
version = "2.1.1"
dependencies = {
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
}
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/process.lua"
description = "Node-style global process table for luvit"
tags = {"luvit", "process"}
]]
local env = require('env')
local hooks = require('hooks')
local os = require('os')
local timer = require('timer')
local utils = require('utils')
local uv = require('uv')
local Emitter = require('core').Emitter
local Readable = require('stream').Readable
local Writable = require('stream').Writable
local pp = require('pretty-print')
local function nextTick(...)
timer.setImmediate(...)
end
local function cwd()
return uv.cwd()
end
local lenv = {}
function lenv.get(key)
return lenv[key]
end
function lenv.iterate()
local keys = env.keys()
local index = 0
return function(...)
index = index + 1
local name = keys[index]
if name then
return name, env.get(name)
end
end, keys, nil
end
setmetatable(lenv, {
__pairs = lenv.iterate,
__index = function(table, key)
return env.get(key)
end,
__newindex = function(table, key, value)
if value then
env.set(key, value, 1)
else
env.unset(key)
end
end
})
local function kill(pid, signal)
uv.kill(pid, signal or 'sigterm')
end
local signalWraps = {}
local function on(self, _type, listener)
if _type == "error" or _type == "uncaughtException" or _type == "exit" then
Emitter.on(self, _type, listener)
else
if not signalWraps[_type] then
local signal = uv.new_signal()
signalWraps[_type] = signal
uv.unref(signal)
uv.signal_start(signal, _type, function() self:emit(_type) end)
end
Emitter.on(self, _type, listener)
end
end
local function removeListener(self, _type, listener)
local signal = signalWraps[_type]
if not signal then return end
signal:stop()
uv.close(signal)
signalWraps[_type] = nil
Emitter.removeListener(self, _type, listener)
end
local function exit(self, code)
local left = 2
code = code or 0
local function onFinish()
left = left - 1
if left > 0 then return end
self:emit('exit', code)
os.exit(code)
end
process.stdout:once('finish', onFinish)
process.stdout:_end()
process.stderr:once('finish', onFinish)
process.stderr:_end()
end
-- Returns the memory usage of the current process in bytes
-- in the form of a table with the structure:
-- { rss = value, heapUsed = value }
-- where rss is the resident set size for the current process,
-- and heapUsed is the memory used by the Lua VM
local function memoryUsage(self)
return {
rss = uv.resident_set_memory(),
heapUsed = collectgarbage("count")*1024
}
end
local MICROS_PER_SEC = 1000000
-- Returns the user and system CPU time usage of the current process in microseconds
-- (as a table of the format {user=value, system=value})
-- The result of a previous call to process:cpuUsage() can optionally be passed as
-- an argument to get a diff reading
local function cpuUsage(self, prevValue)
local rusage, err = uv.getrusage()
if not rusage then
return nil, err
end
local user = MICROS_PER_SEC * rusage.utime.sec + rusage.utime.usec
local system = MICROS_PER_SEC * rusage.stime.sec + rusage.stime.usec
if prevValue then
user = user - prevValue.user
system = system - prevValue.system
end
return {user=user, system=system}
end
local UvStreamWritable = Writable:extend()
function UvStreamWritable:initialize(handle)
Writable.initialize(self)
self.handle = handle
end
function UvStreamWritable:_write(data, callback)
uv.write(self.handle, data, callback)
end
local UvStreamReadable = Readable:extend()
function UvStreamReadable:initialize(handle)
Readable.initialize(self, { highWaterMark = 0 })
self._readableState.reading = false
self.reading = false
self.handle = handle
self:on('pause', utils.bind(self._onPause, self))
end
function UvStreamReadable:_onPause()
self._readableState.reading = false
self.reading = false
uv.read_stop(self.handle)
end
function UvStreamReadable:_read(n)
local function onRead(err, data)
if err then
return self:emit('error', err)
end
self:push(data)
end
if not uv.is_active(self.handle) then
self.reading = true
uv.read_start(self.handle, onRead)
end
end
local function globalProcess()
local process = Emitter:new()
process.argv = args
process.exitCode = 0
process.nextTick = nextTick
process.env = lenv
process.cwd = cwd
process.kill = kill
process.pid = uv.getpid()
process.on = on
process.exit = exit
process.memoryUsage = memoryUsage
process.cpuUsage = cpuUsage
process.removeListener = removeListener
process.stdin = UvStreamReadable:new(pp.stdin)
process.stdout = UvStreamWritable:new(pp.stdout)
process.stderr = UvStreamWritable:new(pp.stderr)
hooks:on('process.exit', utils.bind(process.emit, process, 'exit'))
hooks:on('process.uncaughtException', utils.bind(process.emit, process, 'uncaughtException'))
return process
end
return { globalProcess = globalProcess }
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/process"
version = "2.1.1"
dependencies = {
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
"luvit/[email protected]",
}
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/process.lua"
description = "Node-style global process table for luvit"
tags = {"luvit", "process"}
]]
local env = require('env')
local hooks = require('hooks')
local os = require('os')
local timer = require('timer')
local utils = require('utils')
local uv = require('uv')
local Emitter = require('core').Emitter
local Readable = require('stream').Readable
local Writable = require('stream').Writable
local pp = require('pretty-print')
local function nextTick(...)
timer.setImmediate(...)
end
local function cwd()
return uv.cwd()
end
local lenv = {}
function lenv.get(key)
return lenv[key]
end
function lenv.iterate()
local keys = env.keys()
local index = 0
return function(...)
index = index + 1
local name = keys[index]
if name then
return name, env.get(name)
end
end, keys, nil
end
setmetatable(lenv, {
__pairs = lenv.iterate,
__index = function(table, key)
return env.get(key)
end,
__newindex = function(table, key, value)
if value then
env.set(key, value, 1)
else
env.unset(key)
end
end
})
local function kill(pid, signal)
uv.kill(pid, signal or 'sigterm')
end
local signalWraps = {}
local function on(self, _type, listener)
if _type == "error" or _type == "uncaughtException" or _type == "exit" then
Emitter.on(self, _type, listener)
else
if not signalWraps[_type] then
local signal = uv.new_signal()
signalWraps[_type] = signal
uv.unref(signal)
uv.signal_start(signal, _type, function() self:emit(_type) end)
end
Emitter.on(self, _type, listener)
end
end
local function removeListener(self, _type, listener)
local signal = signalWraps[_type]
if not signal then return end
signal:stop()
uv.close(signal)
signalWraps[_type] = nil
Emitter.removeListener(self, _type, listener)
end
local function exit(self, code)
local left = 2
code = code or 0
local function onFinish()
left = left - 1
if left > 0 then return end
self:emit('exit', code)
os.exit(code)
end
process.stdout:once('finish', onFinish)
process.stdout:_end()
process.stderr:once('finish', onFinish)
process.stderr:_end()
end
-- Returns the memory usage of the current process in bytes
-- in the form of a table with the structure:
-- { rss = value, heapUsed = value }
-- where rss is the resident set size for the current process,
-- and heapUsed is the memory used by the Lua VM
local function memoryUsage(self)
return {
rss = uv.resident_set_memory(),
heapUsed = collectgarbage("count")*1024
}
end
local MICROS_PER_SEC = 1000000
-- Returns the user and system CPU time usage of the current process in microseconds
-- (as a table of the format {user=value, system=value})
-- The result of a previous call to process:cpuUsage() can optionally be passed as
-- an argument to get a diff reading
local function cpuUsage(self, prevValue)
local rusage, err = uv.getrusage()
if not rusage then
return nil, err
end
local user = MICROS_PER_SEC * rusage.utime.sec + rusage.utime.usec
local system = MICROS_PER_SEC * rusage.stime.sec + rusage.stime.usec
if prevValue then
user = user - prevValue.user
system = system - prevValue.system
end
return {user=user, system=system}
end
local UvStreamWritable = Writable:extend()
function UvStreamWritable:initialize(handle)
Writable.initialize(self)
self.handle = handle
end
function UvStreamWritable:_write(data, callback)
uv.write(self.handle, data, callback)
end
local UvStreamReadable = Readable:extend()
function UvStreamReadable:initialize(handle)
Readable.initialize(self, { highWaterMark = 0 })
self._readableState.reading = false
self.reading = false
self.handle = handle
self:on('pause', utils.bind(self._onPause, self))
end
function UvStreamReadable:_onPause()
self._readableState.reading = false
self.reading = false
uv.read_stop(self.handle)
end
function UvStreamReadable:_read(n)
local function onRead(err, data)
if err then
return self:emit('error', err)
end
self:push(data)
end
if not uv.is_active(self.handle) then
self.reading = true
uv.read_start(self.handle, onRead)
end
end
local function globalProcess()
local process = Emitter:new()
process.argv = args
process.exitCode = 0
process.nextTick = nextTick
process.env = lenv
process.cwd = cwd
process.kill = kill
process.pid = uv.getpid()
process.on = on
process.exit = exit
process.memoryUsage = memoryUsage
process.cpuUsage = cpuUsage
process.removeListener = removeListener
if uv.guess_handle(0) ~= "file" then
process.stdin = UvStreamReadable:new(pp.stdin)
else
-- special case for 'file' stdin handle to avoid aborting from
-- reading from a pipe to a file descriptor
-- see https://github.com/luvit/luvit/issues/1094
process.stdin = require('fs').ReadStream:new(nil, {fd=0})
end
process.stdout = UvStreamWritable:new(pp.stdout)
process.stderr = UvStreamWritable:new(pp.stderr)
hooks:on('process.exit', utils.bind(process.emit, process, 'exit'))
hooks:on('process.uncaughtException', utils.bind(process.emit, process, 'uncaughtException'))
return process
end
return { globalProcess = globalProcess }
|
Fix process.stdin abort when stdin is redirected from a file
|
Fix process.stdin abort when stdin is redirected from a file
This is a hacky band-aid fix that should be replaced with a more comprehensive solution, see https://github.com/luvit/luvit/issues/1094
This only 'fixes' process.stdin, but utils.stdin and pretty-print.stdin will still abort if they are attempted to be read from when stdin is a file.
This does fix the example code in https://github.com/luvit/luvit/issues/1023, though
|
Lua
|
apache-2.0
|
zhaozg/luvit,luvit/luvit,zhaozg/luvit,luvit/luvit
|
171744c989e81edb2cf2676914e75c38854a3e81
|
packages/lime-webui/src/model/essentials.lua
|
packages/lime-webui/src/model/essentials.lua
|
--[[
Copyright (C) 2011 Fundacio Privada per a la Xarxa Oberta, Lliure i Neutral guifi.net
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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
m = Map("lime", "Libre-Mesh")
-- Create sections
local system = m:section(NamedSection, "system", "lime","System","System")
system.addremove = true
local network = m:section(NamedSection, "network", "lime","Network","Network")
network.addremove = true
local wifi = m:section(TypedSection, "wifi","WiFi","WiFi")
wifi.addremove = true
-- hostname
system:option(Value,"hostname",translate("Hostname"),translate("Name for this node"))
-- network
network:option(Value,"main_ipv4",translate("Main IPv4"),translate("The main IPv4 configured for this node"))
network:option(Value,"main_ipv6",translate("Main IPv6"),translate("The main IPv6 configured for this node"))
-- wifi
wifi:option(Value,"public_essid",translate("Public SSID"),translate("The SSID (WiFi network name) used for this node"))
wifi:option(Value,"channel",translate("Channel"),translate("Channel used for this interface"))
wifi:option(Value,"ap_essid",translate("AP SSID"),translate("The SSID (WiFi network name) used for the access point devices"))
wifi:option(Value,"adhoc_essid",translate("Mesh SSID"),translate("The SSID (WiFi network name) used for the ad-hoc device"))
wifi:option(Value,"adhoc_bssid",translate("Mesh BSSID"),translate("The BSSID (WiFi network identifier) used for the ad-hoc network"))
-- commit
function m.on_commit(self,map)
luci.sys.call('true')
end
return m
|
--[[
Copyright (C) 2011 Fundacio Privada per a la Xarxa Oberta, Lliure i Neutral guifi.net
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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
m = Map("lime", "Libre-Mesh")
-- Create sections
local system = m:section(NamedSection, "system", "lime","System","System")
system.addremove = true
local network = m:section(NamedSection, "network", "lime","Network","Network")
network.addremove = true
local wifi = m:section(TypedSection, "wifi","WiFi","WiFi")
wifi.addremove = true
-- hostname
system:option(Value,"hostname",translate("Hostname"),translate("Name for this node"))
-- network
network:option(Value,"main_ipv4_address",translate("Main IPv4"),translate("The main IPv4 configured for this node, with slash notation (for ex. 1.2.3.4/24)"))
network:option(Value,"main_ipv6_address",translate("Main IPv6"),translate("The main IPv6 configured for this node, with slash notation (for ex. 2001:db8::1/64)"))
-- wifi
wifi:option(Value,"public_essid",translate("Public SSID"),translate("The SSID (WiFi network name) used for this node"))
wifi:option(Value,"channel",translate("Channel"),translate("Channel used for this interface"))
wifi:option(Value,"ap_essid",translate("AP SSID"),translate("The SSID (WiFi network name) used for the access point devices"))
wifi:option(Value,"adhoc_essid",translate("Mesh SSID"),translate("The SSID (WiFi network name) used for the ad-hoc device"))
wifi:option(Value,"adhoc_bssid",translate("Mesh BSSID"),translate("The BSSID (WiFi network identifier) used for the ad-hoc network"))
-- commit
function m.on_commit(self,map)
luci.sys.call('true')
end
return m
|
lime-webui: fix uci name for lime.network.main_ipv[46] -> _address
|
lime-webui: fix uci name for lime.network.main_ipv[46] -> _address
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages
|
bf7529f939ae793dc7d64e87af85e582f09eec42
|
core/componentmanager.lua
|
core/componentmanager.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 prosody = _G.prosody;
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local modulemanager = require "core.modulemanager";
local jid_split = require "util.jid".split;
local fire_event = require "core.eventmanager".fire_event;
local events_new = require "util.events".new;
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 = {};
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
origin.send(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] = create_component(host);
hosts[host].connected = false;
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
fire_event("component-activated", host, host_config);
log("debug", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
if prosody and prosody.events then
prosody.events.add_handler("server-starting", load_enabled_components);
end
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if host then
if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
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: "..tostring(stanza));
default_component_handler(origin, stanza);
end
end
function create_component(host, component, events)
-- TODO check for host well-formedness
local ssl_ctx;
if host then
-- We need to find SSL context to use...
-- Discussion in prosody@ concluded that
-- 1 level back is usually enough by default
local base_host = host:gsub("^[^%.]+%.", "");
if hosts[base_host] then
ssl_ctx = hosts[base_host].ssl_ctx;
end
end
return { type = "component", host = host, connected = true, s2sout = {},
ssl_ctx = ssl_ctx, events = events or events_new() };
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
local old_events = hosts[host] and hosts[host].events;
components[host] = component;
hosts[host] = session or create_component(host, component, old_events);
-- Add events object if not already one
if not hosts[host].events then
hosts[host].events = old_events or events_new();
end
-- 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
modulemanager.load(host, "dialback");
modulemanager.load(host, "tls");
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, "tls");
modulemanager.unload(host, "dialback");
hosts[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
function get_children(host)
return disco_items:get(host) or NULL;
end
return _M;
|
-- 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 prosody = _G.prosody;
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local modulemanager = require "core.modulemanager";
local jid_split = require "util.jid".split;
local fire_event = require "core.eventmanager".fire_event;
local events_new = require "util.events".new;
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 = {};
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
origin.send(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] = create_component(host);
hosts[host].connected = false;
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
fire_event("component-activated", host, host_config);
log("debug", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
if prosody and prosody.events then
prosody.events.add_handler("server-starting", load_enabled_components);
end
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if host then
if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
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: "..tostring(stanza));
default_component_handler(origin, stanza);
end
end
function create_component(host, component, events)
-- TODO check for host well-formedness
local ssl_ctx;
if host then
-- We need to find SSL context to use...
-- Discussion in prosody@ concluded that
-- 1 level back is usually enough by default
local base_host = host:gsub("^[^%.]+%.", "");
if hosts[base_host] then
ssl_ctx = hosts[base_host].ssl_ctx;
end
end
return { type = "component", host = host, connected = true, s2sout = {},
ssl_ctx = ssl_ctx, events = events or events_new() };
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
local old_events = hosts[host] and hosts[host].events;
components[host] = component;
hosts[host] = session or create_component(host, component, old_events);
-- Add events object if not already one
if not hosts[host].events then
hosts[host].events = old_events or events_new();
end
-- 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
modulemanager.load(host, "dialback");
modulemanager.load(host, "tls");
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, "tls");
modulemanager.unload(host, "dialback");
hosts[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; -- FIXME do proper unload of all modules and other cleanup before removing
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
function get_children(host)
return disco_items:get(host) or NULL;
end
return _M;
|
componentmanager: Added a FIXME comment.
|
componentmanager: Added a FIXME comment.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
38747256c0d140236a38280ba97415e7400afe6d
|
src/lua-factory/sources/grl-metrolyrics.lua
|
src/lua-factory/sources/grl-metrolyrics.lua
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[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
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, "fetch_page_cb", netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>'
local noise_array = {
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[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
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, "fetch_page_cb", netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
metrolyrics: fix source by removing noise
|
metrolyrics: fix source by removing noise
Some changes in the metrolyrics website included more html noise in the
lyrics.
https://bugzilla.gnome.org/show_bug.cgi?id=754275
|
Lua
|
lgpl-2.1
|
MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins
|
41d5eb5a80aa784666b3892c3dd2241e6b46b2d8
|
viewlog.lua
|
viewlog.lua
|
local lgi = require('lgi')
local Gio = lgi.require('Gio')
local GLib = lgi.require('GLib')
hexchat.register("viewlog", "1.2.0", "Open log file for the current context")
--[=[
We would like to use Gio.AppInfo.get_recommended_for_type("text/plain"),
but it doesn't work (on Windows).
Gio.AppInfo.launch_default_for_uri also launches notepad on Windows, so no help.
Instead, we require the user
to provide a program (and arguments).
The first `nil` occurance
will be replaced with the logfile path.
Note that on Windows,
"notepad.exe" can not handle LF line breaks,
which Hexchats writes in recent versions.
Example:
local DEFAULT_PROGRAM = {[[e:\Program Files\Sublime Text 3\sublime_text.exe]]}
]=]
local DEFAULT_PROGRAM = {"subl"} -- MODIFY THIS --
---------------------------------------------------------------------------------------------------
-- Relies on window pointer implementation to determine whether we're on Windows or not
-- (instead of using ffi.os, which is not available in vanilla lua).
local is_windows = hexchat.get_info('win_ptr') ~= hexchat.get_info('gtkwin_ptr')
-- util.c:rfc_strlower -> -- util.h:rfc_tolower -> util.c:rfc_tolowertab
-- https://github.com/hexchat/hexchat/blob/c79ce843f495b913ddafa383e6cf818ac99b4f15/src/common/util.c#L1079-L1081
local function rfc_strlower(str)
-- almost according to rfc2812,
-- except for ^ -> ~ (should be ~ -> ^)
-- https://tools.ietf.org/html/rfc2812
return str:gsub("[A-Z%[%]\\^]", function (letter)
return string.char(letter:byte() + 0x20)
end)
end
-- text.c:log_create_filename
local function log_create_filename(channame)
if not channame then
return channame
elseif is_windows then
return channame:gsub('[\\|/><:"*?]', "_")
else
return rfc_strlower(channame)
end
end
-- text.c:log_create_pathname
local function log_create_pathname(ctx)
local network = log_create_filename(ctx:get_info('network')) or "NETWORK"
local server = log_create_filename(ctx:get_info('server'))
local channel = log_create_filename(ctx:get_info('channel'))
-- print(("n: %s, s: %s, c: %s"):format(network, server, channel))
if not server then
return nil
end
if server and hexchat.nickcmp(channel, server) == 0 then
channel = 'server';
end
local logmask = hexchat.prefs['irc_logmask']
local fname = logmask
-- substitute variables after strftime expansion
fname = fname:gsub("%%([scn])", "\001%1")
fname = os.date(fname) -- strftime
-- text.c:log_insert_vars & text.c:log_escape_strcpy
-- parentheses are required because gsub returns two values
fname = fname:gsub("\001n", (network:gsub("%%", "%%%%")))
fname = fname:gsub("\001s", (server:gsub("%%", "%%%%")))
fname = fname:gsub("\001c", (channel:gsub("%%", "%%%%")))
-- Calling GLib.filename_from_utf8 crashes on Windows
-- (https://github.com/hexchat/hexchat/issues/1824)
-- local config_dir = GLib.filename_from_utf8(hexchat.get_info('configdir'), -1)
-- local log_path = GLib.build_filenamev({config_dir, GLib.filename_from_utf8("logs", -1)})
local log_path = GLib.build_filenamev({hexchat.get_info('configdir'), "logs"})
return Gio.File.new_for_commandline_arg_and_cwd(fname, log_path)
end
function subprocess(cmd)
local launcher = Gio.SubprocessLauncher.new(0) -- Gio.SubprocessFlags.STDOUT_SILENCE
return launcher:spawnv(cmd)
end
local function viewlog_cb(word, word_eol)
local program
if #word > 1 then
program = {word_eol[2]} -- TODO what about arguments?
else
program = DEFAULT_PROGRAM
end
if not type(program) == 'table' or #program == 0 then
hexchat.command('GUI MSGBOX "You need to specify a program to launch in the source code."')
return hexchat.EAT_ALL
end
local logfile = log_create_pathname(hexchat.get_context())
if logfile == nil then
return hexchat.EAT_ALL
end
-- Build cmd and replace first 'nil' in program.
-- This will end up appending if there is no nil in the middle.
local cmd = program
for i = 1, #program + 1 do
if cmd[i] == nil then
cmd[i] = logfile:get_path()
break
end
end
if logfile:query_exists() then
if subprocess(cmd) == nil then
hexchat.command('GUI MSGBOX "Unable to launch program."')
end
else
hexchat.command(('GUI MSGBOX "Log file for the current channel/dialog does not seem to '
.. 'exist.\n\n""%s""')
:format(logfile:get_path()))
end
return hexchat.EAT_ALL
end
hexchat.hook_command("viewlog", viewlog_cb,
"Usage: /viewlog [program] - Open log file of the current context in "
.. "'program' (path to executable). \n"
.. "You should set a program (and arguments) in the script's source code.")
|
local lgi = require('lgi')
local Gio = lgi.require('Gio')
local GLib = lgi.require('GLib')
hexchat.register("viewlog", "1.2.1", "Open log file for the current context")
--[=[
We would like to use Gio.AppInfo.get_recommended_for_type("text/plain"),
but it doesn't work (on Windows).
Gio.AppInfo.launch_default_for_uri also launches notepad on Windows, so no help.
Instead, we require the user
to provide a program (and arguments).
The first `nil` occurance
will be replaced with the logfile path.
Note that on Windows,
"notepad.exe" can not handle LF line breaks,
which Hexchats writes in recent versions.
Example:
local DEFAULT_PROGRAM = {[[e:\Program Files\Sublime Text 3\sublime_text.exe]]}
]=]
local DEFAULT_PROGRAM = {"subl"} -- MODIFY THIS --
---------------------------------------------------------------------------------------------------
-- Relies on window pointer implementation to determine whether we're on Windows or not
-- (instead of using ffi.os, which is not available in vanilla lua).
local is_windows = hexchat.get_info('win_ptr') ~= hexchat.get_info('gtkwin_ptr')
-- util.c:rfc_strlower -> -- util.h:rfc_tolower -> util.c:rfc_tolowertab
-- https://github.com/hexchat/hexchat/blob/c79ce843f495b913ddafa383e6cf818ac99b4f15/src/common/util.c#L1079-L1081
local function rfc_strlower(str)
-- almost according to rfc2812,
-- except for ^ -> ~ (should be ~ -> ^)
-- https://tools.ietf.org/html/rfc2812
return str:gsub("[A-Z%[%]\\^]", function (letter)
return string.char(letter:byte() + 0x20)
end)
end
-- text.c:log_create_filename
local function log_create_filename(channame)
if not channame then
return channame
elseif is_windows then
return channame:gsub('[\\|/><:"*?]', "_")
else
channame = channame:gsub('/', "_")
return rfc_strlower(channame)
end
end
-- text.c:log_create_pathname
local function log_create_pathname(ctx)
local network = log_create_filename(ctx:get_info('network')) or "NETWORK"
local server = log_create_filename(ctx:get_info('server'))
local channel = log_create_filename(ctx:get_info('channel'))
-- print(("n: %s, s: %s, c: %s"):format(network, server, channel))
if not server then
return nil
end
if server and hexchat.nickcmp(channel, server) == 0 then
channel = 'server';
end
local logmask = hexchat.prefs['irc_logmask']
local fname = logmask
-- substitute variables after strftime expansion
fname = fname:gsub("%%([scn])", "\001%1")
fname = os.date(fname) -- strftime
-- text.c:log_insert_vars & text.c:log_escape_strcpy
-- parentheses are required because gsub returns two values
fname = fname:gsub("\001n", (network:gsub("%%", "%%%%")))
fname = fname:gsub("\001s", (server:gsub("%%", "%%%%")))
fname = fname:gsub("\001c", (channel:gsub("%%", "%%%%")))
-- Calling GLib.filename_from_utf8 crashes on Windows
-- (https://github.com/hexchat/hexchat/issues/1824)
-- local config_dir = GLib.filename_from_utf8(hexchat.get_info('configdir'), -1)
-- local log_path = GLib.build_filenamev({config_dir, GLib.filename_from_utf8("logs", -1)})
local log_path = GLib.build_filenamev({hexchat.get_info('configdir'), "logs"})
return Gio.File.new_for_commandline_arg_and_cwd(fname, log_path)
end
function subprocess(cmd)
local launcher = Gio.SubprocessLauncher.new(0) -- Gio.SubprocessFlags.STDOUT_SILENCE
return launcher:spawnv(cmd)
end
local function viewlog_cb(word, word_eol)
local program
if #word > 1 then
program = {word_eol[2]} -- TODO what about arguments?
else
program = DEFAULT_PROGRAM
end
if not type(program) == 'table' or #program == 0 then
hexchat.command('GUI MSGBOX "You need to specify a program to launch in the source code."')
return hexchat.EAT_ALL
end
local logfile = log_create_pathname(hexchat.get_context())
if logfile == nil then
return hexchat.EAT_ALL
end
-- Build cmd and replace first 'nil' in program.
-- This will end up appending if there is no nil in the middle.
local cmd = program
for i = 1, #program + 1 do
if cmd[i] == nil then
cmd[i] = logfile:get_path()
break
end
end
if logfile:query_exists() then
if subprocess(cmd) == nil then
hexchat.command('GUI MSGBOX "Unable to launch program."')
end
else
hexchat.command(('GUI MSGBOX "Log file for the current channel/dialog does not seem to '
.. 'exist.\n\n""%s""')
:format(logfile:get_path()))
end
return hexchat.EAT_ALL
end
hexchat.hook_command("viewlog", viewlog_cb,
"Usage: /viewlog [program] - Open log file of the current context in "
.. "'program' (path to executable). \n"
.. "You should set a program (and arguments) in the script's source code.")
|
Fix forward slashes in channel names
|
Fix forward slashes in channel names
|
Lua
|
mit
|
FichteFoll/hexchat-addons
|
cca08620c18593c58a149cc187d28b65e4c9b27e
|
agents/monitoring/lua/lib/info.lua
|
agents/monitoring/lua/lib/info.lua
|
local Object = require('core').Object
local JSON = require('json')
--[[ Info ]]--
local Info = Object:extend()
function Info:initialize()
self._s = sigar:new()
self._params = {}
end
function Info:serialize()
return {
jsonPayload = JSON.stringify(self._params)
}
end
local NilInfo = Info:extend()
--[[ CPUInfo ]]--
local CPUInfo = Info:extend()
function CPUInfo:initialize()
Info.initialize(self)
local cpus = self._s:cpus()
self._params = {}
for i=1, #cpus do
local info = cpus[i]:info()
local data = cpus[i]:data()
local bucket = 'cpu.' .. i - 1
self._params[bucket] = {}
for k, v in pairs(info) do
self._params[bucket][k] = v
end
for k, v in pairs(data) do
self._params[bucket][k] = v
end
end
end
--[[ DiskInfo ]]--
local DiskInfo = Info:extend()
function DiskInfo:initialize()
Info.initialize(self)
local disks = self._s:disks()
local name, usage
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
self._params[name] = {}
for key, value in pairs(usage) do
self._params[name][key] = value
end
end
end
end
--[[ MemoryInfo ]]--
local MemoryInfo = Info:extend()
function MemoryInfo:initialize()
Info.initialize(self)
local meminfo = self._s:mem()
for key, value in pairs(meminfo) do
self._params[key] = value
end
end
--[[ NetworkInfo ]]--
local NetworkInfo = Info:extend()
function NetworkInfo:initialize()
Info.initialize(self)
local netifs = self._s:netifs()
for i=1,#netifs do
self._params.netifs[i] = {}
self._params.netifs[i].info = netifs[i]:info()
self._params.netifs[i].usage = netifs[i]:usage()
end
end
--[[ Factory ]]--
function create(infoType)
if infoType == 'CPU' then
return CPUInfo:new()
elseif infoType == 'MEMORY' then
return MemoryInfo:new()
elseif infoType == 'NETWORK' then
return NetworkInfo:new()
elseif infoType == 'DISK' then
return DiskInfo:new()
end
return NilInfo:new()
end
--[[ Exports ]]--
local info = {}
info.CPUInfo = CPUInfo
info.DiskInfo = DiskInfo
info.MemoryInfo = MemoryInfo
info.NetworkInfo = NetworkInfo
info.create = create
return info
|
local Object = require('core').Object
local JSON = require('json')
--[[ Info ]]--
local Info = Object:extend()
function Info:initialize()
self._s = sigar:new()
self._params = {}
end
function Info:serialize()
return {
jsonPayload = JSON.stringify(self._params)
}
end
local NilInfo = Info:extend()
--[[ CPUInfo ]]--
local CPUInfo = Info:extend()
function CPUInfo:initialize()
Info.initialize(self)
local cpus = self._s:cpus()
self._params = {}
for i=1, #cpus do
local info = cpus[i]:info()
local data = cpus[i]:data()
local bucket = 'cpu.' .. i - 1
self._params[bucket] = {}
for k, v in pairs(info) do
self._params[bucket][k] = v
end
for k, v in pairs(data) do
self._params[bucket][k] = v
end
end
end
--[[ DiskInfo ]]--
local DiskInfo = Info:extend()
function DiskInfo:initialize()
Info.initialize(self)
local disks = self._s:disks()
local name, usage
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
self._params[name] = {}
for key, value in pairs(usage) do
self._params[name][key] = value
end
end
end
end
--[[ MemoryInfo ]]--
local MemoryInfo = Info:extend()
function MemoryInfo:initialize()
Info.initialize(self)
local meminfo = self._s:mem()
for key, value in pairs(meminfo) do
self._params[key] = value
end
end
--[[ NetworkInfo ]]--
local NetworkInfo = Info:extend()
function NetworkInfo:initialize()
Info.initialize(self)
local netifs = self._s:netifs()
for i=1,#netifs do
local info = netifs[i]:info()
local usage = netifs[i]:usage()
local name = info.name
self._params[name] = {}
for k, v in pairs(info) do
self._params[name][k] = v
end
for k, v in pairs(usage) do
self._params[name][k] = v
end
end
end
--[[ Factory ]]--
function create(infoType)
if infoType == 'CPU' then
return CPUInfo:new()
elseif infoType == 'MEMORY' then
return MemoryInfo:new()
elseif infoType == 'NETWORK' then
return NetworkInfo:new()
elseif infoType == 'DISK' then
return DiskInfo:new()
end
return NilInfo:new()
end
--[[ Exports ]]--
local info = {}
info.CPUInfo = CPUInfo
info.DiskInfo = DiskInfo
info.MemoryInfo = MemoryInfo
info.NetworkInfo = NetworkInfo
info.create = create
return info
|
fix network info
|
fix network info
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
302a46e87adaf3459cc0a079cf2b7a39613f494e
|
MMOCoreORB/bin/scripts/object/tangible/lair/base/objective_dantari_monolith.lua
|
MMOCoreORB/bin/scripts/object/tangible/lair/base/objective_dantari_monolith.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program 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; 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_objective_dantari_monolith = object_tangible_lair_base_shared_objective_dantari_monolith:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_base_objective_dantari_monolith, "object/tangible/lair/base/objective_dantari_monolith.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program 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; 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_objective_dantari_monolith = object_tangible_lair_base_shared_objective_dantari_monolith:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
objectName = "@lair_n:dantari_monilith",
}
ObjectTemplates:addTemplate(object_tangible_lair_base_objective_dantari_monolith, "object/tangible/lair/base/objective_dantari_monolith.iff")
|
[Fixed] Displayed name on Dantari totems - mantis 3861/3538
|
[Fixed] Displayed name on Dantari totems - mantis 3861/3538
Change-Id: I070fedf5038775fdf808efb063accc78387e3b7d
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
fb71a1b39bdb4775c310f7682814cb336ab09ee3
|
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
|
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
|
--[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("l_d_d_nd_netdiscover_to_devinfo_descr"))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, false)
return m
|
--[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scans for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, false)
return m
|
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]>
|
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]>
|
Lua
|
apache-2.0
|
artynet/luci,jlopenwrtluci/luci,oyido/luci,bittorf/luci,maxrio/luci981213,tcatm/luci,shangjiyu/luci-with-extra,mumuqz/luci,Sakura-Winkey/LuCI,NeoRaider/luci,MinFu/luci,slayerrensky/luci,marcel-sch/luci,zhaoxx063/luci,harveyhu2012/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,cappiewu/luci,NeoRaider/luci,jorgifumi/luci,Kyklas/luci-proto-hso,maxrio/luci981213,zhaoxx063/luci,slayerrensky/luci,thess/OpenWrt-luci,cappiewu/luci,fkooman/luci,dwmw2/luci,urueedi/luci,marcel-sch/luci,slayerrensky/luci,jlopenwrtluci/luci,nmav/luci,lbthomsen/openwrt-luci,sujeet14108/luci,wongsyrone/luci-1,openwrt/luci,florian-shellfire/luci,hnyman/luci,thess/OpenWrt-luci,ff94315/luci-1,LuttyYang/luci,ff94315/luci-1,NeoRaider/luci,forward619/luci,ff94315/luci-1,teslamint/luci,oneru/luci,Wedmer/luci,nwf/openwrt-luci,MinFu/luci,forward619/luci,tobiaswaldvogel/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,marcel-sch/luci,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,artynet/luci,joaofvieira/luci,tcatm/luci,kuoruan/luci,teslamint/luci,zhaoxx063/luci,obsy/luci,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,cshore/luci,Hostle/openwrt-luci-multi-user,nmav/luci,thess/OpenWrt-luci,thesabbir/luci,david-xiao/luci,maxrio/luci981213,bright-things/ionic-luci,ollie27/openwrt_luci,male-puppies/luci,daofeng2015/luci,jchuang1977/luci-1,bittorf/luci,forward619/luci,tobiaswaldvogel/luci,daofeng2015/luci,jlopenwrtluci/luci,nwf/openwrt-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,981213/luci-1,RuiChen1113/luci,obsy/luci,daofeng2015/luci,aa65535/luci,tcatm/luci,nmav/luci,forward619/luci,david-xiao/luci,palmettos/cnLuCI,wongsyrone/luci-1,harveyhu2012/luci,jlopenwrtluci/luci,Wedmer/luci,marcel-sch/luci,ollie27/openwrt_luci,nmav/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,palmettos/test,Hostle/openwrt-luci-multi-user,obsy/luci,thesabbir/luci,jchuang1977/luci-1,palmettos/test,cshore/luci,oneru/luci,teslamint/luci,ff94315/luci-1,daofeng2015/luci,tcatm/luci,wongsyrone/luci-1,ff94315/luci-1,slayerrensky/luci,MinFu/luci,teslamint/luci,RuiChen1113/luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,bittorf/luci,bright-things/ionic-luci,oneru/luci,florian-shellfire/luci,chris5560/openwrt-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,mumuqz/luci,oyido/luci,dismantl/luci-0.12,nmav/luci,ollie27/openwrt_luci,jlopenwrtluci/luci,zhaoxx063/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,fkooman/luci,opentechinstitute/luci,opentechinstitute/luci,tcatm/luci,cappiewu/luci,mumuqz/luci,harveyhu2012/luci,urueedi/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,mumuqz/luci,male-puppies/luci,sujeet14108/luci,Hostle/luci,jorgifumi/luci,fkooman/luci,joaofvieira/luci,lcf258/openwrtcn,ff94315/luci-1,openwrt-es/openwrt-luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,jchuang1977/luci-1,bittorf/luci,ollie27/openwrt_luci,thesabbir/luci,thess/OpenWrt-luci,jorgifumi/luci,male-puppies/luci,hnyman/luci,jorgifumi/luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,urueedi/luci,zhaoxx063/luci,Noltari/luci,dwmw2/luci,remakeelectric/luci,lcf258/openwrtcn,rogerpueyo/luci,joaofvieira/luci,wongsyrone/luci-1,jlopenwrtluci/luci,wongsyrone/luci-1,fkooman/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,keyidadi/luci,cappiewu/luci,tcatm/luci,kuoruan/luci,schidler/ionic-luci,slayerrensky/luci,mumuqz/luci,Hostle/luci,shangjiyu/luci-with-extra,forward619/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,taiha/luci,dwmw2/luci,thesabbir/luci,981213/luci-1,nmav/luci,male-puppies/luci,bright-things/ionic-luci,openwrt/luci,lcf258/openwrtcn,artynet/luci,remakeelectric/luci,forward619/luci,florian-shellfire/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,nmav/luci,dismantl/luci-0.12,urueedi/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,fkooman/luci,chris5560/openwrt-luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,deepak78/new-luci,rogerpueyo/luci,florian-shellfire/luci,keyidadi/luci,981213/luci-1,schidler/ionic-luci,deepak78/new-luci,MinFu/luci,ff94315/luci-1,ollie27/openwrt_luci,chris5560/openwrt-luci,oneru/luci,dwmw2/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,bittorf/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,kuoruan/luci,openwrt/luci,thess/OpenWrt-luci,Hostle/luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,taiha/luci,artynet/luci,palmettos/cnLuCI,remakeelectric/luci,joaofvieira/luci,remakeelectric/luci,Kyklas/luci-proto-hso,obsy/luci,obsy/luci,MinFu/luci,cshore-firmware/openwrt-luci,teslamint/luci,bittorf/luci,RedSnake64/openwrt-luci-packages,bittorf/luci,artynet/luci,Wedmer/luci,lbthomsen/openwrt-luci,MinFu/luci,lcf258/openwrtcn,Noltari/luci,mumuqz/luci,david-xiao/luci,opentechinstitute/luci,maxrio/luci981213,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,Kyklas/luci-proto-hso,aa65535/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,aa65535/luci,Wedmer/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,tcatm/luci,rogerpueyo/luci,oneru/luci,mumuqz/luci,slayerrensky/luci,palmettos/test,chris5560/openwrt-luci,palmettos/test,RuiChen1113/luci,Hostle/luci,nwf/openwrt-luci,Noltari/luci,joaofvieira/luci,981213/luci-1,Hostle/openwrt-luci-multi-user,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,dwmw2/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,thesabbir/luci,rogerpueyo/luci,florian-shellfire/luci,remakeelectric/luci,aa65535/luci,kuoruan/luci,cshore-firmware/openwrt-luci,palmettos/test,LuttyYang/luci,chris5560/openwrt-luci,openwrt/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,artynet/luci,jchuang1977/luci-1,Hostle/luci,daofeng2015/luci,dismantl/luci-0.12,keyidadi/luci,artynet/luci,jchuang1977/luci-1,hnyman/luci,thess/OpenWrt-luci,taiha/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,ff94315/luci-1,sujeet14108/luci,nwf/openwrt-luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,urueedi/luci,lbthomsen/openwrt-luci,fkooman/luci,joaofvieira/luci,nmav/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,981213/luci-1,deepak78/new-luci,981213/luci-1,cappiewu/luci,Hostle/luci,dismantl/luci-0.12,david-xiao/luci,openwrt/luci,nwf/openwrt-luci,maxrio/luci981213,jorgifumi/luci,sujeet14108/luci,teslamint/luci,cappiewu/luci,taiha/luci,sujeet14108/luci,schidler/ionic-luci,lcf258/openwrtcn,taiha/luci,schidler/ionic-luci,openwrt/luci,joaofvieira/luci,tobiaswaldvogel/luci,dwmw2/luci,dwmw2/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,marcel-sch/luci,Noltari/luci,schidler/ionic-luci,deepak78/new-luci,Hostle/luci,forward619/luci,oyido/luci,florian-shellfire/luci,lcf258/openwrtcn,fkooman/luci,ReclaimYourPrivacy/cloak-luci,cappiewu/luci,remakeelectric/luci,NeoRaider/luci,kuoruan/lede-luci,male-puppies/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,thesabbir/luci,zhaoxx063/luci,keyidadi/luci,schidler/ionic-luci,florian-shellfire/luci,MinFu/luci,rogerpueyo/luci,keyidadi/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,Wedmer/luci,sujeet14108/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,taiha/luci,taiha/luci,sujeet14108/luci,maxrio/luci981213,david-xiao/luci,florian-shellfire/luci,LuttyYang/luci,LuttyYang/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,male-puppies/luci,kuoruan/luci,remakeelectric/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,nmav/luci,male-puppies/luci,oyido/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,cshore/luci,kuoruan/lede-luci,oyido/luci,slayerrensky/luci,Hostle/luci,Noltari/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,NeoRaider/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,remakeelectric/luci,kuoruan/lede-luci,thesabbir/luci,fkooman/luci,RuiChen1113/luci,opentechinstitute/luci,MinFu/luci,opentechinstitute/luci,tcatm/luci,LuttyYang/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,taiha/luci,oneru/luci,NeoRaider/luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,maxrio/luci981213,aa65535/luci,kuoruan/lede-luci,bright-things/ionic-luci,teslamint/luci,nwf/openwrt-luci,keyidadi/luci,Sakura-Winkey/LuCI,deepak78/new-luci,cshore/luci,Noltari/luci,Wedmer/luci,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,kuoruan/lede-luci,joaofvieira/luci,cshore/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,cshore/luci,marcel-sch/luci,cshore/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,mumuqz/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,thess/OpenWrt-luci,RuiChen1113/luci,LuttyYang/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,harveyhu2012/luci,obsy/luci,obsy/luci,palmettos/test,wongsyrone/luci-1,hnyman/luci,RedSnake64/openwrt-luci-packages,keyidadi/luci,male-puppies/luci,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,palmettos/test,NeoRaider/luci,deepak78/new-luci,Noltari/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,zhaoxx063/luci,openwrt-es/openwrt-luci,aa65535/luci,palmettos/cnLuCI,oyido/luci,maxrio/luci981213,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,cshore/luci,deepak78/new-luci,david-xiao/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,jorgifumi/luci,RuiChen1113/luci,palmettos/test,opentechinstitute/luci,dwmw2/luci,nwf/openwrt-luci,opentechinstitute/luci,lcf258/openwrtcn,hnyman/luci,openwrt-es/openwrt-luci,artynet/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,daofeng2015/luci,harveyhu2012/luci,thesabbir/luci,jchuang1977/luci-1,Noltari/luci,bright-things/ionic-luci,forward619/luci,urueedi/luci,oneru/luci,rogerpueyo/luci,oyido/luci,Hostle/openwrt-luci-multi-user
|
dcae5945ac8361f4cfcf348dd12a799a4aa7c5e7
|
src/apenode/models/base_model.lua
|
src/apenode/models/base_model.lua
|
-- Copyright (C) Mashape, Inc.
local rex = require("rex_pcre")
local Object = require "classic"
local BaseModel = Object:extend()
-------------
-- PRIVATE --
-------------
local function add_error(errors, k, v)
if not errors then errors = {} end
if errors[k] then
local list = {}
table.insert(list, errors[k])
table.insert(list, v)
errors[k] = list
else
errors[k] = v
end
return errors
end
-- Validate a table against a given schema
-- @param table schema A model schema to validate the entity against
-- @param table t A given entity to be validated against the schema
-- @param boolean is_update Ignores read_only fields during the validation if true
-- @return A filtered, valid table if success, nil if error
-- @return table A list of encountered errors during the validation
function BaseModel:_validate(schema, t, is_update)
local result = {}
local errors
-- Check the given table against a given schema
for k,v in pairs(schema) do
if not t[k] and v.default ~= nil then -- Set default value for the filed if given
if type(v.default) == "function" then
t[k] = v.default()
else
t[k] = v.default
end
elseif v.required and (t[k] == nil or t[k] == "") then -- Check required field is set
errors = add_error(errors, k, k .. " is required")
elseif t[k] and not is_update and v.read_only then -- Check field is not read only
errors = add_error(errors, k, k .. " is read only")
elseif t[k] and type(t[k]) ~= v.type then -- Check type of the field
errors = add_error(errors, k, k .. " should be a " .. v.type)
elseif v.func then -- Check field against a function
local success, err = v.func(t[k], t, self._dao_factory)
if not success then
errors = add_error(errors, k, err)
end
end
-- Check field against a regex
if t[k] and v.regex then
if not rex.match(t[k], v.regex) then
errors = add_error(errors, k, k .. " has an invalid value")
end
end
-- Check if field's value is unique
if t[k] and v.unique then
local data, err = self._find_one({[k] = t[k]}, self._dao)
if data ~= nil then
errors = add_error(errors, k, k .. " with value " .. "\"" .. t[k] .. "\"" .. " already exists")
end
end
if t[k] and v.type == "table" then
if v.schema_from_func then
local table_schema, err = v.schema_from_func(t)
if not table_schema then
errors = add_error(errors, k, err)
else
local _, table_schema_err = BaseModel:_validate(table_schema, t[k], false)
if table_schema_err then
errors = add_error(errors, k, table_schema_err)
end
end
end
end
result[k] = t[k]
end
-- Check for unexpected fields in the entity
for k,v in pairs(t) do
if not schema[k] then
errors = add_error(errors, k, k .. " is an unknown field")
end
end
if errors then
result = nil
end
return result, errors
end
---------------
-- BaseModel --
---------------
function BaseModel:new(collection, schema, t, dao_factory)
-- The collection needs to be declared before just in case
-- the validator needs it for the "unique" check
self._schema = schema
self._collection = collection
self._dao = dao_factory[collection]
self._dao_factory = dao_factory
-- Populate the new object with the same fields
if not t then t = {} end
for k,v in pairs(t) do
self[k] = t[k]
end
self._t = t
end
function BaseModel:save()
local res, err = self:_validate(self._schema, self._t, false)
if not res then
return nil, err
else
local data, err = self._dao:insert_or_update(self._t)
return data, err
end
end
function BaseModel:delete()
local n_success, err = self._dao:delete_by_id(self._t.id)
return n_success, err
end
function BaseModel:update()
local res, err = self:_validate(self._schema, self._t, true)
if not res then
return nil, err
else
local data, err = self._dao:update(self._t)
return data, err
end
end
function BaseModel._find_one(args, dao)
local data, err = dao:find_one(args)
return data, err
end
function BaseModel._find(args, page, size, dao)
local data, total, err = dao:find(args, page, size)
return data, total, err
end
return BaseModel
|
-- Copyright (C) Mashape, Inc.
local rex = require("rex_pcre")
local Object = require "classic"
local BaseModel = Object:extend()
-------------
-- PRIVATE --
-------------
local function add_error(errors, k, v)
if not errors then errors = {} end
if errors[k] then
local list = {}
table.insert(list, errors[k])
table.insert(list, v)
errors[k] = list
else
errors[k] = v
end
return errors
end
-- Validate a table against a given schema
-- @param table schema A model schema to validate the entity against
-- @param table t A given entity to be validated against the schema
-- @param boolean is_update Ignores read_only fields during the validation if true
-- @return A filtered, valid table if success, nil if error
-- @return table A list of encountered errors during the validation
function BaseModel:_validate(schema, t, is_update)
local result = {}
local errors
-- Check the given table against a given schema
for k,v in pairs(schema) do
if not t[k] and v.default ~= nil then -- Set default value for the filed if given
if type(v.default) == "function" then
t[k] = v.default()
else
t[k] = v.default
end
elseif v.required and (t[k] == nil or t[k] == "") then -- Check required field is set
errors = add_error(errors, k, k .. " is required")
elseif t[k] and not is_update and v.read_only then -- Check field is not read only
errors = add_error(errors, k, k .. " is read only")
elseif t[k] and type(t[k]) ~= v.type then -- Check type of the field
errors = add_error(errors, k, k .. " should be a " .. v.type)
elseif v.func then -- Check field against a function
local success, err = v.func(t[k], t, self._dao_factory)
if not success then
errors = add_error(errors, k, err)
end
end
-- Check field against a regex
if t[k] and v.regex then
if not rex.match(t[k], v.regex) then
errors = add_error(errors, k, k .. " has an invalid value")
end
end
-- Check if field's value is unique
if t[k] and v.unique and not is_update then
local data, err = self._find_one({[k] = t[k]}, self._dao)
if data ~= nil then
errors = add_error(errors, k, k .. " with value " .. "\"" .. t[k] .. "\"" .. " already exists")
end
end
if t[k] and v.type == "table" then
if v.schema_from_func then
local table_schema, err = v.schema_from_func(t)
if not table_schema then
errors = add_error(errors, k, err)
else
local _, table_schema_err = BaseModel:_validate(table_schema, t[k], false)
if table_schema_err then
errors = add_error(errors, k, table_schema_err)
end
end
end
end
result[k] = t[k]
end
-- Check for unexpected fields in the entity
for k,v in pairs(t) do
if not schema[k] then
errors = add_error(errors, k, k .. " is an unknown field")
end
end
if errors then
result = nil
end
return result, errors
end
---------------
-- BaseModel --
---------------
function BaseModel:new(collection, schema, t, dao_factory)
-- The collection needs to be declared before just in case
-- the validator needs it for the "unique" check
self._schema = schema
self._collection = collection
self._dao = dao_factory[collection]
self._dao_factory = dao_factory
-- Populate the new object with the same fields
if not t then t = {} end
for k,v in pairs(t) do
self[k] = t[k]
end
self._t = t
end
function BaseModel:save()
local res, err = self:_validate(self._schema, self._t, false)
if not res then
return nil, err
else
local data, err = self._dao:insert_or_update(self._t)
return data, err
end
end
function BaseModel:delete()
local n_success, err = self._dao:delete_by_id(self._t.id)
return n_success, err
end
function BaseModel:update()
-- Check if there are updated fields
for k,_ in pairs(self._t) do
self._t[k] = self[k]
end
local res, err = self:_validate(self._schema, self._t, true)
if not res then
return nil, err
else
local data, err = self._dao:update(self._t)
return data, err
end
end
function BaseModel._find_one(args, dao)
local data, err = dao:find_one(args)
return data, err
end
function BaseModel._find(args, page, size, dao)
local data, total, err = dao:find(args, page, size)
return data, total, err
end
return BaseModel
|
fixing update
|
fixing update
|
Lua
|
mit
|
vmercierfr/kong,xvaara/kong,Kong/kong,isdom/kong,salazar/kong,Kong/kong,vzaramel/kong,akh00/kong,ropik/kong,streamdataio/kong,paritoshmmmec/kong,ccyphers/kong,chourobin/kong,jebenexer/kong,skynet/kong,li-wl/kong,streamdataio/kong,kyroskoh/kong,Kong/kong,jerizm/kong,Mashape/kong,rafael/kong,icyxp/kong,ejoncas/kong,ind9/kong,Vermeille/kong,ind9/kong,shiprabehera/kong,peterayeni/kong,bbalu/kong,kyroskoh/kong,rafael/kong,ajayk/kong,sbuettner/kong,isdom/kong,ejoncas/kong,Skyscanner/kong,wakermahmud/kong,vzaramel/kong,ChristopherBiscardi/kong,AnsonSmith/kong,smanolache/kong,beauli/kong,puug/kong
|
3f7a06c40351f3ea89d9c943626e94e84bef0cff
|
what-is-missing_0.18.1/async.lua
|
what-is-missing_0.18.1/async.lua
|
local tasks = {}
-- Functions for handling long-running things over a period of time.
Async = {}
Async.__index = Async
local async_tasks = {}
local function add_async_task(task)
for k, existing_task in pairs(async_tasks) do
if existing_task:is_completed() then
async_tasks[k] = task
return
end
end
table.insert(async_tasks, task)
end
function Async:perform_once(loops, perform_function)
local obj = {}
setmetatable(obj, Async)
obj.completions = 0
obj.interval = 1
obj.remaining = 1
obj.loops = loops
obj.loop_counts = table_size(loops)
obj.perform_function = perform_function
obj:restart_loops()
add_async_task(obj)
return obj
end
local function loop_next(loop, current)
if loop.type == "loop" then
if current == nil then
return loop.start, loop.start
elseif current == loop.stop then
return nil, nil
else
return current + 1, current + 1
end
elseif loop.type == "loop_values" then
return next(loop.values, current)
else
error("Unknown loop type: " .. loop.type)
end
end
function Async:loop(name, start, stop)
return { type = "loop", identifier = name, start = start, stop = stop }
end
function Async:loop_values(name, values)
return { type = "loop_values", identifier = name, values = values }
end
function Async:restart_loops()
self.state = {}
self.loops_iterator = nil
self.iterators = {}
for loop_index, loop in pairs(self.loops) do
local loop = self.loops[loop_index]
local it, value = loop_next(loop, nil)
self.iterators[loop_index] = it
self.state[loop.identifier] = value
end
end
function Async:next_iteration()
local loop_index = self.loop_counts
while true do
local loop = self.loops[loop_index]
local it, value = loop_next(loop, self.iterators[loop_index])
self.iterators[loop_index] = it
self.state[loop.identifier] = value
if it == nil then
-- if iterator on loop_index is nil, then the current loop is finished so we must go to the next loop and iterate to the next there
loop_index = loop_index - 1
if loop_index == 0 then
self:finished()
return
end
elseif self.iterators[loop_index] and loop_index == self.loop_counts then
-- if we're on last loop and last loop is not nil, then we're good to go for next perform call.
return
else
loop_index = loop_index + 1
end
end
end
function Async:finished()
self.completions = self.completions + 1
self.remaining = self.remaining - 1
end
function Async:call_perform_function()
log("Call perform with " .. serpent.line(self.state))
self.perform_function(self.state)
end
function Async:tick(tick)
if self.remaining == 0 then
return
end
if tick % self.interval == 0 then
self:call_perform_function()
self:next_iteration()
end
end
function Async:is_completed()
return self.remaining == 0
end
function Async:on_tick()
local tick = game.tick
for k, task in pairs(async_tasks) do
task:tick(tick)
end
if tick % 3600 == 2700 then
-- Cleanup tasks
log("Cleanup async tasks")
for k, task in pairs(async_tasks) do
if task:is_completed() then
log("Cleaned async task " .. k)
async_tasks[k] = nil
end
end
return
end
end
function Async:on_load()
async_tasks = global.async_tasks
end
function Async:on_init()
global.async_tasks = global.async_tasks or {}
async_tasks = global.async_tasks
end
local function async_command_step(event)
local player = game.players[event.player_index]
if event.command == "async_create" then
local loop1 = Async:loop_values("a", {"ONE", "TWO", "THREE"})
local loop2 = Async:loop("b", 1, 2)
local loop3 = Async:loop("c", 1, 3)
local perform = function(state)
game.print(serpent.line(state))
end
local new_async = Async:perform_once({ loop1, loop2, loop3 }, perform)
game.print("Created loop example task")
end
if event.command == "async_test" then
for _, task in pairs(async_tasks) do
task:tick(game.tick)
end
end
if event.command == "async_once" then
end
end
script.on_event(defines.events.on_console_command, async_command_step)
return Async
|
local tasks = {}
-- Functions for handling long-running things over a period of time.
Async = {}
Async.__index = Async
local async_tasks = {}
local function add_async_task(task)
if not async_tasks then
async_tasks = {}
global.async_tasks = async_tasks
end
for k, existing_task in pairs(async_tasks) do
if existing_task:is_completed() then
async_tasks[k] = task
return
end
end
table.insert(async_tasks, task)
end
function Async:perform_once(loops, perform_function)
local obj = {}
setmetatable(obj, Async)
obj.completions = 0
obj.interval = 1
obj.remaining = 1
obj.loops = loops
obj.loop_counts = table_size(loops)
obj.perform_function = perform_function
obj:restart_loops()
add_async_task(obj)
return obj
end
local function loop_next(loop, current)
if loop.type == "loop" then
if current == nil then
return loop.start, loop.start
elseif current == loop.stop then
return nil, nil
else
return current + 1, current + 1
end
elseif loop.type == "loop_values" then
return next(loop.values, current)
else
error("Unknown loop type: " .. loop.type)
end
end
function Async:loop(name, start, stop)
return { type = "loop", identifier = name, start = start, stop = stop }
end
function Async:loop_values(name, values)
return { type = "loop_values", identifier = name, values = values }
end
function Async:restart_loops()
self.state = {}
self.loops_iterator = nil
self.iterators = {}
for loop_index, loop in pairs(self.loops) do
local loop = self.loops[loop_index]
local it, value = loop_next(loop, nil)
self.iterators[loop_index] = it
self.state[loop.identifier] = value
end
end
function Async:next_iteration()
local loop_index = self.loop_counts
while true do
local loop = self.loops[loop_index]
local it, value = loop_next(loop, self.iterators[loop_index])
self.iterators[loop_index] = it
self.state[loop.identifier] = value
if it == nil then
-- if iterator on loop_index is nil, then the current loop is finished so we must go to the next loop and iterate to the next there
loop_index = loop_index - 1
if loop_index == 0 then
self:finished()
return
end
elseif self.iterators[loop_index] and loop_index == self.loop_counts then
-- if we're on last loop and last loop is not nil, then we're good to go for next perform call.
return
else
loop_index = loop_index + 1
end
end
end
function Async:finished()
self.completions = self.completions + 1
self.remaining = self.remaining - 1
end
function Async:call_perform_function()
log("Call perform with " .. serpent.line(self.state))
self.perform_function(self.state)
end
function Async:tick(tick)
if self.remaining == 0 then
return
end
if tick % self.interval == 0 then
self:call_perform_function()
self:next_iteration()
end
end
function Async:is_completed()
return self.remaining == 0
end
function Async:on_tick()
if async_tasks == nil then
return
end
local tick = game.tick
for k, task in pairs(async_tasks) do
task:tick(tick)
end
if tick % 3600 == 2700 then
-- Cleanup tasks
log("Cleanup async tasks")
for k, task in pairs(async_tasks) do
if task:is_completed() then
log("Cleaned async task " .. k)
async_tasks[k] = nil
end
end
return
end
end
function Async:on_load()
async_tasks = global.async_tasks
end
function Async:on_init()
global.async_tasks = global.async_tasks or {}
async_tasks = global.async_tasks
end
local function async_command_step(event)
local player = game.players[event.player_index]
if event.command == "async_create" then
local loop1 = Async:loop_values("a", {"ONE", "TWO", "THREE"})
local loop2 = Async:loop("b", 1, 2)
local loop3 = Async:loop("c", 1, 3)
local perform = function(state)
game.print(serpent.line(state))
end
local new_async = Async:perform_once({ loop1, loop2, loop3 }, perform)
game.print("Created loop example task")
end
if event.command == "async_test" then
for _, task in pairs(async_tasks) do
task:tick(game.tick)
end
end
if event.command == "async_once" then
end
end
script.on_event(defines.events.on_console_command, async_command_step)
return Async
|
Async utility: Fix the case when async_tasks does not previously exist
|
Async utility: Fix the case when async_tasks does not previously exist
|
Lua
|
mit
|
Zomis/FactorioMods
|
4c69cbe24df315ed14ade5026116d69c03b6e85e
|
test/autobahn_co_client_test.lua
|
test/autobahn_co_client_test.lua
|
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.websocket.luasocket"
local stp = require "StackTracePlus"
local Autobahn = require "./autobahn"
local ctx do
local ok, ssl = pcall(require, "lluv.ssl")
if ok then
ctx = assert(ssl.context{
protocol = "tlsv1",
certificate = "./wss/server.crt",
})
end
end
local Client = function() return socket.ws{ssl = ctx, utf8 = true} end
local URI = arg[1] or "ws://127.0.0.1:9001"
local reportDir = "./reports/clients"
local agent = "lluv.ws.luasocket"
local caseCount = 0
local currentCaseId = 0
local function getCaseCount(cont)
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.getCaseCount(URI))
if not ok then
cli:close()
return print("WS ERROR:", err)
end
local msg = cli:receive("*r")
caseCount = tonumber(msg)
cli:close()
cont()
end)
end
local function runTestCase(no, cb)
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.runTestCase(URI, no, agent))
if not ok then
cli:close()
return print("WS ERROR:", err)
end
print("Executing test case " .. no .. "/" .. caseCount)
while true do
local msg, opcode = cli:receive("*l")
if not msg then break end
if opcode == socket.TEXT or opcode == socket.BINARY then
cli:send(msg, opcode)
end
end
cli:close()
uv.defer(cb)
end)
end
local function updateReports()
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.updateReports(URI, agent))
if not ok then print("WS ERROR:", err) end
cli:close()
end)
end
local function runNextCase()
runTestCase(currentCaseId, function(_, err, code, reason)
currentCaseId = currentCaseId + 1
if currentCaseId <= caseCount then
runNextCase()
else
print("All test cases executed.")
updateReports()
end
end)
end
local function runAll()
currentCaseId = 1
Autobahn.cleanReports(reportDir)
getCaseCount(runNextCase)
uv.run(stp.stacktrace)
if not Autobahn.verifyReport(reportDir, agent, true) then
return os.exit(-1)
end
end
runAll()
|
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.websocket.luasocket"
local Autobahn = require "./autobahn"
local ctx do
local ok, ssl = pcall(require, "lluv.ssl")
if ok then
ctx = assert(ssl.context{
protocol = "tlsv1",
certificate = "./wss/server.crt",
})
end
end
local Client = function() return socket.ws{ssl = ctx, utf8 = true} end
local URI = arg[1] or "ws://127.0.0.1:9001"
local reportDir = "./reports/clients"
local agent = "lluv.ws.luasocket"
local caseCount = 0
local currentCaseId = 0
local function getCaseCount(cont)
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.getCaseCount(URI))
if not ok then
cli:close()
return print("WS ERROR:", err)
end
local msg = cli:receive("*r")
caseCount = tonumber(msg)
cli:close()
cont()
end)
end
local function runTestCase(no, cb)
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.runTestCase(URI, no, agent))
if not ok then
cli:close()
return print("WS ERROR:", err)
end
print("Executing test case " .. no .. "/" .. caseCount)
while true do
local msg, opcode = cli:receive("*l")
if not msg then break end
if opcode == socket.TEXT or opcode == socket.BINARY then
cli:send(msg, opcode)
end
end
cli:close()
uv.defer(cb)
end)
end
local function updateReports()
ut.corun(function()
local cli = Client()
local ok, err = cli:connect(Autobahn.Server.updateReports(URI, agent))
if not ok then print("WS ERROR:", err) end
cli:close()
end)
end
local function runNextCase()
runTestCase(currentCaseId, function(_, err, code, reason)
currentCaseId = currentCaseId + 1
if currentCaseId <= caseCount then
runNextCase()
else
print("All test cases executed.")
updateReports()
end
end)
end
local function runAll()
currentCaseId = 1
Autobahn.cleanReports(reportDir)
getCaseCount(runNextCase)
uv.run(debug.traceback)
if not Autobahn.verifyReport(reportDir, agent, true) then
return os.exit(-1)
end
end
runAll()
|
Fix. Remove use StackTraceBack library in test.
|
Fix. Remove use StackTraceBack library in test.
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
57f08426ee9f7bd44a8edc4231b94625e2b580d3
|
service/clusterd.lua
|
service/clusterd.lua
|
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data, padding
end
local function open_channel(t, key)
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
nodelay = true,
}
assert(c:connect(true))
t[key] = c
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
for name,address in pairs(tmp) do
assert(type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
end
node_address[name] = address
end
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
local function send_request(source, node, addr, msg, sz)
local session = node_session[node] or 1
-- msg is a local pointer, cluster.packrequest will free it
local request, new_session, padding = cluster.packrequest(addr, session, msg, sz)
node_session[node] = new_session
-- node_channel[node] may yield or throw error
local c = node_channel[node]
return c:request(request, session, padding)
end
function command.req(...)
local ok, msg, sz = pcall(send_request, ...)
if ok then
if type(msg) == "table" then
skynet.ret(cluster.concat(msg))
else
skynet.ret(msg)
end
else
skynet.error(msg)
skynet.response()(false)
end
end
function command.push(source, node, addr, msg, sz)
local session = node_session[node] or 1
local request, new_session, padding = cluster.packpush(addr, session, msg, sz)
if padding then -- is multi push
node_session[node] = new_session
end
-- node_channel[node] may yield or throw error
local c = node_channel[node]
c:request(request, nil, padding)
-- notice: push may fail where the channel is disconnected or broken.
end
local proxy = {}
function command.proxy(source, node, name)
local fullname = node .. "." .. name
if proxy[fullname] == nil then
proxy[fullname] = skynet.newservice("clusterproxy", node, name)
end
skynet.ret(skynet.pack(proxy[fullname]))
end
local register_name = {}
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
local large_request = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local sz
local addr, session, msg, padding, is_push = cluster.unpackrequest(msg)
if padding then
local requests = large_request[fd]
if requests == nil then
requests = {}
large_request[fd] = requests
end
local req = requests[session] or { addr = addr , is_push = is_push }
requests[session] = req
table.insert(req, msg)
return
else
local requests = large_request[fd]
if requests then
local req = requests[session]
if req then
requests[session] = nil
table.insert(req, msg)
msg,sz = cluster.concat(req)
addr = req.addr
is_push = req.is_push
end
end
if not msg then
local response = cluster.packresponse(session, false, "Invalid large req")
socket.write(fd, response)
return
end
end
local ok, response
if addr == 0 then
local name = skynet.unpack(msg, sz)
local addr = register_name[name]
if addr then
ok = true
msg, sz = skynet.pack(addr)
else
ok = false
msg = "name not found"
end
elseif is_push then
skynet.rawsend(addr, "lua", msg, sz)
return -- no response
else
ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg, sz)
end
if ok then
response = cluster.packresponse(session, true, msg, sz)
if type(response) == "table" then
for _, v in ipairs(response) do
socket.lwrite(fd, v)
end
else
socket.write(fd, response)
end
else
response = cluster.packresponse(session, false, msg)
socket.write(fd, response)
end
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
large_request[fd] = nil
skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or ""))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data, padding
end
local connecting = {}
local function open_channel(t, key)
local ct = connecting[key]
if ct then
local co = coroutine.running()
table.insert(ct, co)
skynet.wait(co)
return assert(ct.channel)
end
ct = {}
connecting[key] = ct
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
nodelay = true,
}
local succ, err = pcall(c.connect, c, true)
if succ then
t[key] = c
ct.channel = c
end
connecting[key] = nil
for _, co in ipairs(ct) do
skynet.wakeup(co)
end
assert(succ, err)
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
for name,address in pairs(tmp) do
assert(type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
end
node_address[name] = address
end
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
local function send_request(source, node, addr, msg, sz)
local session = node_session[node] or 1
-- msg is a local pointer, cluster.packrequest will free it
local request, new_session, padding = cluster.packrequest(addr, session, msg, sz)
node_session[node] = new_session
-- node_channel[node] may yield or throw error
local c = node_channel[node]
return c:request(request, session, padding)
end
function command.req(...)
local ok, msg, sz = pcall(send_request, ...)
if ok then
if type(msg) == "table" then
skynet.ret(cluster.concat(msg))
else
skynet.ret(msg)
end
else
skynet.error(msg)
skynet.response()(false)
end
end
function command.push(source, node, addr, msg, sz)
local session = node_session[node] or 1
local request, new_session, padding = cluster.packpush(addr, session, msg, sz)
if padding then -- is multi push
node_session[node] = new_session
end
-- node_channel[node] may yield or throw error
local c = node_channel[node]
c:request(request, nil, padding)
-- notice: push may fail where the channel is disconnected or broken.
end
local proxy = {}
function command.proxy(source, node, name)
local fullname = node .. "." .. name
if proxy[fullname] == nil then
proxy[fullname] = skynet.newservice("clusterproxy", node, name)
end
skynet.ret(skynet.pack(proxy[fullname]))
end
local register_name = {}
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
local large_request = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local sz
local addr, session, msg, padding, is_push = cluster.unpackrequest(msg)
if padding then
local requests = large_request[fd]
if requests == nil then
requests = {}
large_request[fd] = requests
end
local req = requests[session] or { addr = addr , is_push = is_push }
requests[session] = req
table.insert(req, msg)
return
else
local requests = large_request[fd]
if requests then
local req = requests[session]
if req then
requests[session] = nil
table.insert(req, msg)
msg,sz = cluster.concat(req)
addr = req.addr
is_push = req.is_push
end
end
if not msg then
local response = cluster.packresponse(session, false, "Invalid large req")
socket.write(fd, response)
return
end
end
local ok, response
if addr == 0 then
local name = skynet.unpack(msg, sz)
local addr = register_name[name]
if addr then
ok = true
msg, sz = skynet.pack(addr)
else
ok = false
msg = "name not found"
end
elseif is_push then
skynet.rawsend(addr, "lua", msg, sz)
return -- no response
else
ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg, sz)
end
if ok then
response = cluster.packresponse(session, true, msg, sz)
if type(response) == "table" then
for _, v in ipairs(response) do
socket.lwrite(fd, v)
end
else
socket.write(fd, response)
end
else
response = cluster.packresponse(session, false, msg)
socket.write(fd, response)
end
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
large_request[fd] = nil
skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or ""))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
concurrent cluster link, fix issue #757
|
concurrent cluster link, fix issue #757
|
Lua
|
mit
|
pigparadise/skynet,codingabc/skynet,bttscut/skynet,hongling0/skynet,icetoggle/skynet,bigrpg/skynet,jxlczjp77/skynet,sanikoyes/skynet,czlc/skynet,bttscut/skynet,codingabc/skynet,firedtoad/skynet,Ding8222/skynet,icetoggle/skynet,sundream/skynet,bigrpg/skynet,sanikoyes/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,cloudwu/skynet,hongling0/skynet,kyle-wang/skynet,great90/skynet,Ding8222/skynet,JiessieDawn/skynet,kyle-wang/skynet,bttscut/skynet,pigparadise/skynet,ag6ag/skynet,xcjmine/skynet,xjdrew/skynet,wangyi0226/skynet,xjdrew/skynet,sundream/skynet,zhangshiqian1214/skynet,codingabc/skynet,fztcjjl/skynet,kyle-wang/skynet,ag6ag/skynet,cloudwu/skynet,icetoggle/skynet,JiessieDawn/skynet,korialuo/skynet,sundream/skynet,czlc/skynet,great90/skynet,bigrpg/skynet,korialuo/skynet,jxlczjp77/skynet,pigparadise/skynet,Ding8222/skynet,wangyi0226/skynet,great90/skynet,zhangshiqian1214/skynet,firedtoad/skynet,wangyi0226/skynet,sanikoyes/skynet,fztcjjl/skynet,korialuo/skynet,xcjmine/skynet,fztcjjl/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,firedtoad/skynet,zhouxiaoxiaoxujian/skynet,xjdrew/skynet,cloudwu/skynet,jxlczjp77/skynet,czlc/skynet,xcjmine/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,JiessieDawn/skynet,hongling0/skynet,ag6ag/skynet
|
cbb0bead6fe87a99f77e0597733dcac453d08097
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / 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.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("luci.fs")
require("luci.util")
require("luci.i18n")
require("luci.statistics.datatree")
-- load language files
luci.i18n.loadc("rrdtool")
luci.i18n.loadc("statistics")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
-- override i18n(): try to translate stat_<str> or fall back to <str>
function _i18n( str )
return luci.i18n.translate( "stat_" .. str, str )
end
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics"
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10)
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
_i18n( section .. "plugins" ),
index * 10
)
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
_i18n( plugin ),
j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), _i18n( plugin ), i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local plugins = { }
for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local plugins = { }
for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local plugins = { }
for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.dispatched.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.dispatched.path ) do
if luci.dispatcher.context.dispatched.path[i] == "graph" then
plugin = luci.dispatcher.context.dispatched.path[i+1]
instances = { luci.dispatcher.context.dispatched.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / 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.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("luci.fs")
require("luci.util")
require("luci.i18n")
require("luci.statistics.datatree")
-- load language files
luci.i18n.loadc("rrdtool")
luci.i18n.loadc("statistics")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
-- override i18n(): try to translate stat_<str> or fall back to <str>
function _i18n( str )
return luci.i18n.translate( "stat_" .. str, str )
end
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics"
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10)
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
_i18n( section .. "plugins" ),
index * 10
)
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
_i18n( plugin ),
j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), _i18n( plugin ), i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local plugins = { }
for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local plugins = { }
for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local plugins = { }
for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
Fixed statistics
|
Fixed statistics
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,cshore/luci,florian-shellfire/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,hnyman/luci,Hostle/luci,deepak78/new-luci,Noltari/luci,Hostle/luci,jorgifumi/luci,rogerpueyo/luci,remakeelectric/luci,rogerpueyo/luci,bittorf/luci,teslamint/luci,ollie27/openwrt_luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,teslamint/luci,981213/luci-1,openwrt/luci,nmav/luci,shangjiyu/luci-with-extra,dwmw2/luci,joaofvieira/luci,NeoRaider/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,openwrt/luci,remakeelectric/luci,dwmw2/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,kuoruan/luci,opentechinstitute/luci,Hostle/luci,981213/luci-1,openwrt-es/openwrt-luci,dismantl/luci-0.12,david-xiao/luci,harveyhu2012/luci,deepak78/new-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,teslamint/luci,forward619/luci,NeoRaider/luci,keyidadi/luci,kuoruan/luci,joaofvieira/luci,wongsyrone/luci-1,mumuqz/luci,dwmw2/luci,aa65535/luci,981213/luci-1,bittorf/luci,deepak78/new-luci,david-xiao/luci,joaofvieira/luci,ollie27/openwrt_luci,sujeet14108/luci,cappiewu/luci,Kyklas/luci-proto-hso,fkooman/luci,ollie27/openwrt_luci,fkooman/luci,chris5560/openwrt-luci,lcf258/openwrtcn,NeoRaider/luci,bittorf/luci,RuiChen1113/luci,david-xiao/luci,Noltari/luci,keyidadi/luci,LuttyYang/luci,fkooman/luci,mumuqz/luci,RuiChen1113/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,obsy/luci,oyido/luci,Sakura-Winkey/LuCI,MinFu/luci,fkooman/luci,jlopenwrtluci/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,NeoRaider/luci,zhaoxx063/luci,forward619/luci,schidler/ionic-luci,tcatm/luci,dismantl/luci-0.12,daofeng2015/luci,artynet/luci,opentechinstitute/luci,nmav/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,Wedmer/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,aa65535/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,dismantl/luci-0.12,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,Hostle/luci,bittorf/luci,ff94315/luci-1,cappiewu/luci,cshore-firmware/openwrt-luci,david-xiao/luci,nmav/luci,openwrt-es/openwrt-luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,florian-shellfire/luci,sujeet14108/luci,palmettos/cnLuCI,thesabbir/luci,sujeet14108/luci,male-puppies/luci,taiha/luci,tcatm/luci,Kyklas/luci-proto-hso,Hostle/luci,zhaoxx063/luci,Wedmer/luci,joaofvieira/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,obsy/luci,keyidadi/luci,dismantl/luci-0.12,thess/OpenWrt-luci,rogerpueyo/luci,daofeng2015/luci,chris5560/openwrt-luci,jchuang1977/luci-1,tobiaswaldvogel/luci,tcatm/luci,marcel-sch/luci,maxrio/luci981213,sujeet14108/luci,Sakura-Winkey/LuCI,aa65535/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,cappiewu/luci,tcatm/luci,oneru/luci,Noltari/luci,thesabbir/luci,mumuqz/luci,forward619/luci,ff94315/luci-1,ff94315/luci-1,male-puppies/luci,david-xiao/luci,remakeelectric/luci,male-puppies/luci,cshore/luci,tobiaswaldvogel/luci,aa65535/luci,marcel-sch/luci,RuiChen1113/luci,LuttyYang/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,nmav/luci,marcel-sch/luci,marcel-sch/luci,keyidadi/luci,daofeng2015/luci,bittorf/luci,thesabbir/luci,artynet/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,oyido/luci,zhaoxx063/luci,openwrt/luci,joaofvieira/luci,chris5560/openwrt-luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,deepak78/new-luci,daofeng2015/luci,mumuqz/luci,lcf258/openwrtcn,jorgifumi/luci,bright-things/ionic-luci,MinFu/luci,joaofvieira/luci,cappiewu/luci,jlopenwrtluci/luci,nwf/openwrt-luci,teslamint/luci,RuiChen1113/luci,openwrt/luci,openwrt/luci,Sakura-Winkey/LuCI,nmav/luci,florian-shellfire/luci,ff94315/luci-1,oyido/luci,981213/luci-1,Kyklas/luci-proto-hso,maxrio/luci981213,lbthomsen/openwrt-luci,cappiewu/luci,kuoruan/luci,tobiaswaldvogel/luci,david-xiao/luci,ollie27/openwrt_luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,obsy/luci,remakeelectric/luci,forward619/luci,deepak78/new-luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,Kyklas/luci-proto-hso,jorgifumi/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,urueedi/luci,jorgifumi/luci,mumuqz/luci,NeoRaider/luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,tcatm/luci,zhaoxx063/luci,Noltari/luci,981213/luci-1,cshore/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,dwmw2/luci,slayerrensky/luci,Wedmer/luci,remakeelectric/luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,joaofvieira/luci,palmettos/test,jlopenwrtluci/luci,wongsyrone/luci-1,marcel-sch/luci,obsy/luci,palmettos/cnLuCI,Noltari/luci,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,oneru/luci,schidler/ionic-luci,palmettos/cnLuCI,nmav/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,MinFu/luci,artynet/luci,chris5560/openwrt-luci,LuttyYang/luci,ollie27/openwrt_luci,urueedi/luci,jlopenwrtluci/luci,forward619/luci,bright-things/ionic-luci,male-puppies/luci,lcf258/openwrtcn,openwrt/luci,male-puppies/luci,RuiChen1113/luci,NeoRaider/luci,hnyman/luci,keyidadi/luci,cshore/luci,MinFu/luci,forward619/luci,oneru/luci,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,sujeet14108/luci,bright-things/ionic-luci,nmav/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,dwmw2/luci,nmav/luci,florian-shellfire/luci,wongsyrone/luci-1,palmettos/cnLuCI,slayerrensky/luci,Noltari/luci,palmettos/cnLuCI,taiha/luci,obsy/luci,nwf/openwrt-luci,jchuang1977/luci-1,nwf/openwrt-luci,cshore/luci,RuiChen1113/luci,harveyhu2012/luci,wongsyrone/luci-1,fkooman/luci,maxrio/luci981213,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,thesabbir/luci,schidler/ionic-luci,maxrio/luci981213,opentechinstitute/luci,urueedi/luci,opentechinstitute/luci,Noltari/luci,harveyhu2012/luci,jorgifumi/luci,obsy/luci,kuoruan/luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,fkooman/luci,thesabbir/luci,lcf258/openwrtcn,opentechinstitute/luci,Wedmer/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,keyidadi/luci,dismantl/luci-0.12,rogerpueyo/luci,jorgifumi/luci,openwrt-es/openwrt-luci,urueedi/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,Noltari/luci,hnyman/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,deepak78/new-luci,Kyklas/luci-proto-hso,jorgifumi/luci,chris5560/openwrt-luci,kuoruan/luci,daofeng2015/luci,cshore/luci,bittorf/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,thess/OpenWrt-luci,remakeelectric/luci,fkooman/luci,lcf258/openwrtcn,ff94315/luci-1,Sakura-Winkey/LuCI,jchuang1977/luci-1,cappiewu/luci,taiha/luci,RedSnake64/openwrt-luci-packages,palmettos/test,LuttyYang/luci,maxrio/luci981213,thess/OpenWrt-luci,dismantl/luci-0.12,chris5560/openwrt-luci,LuttyYang/luci,slayerrensky/luci,Hostle/luci,jchuang1977/luci-1,schidler/ionic-luci,palmettos/cnLuCI,oyido/luci,teslamint/luci,urueedi/luci,lcf258/openwrtcn,kuoruan/lede-luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,urueedi/luci,jlopenwrtluci/luci,lcf258/openwrtcn,slayerrensky/luci,thesabbir/luci,Hostle/luci,florian-shellfire/luci,harveyhu2012/luci,LuttyYang/luci,sujeet14108/luci,tcatm/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,cshore/luci,remakeelectric/luci,marcel-sch/luci,tcatm/luci,schidler/ionic-luci,mumuqz/luci,joaofvieira/luci,daofeng2015/luci,MinFu/luci,cshore/luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,tcatm/luci,bittorf/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,lcf258/openwrtcn,artynet/luci,harveyhu2012/luci,981213/luci-1,teslamint/luci,nwf/openwrt-luci,hnyman/luci,mumuqz/luci,hnyman/luci,bittorf/luci,NeoRaider/luci,hnyman/luci,opentechinstitute/luci,forward619/luci,dwmw2/luci,urueedi/luci,chris5560/openwrt-luci,dismantl/luci-0.12,aa65535/luci,oneru/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,maxrio/luci981213,jlopenwrtluci/luci,urueedi/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,kuoruan/lede-luci,sujeet14108/luci,taiha/luci,Wedmer/luci,artynet/luci,palmettos/cnLuCI,Wedmer/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,obsy/luci,kuoruan/lede-luci,kuoruan/lede-luci,palmettos/test,cshore-firmware/openwrt-luci,oneru/luci,taiha/luci,rogerpueyo/luci,harveyhu2012/luci,Wedmer/luci,openwrt/luci,hnyman/luci,thess/OpenWrt-luci,florian-shellfire/luci,fkooman/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,taiha/luci,kuoruan/luci,forward619/luci,jchuang1977/luci-1,Noltari/luci,slayerrensky/luci,kuoruan/luci,artynet/luci,male-puppies/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,981213/luci-1,florian-shellfire/luci,tobiaswaldvogel/luci,palmettos/test,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,nmav/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,oneru/luci,thess/OpenWrt-luci,male-puppies/luci,rogerpueyo/luci,artynet/luci,obsy/luci,RuiChen1113/luci,palmettos/cnLuCI,maxrio/luci981213,daofeng2015/luci,jchuang1977/luci-1,bright-things/ionic-luci,thesabbir/luci,oneru/luci,shangjiyu/luci-with-extra,LuttyYang/luci,ff94315/luci-1,marcel-sch/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,schidler/ionic-luci,ff94315/luci-1,dwmw2/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,openwrt/luci,oyido/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,male-puppies/luci,slayerrensky/luci,artynet/luci,oyido/luci,Hostle/luci,keyidadi/luci,Sakura-Winkey/LuCI,cappiewu/luci,deepak78/new-luci,david-xiao/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,sujeet14108/luci,palmettos/test,taiha/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,bright-things/ionic-luci,florian-shellfire/luci,tobiaswaldvogel/luci,teslamint/luci,zhaoxx063/luci,chris5560/openwrt-luci,daofeng2015/luci,oneru/luci,LuttyYang/luci,rogerpueyo/luci,palmettos/test
|
7d3509ddcaab09fdac965ffa3c552b69c6155536
|
build/premake5.lua
|
build/premake5.lua
|
function setTargetObjDir(outDir)
targetdir(outDir)
objdir(string.lower("../intermediate/%{cfg.shortname}/" .. _ACTION))
targetsuffix(string.lower("_%{cfg.shortname}_" .. _ACTION))
end
function copyfiles(dstDir, srcWildcard)
os.mkdir(dstDir)
local matches = os.matchfiles(srcWildcard)
for _, f in ipairs(matches) do
local filename = string.match(f, ".-([^\\/]-%.?[^%.\\/]*)$")
os.copyfile(f, dstDir .. "/" .. filename)
end
end
function gmake_common()
buildoptions "-march=native -Wall -Wextra"
links { "boost_system", "boost_thread-mt", "boost_locale-mt" }
if (os.findlib("PocoJSON")) then
defines { "HAS_POCO=1" }
links { "PocoFoundation", "PocoJSON" }
end
end
solution "benchmark"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines { "__STDC_FORMAT_MACROS=1" }
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
project "nativejson"
kind "ConsoleApp"
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
files {
"../src/*.h",
"../src/*.cpp",
"../src/tests/*.cpp",
}
libdirs { "../bin" }
setTargetObjDir("../bin")
-- linkLib("jsonclibs")
links "jsonclibs"
configuration "gmake"
buildoptions "-std=c++14 -lstdc++"
solution "jsonstat"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines {
"USE_MEMORYSTAT=0",
"TEST_PARSE=1",
"TEST_STRINGIFY=0",
"TEST_PRETTIFY=0",
"TEST_TEST_STATISTICS=1",
"TEST_SAXROUNDTRIP=0",
"TEST_SAXSTATISTICS=0",
"TEST_SAXSTATISTICSUTF16=0",
"TEST_CONFORMANCE=0",
"TEST_INFO=0"
}
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs2"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin/jsonstat")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
local testfiles = os.matchfiles("../src/tests/*.cpp")
for _, testfile in ipairs(testfiles) do
project("jsonstat_" .. path.getbasename(testfile))
kind "ConsoleApp"
files {
"../src/jsonstat/jsonstatmain.cpp",
"../src/memorystat.cpp",
testfile
}
libdirs { "../bin/jsonstat" }
links "jsonclibs2"
setTargetObjDir("../bin/jsonstat")
configuration "gmake"
buildoptions "-std=c++14 -stdlib=libc++"
end
|
function setTargetObjDir(outDir)
targetdir(outDir)
objdir(string.lower("../intermediate/%{cfg.shortname}/" .. _ACTION))
targetsuffix(string.lower("_%{cfg.shortname}_" .. _ACTION))
end
function copyfiles(dstDir, srcWildcard)
os.mkdir(dstDir)
local matches = os.matchfiles(srcWildcard)
for _, f in ipairs(matches) do
local filename = string.match(f, ".-([^\\/]-%.?[^%.\\/]*)$")
os.copyfile(f, dstDir .. "/" .. filename)
end
end
function gmake_common()
buildoptions "-march=native -Wall -Wextra"
links { "boost_system" }
if (os.findlib("boost_thread")) then
links { "boost_thread" }
elseif (os.findlib("boost_thread-mt")) then
links { "boost_thread-mt" }
end
if (os.findlib("boost_locale")) then
links { "boost_locale" }
elseif (os.findlib("boost_locale-mt")) then
links { "boost_locale-mt" }
end
if (os.findlib("PocoJSON")) then
defines { "HAS_POCO=1" }
links { "PocoFoundation", "PocoJSON" }
end
end
solution "benchmark"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines { "__STDC_FORMAT_MACROS=1" }
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
project "nativejson"
kind "ConsoleApp"
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
files {
"../src/*.h",
"../src/*.cpp",
"../src/tests/*.cpp",
}
libdirs { "../bin" }
setTargetObjDir("../bin")
-- linkLib("jsonclibs")
links "jsonclibs"
configuration "gmake"
buildoptions "-std=c++14 -lstdc++"
solution "jsonstat"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines {
"USE_MEMORYSTAT=0",
"TEST_PARSE=1",
"TEST_STRINGIFY=0",
"TEST_PRETTIFY=0",
"TEST_TEST_STATISTICS=1",
"TEST_SAXROUNDTRIP=0",
"TEST_SAXSTATISTICS=0",
"TEST_SAXSTATISTICSUTF16=0",
"TEST_CONFORMANCE=0",
"TEST_INFO=0"
}
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs2"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin/jsonstat")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
local testfiles = os.matchfiles("../src/tests/*.cpp")
for _, testfile in ipairs(testfiles) do
project("jsonstat_" .. path.getbasename(testfile))
kind "ConsoleApp"
files {
"../src/jsonstat/jsonstatmain.cpp",
"../src/memorystat.cpp",
testfile
}
libdirs { "../bin/jsonstat" }
links "jsonclibs2"
setTargetObjDir("../bin/jsonstat")
configuration "gmake"
buildoptions "-std=c++14 -stdlib=libc++"
end
|
Fix boost linking
|
Fix boost linking
|
Lua
|
mit
|
miloyip/nativejson-benchmark,miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,DavadDi/nativejson-benchmark,DavadDi/nativejson-benchmark,miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,miloyip/nativejson-benchmark
|
d45f27897207edcc82192aef5af9d012956971eb
|
Peripherals/GPU/modules/cursor.lua
|
Peripherals/GPU/modules/cursor.lua
|
--GPU: Mouse Cursor.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local lg = love.graphics
local events = require("Engine.events")
local PaletteVars = GPUVars.Palette
local RenderVars = GPUVars.Render
local SharedVars = GPUVars.Shared
local WindowVars = GPUVars.Window
local CursorVars = GPUVars.Cursor
--==Varss Constants==--
local _ImageTransparent = PaletteVars.ImageTransparent
local PaletteStack = PaletteVars.PaletteStack
local Verify = SharedVars.Verify
--==Local Functions==--
--Apply transparent colors effect on LIKO12 Images when encoded to PNG
local function _EncodeTransparent(_,_, r,g,b,a)
if _ImageTransparent[math.floor(r*255)+1] == 0 then return 0,0,0,0 end
return r,g,b,a
end
--==Vars Variables==--
CursorVars.GrappedCursor = false --If the cursor must be drawed by the GPU (not using a system cursor)
CursorVars.Cursor = "none"
--==Local Variables==--
local _CursorsCache = {}
--==GPU Cursor API==--
function GPU.cursor(imgdata,name,hx,hy)
if type(imgdata) == "string" then --Set the current cursor
if CursorVars.GrappedCursor then if not name then RenderVars.AlwaysDraw = false; RenderVars.ShouldDraw = true end elseif name then RenderVars.AlwaysDraw = true end
if CursorVars.Cursor == imgdata and not ((CursorVars.GrappedCursor and not name) or (name and not CursorVars.GrappedCursor)) then return end
CursorVars.GrappedCursor = name
if (not _CursorsCache[imgdata]) and (imgdata ~= "none") then return error("Cursor doesn't exists: "..imgdata) end
CursorVars.Cursor = imgdata
if CursorVars.Cursor == "none" or CursorVars.GrappedCursor then
love.mouse.setVisible(false)
elseif love.mouse.isCursorSupported() then
love.mouse.setVisible(true)
love.mouse.setCursor(_CursorsCache[CursorVars.Cursor].cursor)
end
elseif type(imgdata) == "table" then --Create a new cursor from an image.
if not( imgdata.enlarge and imgdata.export and imgdata.type ) then return error("Invalied image") end
if imgdata:type() ~= "GPU.imageData" then return error("Invalied image object") end
name = name or "default"
Verify(name,"Name","string")
hx, hy = hx or 0, hy or 0
hx = Verify(hx,"Hot X","number",true)
hy = Verify(hy,"Hot Y","number",true)
local enimg = imgdata:enlarge(WindowVars.LIKOScale)
--local img = lg.newImage(love.filesystem.newFileData(imgdata:export(),"cursor.png"))
local limg = love.image.newImageData(love.filesystem.newFileData(enimg:export(),"cursor.png")) --Take it out to love image object
local gifimg = love.image.newImageData(imgdata:size())
gifimg:mapPixel(function(x,y) return imgdata:getPixel(x,y)/255,0,0,1 end)
gifimg:mapPixel(_EncodeTransparent)
gifimg = lg.newImage(gifimg)
local hotx, hoty = hx*math.floor(WindowVars.LIKOScale), hy*math.floor(WindowVars.LIKOScale) --Converted to host scale
local cur = love.mouse.isCursorSupported() and love.mouse.newCursor(limg,hotx,hoty) or {}
local palt = {}
for i=1, 16 do
table.insert(palt,_ImageTransparent[i])
end
_CursorsCache[name] = {cursor=cur,imgdata=imgdata,gifimg=gifimg,hx=hx,hy=hy,palt=palt}
elseif type(imgdata) == "nil" then
if CursorVars.Cursor == "none" then
return CursorVars.Cursor
else
return CursorVars.Cursor, _CursorsCache[CursorVars.Cursor].imgdata, _CursorsCache[CursorVars.Cursor].hx+1, _CursorsCache[CursorVars.Cursor].hy+1
end
else --Invalied
return error("The first argument must be a string, image or nil")
end
end
events.register("love:resize",function() --The new size will be calculated in the top, because events are called by the order they were registered with
if not love.mouse.isCursorSupported() then return end
for k, cursor in pairs(_CursorsCache) do
--Hack
GPU.pushPalette()
GPU.pushPalette()
for i=1, 16 do
PaletteStack[#PaletteStack].trans[i] = cursor.palt[i]
end
GPU.popPalette()
local enimg = cursor.imgdata:enlarge(WindowVars.LIKOScale)
local limg = love.image.newImageData(love.filesystem.newFileData(enimg:export(),"cursor.png")) --Take it out to love image object
local hotx, hoty = cursor.hx*math.floor(WindowVars.LIKOScale), cursor.hy*math.floor(WindowVars.LIKOScale) --Converted to host scale
local cur = love.mouse.newCursor(limg,hotx,hoty)
_CursorsCache[k].cursor = cur
GPU.popPalette()
end
local cursor = CursorVars.Cursor; CursorVars.Cursor = "none" --Force the cursor to update.
GPU.cursor(cursor,CursorVars.GrappedCursor)
end)
--==GPUVars Exports==--
CursorVars.CursorsCache = _CursorsCache
|
--GPU: Mouse Cursor.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local lg = love.graphics
local events = require("Engine.events")
local PaletteVars = GPUVars.Palette
local RenderVars = GPUVars.Render
local SharedVars = GPUVars.Shared
local WindowVars = GPUVars.Window
local CursorVars = GPUVars.Cursor
--==Varss Constants==--
local _ImageTransparent = PaletteVars.ImageTransparent
local PaletteStack = PaletteVars.PaletteStack
local Verify = SharedVars.Verify
--==Local Functions==--
--Apply transparent colors effect on LIKO12 Images when encoded to PNG
local function _EncodeTransparent(_,_, r,g,b,a)
if _ImageTransparent[math.floor(r*255)+1] == 0 then return 0,0,0,0 end
return r,g,b,a
end
--==Vars Variables==--
CursorVars.GrappedCursor = false --If the cursor must be drawed by the GPU (not using a system cursor)
CursorVars.Cursor = "none"
--==Local Variables==--
local _CursorsCache = {}
--==GPU Cursor API==--
function GPU.cursor(imgdata,name,hx,hy)
if type(imgdata) == "string" then --Set the current cursor
if CursorVars.GrappedCursor then if not name then RenderVars.AlwaysDraw = false; RenderVars.ShouldDraw = true end elseif name then RenderVars.AlwaysDraw = true end
if CursorVars.Cursor == imgdata and not ((CursorVars.GrappedCursor and not name) or (name and not CursorVars.GrappedCursor)) then return end
CursorVars.GrappedCursor = name
if (not _CursorsCache[imgdata]) and (imgdata ~= "none") then return error("Cursor doesn't exists: "..imgdata) end
CursorVars.Cursor = imgdata
if CursorVars.Cursor == "none" or CursorVars.GrappedCursor then
love.mouse.setVisible(false)
elseif love.mouse.isCursorSupported() then
love.mouse.setVisible(true)
love.mouse.setCursor(_CursorsCache[CursorVars.Cursor].cursor)
end
elseif type(imgdata) == "table" then --Create a new cursor from an image.
if not( imgdata.enlarge and imgdata.export and imgdata.type ) then return error("Invalied image") end
if imgdata:type() ~= "GPU.imageData" then return error("Invalied image object") end
name = name or "default"
Verify(name,"Name","string")
hx, hy = hx or 0, hy or 0
hx = Verify(hx,"Hot X","number",true)
hy = Verify(hy,"Hot Y","number",true)
local enimg = imgdata:enlarge(WindowVars.LIKOScale)
--local img = lg.newImage(love.filesystem.newFileData(imgdata:export(),"cursor.png"))
local limg = love.image.newImageData(love.filesystem.newFileData(enimg:export(),"cursor.png")) --Take it out to love image object
local gifimg = love.image.newImageData(imgdata:size())
gifimg:mapPixel(function(x,y) return imgdata:getPixel(x,y)/255,0,0,1 end)
gifimg:mapPixel(_EncodeTransparent)
gifimg = lg.newImage(gifimg)
local hotx, hoty = hx*math.floor(WindowVars.LIKOScale), hy*math.floor(WindowVars.LIKOScale) --Converted to host scale
local cur = love.mouse.isCursorSupported() and love.mouse.newCursor(limg,hotx,hoty) or {}
local palt = {}
for i=1, 16 do
table.insert(palt,_ImageTransparent[i])
end
_CursorsCache[name] = {cursor=cur,imgdata=imgdata,gifimg=gifimg,hx=hx,hy=hy,palt=palt}
elseif type(imgdata) == "nil" then
if CursorVars.Cursor == "none" then
return CursorVars.Cursor
else
return CursorVars.Cursor, _CursorsCache[CursorVars.Cursor].imgdata, _CursorsCache[CursorVars.Cursor].hx+1, _CursorsCache[CursorVars.Cursor].hy+1
end
else --Invalied
return error("The first argument must be a string, image or nil")
end
end
events.register("love:resize",function() --The new size will be calculated in the top, because events are called by the order they were registered with
if not love.mouse.isCursorSupported() then return end
for k, cursor in pairs(_CursorsCache) do
--Hack
GPU.pushPalette()
GPU.pushPalette()
for i=1, 16 do
PaletteStack[#PaletteStack].trans[i] = cursor.palt[i]
end
GPU.popPalette()
local enimg = cursor.imgdata:enlarge(WindowVars.LIKOScale)
local limg = love.image.newImageData(love.filesystem.newFileData(enimg:export(),"cursor.png")) --Take it out to love image object
local hotx, hoty = cursor.hx*math.floor(WindowVars.LIKOScale), cursor.hy*math.floor(WindowVars.LIKOScale) --Converted to host scale
local cur = love.mouse.newCursor(limg,hotx,hoty)
_CursorsCache[k].cursor = cur
GPU.popPalette()
end
local cursor = CursorVars.Cursor; CursorVars.Cursor = "none" --Force the cursor to update.
GPU.cursor(cursor,CursorVars.GrappedCursor)
end)
--==GPUVars Exports==--
CursorVars.CursorsCache = _CursorsCache
|
Fix identation
|
Fix identation
Former-commit-id: c1886ee3687eaa5ffa5e748f89c80bab541ce2b3
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
59c131ec774f5571678a56c082842be9ef66071d
|
modules/textadept/run.lua
|
modules/textadept/run.lua
|
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
---
-- Module for running/executing source files.
module('_m.textadept.run', package.seeall)
---
-- [Local function] Prints a command to Textadept.
-- @param cmd The OS command executed.
-- @param output The output from that OS command.
local function print_command(cmd, output)
textadept.print('> '..cmd..'\n'..output)
buffer:goto_pos(buffer.length)
end
---
-- Passes the current file to a specified compiler to run with the given flags
-- and prints the output to Textadept.
-- @param compiler The system's compiler for the file.
-- @param cflags A string of flags to pass to the interpreter.
-- @param args Table of arguments key keys as follows:
-- * filename_noext_with_flag The value of this flag passed to the compiler
-- is the filename without its extension.
function compiler(compiler, cflags, args)
if type(cflags) ~= 'string' then cflags = '' end
if not args then args = {} end
local file = buffer.filename
if args.filename_noext_with_flag then
local filename_noext = file:match('^(.+)%.')
local flag = args.filename_noext_with_flag
cflags = string.format('%s %s"%s"', cflags, flag, filename_noext)
end
local command = string.format('%s %s "%s" 2>&1', compiler, cflags, file)
local p = io.popen(command)
local out = p:read('*all')
p:close()
print_command(command, out)
end
---
-- Passes the current file to a specified interpreter to run with the given
-- flags and prints the output to Textadept.
-- @param interpreter The system's interpreter for the file.
-- @param flags A string of flags to pass to the interpreter.
-- @param args Table of arguments with keys as follows:
-- * noext Do not include the filename's extension when passing to the
-- interpreter.
-- * nopath Do not include the full filepath, only the file's name.
-- * nopath_path_with_flag Same as nopath, but use the path as the value of
-- a flag passed to the interpreter.
function interpreter(interpreter, flags, args)
if type(flags) ~= 'string' then flags = '' end
if not args then args = {} end
local file = buffer.filename
if args.noext then file = file:match('^(.+)%.') end
if args.nopath then file = file:match('[^/\\]+$') end
if args.nopath_path_with_flag then
local path = file:match('^.+/')
local flag = args.nopath_path_with_flag
flags = string.format('%s %s"%s"', flags, flag, path)
file = file:match('[^/\\]+$')
end
local command = string.format('%s %s "%s" 2>&1', interpreter, flags, file)
local p = io.popen(command)
local out = p:read('*all')
p:close()
print_command(command, out)
end
-- TODO: makefile
-- TODO: etc.
---
-- [Local table] File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a table with the compile function
-- and parameters given as an ordered list.
-- @class table
-- @name compile_for_ext
local compile_for_ext = {
c = { compiler, 'gcc', '-pedantic -Os',
{ filename_noext_with_flag = '-o ' } },
cpp = { compiler, 'g++', '-pedantic -Os',
{ filename_noext_with_flag = '-o ' } },
java = { compiler, 'javac' },
}
---
-- Compiles the file as specified by its extension in the compile_for_ext table.
-- @see compile_for_ext
function compile()
local ext = buffer.filename:match('[^.]+$')
local action = compile_for_ext[ext]
if not action then return end
local f, args = action[1], { unpack(action) }
table.remove(args, 1) -- function
f(unpack(args))
end
---
-- [Local table] File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is a table with the run function
-- and parameters given as an ordered list.
-- @class table
-- @name go_for_ext
local go_for_ext = {
c = { interpreter, '', '', { noext = true } },
cpp = { interpreter, '', '', { noext = true } },
java = { interpreter, 'java', '',
{ noext = true, nopath_path_with_flag = '-cp ' } },
lua = { interpreter, 'lua' },
pl = { interpreter, 'perl' },
php = { interpreter, 'php', '-f' },
py = { interpreter, 'python' },
rb = { interpreter, 'ruby' },
}
---
-- Runs/executes the file as specified by its extension in the go_for_ext table.
-- @see go_for_ext
function go()
local ext = buffer.filename:match('[^.]+$')
local action = go_for_ext[ext]
if not action then return end
local f, args = action[1], { unpack(action) }
table.remove(args, 1) -- function
f(unpack(args))
end
---
-- [Local table] A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- @class table
-- @name error_details
local error_details = {
-- c, c++, and java errors and warnings have the same format as ruby ones
lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
perl = {
pattern = '^(.+) at (.-) line (%d+)',
message = 1, filename = 2, line = 3
},
php_error = {
pattern = '^Parse error: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
php_warning = {
pattern = '^Warning: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
python = {
pattern = '^%s*File "([^"]+)", line (%d+)',
filename = 1, line = 2
},
ruby = {
pattern = '^(.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_details
function goto_error(pos, line_num)
if buffer.shows_messages then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_details) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
textadept.io.open(captures[error_detail.filename])
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
break
end
end
end
end
textadept.events.add_handler('double_click', goto_error)
|
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
---
-- Module for running/executing source files.
module('_m.textadept.run', package.seeall)
---
-- [Local function] Prints a command to Textadept.
-- @param cmd The OS command executed.
-- @param output The output from that OS command.
local function print_command(cmd, output)
textadept.print('> '..cmd..'\n'..output)
buffer:goto_pos(buffer.length)
end
---
-- Passes the current file to a specified compiler to run with the given flags
-- and prints the output to Textadept.
-- @param compiler The system's compiler for the file.
-- @param cflags A string of flags to pass to the interpreter.
-- @param args Table of arguments key keys as follows:
-- * filename_noext_with_flag The value of this flag passed to the compiler
-- is the filename without its extension.
function compiler(compiler, cflags, args)
if type(cflags) ~= 'string' then cflags = '' end
if not args then args = {} end
local file = buffer.filename
if args.filename_noext_with_flag then
local filename_noext = file:match('^(.+)%.')
local flag = args.filename_noext_with_flag
cflags = string.format('%s %s"%s"', cflags, flag, filename_noext)
end
local command = string.format('%s %s "%s" 2>&1', compiler, cflags, file)
local p = io.popen(command)
local out = p:read('*all')
p:close()
print_command(command, out)
end
---
-- Passes the current file to a specified interpreter to run with the given
-- flags and prints the output to Textadept.
-- @param interpreter The system's interpreter for the file.
-- @param flags A string of flags to pass to the interpreter.
-- @param args Table of arguments with keys as follows:
-- * noext Do not include the filename's extension when passing to the
-- interpreter.
-- * nopath Do not include the full filepath, only the file's name.
-- * nopath_path_with_flag Same as nopath, but use the path as the value of
-- a flag passed to the interpreter.
function interpreter(interpreter, flags, args)
if type(flags) ~= 'string' then flags = '' end
if not args then args = {} end
local file = buffer.filename
if args.noext then file = file:match('^(.+)%.') end
if args.nopath then file = file:match('[^/\\]+$') end
if args.nopath_path_with_flag then
local path = file:match('^.+/')
local flag = args.nopath_path_with_flag
flags = string.format('%s %s"%s"', flags, flag, path)
file = file:match('[^/\\]+$')
end
local command = string.format('%s %s "%s" 2>&1', interpreter, flags, file)
local p = io.popen(command)
local out = p:read('*all')
p:close()
print_command(command, out)
end
-- TODO: makefile
-- TODO: etc.
---
-- [Local table] File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a table with the compile function
-- and parameters given as an ordered list.
-- @class table
-- @name compile_for_ext
local compile_for_ext = {
c = { compiler, 'gcc', '-pedantic -Os',
{ filename_noext_with_flag = '-o ' } },
cpp = { compiler, 'g++', '-pedantic -Os',
{ filename_noext_with_flag = '-o ' } },
java = { compiler, 'javac' },
}
---
-- Compiles the file as specified by its extension in the compile_for_ext table.
-- @see compile_for_ext
function compile()
if not buffer.filename then return end
local ext = buffer.filename:match('[^.]+$')
local action = compile_for_ext[ext]
if not action then return end
local f, args = action[1], { unpack(action) }
table.remove(args, 1) -- function
f(unpack(args))
end
---
-- [Local table] File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is a table with the run function
-- and parameters given as an ordered list.
-- @class table
-- @name go_for_ext
local go_for_ext = {
c = { interpreter, '', '', { noext = true } },
cpp = { interpreter, '', '', { noext = true } },
java = { interpreter, 'java', '',
{ noext = true, nopath_path_with_flag = '-cp ' } },
lua = { interpreter, 'lua' },
pl = { interpreter, 'perl' },
php = { interpreter, 'php', '-f' },
py = { interpreter, 'python' },
rb = { interpreter, 'ruby' },
}
---
-- Runs/executes the file as specified by its extension in the go_for_ext table.
-- @see go_for_ext
function go()
if not buffer.filename then return end
local ext = buffer.filename:match('[^.]+$')
local action = go_for_ext[ext]
if not action then return end
local f, args = action[1], { unpack(action) }
table.remove(args, 1) -- function
f(unpack(args))
end
---
-- [Local table] A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- @class table
-- @name error_details
local error_details = {
-- c, c++, and java errors and warnings have the same format as ruby ones
lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
perl = {
pattern = '^(.+) at (.-) line (%d+)',
message = 1, filename = 2, line = 3
},
php_error = {
pattern = '^Parse error: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
php_warning = {
pattern = '^Warning: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
python = {
pattern = '^%s*File "([^"]+)", line (%d+)',
filename = 1, line = 2
},
ruby = {
pattern = '^(.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_details
function goto_error(pos, line_num)
if buffer.shows_messages or buffer.shows_errors then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_details) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
textadept.io.open(captures[error_detail.filename])
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
break
end
end
end
end
textadept.events.add_handler('double_click', goto_error)
|
Bugfixes in modules/textadept/run.lua If buffer.shows_errors, double-click should go to the error as well. Also, if the buffer's filename doesn't exist, don't Run or Compile it.
|
Bugfixes in modules/textadept/run.lua
If buffer.shows_errors, double-click should go to the error as well. Also, if
the buffer's filename doesn't exist, don't Run or Compile it.
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
5a282abd52cff4c49eb41dede4c9d493b3ae2715
|
testserver/item/id_2830_chest.lua
|
testserver/item/id_2830_chest.lua
|
-- UPDATE common SET com_script='item.id_2830_chest' WHERE com_itemid=2830;
require("base.common")
require("base.treasure")
module("item.id_2830_chest", package.seeall)
function LookAtItem(User, Item)
local TreasureName = base.treasure.GetTreasureName(tonumber(Item:getData("trsCat")), User:getPlayerLanguage(), false );
world:itemInform( User, Item, TreasureName );
end
function UseItem(User,SourceItem)
local level=tonumber(SourceItem:getData("trsCat"))
local posi=SourceItem.pos;
base.common.InformNLS(User, "Du ffnest die Schatzkiste...", "You open the treasure chest...");
world:erase(SourceItem,1);
if (level ~= nil) and (level < 10) then
world:gfx(16,posi);
world:makeSound(13,posi);
base.treasure.SpawnTreasure( level, posi );
else
base.common.InformNLS(User, "...sie ist leer!", "...it is empty!");
end
end
|
-- UPDATE common SET com_script='item.id_2830_chest' WHERE com_itemid=2830;
require("base.common")
require("base.treasure")
module("item.id_2830_chest", package.seeall)
function LookAtItem(User, Item)
local TreasureName = base.treasure.GetTreasureName(tonumber(Item:getData("trsCat")), User:getPlayerLanguage(), false );
base.lookat.SetSpecialDescription(Item,TreasureName, TreasureName);
world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) );
end
function UseItem(User,SourceItem)
local level=tonumber(SourceItem:getData("trsCat"))
local posi=SourceItem.pos;
base.common.InformNLS(User, "Du ffnest die Schatzkiste...", "You open the treasure chest...");
world:erase(SourceItem,1);
if (level ~= nil) and (level < 10) then
world:gfx(16,posi);
world:makeSound(13,posi);
base.treasure.SpawnTreasure( level, posi );
else
base.common.InformNLS(User, "...sie ist leer!", "...it is empty!");
end
end
|
lookat fix
|
lookat fix
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
|
5845be83c1cdc063873a652e122862fc4009f349
|
xmake/rules/winsdk/xmake.lua
|
xmake/rules/winsdk/xmake.lua
|
--!A cross-platform build utility based on 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.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: application
rule("win.sdk.application")
-- after load
after_load(function (target)
-- set kind: binary
target:set("kind", "binary")
-- set subsystem: windows
local subsystem = false
for _, ldflag in ipairs(target:get("ldflags")) do
ldflag = ldflag:lower()
if ldflag:find("[/%-]subsystem:") then
subsystem = true
break
end
end
if not subsystem then
target:add("ldflags", "-subsystem:windows", {force = true})
end
-- add links
target:add("links", "kernel32", "user32", "gdi32", "winspool", "comdlg32", "advapi32")
target:add("links", "shell32", "ole32", "oleaut32", "uuid", "odbc32", "odbccp32", "comctl32")
target:add("links", "cfgmgr32", "comdlg32", "setupapi", "strsafe", "shlwapi")
end)
|
--!A cross-platform build utility based on 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.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: application
rule("win.sdk.application")
-- add deps
add_deps("win.sdk.dotnet")
-- after load
after_load(function (target)
-- set kind: binary
target:set("kind", "binary")
-- set subsystem: windows
local subsystem = false
for _, ldflag in ipairs(target:get("ldflags")) do
ldflag = ldflag:lower()
if ldflag:find("[/%-]subsystem:") then
subsystem = true
break
end
end
if not subsystem then
target:add("ldflags", "-subsystem:windows", {force = true})
end
-- add links
target:add("links", "kernel32", "user32", "gdi32", "winspool", "comdlg32", "advapi32")
target:add("links", "shell32", "ole32", "oleaut32", "uuid", "odbc32", "odbccp32", "comctl32")
target:add("links", "cfgmgr32", "comdlg32", "setupapi", "strsafe", "shlwapi")
end)
|
fix win.sdk rule
|
fix win.sdk rule
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
|
8aeff3c84496a045088b9b445274b3d934bdf7bc
|
service/root.lua
|
service/root.lua
|
local ltask = require "ltask"
local root = require "ltask.root"
local config = ...
local MESSAGE_ERROR <const> = 3
local MESSAGE_SCHEDULE_NEW <const> = 0
local MESSAGE_SCHEDULE_DEL <const> = 1
local MESSAGE_SCHEDULE_HANG <const> = 2
local S = {}
local anonymous_services = {}
local named_services = {}
local labels = {
[0] = "system",
[1] = "root",
}
local function writelog()
while true do
local ti, id, msg, sz = ltask.poplog()
if ti == nil then
break
end
local tsec = ti // 100
local msec = ti % 100
local t = table.pack(ltask.unpack_remove(msg, sz))
local str = {}
for i = 1, t.n do
str[#str+1] = tostring(t[i])
end
io.write(string.format("[%s.%02d : %-10s]\t%s\n", os.date("%c", tsec), msec, labels[id], table.concat(str, "\t")))
end
end
do
-- root init response to itself
local function init_receipt(type, session, msg, sz)
if type == MESSAGE_ERROR then
ltask.log("Root init error:", ltask.unpack_remove(msg, sz))
writelog()
ltask.quit()
end
end
ltask.suspend(0, coroutine.create(init_receipt))
end
local tokenmap = {}
local function multi_wait(key)
local mtoken = tokenmap[key]
if not mtoken then
mtoken = {}
tokenmap[key] = mtoken
end
local t = {}
mtoken[#mtoken+1] = t
return ltask.wait(t)
end
local function multi_wakeup(key, ...)
local mtoken = tokenmap[key]
if mtoken then
tokenmap[key] = nil
for _, token in ipairs(mtoken) do
ltask.wakeup(token, ...)
end
end
end
local function multi_interrupt(key, ...)
local mtoken = tokenmap[key]
if mtoken then
tokenmap[key] = nil
for _, token in ipairs(mtoken) do
ltask.interrupt(token, ...)
end
end
end
local function init_service(address, name, ...)
root.init_service(address, name, config.init_service)
ltask.syscall(address, "init", {
lua_path = config.lua_path,
lua_cpath = config.lua_cpath,
service_path = config.service_path,
name = name,
args = {...},
})
end
local function new_service(name, ...)
local address = assert(ltask.post_message(0, 0, MESSAGE_SCHEDULE_NEW))
anonymous_services[address] = true
labels[address] = name
local ok, err = pcall(init_service, address, name, ...)
if not ok then
S.kill(address)
anonymous_services[address] = nil
labels[address] = nil
return nil, err
end
return address
end
local function register_service(address, name)
if named_services[name] then
error(("Name `%s` already exists."):format(name))
end
anonymous_services[address] = nil
named_services[#named_services+1] = name
named_services[name] = address
multi_wakeup("query."..name, address)
end
function S.report_error(addr, session, errobj)
ltask.error(addr, session, errobj)
end
function S.spawn(name, ...)
local address, err = new_service(name, ...)
if not address then
error(err)
end
return address
end
function S.kill(address)
if ltask.post_message(0, address, MESSAGE_SCHEDULE_HANG) then
return true
end
return false
end
function S.label(address)
return labels[address]
end
function S.register(name)
local session = ltask.current_session()
register_service(session.from, name)
end
function S.queryservice(name)
local address = named_services[name]
if address then
return address
end
return multi_wait("query."..name)
end
function S.uniqueservice(name, ...)
local address = named_services[name]
if address then
return address
end
local key = "unique."..name
if not tokenmap[key] then
ltask.fork(function (...)
local addr, err = new_service(name, ...)
if not addr then
multi_interrupt(key, err)
else
register_service(addr, name)
multi_wakeup(key, addr)
end
end, ...)
end
return multi_wait(key)
end
local function del_service(address)
if anonymous_services[address] then
anonymous_services[address] = nil
else
for _, name in ipairs(named_services) do
if named_services[name] == address then
break
end
end
end
local msg = root.close_service(address)
ltask.post_message(0,address, MESSAGE_SCHEDULE_DEL)
if msg then
for i=1, #msg, 2 do
local addr = msg[i]
local session = msg[i+1]
ltask.error(addr, session, "Service has been quit.")
end
end
end
local function signal_handler(from)
del_service(from)
if next(anonymous_services) == nil then
ltask.signal_handler(del_service)
for i = #named_services, 1, -1 do
local name = named_services[i]
local address = named_services[name]
local ok, err = pcall(ltask.syscall, address, "quit")
if not ok then
print(string.format("named service %s(%d) quit error: %s.", name, address, err))
end
end
writelog()
ltask.quit()
end
end
ltask.signal_handler(signal_handler)
local function boot()
local request = ltask.request()
for i, t in ipairs(config.exclusive) do
local name, args
if type(t) == "table" then
name = table.remove(t, 1)
args = t
else
name = t
args = {}
end
local id = i + 1
labels[id] = name
register_service(id, name)
request:add { id, proto = "system", "init", {
lua_path = config.lua_path,
lua_cpath = config.lua_cpath,
service_path = config.service_path,
name = name,
args = args,
exclusive = true,
}}
end
for req, resp in request:select() do
if not resp then
error(string.format("exclusive %d init error: %s.", req[1], req.error))
end
end
S.uniqueservice(table.unpack(config.logger))
S.spawn(table.unpack(config.bootstrap))
end
ltask.dispatch(S)
boot()
|
local ltask = require "ltask"
local root = require "ltask.root"
local config = ...
local MESSAGE_ERROR <const> = 3
local MESSAGE_SCHEDULE_NEW <const> = 0
local MESSAGE_SCHEDULE_DEL <const> = 1
local MESSAGE_SCHEDULE_HANG <const> = 2
local S = {}
local anonymous_services = {}
local named_services = {}
local labels = {
[0] = "system",
[1] = "root",
}
local function writelog()
while true do
local ti, id, msg, sz = ltask.poplog()
if ti == nil then
break
end
local tsec = ti // 100
local msec = ti % 100
local t = table.pack(ltask.unpack_remove(msg, sz))
local str = {}
for i = 1, t.n do
str[#str+1] = tostring(t[i])
end
io.write(string.format("[%s.%02d : %-10s]\t%s\n", os.date("%c", tsec), msec, labels[id], table.concat(str, "\t")))
end
end
do
-- root init response to itself
local function init_receipt(type, session, msg, sz)
if type == MESSAGE_ERROR then
ltask.log("Root init error:", ltask.unpack_remove(msg, sz))
writelog()
ltask.quit()
end
end
ltask.suspend(0, coroutine.create(init_receipt))
end
local tokenmap = {}
local function multi_wait(key)
local mtoken = tokenmap[key]
if not mtoken then
mtoken = {}
tokenmap[key] = mtoken
end
local t = {}
mtoken[#mtoken+1] = t
return ltask.wait(t)
end
local function multi_wakeup(key, ...)
local mtoken = tokenmap[key]
if mtoken then
tokenmap[key] = nil
for _, token in ipairs(mtoken) do
ltask.wakeup(token, ...)
end
end
end
local function multi_interrupt(key, ...)
local mtoken = tokenmap[key]
if mtoken then
tokenmap[key] = nil
for _, token in ipairs(mtoken) do
ltask.interrupt(token, ...)
end
end
end
local function init_service(address, name, ...)
root.init_service(address, name, config.init_service)
ltask.syscall(address, "init", {
lua_path = config.lua_path,
lua_cpath = config.lua_cpath,
service_path = config.service_path,
name = name,
args = {...},
})
end
local function new_service(name, ...)
local address = assert(ltask.post_message(0, 0, MESSAGE_SCHEDULE_NEW))
anonymous_services[address] = true
labels[address] = name
local ok, err = pcall(init_service, address, name, ...)
if not ok then
S.kill(address)
return nil, err
end
return address
end
local function register_service(address, name)
if named_services[name] then
error(("Name `%s` already exists."):format(name))
end
anonymous_services[address] = nil
named_services[#named_services+1] = name
named_services[name] = address
multi_wakeup("query."..name, address)
end
function S.report_error(addr, session, errobj)
ltask.error(addr, session, errobj)
end
function S.spawn(name, ...)
local address, err = new_service(name, ...)
if not address then
error(err)
end
return address
end
function S.kill(address)
if ltask.post_message(0, address, MESSAGE_SCHEDULE_HANG) then
return true
end
return false
end
function S.label(address)
return labels[address]
end
function S.register(name)
local session = ltask.current_session()
register_service(session.from, name)
end
function S.queryservice(name)
local address = named_services[name]
if address then
return address
end
return multi_wait("query."..name)
end
function S.uniqueservice(name, ...)
local address = named_services[name]
if address then
return address
end
local key = "unique."..name
if not tokenmap[key] then
ltask.fork(function (...)
local addr, err = new_service(name, ...)
if not addr then
multi_interrupt(key, err)
else
register_service(addr, name)
multi_wakeup(key, addr)
end
end, ...)
end
return multi_wait(key)
end
local function del_service(address)
labels[address] = nil
if anonymous_services[address] then
anonymous_services[address] = nil
else
for _, name in ipairs(named_services) do
if named_services[name] == address then
break
end
end
end
local msg = root.close_service(address)
ltask.post_message(0,address, MESSAGE_SCHEDULE_DEL)
if msg then
for i=1, #msg, 2 do
local addr = msg[i]
local session = msg[i+1]
ltask.error(addr, session, "Service has been quit.")
end
end
end
local function signal_handler(from)
del_service(from)
if next(anonymous_services) == nil then
ltask.signal_handler(del_service)
for i = #named_services, 1, -1 do
local name = named_services[i]
local address = named_services[name]
local ok, err = pcall(ltask.syscall, address, "quit")
if not ok then
print(string.format("named service %s(%d) quit error: %s.", name, address, err))
end
end
writelog()
ltask.quit()
end
end
ltask.signal_handler(signal_handler)
local function boot()
local request = ltask.request()
for i, t in ipairs(config.exclusive) do
local name, args
if type(t) == "table" then
name = table.remove(t, 1)
args = t
else
name = t
args = {}
end
local id = i + 1
labels[id] = name
register_service(id, name)
request:add { id, proto = "system", "init", {
lua_path = config.lua_path,
lua_cpath = config.lua_cpath,
service_path = config.service_path,
name = name,
args = args,
exclusive = true,
}}
end
for req, resp in request:select() do
if not resp then
error(string.format("exclusive %d init error: %s.", req[1], req.error))
end
end
S.uniqueservice(table.unpack(config.logger))
S.spawn(table.unpack(config.bootstrap))
end
ltask.dispatch(S)
boot()
|
fixes bug
|
fixes bug
|
Lua
|
mit
|
cloudwu/ltask
|
1a29651ab087e5bff8d392162b19609b1a4f39f5
|
test_scripts/Smoke/Resumption/008_Resumption_heartbeat_disconnect.lua
|
test_scripts/Smoke/Resumption/008_Resumption_heartbeat_disconnect.lua
|
-- Requirement summary:
-- [Data Resumption]: Data resumption on Unexpected Disconnect
--
-- Description:
-- Check that SDL perform resumption after heartbeat disconnect.
-- 1. Used precondition
-- In smartDeviceLink.ini file HeartBeatTimeout parameter is:
-- HeartBeatTimeout = 7000.
-- App is registerer and activated on HMI.
-- App has added 1 sub menu, 1 command and 1 choice set.
--
-- 2. Performed steps
-- Wait 20 seconds.
-- Register App with hashId.
--
-- Expected behavior:
-- 1. SDL sends OnAppUnregistered to HMI.
-- 2. App is registered and SDL resumes all App data, sends BC.ActivateApp to HMI, app gets FULL HMI level.
---------------------------------------------------------------------------------------------------
--[[ General Precondition before ATF start ]]
config.defaultProtocolVersion = 3
config.application1.registerAppInterfaceParams.isMediaApplication = true
-- [[ Required Shared Libraries ]]
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonStepsResumption = require('user_modules/shared_testcases/commonStepsResumption')
local mobile_session = require('mobile_session')
local events = require("events")
--[[ General Settings for configuration ]]
Test = require('user_modules/dummy_connecttest')
require('cardinalities')
require('user_modules/AppTypes')
-- [[Local variables]]
local default_app_params = config.application1.registerAppInterfaceParams
-- [[Local functions]]
local function connectMobile(self)
self.mobileConnection:Connect()
return EXPECT_EVENT(events.connectedEvent, "Connected")
end
local function delayedExp(pTime, self)
local event = events.Event()
event.matches = function(e1, e2) return e1 == e2 end
EXPECT_HMIEVENT(event, "Delayed event")
:Timeout(pTime + 5000)
local function toRun()
event_dispatcher:RaiseEvent(self.hmiConnection, event)
end
RUN_AFTER(toRun, pTime)
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
commonSteps:DeletePolicyTable()
commonSteps:DeleteLogsFiles()
function Test:StartSDL_With_One_Activated_App()
self:runSDL()
commonFunctions:waitForSDLStart(self):Do(function()
self:initHMI():Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady():Do(function ()
commonFunctions:userPrint(35, "HMI is ready")
connectMobile(self):Do(function ()
commonFunctions:userPrint(35, "Mobile Connected")
self:startSession():Do(function ()
commonFunctions:userPrint(35, "App is registered")
commonSteps:ActivateAppInSpecificLevel(self, self.applications[default_app_params.appName])
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL",audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
commonFunctions:userPrint(35, "App is activated")
end)
end)
end)
end)
end)
end
function Test.AddCommand()
commonStepsResumption:AddCommand()
end
function Test.AddSubMenu()
commonStepsResumption:AddSubMenu()
end
function Test.AddChoiceSet()
commonStepsResumption:AddChoiceSet()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Check that SDL perform resumption after heartbeat disconnect")
function Test:Wait_20_sec()
self.mobileSession:StopHeartbeat()
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[default_app_params], unexpectedDisconnect = true })
:Timeout(20000)
EXPECT_EVENT(events.disconnectedEvent, "Disconnected")
<<<<<<< HEAD:test_scripts/Smoke/Resumption/ATF_Resumption_heartbeat_disconnect.lua
:Times(0)
delayedExp(20000, self)
=======
:Do(function()
print("Disconnected!!!")
end)
:Timeout(20000)
end
function Test:Connect_Mobile()
connectMobile(self)
>>>>>>> origin/develop:test_scripts/Smoke/Resumption/008_Resumption_heartbeat_disconnect.lua
end
function Test:Register_And_Resume_App_And_Data()
local mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
local on_rpc_service_started = mobileSession:StartRPC()
on_rpc_service_started:Do(function()
default_app_params.hashID = self.currentHashID
commonStepsResumption:Expect_Resumption_Data(default_app_params)
commonStepsResumption:RegisterApp(default_app_params, commonStepsResumption.ExpectResumeAppFULL, true)
end)
end
-- [[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postcondition")
function Test.Stop_SDL()
StopSDL()
end
return Test
|
-- Requirement summary:
-- [Data Resumption]: Data resumption on Unexpected Disconnect
--
-- Description:
-- Check that SDL perform resumption after heartbeat disconnect.
-- 1. Used precondition
-- In smartDeviceLink.ini file HeartBeatTimeout parameter is:
-- HeartBeatTimeout = 7000.
-- App is registerer and activated on HMI.
-- App has added 1 sub menu, 1 command and 1 choice set.
--
-- 2. Performed steps
-- Wait 20 seconds.
-- Register App with hashId.
--
-- Expected behavior:
-- 1. SDL sends OnAppUnregistered to HMI.
-- 2. App is registered and SDL resumes all App data, sends BC.ActivateApp to HMI, app gets FULL HMI level.
---------------------------------------------------------------------------------------------------
--[[ General Precondition before ATF start ]]
config.defaultProtocolVersion = 3
config.application1.registerAppInterfaceParams.isMediaApplication = true
-- [[ Required Shared Libraries ]]
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonStepsResumption = require('user_modules/shared_testcases/commonStepsResumption')
local mobile_session = require('mobile_session')
local events = require("events")
--[[ General Settings for configuration ]]
Test = require('user_modules/dummy_connecttest')
require('cardinalities')
require('user_modules/AppTypes')
-- [[Local variables]]
local default_app_params = config.application1.registerAppInterfaceParams
-- [[Local functions]]
local function connectMobile(self)
self.mobileConnection:Connect()
return EXPECT_EVENT(events.connectedEvent, "Connected")
end
local function delayedExp(pTime, self)
local event = events.Event()
event.matches = function(e1, e2) return e1 == e2 end
EXPECT_HMIEVENT(event, "Delayed event")
:Timeout(pTime + 5000)
local function toRun()
event_dispatcher:RaiseEvent(self.hmiConnection, event)
end
RUN_AFTER(toRun, pTime)
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
commonSteps:DeletePolicyTable()
commonSteps:DeleteLogsFiles()
function Test:StartSDL_With_One_Activated_App()
self:runSDL()
commonFunctions:waitForSDLStart(self):Do(function()
self:initHMI():Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady():Do(function ()
commonFunctions:userPrint(35, "HMI is ready")
connectMobile(self):Do(function ()
commonFunctions:userPrint(35, "Mobile Connected")
self:startSession():Do(function ()
commonFunctions:userPrint(35, "App is registered")
commonSteps:ActivateAppInSpecificLevel(self, self.applications[default_app_params.appName])
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL",audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
commonFunctions:userPrint(35, "App is activated")
end)
end)
end)
end)
end)
end
function Test.AddCommand()
commonStepsResumption:AddCommand()
end
function Test.AddSubMenu()
commonStepsResumption:AddSubMenu()
end
function Test.AddChoiceSet()
commonStepsResumption:AddChoiceSet()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Check that SDL perform resumption after heartbeat disconnect")
function Test:Wait_20_sec()
self.mobileSession:StopHeartbeat()
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[default_app_params], unexpectedDisconnect = true })
:Timeout(20000)
EXPECT_EVENT(events.disconnectedEvent, "Disconnected")
:Times(0)
delayedExp(20000, self)
end
function Test:Register_And_Resume_App_And_Data()
local mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
local on_rpc_service_started = mobileSession:StartRPC()
on_rpc_service_started:Do(function()
default_app_params.hashID = self.currentHashID
commonStepsResumption:Expect_Resumption_Data(default_app_params)
commonStepsResumption:RegisterApp(default_app_params, commonStepsResumption.ExpectResumeAppFULL, true)
end)
end
-- [[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postcondition")
function Test.Stop_SDL()
StopSDL()
end
return Test
|
Fix merge conflict
|
Fix merge conflict
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
37af81e489a1f380b91500495caf1cca47bc8ba0
|
kong/plugins/oauth2/migrations/postgres.lua
|
kong/plugins/oauth2/migrations/postgres.lua
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
}
}
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local schema = factory.oauth2_credentials.schema
schema.fields.redirect_uri.type = "string"
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
}
}
|
hotfix(oauth2) missing migration for postgres (#1911)
|
hotfix(oauth2) missing migration for postgres (#1911)
|
Lua
|
apache-2.0
|
shiprabehera/kong,Kong/kong,Vermeille/kong,jebenexer/kong,salazar/kong,Mashape/kong,beauli/kong,Kong/kong,Kong/kong,akh00/kong,icyxp/kong,li-wl/kong,ccyphers/kong
|
58821b4bcb882a40dd8878a6347588a936df9397
|
gin/cli/launcher.lua
|
gin/cli/launcher.lua
|
-- dep
local ansicolors = require 'ansicolors'
-- gin
local Gin = require 'gin.core.gin'
local BaseLauncher = require 'gin.cli.base_launcher'
local helpers = require 'gin.helpers.common'
-- settings
local nginx_conf_source = 'config/nginx.conf'
local GinLauncher = {}
-- convert true|false to on|off
local function convert_boolean_to_onoff(value)
if value == true then value = 'on' else value = 'off' end
return value
end
-- get application database modules
local function database_modules()
return helpers.module_names_in_path(Gin.app_dirs.db)
end
-- add locations for databases
local function gin_init_databases(gin_init)
local modules = database_modules()
for _, module_name in ipairs(modules) do
local db = require(module_name)
if db.options.adapter == 'postgresql' then
local name = db.adapter.location_for(db.options)
gin_init = gin_init .. [[
upstream ]] .. name .. [[ {
postgres_server ]] .. db.options.host .. [[:]] .. db.options.port .. [[ dbname=]] .. db.options.database .. [[ user=]] .. db.options.user .. [[ password=]] .. db.options.password .. [[;
}
]]
end
end
return gin_init
end
-- gin init
local function gin_init(nginx_content)
-- gin init
local gin_init = [[
lua_code_cache ]] .. convert_boolean_to_onoff(Gin.settings.code_cache) .. [[;
lua_package_path "./?.lua;$prefix/lib/?.lua;#{= LUA_PACKAGE_PATH };;";
]]
-- add db upstreams
gin_init = gin_init_databases(gin_init)
return string.gsub(nginx_content, "{{GIN_INIT}}", gin_init)
end
-- add locations for databases
local function gin_runtime_databases(gin_runtime)
local modules = database_modules()
local postgresql_adapter = require 'gin.db.sql.postgresql.adapter'
for _, module_name in ipairs(modules) do
local db = require(module_name)
if db.options.adapter == 'postgresql' then
local location = postgresql_adapter.location_for(db.options)
local execute_location = postgresql_adapter.execute_location_for(db.options)
gin_runtime = gin_runtime .. [[
location = /]] .. execute_location .. [[ {
internal;
postgres_pass ]] .. location .. [[;
postgres_query $echo_request_body;
}
]]
end
end
return gin_runtime
end
-- gin runtime
local function gin_runtime(nginx_content)
local gin_runtime = [[
location / {
content_by_lua 'require(\"gin.core.router\").handler(ngx)';
}
]]
if Gin.settings.expose_api_console == true then
gin_runtime = gin_runtime .. [[
location /ginconsole {
content_by_lua 'require(\"gin.cli.api_console\").handler(ngx)';
}
]]
end
-- add db locations
gin_runtime = gin_runtime_databases(gin_runtime)
return string.gsub(nginx_content, "{{GIN_RUNTIME}}", gin_runtime)
end
function GinLauncher.nginx_conf_content()
-- read nginx.conf file
local nginx_conf_template = helpers.read_file(nginx_conf_source)
-- append notice
nginx_conf_template = [[
# ===================================================================== #
# THIS FILE IS AUTO GENERATED. DO NOT MODIFY. #
# IF YOU CAN SEE IT, THERE PROBABLY IS A RUNNING SERVER REFERENCING IT. #
# ===================================================================== #
]] .. nginx_conf_template
-- inject params in content
local nginx_content = nginx_conf_template
nginx_content = string.gsub(nginx_content, "{{GIN_PORT}}", Gin.settings.port)
nginx_content = string.gsub(nginx_content, "{{GIN_ENV}}", Gin.env)
-- gin imit & runtime
nginx_content = gin_init(nginx_content)
nginx_content = gin_runtime(nginx_content)
-- return
return nginx_content
end
function nginx_conf_file_path()
return Gin.app_dirs.tmp .. "/" .. Gin.env .. "-nginx.conf"
end
function base_launcher()
return BaseLauncher.new(GinLauncher.nginx_conf_content(), nginx_conf_file_path())
end
function GinLauncher.start(env)
-- init base_launcher
local ok, base_launcher = pcall(function() return base_launcher() end)
if ok == false then
print(ansicolors("%{red}ERROR:%{reset} Cannot initialize launcher: " .. base_launcher))
return
end
result = base_launcher:start(env)
if result == 0 then
if Gin.env ~= 'test' then
print(ansicolors("Gin app in %{cyan}" .. Gin.env .. "%{reset} was succesfully started on port " .. Gin.settings.port .. "."))
end
else
print(ansicolors("%{red}ERROR:%{reset} Could not start Gin app on port " .. Gin.settings.port .. " (is it running already?)."))
end
end
function GinLauncher.stop(env)
-- init base_launcher
local base_launcher = base_launcher()
result = base_launcher:stop(env)
if Gin.env ~= 'test' then
if result == 0 then
print(ansicolors("Gin app in %{cyan}" .. Gin.env .. "%{reset} was succesfully stopped."))
else
print(ansicolors("%{red}ERROR:%{reset} Could not stop Gin app (are you sure it is running?)."))
end
end
end
return GinLauncher
|
-- dep
local ansicolors = require 'ansicolors'
-- gin
local Gin = require 'gin.core.gin'
local BaseLauncher = require 'gin.cli.base_launcher'
local helpers = require 'gin.helpers.common'
-- settings
local nginx_conf_source = 'config/nginx.conf'
local GinLauncher = {}
-- convert true|false to on|off
local function convert_boolean_to_onoff(value)
if value == true then value = 'on' else value = 'off' end
return value
end
-- get application database modules
local function database_modules()
return helpers.module_names_in_path(Gin.app_dirs.db)
end
-- add upstream for databases
local function gin_init_databases(gin_init)
local modules = database_modules()
for _, module_name in ipairs(modules) do
local db = require(module_name)
if type(db) == "table" and db.options.adapter == 'postgresql' then
local name = db.adapter.location_for(db.options)
gin_init = gin_init .. [[
upstream ]] .. name .. [[ {
postgres_server ]] .. db.options.host .. [[:]] .. db.options.port .. [[ dbname=]] .. db.options.database .. [[ user=]] .. db.options.user .. [[ password=]] .. db.options.password .. [[;
}
]]
end
end
return gin_init
end
-- gin init
local function gin_init(nginx_content)
-- gin init
local gin_init = [[
lua_code_cache ]] .. convert_boolean_to_onoff(Gin.settings.code_cache) .. [[;
lua_package_path "./?.lua;$prefix/lib/?.lua;#{= LUA_PACKAGE_PATH };;";
]]
-- add db upstreams
gin_init = gin_init_databases(gin_init)
return string.gsub(nginx_content, "{{GIN_INIT}}", gin_init)
end
-- add locations for databases
local function gin_runtime_databases(gin_runtime)
local modules = database_modules()
local postgresql_adapter = require 'gin.db.sql.postgresql.adapter'
for _, module_name in ipairs(modules) do
local db = require(module_name)
if type(db) == "table" and db.options.adapter == 'postgresql' then
local location = postgresql_adapter.location_for(db.options)
local execute_location = postgresql_adapter.execute_location_for(db.options)
gin_runtime = gin_runtime .. [[
location = /]] .. execute_location .. [[ {
internal;
postgres_pass ]] .. location .. [[;
postgres_query $echo_request_body;
}
]]
end
end
return gin_runtime
end
-- gin runtime
local function gin_runtime(nginx_content)
local gin_runtime = [[
location / {
content_by_lua 'require(\"gin.core.router\").handler(ngx)';
}
]]
if Gin.settings.expose_api_console == true then
gin_runtime = gin_runtime .. [[
location /ginconsole {
content_by_lua 'require(\"gin.cli.api_console\").handler(ngx)';
}
]]
end
-- add db locations
gin_runtime = gin_runtime_databases(gin_runtime)
return string.gsub(nginx_content, "{{GIN_RUNTIME}}", gin_runtime)
end
function GinLauncher.nginx_conf_content()
-- read nginx.conf file
local nginx_conf_template = helpers.read_file(nginx_conf_source)
-- append notice
nginx_conf_template = [[
# ===================================================================== #
# THIS FILE IS AUTO GENERATED. DO NOT MODIFY. #
# IF YOU CAN SEE IT, THERE PROBABLY IS A RUNNING SERVER REFERENCING IT. #
# ===================================================================== #
]] .. nginx_conf_template
-- inject params in content
local nginx_content = nginx_conf_template
nginx_content = string.gsub(nginx_content, "{{GIN_PORT}}", Gin.settings.port)
nginx_content = string.gsub(nginx_content, "{{GIN_ENV}}", Gin.env)
-- gin imit & runtime
nginx_content = gin_init(nginx_content)
nginx_content = gin_runtime(nginx_content)
-- return
return nginx_content
end
function nginx_conf_file_path()
return Gin.app_dirs.tmp .. "/" .. Gin.env .. "-nginx.conf"
end
function base_launcher()
return BaseLauncher.new(GinLauncher.nginx_conf_content(), nginx_conf_file_path())
end
function GinLauncher.start(env)
-- init base_launcher
local ok, base_launcher = pcall(function() return base_launcher() end)
if ok == false then
print(ansicolors("%{red}ERROR:%{reset} Cannot initialize launcher: " .. base_launcher))
return
end
result = base_launcher:start(env)
if result == 0 then
if Gin.env ~= 'test' then
print(ansicolors("Gin app in %{cyan}" .. Gin.env .. "%{reset} was succesfully started on port " .. Gin.settings.port .. "."))
end
else
print(ansicolors("%{red}ERROR:%{reset} Could not start Gin app on port " .. Gin.settings.port .. " (is it running already?)."))
end
end
function GinLauncher.stop(env)
-- init base_launcher
local base_launcher = base_launcher()
result = base_launcher:stop(env)
if Gin.env ~= 'test' then
if result == 0 then
print(ansicolors("Gin app in %{cyan}" .. Gin.env .. "%{reset} was succesfully stopped."))
else
print(ansicolors("%{red}ERROR:%{reset} Could not stop Gin app (are you sure it is running?)."))
end
end
end
return GinLauncher
|
Fix issue #6.
|
Fix issue #6.
|
Lua
|
mit
|
ostinelli/gin,istr/gin
|
a73186b76c6e24ff22139c06db22642cc4a0ed5c
|
Modules/Utility/Raycaster.lua
|
Modules/Utility/Raycaster.lua
|
--- Repeats raycasting attempts while ignoring items via a filter function
-- @classmod Raycaster
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Workspace = game:GetService("Workspace")
local Table = require("Table")
local Raycaster = {}
Raycaster.ClassName = "Raycaster"
function Raycaster.new()
local self = setmetatable({
_ignoreWater = false,
_maxCasts = 5,
_ignoreList = {},
}, Raycaster)
return self
end
function Raycaster:Ignore(value)
local ignoreList = self.IgnoreList
if typeof(value) == "Instance" then
table.insert(ignoreList, value)
return
end
assert(type(value) == "table")
for _, item in pairs(value) do
table.insert(ignoreList, item)
end
end
function Raycaster:FindPartOnRay(ray)
assert(typeof(ray) == "Ray")
local casts = self.MaxCasts
while casts > 0 do
local result = self:_tryCast(ray)
if result then
return result
end
casts = casts - 1
end
end
function Raycaster:__index(index)
if index == "IgnoreList" then
return rawget(self, "_ignoreList")
elseif index == "Filter" then
return rawget(self, "_filter")
elseif index == "IgnoreWater" then
return rawget(self, "_ignoreWater")
elseif index == "MaxCasts" then
return rawget(self, "_maxCasts")
elseif Raycaster[index] then
return Raycaster[index]
else
error(("Unknown index '%s'"):format(tostring(index)))
end
end
function Raycaster:__newindex(index, value)
if index == "IgnoreWater" then
assert(type(value) == "boolean")
rawset(self, "_ignoreWater", value)
elseif index == "MaxCasts" then
assert(type(value) == "number")
rawset(self, "_maxCasts", value)
elseif index == "Filter" then
assert(type(value) == "function")
rawset(self, "_filter", value)
else
error(("Unknown index '%s'"):format(tostring(index)))
end
end
function Raycaster:_tryCast(ray)
local ignoreList = Table.Copy(self.IgnoreList)
local part, position, normal, material = Workspace:FindPartOnRayWithIgnoreList(
ray, ignoreList, false, self._ignoreWater)
if not part then
return nil
end
local data = {
Part = part;
Position = position;
Normal = normal;
Material = material;
}
local filter = self.Filter
if filter and filter(data) then
table.insert(ignoreList, part)
return nil
end
return data
end
return Raycaster
|
--- Repeats raycasting attempts while ignoring items via a filter function
-- @classmod Raycaster
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Workspace = game:GetService("Workspace")
local Table = require("Table")
local Raycaster = {}
Raycaster.ClassName = "Raycaster"
function Raycaster.new()
local self = setmetatable({
_ignoreWater = false,
_maxCasts = 5,
_ignoreList = {},
}, Raycaster)
return self
end
function Raycaster:Ignore(value)
local ignoreList = self.IgnoreList
if typeof(value) == "Instance" then
table.insert(ignoreList, value)
return
end
assert(type(value) == "table")
for _, item in pairs(value) do
table.insert(ignoreList, item)
end
end
function Raycaster:FindPartOnRay(ray)
assert(typeof(ray) == "Ray")
local ignoreList = Table.Copy(self._ignoreList)
local casts = self.MaxCasts
while casts > 0 do
local result = self:_tryCast(ray, ignoreList)
if result then
return result
end
casts = casts - 1
end
warn("Ran out of casts")
return nil
end
function Raycaster:__index(index)
if index == "IgnoreList" then
return rawget(self, "_ignoreList")
elseif index == "Filter" then
return rawget(self, "_filter")
elseif index == "IgnoreWater" then
return rawget(self, "_ignoreWater")
elseif index == "MaxCasts" then
return rawget(self, "_maxCasts")
elseif Raycaster[index] then
return Raycaster[index]
else
error(("Unknown index '%s'"):format(tostring(index)))
end
end
function Raycaster:__newindex(index, value)
if index == "IgnoreWater" then
assert(type(value) == "boolean")
rawset(self, "_ignoreWater", value)
elseif index == "MaxCasts" then
assert(type(value) == "number")
rawset(self, "_maxCasts", value)
elseif index == "Filter" then
assert(type(value) == "function")
rawset(self, "_filter", value)
else
error(("Unknown index '%s'"):format(tostring(index)))
end
end
function Raycaster:_tryCast(ray, ignoreList)
local part, position, normal, material = Workspace:FindPartOnRayWithIgnoreList(
ray, ignoreList, false, self._ignoreWater)
if not part then
return nil
end
local data = {
Part = part;
Position = position;
Normal = normal;
Material = material;
}
local filter = self.Filter
if filter and filter(data) then
table.insert(ignoreList, part)
return nil
end
return data
end
return Raycaster
|
Fix raycaster
|
Fix raycaster
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
66ab74194d5270b2ba8dd028aead6c7f9a661d50
|
mods/mesecons/mesecons_blinkyplant/init.lua
|
mods/mesecons/mesecons_blinkyplant/init.lua
|
-- The BLINKY_PLANT
local toggle_timer = function (pos)
local timer = minetest.get_node_timer(pos)
if timer:is_started() then
timer:stop()
else
timer:start(mesecon.setting("blinky_plant_interval", 3))
end
end
local on_timer = function (pos)
local node = minetest.get_node(pos)
if(mesecon.flipstate(pos, node) == "on") then
mesecon.receptor_on(pos)
else
mesecon.receptor_off(pos)
end
toggle_timer(pos)
end
mesecon.register_node("mesecons_blinkyplant:blinky_plant", {
description="Blinky Plant",
drawtype = "plantlike",
inventory_image = "jeija_blinky_plant_off.png",
paramtype = "light",
walkable = false,
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, -0.5+0.7, 0.3},
},
on_timer = on_timer,
on_rightclick = toggle_timer,
on_construct = toggle_timer
},{
tiles = {"jeija_blinky_plant_off.png"},
groups = {dig_immediate=3},
mesecons = {receptor = { state = mesecon.state.off }}
},{
tiles = {"jeija_blinky_plant_on.png"},
groups = {dig_immediate=3, not_in_creative_inventory=1},
mesecons = {receptor = { state = mesecon.state.on }}
})
minetest.register_craft({
output = "mesecons_blinkyplant:blinky_plant_off 1",
recipe = { {"","group:mesecon_conductor_craftable",""},
{"","group:mesecon_conductor_craftable",""},
{"group:sapling","group:sapling","group:sapling"}}
})
|
-- The BLINKY_PLANT
local toggle_timer = function (pos)
local timer = minetest.get_node_timer(pos)
if timer:is_started() then
timer:stop()
else
timer:start(mesecon.setting("blinky_plant_interval", 3))
end
end
local on_timer = function (pos)
-- DO NOT TOUCH OR.. THREATS! Thanks, MFF
local activate = false
for _, player in pairs(minetest.get_connected_players()) do
local p = player:getpos()
local dist = ((p.x-pos.x)^2 + (p.y-pos.y)^2 + (p.z-pos.z)^2)^0.5
if dist < 40 then
activate = true
break
end
end
if activate then
local node = minetest.get_node(pos)
if(mesecon.flipstate(pos, node) == "on") then
mesecon.receptor_on(pos)
else
mesecon.receptor_off(pos)
end
-- Our modification stops there, thank you, @crabman77
end
toggle_timer(pos)
end
mesecon.register_node("mesecons_blinkyplant:blinky_plant", {
description="Blinky Plant",
drawtype = "plantlike",
inventory_image = "jeija_blinky_plant_off.png",
paramtype = "light",
walkable = false,
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, -0.5+0.7, 0.3},
},
on_timer = on_timer,
on_rightclick = toggle_timer,
on_construct = toggle_timer
},{
tiles = {"jeija_blinky_plant_off.png"},
groups = {dig_immediate=3},
mesecons = {receptor = { state = mesecon.state.off }}
},{
tiles = {"jeija_blinky_plant_on.png"},
groups = {dig_immediate=3, not_in_creative_inventory=1},
mesecons = {receptor = { state = mesecon.state.on }}
})
minetest.register_craft({
output = "mesecons_blinkyplant:blinky_plant_off 1",
recipe = { {"","group:mesecon_conductor_craftable",""},
{"","group:mesecon_conductor_craftable",""},
{"group:sapling","group:sapling","group:sapling"}}
})
|
[mesecons] Add back blinky fix with flags
|
[mesecons] Add back blinky fix with flags
|
Lua
|
unlicense
|
LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server
|
4988af5db4ee8887567bad1763fbac3df267950a
|
src/base/os.lua
|
src/base/os.lua
|
--
-- os.lua
-- Additions to the OS namespace.
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
--
-- Same as os.execute(), but accepts string formatting arguments.
--
function os.executef(cmd, ...)
cmd = string.format(cmd, unpack(arg))
return os.execute(cmd)
end
--
-- Scan the well-known system locations for a particular library.
--
function os.findlib(libname)
local path, formats
-- assemble a search path, depending on the platform
if os.is("windows") then
formats = { "%s.dll", "%s" }
path = os.getenv("PATH")
elseif os.is("haiku") then
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LIBRARY_PATH")
else
if os.is("macosx") then
formats = { "lib%s.dylib", "%s.dylib" }
path = os.getenv("DYLD_LIBRARY_PATH")
else
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LD_LIBRARY_PATH") or ""
io.input("/etc/ld.so.conf")
if io.input() then
for line in io.lines() do
path = path .. ":" .. line
end
io.input():close()
end
end
table.insert(formats, "%s")
path = path or ""
if os.is64bit() then
path = path .. ":/lib64:/usr/lib64/:usr/local/lib64"
end
path = ":/lib:/usr/lib:/usr/local/lib"
end
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
local result = os.pathsearch(name, path)
if result then return result end
end
end
--
-- Retrieve the current operating system ID string.
--
function os.get()
return _OPTIONS.os or _OS
end
--
-- Check the current operating system; may be set with the /os command line flag.
--
function os.is(id)
return (os.get():lower() == id:lower())
end
--
-- Determine if the current system is running a 64-bit architecture
--
local _64BitHostTypes = {
"x86_64",
"ia64",
"amd64",
"ppc64",
"powerpc64",
"sparc64"
}
function os.is64bit()
-- Call the native code implementation. If this returns true then
-- we're 64-bit, otherwise do more checking locally
if (os._is64bit()) then
return true
end
-- Identify the system
local arch
if _OS == "windows" then
arch = os.getenv("PROCESSOR_ARCHITECTURE")
elseif _OS == "macosx" then
arch = os.outputof("echo $HOSTTYPE")
else
arch = os.outputof("uname -m")
end
-- Check our known 64-bit identifiers
arch = arch:lower()
for _, hosttype in ipairs(_64BitHostTypes) do
if arch:find(hosttype) then
return true
end
end
return false
end
--
-- The os.matchdirs() and os.matchfiles() functions
--
local function domatch(result, mask, wantfiles)
-- need to remove extraneous path info from the mask to ensure a match
-- against the paths returned by the OS. Haven't come up with a good
-- way to do it yet, so will handle cases as they come up
if mask:startswith("./") then
mask = mask:sub(3)
end
-- strip off any leading directory information to find out
-- where the search should take place
local basedir = mask
local starpos = mask:find("%*")
if starpos then
basedir = basedir:sub(1, starpos - 1)
end
basedir = path.getdirectory(basedir)
if (basedir == ".") then basedir = "" end
-- recurse into subdirectories?
local recurse = mask:find("**", nil, true)
-- convert mask to a Lua pattern
mask = path.wildcards(mask)
local function matchwalker(basedir)
local wildcard = path.join(basedir, "*")
-- retrieve files from OS and test against mask
local m = os.matchstart(wildcard)
while (os.matchnext(m)) do
local isfile = os.matchisfile(m)
if ((wantfiles and isfile) or (not wantfiles and not isfile)) then
local fname = path.join(basedir, os.matchname(m))
if fname:match(mask) == fname then
table.insert(result, fname)
end
end
end
os.matchdone(m)
-- check subdirectories
if recurse then
m = os.matchstart(wildcard)
while (os.matchnext(m)) do
if not os.matchisfile(m) then
local dirname = os.matchname(m)
matchwalker(path.join(basedir, dirname))
end
end
os.matchdone(m)
end
end
matchwalker(basedir)
end
function os.matchdirs(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, false)
end
return result
end
function os.matchfiles(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, true)
end
return result
end
--
-- An overload of the os.mkdir() function, which will create any missing
-- subdirectories along the path.
--
local builtin_mkdir = os.mkdir
function os.mkdir(p)
local dir = iif(p:startswith("/"), "/", "")
for part in p:gmatch("[^/]+") do
dir = dir .. part
if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then
local ok, err = builtin_mkdir(dir)
if (not ok) then
return nil, err
end
end
dir = dir .. "/"
end
return true
end
--
-- Run a shell command and return the output.
--
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
return result
end
--
-- Remove a directory, along with any contained files or subdirectories.
--
local builtin_rmdir = os.rmdir
function os.rmdir(p)
-- recursively remove subdirectories
local dirs = os.matchdirs(p .. "/*")
for _, dname in ipairs(dirs) do
os.rmdir(dname)
end
-- remove any files
local files = os.matchfiles(p .. "/*")
for _, fname in ipairs(files) do
os.remove(fname)
end
-- remove this directory
builtin_rmdir(p)
end
|
--
-- os.lua
-- Additions to the OS namespace.
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
--
-- Same as os.execute(), but accepts string formatting arguments.
--
function os.executef(cmd, ...)
cmd = string.format(cmd, unpack(arg))
return os.execute(cmd)
end
--
-- Scan the well-known system locations for a particular library.
--
function os.findlib(libname)
local path, formats
-- assemble a search path, depending on the platform
if os.is("windows") then
formats = { "%s.dll", "%s" }
path = os.getenv("PATH")
elseif os.is("haiku") then
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LIBRARY_PATH")
else
if os.is("macosx") then
formats = { "lib%s.dylib", "%s.dylib" }
path = os.getenv("DYLD_LIBRARY_PATH")
else
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LD_LIBRARY_PATH") or ""
io.input("/etc/ld.so.conf")
if io.input() then
for line in io.lines() do
path = path .. ":" .. line
end
io.input():close()
end
end
table.insert(formats, "%s")
path = path or ""
if os.is64bit() then
path = path .. ":/lib64:/usr/lib64/:usr/local/lib64"
end
path = path .. ":/lib:/usr/lib:/usr/local/lib"
end
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
local result = os.pathsearch(name, path)
if result then return result end
end
end
--
-- Retrieve the current operating system ID string.
--
function os.get()
return _OPTIONS.os or _OS
end
--
-- Check the current operating system; may be set with the /os command line flag.
--
function os.is(id)
return (os.get():lower() == id:lower())
end
--
-- Determine if the current system is running a 64-bit architecture
--
local _64BitHostTypes = {
"x86_64",
"ia64",
"amd64",
"ppc64",
"powerpc64",
"sparc64"
}
function os.is64bit()
-- Call the native code implementation. If this returns true then
-- we're 64-bit, otherwise do more checking locally
if (os._is64bit()) then
return true
end
-- Identify the system
local arch
if _OS == "windows" then
arch = os.getenv("PROCESSOR_ARCHITECTURE")
elseif _OS == "macosx" then
arch = os.outputof("echo $HOSTTYPE")
else
arch = os.outputof("uname -m")
end
-- Check our known 64-bit identifiers
arch = arch:lower()
for _, hosttype in ipairs(_64BitHostTypes) do
if arch:find(hosttype) then
return true
end
end
return false
end
--
-- The os.matchdirs() and os.matchfiles() functions
--
local function domatch(result, mask, wantfiles)
-- need to remove extraneous path info from the mask to ensure a match
-- against the paths returned by the OS. Haven't come up with a good
-- way to do it yet, so will handle cases as they come up
if mask:startswith("./") then
mask = mask:sub(3)
end
-- strip off any leading directory information to find out
-- where the search should take place
local basedir = mask
local starpos = mask:find("%*")
if starpos then
basedir = basedir:sub(1, starpos - 1)
end
basedir = path.getdirectory(basedir)
if (basedir == ".") then basedir = "" end
-- recurse into subdirectories?
local recurse = mask:find("**", nil, true)
-- convert mask to a Lua pattern
mask = path.wildcards(mask)
local function matchwalker(basedir)
local wildcard = path.join(basedir, "*")
-- retrieve files from OS and test against mask
local m = os.matchstart(wildcard)
while (os.matchnext(m)) do
local isfile = os.matchisfile(m)
if ((wantfiles and isfile) or (not wantfiles and not isfile)) then
local fname = path.join(basedir, os.matchname(m))
if fname:match(mask) == fname then
table.insert(result, fname)
end
end
end
os.matchdone(m)
-- check subdirectories
if recurse then
m = os.matchstart(wildcard)
while (os.matchnext(m)) do
if not os.matchisfile(m) then
local dirname = os.matchname(m)
matchwalker(path.join(basedir, dirname))
end
end
os.matchdone(m)
end
end
matchwalker(basedir)
end
function os.matchdirs(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, false)
end
return result
end
function os.matchfiles(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, true)
end
return result
end
--
-- An overload of the os.mkdir() function, which will create any missing
-- subdirectories along the path.
--
local builtin_mkdir = os.mkdir
function os.mkdir(p)
local dir = iif(p:startswith("/"), "/", "")
for part in p:gmatch("[^/]+") do
dir = dir .. part
if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then
local ok, err = builtin_mkdir(dir)
if (not ok) then
return nil, err
end
end
dir = dir .. "/"
end
return true
end
--
-- Run a shell command and return the output.
--
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
return result
end
--
-- Remove a directory, along with any contained files or subdirectories.
--
local builtin_rmdir = os.rmdir
function os.rmdir(p)
-- recursively remove subdirectories
local dirs = os.matchdirs(p .. "/*")
for _, dname in ipairs(dirs) do
os.rmdir(dname)
end
-- remove any files
local files = os.matchfiles(p .. "/*")
for _, fname in ipairs(files) do
os.remove(fname)
end
-- remove this directory
builtin_rmdir(p)
end
|
Fixed broken lib search path from last commit (h/t coh)
|
Fixed broken lib search path from last commit (h/t coh)
|
Lua
|
bsd-3-clause
|
warrenseine/premake,annulen/premake,annulen/premake,annulen/premake,warrenseine/premake,warrenseine/premake,Lusito/premake,Lusito/premake,annulen/premake,Lusito/premake,Lusito/premake
|
2487ed2856f91cd0e55fc52d5dd20192f8760886
|
hikyuu_cpp/unit_test/xmake.lua
|
hikyuu_cpp/unit_test/xmake.lua
|
add_requires("doctest")
function coverage_report(target)
if is_mode("coverage") and not is_plat("windows") and not (linuxos.name() == "ubuntu" and linuxos.version():lt("20.0")) then
-- 如需分支覆盖,须在下面 lcov, genhtml 命令后都加入: --rc lcov_branch_coverage=1
print("Processing coverage info ...")
if not os.isfile("cover-init.info") then
-- 初始化并创建基准数据文件
os.run("lcov -c -i -d ./ -o cover-init.info")
end
-- 移除之前的结果,否则容易出错
os.tryrm('cover.info')
os.tryrm('cover-total.info')
-- 收集当前测试文件运行后产生的覆盖率文件
os.run("lcov -c -d ./ -o cover.info")
-- 合并基准数据和执行测试文件后生成的覆盖率数据
os.exec("lcov -a cover-init.info -a cover.info -o cover-total.info")
-- 删除统计信息中如下的代码或文件,支持正则
os.run("lcov --remove cover-total.info '*/usr/include/*' \
'*/usr/lib/*' '*/usr/lib64/*' '*/usr/local/include/*' '*/usr/local/lib/*' '*/usr/local/lib64/*' \
'*/test/*' '*/.xmake*' '*/boost/*' '*/ffmpeg/*' \
'*/cpp/yihua/ocr_module/clipper.*' -o cover-final.info")
-- 生成的html及相关文件的目录名称,--legend 简单的统计信息说明
os.exec("genhtml -o cover_report --legend --title 'yhsdk' --prefix=" .. os.projectdir() .. " cover-final.info")
-- 生成 sonar 可读取报告
if is_plat("linux") then
os.run("gcovr -r . -e cpp/test -e 'cpp/yihua/ocr_module/clipper.*' --xml -o coverage.xml")
end
end
end
target("unit-test")
set_kind("binary")
set_default(false)
add_packages("fmt", "spdlog", "doctest", "mysql", "sqlite3")
add_includedirs("..")
if is_plat("windows") then
add_cxflags("-wd4267")
add_cxflags("-wd4251")
add_cxflags("-wd4244")
add_cxflags("-wd4805")
add_cxflags("-wd4566")
else
add_cxflags("-Wno-unused-variable", "-Wno-missing-braces")
add_cxflags("-Wno-sign-compare")
end
if is_plat("windows") and is_mode("release") then
add_defines("HKU_API=__declspec(dllimport)")
end
add_defines("TEST_ALL_IN_ONE")
add_deps("hikyuu")
if is_plat("linux") or is_plat("macosx") then
add_links("boost_unit_test_framework")
add_links("boost_filesystem")
add_links("boost_serialization")
add_links("sqlite3")
add_shflags("-Wl,-rpath=$ORIGIN", "-Wl,-rpath=$ORIGIN/../lib")
end
if is_plat("macosx") then
add_includedirs("/usr/local/opt/mysql-client/include")
add_linkdirs("/usr/local/opt/mysql-client/lib")
end
-- add files
add_files("**.cpp")
after_run(coverage_report)
target_end()
target("small-test")
set_kind("binary")
set_default(false)
add_packages("fmt", "spdlog", "doctest", "mysql", "sqlite3")
add_includedirs("..")
--add_defines("BOOST_TEST_DYN_LINK")
if is_plat("windows") then
add_cxflags("-wd4267")
add_cxflags("-wd4251")
add_cxflags("-wd4244")
add_cxflags("-wd4805")
add_cxflags("-wd4566")
else
add_cxflags("-Wno-unused-variable", "-Wno-missing-braces")
add_cxflags("-Wno-sign-compare")
end
if is_plat("windows") and is_mode("release") then
add_defines("HKU_API=__declspec(dllimport)")
end
add_defines("TEST_ALL_IN_ONE")
add_deps("hikyuu")
if is_plat("linux") or is_plat("macosx") then
add_links("boost_unit_test_framework")
add_links("boost_filesystem")
add_shflags("-Wl,-rpath=$ORIGIN", "-Wl,-rpath=$ORIGIN/../lib")
end
-- add files
add_files("./hikyuu/hikyuu/**.cpp");
add_files("./hikyuu/test_main.cpp")
after_run(coverage_report)
target_end()
|
add_requires("doctest")
function coverage_report(target)
if is_mode("coverage") and not is_plat("windows") and not (linuxos.name() == "ubuntu" and linuxos.version():lt("20.0")) then
-- 如需分支覆盖,须在下面 lcov, genhtml 命令后都加入: --rc lcov_branch_coverage=1
print("Processing coverage info ...")
if not os.isfile("cover-init.info") then
-- 初始化并创建基准数据文件
os.run("lcov -c -i -d ./ -o cover-init.info")
end
-- 移除之前的结果,否则容易出错
os.tryrm('cover.info')
os.tryrm('cover-total.info')
-- 收集当前测试文件运行后产生的覆盖率文件
os.run("lcov -c -d ./ -o cover.info")
-- 合并基准数据和执行测试文件后生成的覆盖率数据
os.exec("lcov -a cover-init.info -a cover.info -o cover-total.info")
-- 删除统计信息中如下的代码或文件,支持正则
os.run("lcov --remove cover-total.info '*/usr/include/*' \
'*/usr/lib/*' '*/usr/lib64/*' '*/usr/local/include/*' '*/usr/local/lib/*' '*/usr/local/lib64/*' \
'*/test/*' '*/.xmake*' '*/boost/*' '*/ffmpeg/*' \
'*/cpp/yihua/ocr_module/clipper.*' -o cover-final.info")
-- 生成的html及相关文件的目录名称,--legend 简单的统计信息说明
os.exec("genhtml -o cover_report --legend --title 'yhsdk' --prefix=" .. os.projectdir() .. " cover-final.info")
-- 生成 sonar 可读取报告
if is_plat("linux") then
os.run("gcovr -r . -e cpp/test -e 'cpp/yihua/ocr_module/clipper.*' --xml -o coverage.xml")
end
end
end
target("unit-test")
set_kind("binary")
set_default(false)
add_packages("fmt", "spdlog", "doctest", "mysql", "sqlite3")
add_includedirs("..")
if is_plat("windows") then
add_cxflags("-wd4267")
add_cxflags("-wd4251")
add_cxflags("-wd4244")
add_cxflags("-wd4805")
add_cxflags("-wd4566")
else
add_cxflags("-Wno-unused-variable", "-Wno-missing-braces")
add_cxflags("-Wno-sign-compare")
end
if is_plat("windows") and is_mode("release") then
add_defines("HKU_API=__declspec(dllimport)")
end
add_defines("TEST_ALL_IN_ONE")
add_deps("hikyuu")
if is_plat("linux") or is_plat("macosx") then
add_links("boost_unit_test_framework")
add_links("boost_filesystem")
add_links("boost_serialization")
add_links("sqlite3")
add_shflags("-Wl,-rpath=$ORIGIN", "-Wl,-rpath=$ORIGIN/../lib")
end
if is_plat("macosx") then
add_includedirs("/usr/local/opt/mysql-client/include")
add_linkdirs("/usr/local/opt/mysql-client/lib")
end
-- add files
add_files("**.cpp")
after_run(coverage_report)
target_end()
target("small-test")
set_kind("binary")
set_default(false)
add_packages("fmt", "spdlog", "doctest", "mysql", "sqlite3")
add_includedirs("..")
--add_defines("BOOST_TEST_DYN_LINK")
if is_plat("windows") then
add_cxflags("-wd4267")
add_cxflags("-wd4251")
add_cxflags("-wd4244")
add_cxflags("-wd4805")
add_cxflags("-wd4566")
else
add_cxflags("-Wno-unused-variable", "-Wno-missing-braces")
add_cxflags("-Wno-sign-compare")
end
if is_plat("windows") and is_mode("release") then
add_defines("HKU_API=__declspec(dllimport)")
end
add_defines("TEST_ALL_IN_ONE")
add_deps("hikyuu")
if is_plat("linux") or is_plat("macosx") then
add_links("boost_unit_test_framework")
add_links("boost_filesystem")
add_links("boost_atomic")
add_shflags("-Wl,-rpath=$ORIGIN", "-Wl,-rpath=$ORIGIN/../lib")
end
-- add files
add_files("./hikyuu/hikyuu/**.cpp");
add_files("./hikyuu/test_main.cpp")
after_run(coverage_report)
target_end()
|
fix: python setup,py test 找不到libboost_atomic.so
|
fix: python setup,py test 找不到libboost_atomic.so
|
Lua
|
mit
|
fasiondog/hikyuu
|
c0cc2843482ac9f5b746cadc0e5191c2c960d96a
|
src/xml2ddsl.lua
|
src/xml2ddsl.lua
|
#!/usr/bin/env lua
--[[
(c) 2005-2015 Copyright, Real-Time Innovations, All rights reserved.
Permission to modify and use for internal purposes granted.
This software is provided "as is", without warranty, express or implied.
--]]
--[[
-------------------------------------------------------------------------------
Purpose: Utility to read an XML file as DDSL, and print the equivalent IDL
Created: Rajive Joshi, 2015 Jun 26
-------------------------------------------------------------------------------
--]]
package.path = '?.lua;?/init.lua;' .. package.path
local xtypes = require('ddsl.xtypes')
local xml = require('ddsl.xtypes.xml')
local xutils = require('ddsl.xtypes.utils')
local function main(arg)
if #arg == 0 then
print('Usage: ' .. arg[0] .. [[' [-t] <xml-file> [ <xml-files> ...]
where:
-t turn tracing ON
<xml-file> is an XML file
Imports all the XML files into a single X-Types global namespace.
Cross-references between files are resolved. However, duplicates
definitions are not permitted within a global namespace.
If there could be duplicates (ie multiple global namespaces), those files
should be processed in separate command line invocations of this utility.
]])
return
end
-- turn on tracing?
if '-t' == arg[1] then
table.remove(arg, 1) -- pop the argument
xml.is_trace_on = true
end
-- import XML files
local ns = xml.filelist2xtypes(arg)
-- print on stdout
print('\n********* DDSL: Global X-Types Namespace *********')
for _, datatype in ipairs(ns) do
-- print IDL
local idl = xutils.visit_model(ns, {'\t'})
print(table.concat(idl, '\n\t'))
-- TODO: print the DDSL representation
end
print('\n********* DDSL: ' .. #ns .. ' elements *********')
end
main(arg)
|
#!/usr/bin/env lua
--[[
(c) 2005-2015 Copyright, Real-Time Innovations, All rights reserved.
Permission to modify and use for internal purposes granted.
This software is provided "as is", without warranty, express or implied.
--]]
--[[
-------------------------------------------------------------------------------
Purpose: Utility to read an XML file as DDSL, and print the equivalent IDL
Created: Rajive Joshi, 2015 Jun 26
-------------------------------------------------------------------------------
--]]
package.path = '?.lua;?/init.lua;' .. package.path
local xtypes = require('ddsl.xtypes')
local xml = require('ddsl.xtypes.xml')
local xutils = require('ddsl.xtypes.utils')
local function main(arg)
if #arg == 0 then
print('Usage: ' .. arg[0] .. [[' [-t] <xml-file> [ <xml-files> ...]
where:
-t turn tracing ON
<xml-file> is an XML file
Imports all the XML files into a single X-Types global namespace.
Cross-references between files are resolved. However, duplicates
definitions are not permitted within a global namespace.
If there could be duplicates (ie multiple global namespaces), those files
should be processed in separate command line invocations of this utility.
]])
return
end
-- turn on tracing?
if '-t' == arg[1] then
table.remove(arg, 1) -- pop the argument
xml.is_trace_on = true
end
-- import XML files
local ns = xml.filelist2xtypes(arg)
-- print as IDL on stdout
print(table.concat(xutils.visit_model(ns), '\n'))
-- TODO: print the DDSL representation
end
main(arg)
|
xml2ddsl program: - fixed output format - fixed duplicate printing
|
xml2ddsl program:
- fixed output format
- fixed duplicate printing
|
Lua
|
apache-2.0
|
rticommunity/rticonnextdds-ddsl,rticommunity/rticonnextdds-ddsl,sutambe/rticonnextdds-ddsl
|
2e5d3740aeae0c5f0f1d2f853cbac145fe52469b
|
lib/bc.lua
|
lib/bc.lua
|
----------------------------------------------------------------------------
-- LuaJIT bytecode listing module.
--
-- Copyright (C) 2005-2010 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module lists the bytecode of a Lua function. If it's loaded by -jbc
-- it hooks into the parser and lists all functions of a chunk as they
-- are parsed.
--
-- Example usage:
--
-- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)'
-- luajit -jbc=- foo.lua
-- luajit -jbc=foo.list foo.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_LISTFILE. The file is overwritten every time the module
-- is started.
--
-- This module can also be used programmatically:
--
-- local bc = require("jit.bc")
--
-- local function foo() print("hello") end
--
-- bc.dump(foo) --> -- BYTECODE -- [...]
-- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello"
--
-- local out = {
-- -- Do something with each line:
-- write = function(t, ...) io.write(...) end,
-- close = function(t) end,
-- flush = function(t) end,
-- }
-- bc.dump(foo, out)
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20000, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local bit = require("bit")
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, band, shr = string.byte, bit.band, bit.rshift
local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck
local funcuvname = jutil.funcuvname
local bcnames = vmdef.bcnames
local stdout, stderr = io.stdout, io.stderr
------------------------------------------------------------------------------
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
elseif c == "\r" then return "\\r"
else return format("\\%03d", byte(c))
end
end
-- Return one bytecode line.
local function bcline(func, pc, prefix)
local ins, m = funcbc(func, pc)
if not ins then return end
local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128)
local a = band(shr(ins, 8), 0xff)
local oidx = 6*band(ins, 0xff)
local s = format("%04d %s %-6s %3s ",
pc, prefix or " ", sub(bcnames, oidx+1, oidx+6), ma == 0 and "" or a)
local d = shr(ins, 16)
if mc == 13*128 then -- BCMjump
if ma == 0 then
return format("%s=> %04d\n", sub(s, 1, -3), pc+d-0x7fff)
end
return format("%s=> %04d\n", s, pc+d-0x7fff)
end
if mb ~= 0 then d = band(d, 0xff) end
local kc
if mc == 10*128 then -- BCMstr
kc = funck(func, -d-1)
kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub))
elseif mc == 9*128 then -- BCMnum
kc = funck(func, d)
elseif mc == 12*128 then -- BCMfunc
local fi = funcinfo(funck(func, -d-1))
if fi.ffid then
kc = vmdef.ffnames[fi.ffid]
else
kc = fi.loc
end
elseif mc == 5*128 then -- BCMuv
kc = funcuvname(func, d)
end
if ma == 5 then -- BCMuv
local ka = funcuvname(func, a)
if kc then kc = ka.." ; "..kc else kc = ka end
end
if mb ~= 0 then
local b = shr(ins, 24)
if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end
return format("%s%3d %3d\n", s, b, d)
end
if kc then return format("%s%3d ; %s\n", s, d, kc) end
if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits
return format("%s%3d\n", s, d)
end
-- Collect branch targets of a function.
local function bctargets(func)
local target = {}
for pc=1,1000000000 do
local ins, m = funcbc(func, pc)
if not ins then break end
if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end
end
return target
end
-- Dump bytecode instructions of a function.
local function bcdump(func, out)
if not out then out = stdout end
local fi = funcinfo(func)
out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined))
local target = bctargets(func)
for pc=1,1000000000 do
local s = bcline(func, pc, target[pc] and "=>")
if not s then break end
out:write(s)
end
out:write("\n")
out:flush()
end
------------------------------------------------------------------------------
-- Active flag and output file handle.
local active, out
-- List handler.
local function h_list(func)
return bcdump(func, out)
end
-- Detach list handler.
local function bclistoff()
if active then
active = false
jit.attach(h_list)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach list handler.
local function bcliston(outfile)
if active then bclistoff() end
if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(h_list, "bc")
active = true
end
-- Public module functions.
module(...)
line = bcline
dump = bcdump
targets = bctargets
on = bcliston
off = bclistoff
start = bcliston -- For -j command line option.
|
----------------------------------------------------------------------------
-- LuaJIT bytecode listing module.
--
-- Copyright (C) 2005-2010 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module lists the bytecode of a Lua function. If it's loaded by -jbc
-- it hooks into the parser and lists all functions of a chunk as they
-- are parsed.
--
-- Example usage:
--
-- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)'
-- luajit -jbc=- foo.lua
-- luajit -jbc=foo.list foo.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_LISTFILE. The file is overwritten every time the module
-- is started.
--
-- This module can also be used programmatically:
--
-- local bc = require("jit.bc")
--
-- local function foo() print("hello") end
--
-- bc.dump(foo) --> -- BYTECODE -- [...]
-- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello"
--
-- local out = {
-- -- Do something with each line:
-- write = function(t, ...) io.write(...) end,
-- close = function(t) end,
-- flush = function(t) end,
-- }
-- bc.dump(foo, out)
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20000, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local bit = require("bit")
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, band, shr = string.byte, bit.band, bit.rshift
local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck
local funcuvname = jutil.funcuvname
local bcnames = vmdef.bcnames
local stdout, stderr = io.stdout, io.stderr
------------------------------------------------------------------------------
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
elseif c == "\r" then return "\\r"
else return format("\\%03d", byte(c))
end
end
-- Return one bytecode line.
local function bcline(func, pc, prefix)
local ins, m = funcbc(func, pc)
if not ins then return end
local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128)
local a = band(shr(ins, 8), 0xff)
local oidx = 6*band(ins, 0xff)
local s = format("%04d %s %-6s %3s ",
pc, prefix or " ", sub(bcnames, oidx+1, oidx+6), ma == 0 and "" or a)
local d = shr(ins, 16)
if mc == 13*128 then -- BCMjump
return format("%s=> %04d\n", s, pc+d-0x7fff)
end
if mb ~= 0 then
d = band(d, 0xff)
elseif mc == 0 then
return s.."\n"
end
local kc
if mc == 10*128 then -- BCMstr
kc = funck(func, -d-1)
kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub))
elseif mc == 9*128 then -- BCMnum
kc = funck(func, d)
elseif mc == 12*128 then -- BCMfunc
local fi = funcinfo(funck(func, -d-1))
if fi.ffid then
kc = vmdef.ffnames[fi.ffid]
else
kc = fi.loc
end
elseif mc == 5*128 then -- BCMuv
kc = funcuvname(func, d)
end
if ma == 5 then -- BCMuv
local ka = funcuvname(func, a)
if kc then kc = ka.." ; "..kc else kc = ka end
end
if mb ~= 0 then
local b = shr(ins, 24)
if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end
return format("%s%3d %3d\n", s, b, d)
end
if kc then return format("%s%3d ; %s\n", s, d, kc) end
if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits
return format("%s%3d\n", s, d)
end
-- Collect branch targets of a function.
local function bctargets(func)
local target = {}
for pc=1,1000000000 do
local ins, m = funcbc(func, pc)
if not ins then break end
if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end
end
return target
end
-- Dump bytecode instructions of a function.
local function bcdump(func, out)
if not out then out = stdout end
local fi = funcinfo(func)
out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined))
local target = bctargets(func)
for pc=1,1000000000 do
local s = bcline(func, pc, target[pc] and "=>")
if not s then break end
out:write(s)
end
out:write("\n")
out:flush()
end
------------------------------------------------------------------------------
-- Active flag and output file handle.
local active, out
-- List handler.
local function h_list(func)
return bcdump(func, out)
end
-- Detach list handler.
local function bclistoff()
if active then
active = false
jit.attach(h_list)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach list handler.
local function bcliston(outfile)
if active then bclistoff() end
if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(h_list, "bc")
active = true
end
-- Public module functions.
module(...)
line = bcline
dump = bcdump
targets = bctargets
on = bcliston
off = bclistoff
start = bcliston -- For -j command line option.
|
Fix dump of bytecode instructions with missing operands.
|
Fix dump of bytecode instructions with missing operands.
|
Lua
|
apache-2.0
|
dpino/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabb,Igalia/snabb,dpino/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,heryii/snabb,snabbco/snabb,snabbco/snabb,heryii/snabb,eugeneia/snabb,eugeneia/snabbswitch,snabbco/snabb,dpino/snabb,heryii/snabb,dpino/snabb,Igalia/snabb,dpino/snabb,Igalia/snabb,dpino/snabbswitch,dpino/snabbswitch,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,heryii/snabb,dpino/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,heryii/snabb,dpino/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,heryii/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,eugeneia/snabb,dpino/snabb,Igalia/snabb
|
3657b8c444c5a0db2864e9f237c20d4f95c00178
|
nyagos.lua
|
nyagos.lua
|
print "Nihongo Yet Another GOing Shell"
print "Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG"
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
function set(equation)
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original) then
right = right .. ";" .. original
else
right = original
end
end
if right then
right = string.gsub(right,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
nyagos.setenv(left,right)
end
end
function alias(equation)
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
exec = nyagos.exec
alias 'assoc=%COMSPEC% /c assoc $*'
alias 'attrib=%COMSPEC% /c attrib $*'
alias 'copy=%COMSPEC% /c copy $*'
alias 'del=%COMSPEC% /c del $*'
alias 'dir=%COMSPEC% /c dir $*'
alias 'for=%COMSPEC% /c for $*'
alias 'md=%COMSPEC% /c md $*'
alias 'mkdir=%COMSPEC% /c mkdir $*'
alias 'mklink=%COMSPEC% /c mklink $*'
alias 'move=%COMSPEC% /c move $*'
alias 'open=%COMSPEC% /c for %I in ($*) do @start "%I"'
alias 'rd=%COMSPEC% /c rd $*'
alias 'ren=%COMSPEC% /c ren $*'
alias 'rename=%COMSPEC% /c rename $*'
alias 'rmdir=%COMSPEC% /c rmdir $*'
alias 'start=%COMSPEC% /c start $*'
alias 'type=%COMSPEC% /c type $*'
alias 'ls=ls -oF $*'
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
exec "cd"
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
print "Nihongo Yet Another GOing Shell"
print "Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG"
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
function set(equation)
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original) then
right = right .. ";" .. original
else
right = original
end
end
if right then
right = string.gsub(right,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
nyagos.setenv(left,right)
end
end
function alias(equation)
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
exec = nyagos.exec
alias 'assoc=%COMSPEC% /c assoc $*'
alias 'attrib=%COMSPEC% /c attrib $*'
alias 'copy=%COMSPEC% /c copy $*'
alias 'del=%COMSPEC% /c del $*'
alias 'dir=%COMSPEC% /c dir $*'
alias 'for=%COMSPEC% /c for $*'
alias 'md=%COMSPEC% /c md $*'
alias 'mkdir=%COMSPEC% /c mkdir $*'
alias 'mklink=%COMSPEC% /c mklink $*'
alias 'move=%COMSPEC% /c move $*'
alias 'open=%COMSPEC% /c for %I in ($*) do @start "%I"'
alias 'rd=%COMSPEC% /c rd $*'
alias 'ren=%COMSPEC% /c ren $*'
alias 'rename=%COMSPEC% /c rename $*'
alias 'rmdir=%COMSPEC% /c rmdir $*'
alias 'start=%COMSPEC% /c start $*'
alias 'type=%COMSPEC% /c type $*'
alias 'ls=ls -oF $*'
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
exec "cd"
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
Fix: nyagos.lua の改行コードが CRLF ではなく、全て LF になっていた
|
Fix: nyagos.lua の改行コードが CRLF ではなく、全て LF になっていた
|
Lua
|
bsd-3-clause
|
hattya/nyagos,tsuyoshicho/nyagos,tyochiai/nyagos,kissthink/nyagos,kissthink/nyagos,hattya/nyagos,hattya/nyagos,kissthink/nyagos,nocd5/nyagos,zetamatta/nyagos
|
e3b52bc7ea58331c0583ccb769c378890df99bd5
|
plugins/itunes_album_artwork.lua
|
plugins/itunes_album_artwork.lua
|
local itunes_album_artwork = {}
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('dkjson')
local functions = require('functions')
function itunes_album_artwork:init(configuration)
itunes_album_artwork.command = 'albumart <song/album>'
itunes_album_artwork.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('albumart', true).table
itunes_album_artwork.documentation = configuration.command_prefix .. 'albumart <song> - Returns a high-quality version of the given song\'s album artwork, from iTunes.'
end
function itunes_album_artwork:action(msg, configuration)
local input = functions.input(msg.text)
if not input then
functions.send_reply(msg, itunes_album_artwork.documentation)
return
else
local url = configuration.apis.itunes .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
functions.send_reply(msg, configuration.errors.connection)
return
else
local jdat = JSON.decode(jstr)
if tonumber(jdat.resultCount) > 0 then
if jdat.results[1].artworkUrl100 then
local artworkUrl100 = jdat.results[1].artworkUrl100:gsub('/100x100bb.jpg', '/10000x10000bb.jpg')
telegram_api.sendChatAction{ chat_id = msg.chat.id, action = 'upload_photo' }
functions.send_photo(msg.chat.id, functions.download_to_file(artworkUrl100))
return
else
functions.send_reply(msg, configuration.errors.results)
return
end
else
functions.send_reply(msg, configuration.errors.results)
return
end
end
end
end
return itunes_album_artwork
|
local itunes_album_artwork = {}
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('dkjson')
local functions = require('functions')
local telegram_api = require('telegram_api')
function itunes_album_artwork:init(configuration)
itunes_album_artwork.command = 'albumart <song/album>'
itunes_album_artwork.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('albumart', true).table
itunes_album_artwork.documentation = configuration.command_prefix .. 'albumart <song> - Returns a high-quality version of the given song\'s album artwork, from iTunes.'
end
function itunes_album_artwork:action(msg, configuration)
local input = functions.input(msg.text)
if not input then
functions.send_reply(msg, itunes_album_artwork.documentation)
return
else
local url = configuration.apis.itunes .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
functions.send_reply(msg, configuration.errors.connection)
return
else
local jdat = JSON.decode(jstr)
if tonumber(jdat.resultCount) > 0 then
if jdat.results[1].artworkUrl100 then
local artworkUrl100 = jdat.results[1].artworkUrl100:gsub('/100x100bb.jpg', '/10000x10000bb.jpg')
telegram_api.sendChatAction{ chat_id = msg.chat.id, action = 'upload_photo' }
functions.send_photo(msg.chat.id, functions.download_to_file(artworkUrl100))
return
else
functions.send_reply(msg, configuration.errors.results)
return
end
else
functions.send_reply(msg, configuration.errors.results)
return
end
end
end
end
return itunes_album_artwork
|
mattata v2.2.1
|
mattata v2.2.1
Minor bug fix (itunes_album_artwork.lua)
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
67a709c1ae2884586539015d1ddd58226720ff08
|
kong/plugins/key-auth/handler.lua
|
kong/plugins/key-auth/handler.lua
|
local constants = require "kong.constants"
local BasePlugin = require "kong.plugins.base_plugin"
local type = type
local _realm = 'Key realm="' .. _KONG._NAME .. '"'
local KeyAuthHandler = BasePlugin:extend()
KeyAuthHandler.PRIORITY = 1003
KeyAuthHandler.VERSION = "0.2.0"
function KeyAuthHandler:new()
KeyAuthHandler.super.new(self, "key-auth")
end
local function load_credential(key)
local cred, err = kong.db.keyauth_credentials:select_by_key(key)
if not cred then
return nil, err
end
return cred
end
local function load_consumer(consumer_id, anonymous)
local result, err = kong.db.consumers:select({ id = consumer_id })
if not result then
if anonymous and not err then
err = 'anonymous consumer "' .. consumer_id .. '" not found'
end
return nil, err
end
return result
end
local function set_consumer(consumer, credential)
local const = constants.HEADERS
local new_headers = {
[const.CONSUMER_ID] = consumer.id,
[const.CONSUMER_CUSTOM_ID] = tostring(consumer.custom_id),
[const.CONSUMER_USERNAME] = consumer.username,
}
kong.client.authenticate(consumer, credential)
if credential then
new_headers[const.CREDENTIAL_USERNAME] = credential.username
kong.service.request.clear_header(const.ANONYMOUS) -- in case of auth plugins concatenation
else
new_headers[const.ANONYMOUS] = true
end
kong.service.request.set_headers(new_headers)
end
local function do_authentication(conf)
if type(conf.key_names) ~= "table" then
kong.log.err("no conf.key_names set, aborting plugin execution")
return nil, { status = 500, message = "Invalid plugin configuration" }
end
local headers = kong.request.get_headers()
local query = kong.request.get_query()
local key
local body
-- read in the body if we want to examine POST args
if conf.key_in_body then
local err
body, err = kong.request.get_body()
if err then
kong.log.err("Cannot process request body: ", err)
return nil, { status = 400, message = "Cannot process request body" }
end
end
-- search in headers & querystring
for i = 1, #conf.key_names do
local name = conf.key_names[i]
local v = headers[name]
if not v then
-- search in querystring
v = query[name]
end
-- search the body, if we asked to
if not v and conf.key_in_body then
v = body[name]
end
if type(v) == "string" then
key = v
if conf.hide_credentials then
query[name] = nil
kong.service.request.set_query(query)
kong.service.request.clear_header(name)
if conf.key_in_body then
body[name] = nil
kong.service.request.set_body(body)
end
end
break
elseif type(v) == "table" then
-- duplicate API key
return nil, { status = 401, message = "Duplicate API key found" }
end
end
-- this request is missing an API key, HTTP 401
if not key then
kong.response.set_header("WWW-Authenticate", _realm)
return nil, { status = 401, message = "No API key found in request" }
end
-- retrieve our consumer linked to this API key
local cache = kong.cache
local credential_cache_key = kong.db.keyauth_credentials:cache_key(key)
local credential, err = cache:get(credential_cache_key, nil, load_credential,
key)
if err then
kong.log.err(err)
return kong.response.exit(500, "An unexpected error occurred")
end
-- no credential in DB, for this key, it is invalid, HTTP 403
if not credential then
return nil, { status = 403, message = "Invalid authentication credentials" }
end
-----------------------------------------
-- Success, this request is authenticated
-----------------------------------------
-- retrieve the consumer linked to this API key, to set appropriate headers
local consumer_cache_key, consumer
consumer_cache_key = kong.db.consumers:cache_key(credential.consumer.id)
consumer, err = cache:get(consumer_cache_key, nil, load_consumer,
credential.consumer.id)
if err then
kong.log.err(err)
return nil, { status = 500, message = "An unexpected error occurred" }
end
set_consumer(consumer, credential)
return true
end
function KeyAuthHandler:access(conf)
KeyAuthHandler.super.access(self)
-- check if preflight request and whether it should be authenticated
if not conf.run_on_preflight and kong.request.get_method() == "OPTIONS" then
return
end
if conf.anonymous and kong.client.get_credential() then
-- we're already authenticated, and we're configured for using anonymous,
-- hence we're in a logical OR between auth methods and we're already done.
return
end
local ok, err = do_authentication(conf)
if not ok then
if conf.anonymous then
-- get anonymous user
local consumer_cache_key = kong.db.consumers:cache_key(conf.anonymous)
local consumer, err = kong.cache:get(consumer_cache_key, nil,
load_consumer, conf.anonymous, true)
if err then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
set_consumer(consumer, nil)
else
return kong.response.exit(err.status, { message = err.message }, err.headers)
end
end
end
return KeyAuthHandler
|
local constants = require "kong.constants"
local BasePlugin = require "kong.plugins.base_plugin"
local kong = kong
local type = type
local _realm = 'Key realm="' .. _KONG._NAME .. '"'
local KeyAuthHandler = BasePlugin:extend()
KeyAuthHandler.PRIORITY = 1003
KeyAuthHandler.VERSION = "1.0.0"
function KeyAuthHandler:new()
KeyAuthHandler.super.new(self, "key-auth")
end
local function load_credential(key)
local cred, err = kong.db.keyauth_credentials:select_by_key(key)
if not cred then
return nil, err
end
return cred
end
local function load_consumer(consumer_id, anonymous)
local result, err = kong.db.consumers:select({ id = consumer_id })
if not result then
if anonymous and not err then
err = 'anonymous consumer "' .. consumer_id .. '" not found'
end
return nil, err
end
return result
end
local function set_consumer(consumer, credential)
local set_header = kong.service.request.set_header
local clear_header = kong.service.request.clear_header
if consumer and consumer.id then
set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
else
clear_header(constants.HEADERS.CONSUMER_ID)
end
if consumer and consumer.custom_id then
set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
else
clear_header(constants.HEADERS.CONSUMER_CUSTOM_ID)
end
if consumer and consumer.username then
set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
else
clear_header(constants.HEADERS.CONSUMER_USERNAME)
end
kong.client.authenticate(consumer, credential)
if credential then
if credential.username then
set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username)
else
clear_header(constants.HEADERS.CREDENTIAL_USERNAME)
end
clear_header(constants.HEADERS.ANONYMOUS)
else
clear_header(constants.HEADERS.CREDENTIAL_USERNAME)
set_header(constants.HEADERS.ANONYMOUS, true)
end
end
local function do_authentication(conf)
if type(conf.key_names) ~= "table" then
kong.log.err("no conf.key_names set, aborting plugin execution")
return nil, { status = 500, message = "Invalid plugin configuration" }
end
local headers = kong.request.get_headers()
local query = kong.request.get_query()
local key
local body
-- read in the body if we want to examine POST args
if conf.key_in_body then
local err
body, err = kong.request.get_body()
if err then
kong.log.err("Cannot process request body: ", err)
return nil, { status = 400, message = "Cannot process request body" }
end
end
-- search in headers & querystring
for i = 1, #conf.key_names do
local name = conf.key_names[i]
local v = headers[name]
if not v then
-- search in querystring
v = query[name]
end
-- search the body, if we asked to
if not v and conf.key_in_body then
v = body[name]
end
if type(v) == "string" then
key = v
if conf.hide_credentials then
query[name] = nil
kong.service.request.set_query(query)
kong.service.request.clear_header(name)
if conf.key_in_body then
body[name] = nil
kong.service.request.set_body(body)
end
end
break
elseif type(v) == "table" then
-- duplicate API key
return nil, { status = 401, message = "Duplicate API key found" }
end
end
-- this request is missing an API key, HTTP 401
if not key then
kong.response.set_header("WWW-Authenticate", _realm)
return nil, { status = 401, message = "No API key found in request" }
end
-- retrieve our consumer linked to this API key
local cache = kong.cache
local credential_cache_key = kong.db.keyauth_credentials:cache_key(key)
local credential, err = cache:get(credential_cache_key, nil, load_credential,
key)
if err then
kong.log.err(err)
return kong.response.exit(500, "An unexpected error occurred")
end
-- no credential in DB, for this key, it is invalid, HTTP 403
if not credential then
return nil, { status = 403, message = "Invalid authentication credentials" }
end
-----------------------------------------
-- Success, this request is authenticated
-----------------------------------------
-- retrieve the consumer linked to this API key, to set appropriate headers
local consumer_cache_key, consumer
consumer_cache_key = kong.db.consumers:cache_key(credential.consumer.id)
consumer, err = cache:get(consumer_cache_key, nil, load_consumer,
credential.consumer.id)
if err then
kong.log.err(err)
return nil, { status = 500, message = "An unexpected error occurred" }
end
set_consumer(consumer, credential)
return true
end
function KeyAuthHandler:access(conf)
KeyAuthHandler.super.access(self)
-- check if preflight request and whether it should be authenticated
if not conf.run_on_preflight and kong.request.get_method() == "OPTIONS" then
return
end
if conf.anonymous and kong.client.get_credential() then
-- we're already authenticated, and we're configured for using anonymous,
-- hence we're in a logical OR between auth methods and we're already done.
return
end
local ok, err = do_authentication(conf)
if not ok then
if conf.anonymous then
-- get anonymous user
local consumer_cache_key = kong.db.consumers:cache_key(conf.anonymous)
local consumer, err = kong.cache:get(consumer_cache_key, nil,
load_consumer, conf.anonymous, true)
if err then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
set_consumer(consumer, nil)
else
return kong.response.exit(err.status, { message = err.message }, err.headers)
end
end
end
return KeyAuthHandler
|
fix(key-auth) make plugin defensive against possible errors and nil header values
|
fix(key-auth) make plugin defensive against possible errors and nil header values
|
Lua
|
apache-2.0
|
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
|
b609a5f4ebafe5b8e31962ba86e69312b23f251b
|
pud/ui/TextEntry.lua
|
pud/ui/TextEntry.lua
|
local Class = require 'lib.hump.class'
local Text = getClass 'pud.ui.Text'
local KeyboardEvent = getClass 'pud.event.KeyboardEvent'
local string_len = string.len
local string_sub = string.sub
local format = string.format
-- TextEntry
-- A text frame that gathers keyboard input.
local TextEntry = Class{name='TextEntry',
inherits=Text,
function(self, ...)
Text.construct(self, ...)
InputEvents:register(self, KeyboardEvent)
end
}
-- destructor
function TextEntry:destroy()
self._isEnteringText = nil
-- Frame will unregister all InputEvents
Text.destroy(self)
end
-- override Frame:onRelease()
function TextEntry:onRelease(button, mods, wasInside)
if wasInside and 'l' == button then
self._isEnteringText = not self._isEnteringText
end
if self._isEnteringText then
self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle
elseif self._hovered then
self._curStyle = self._hoverStyle or self._normalStyle
else
self._curStyle = self._normalStyle
end
self:_drawFB()
end
-- override Frame:onHoverIn()
function TextEntry:onHoverIn(x, y)
if self._isEnteringText then return end
Text.onHoverIn(self, x, y)
end
-- override TextEntry:onHoverOut()
function TextEntry:onHoverOut(x, y)
if self._isEnteringText then return end
Text.onHoverOut(self, x, y)
end
-- capture text input if in editing mode
function TextEntry:KeyboardEvent(e)
if not self._isEnteringText then return end
if self._text then
-- copy the entire text
local text = {}
local numLines = #self._text
for i=1,numLines do text[i] = self._text[i] end
local lineNum = numLines
if lineNum < 1 then lineNum = 1 end
local line = text[lineNum] or ''
local key = e:getKey()
switch(key) {
backspace = function()
line = string_sub(line, 1, -2)
if string.len(line) < 1 then
text[lineNum] = nil
lineNum = lineNum - 1
if lineNum < 1 then lineNum = 1 end
line = text[lineNum] or ''
end
end,
['return'] = function()
local nextLine = lineNum + 1
if nextLine > self._maxLines then nextLine = self._maxLines end
text[nextLine] = text[nextLine] or ''
end,
escape = function()
self._isEnteringText = false
self:onRelease()
end,
default = function()
local unicode = e:getUnicode()
if unicode then
line = format('%s%s', line, unicode)
end
end,
}
text[lineNum] = line
self:setText(text)
self:_drawFB()
else
warning('Text is missing!')
end
end
-- the class
return TextEntry
|
local Class = require 'lib.hump.class'
local Text = getClass 'pud.ui.Text'
local KeyboardEvent = getClass 'pud.event.KeyboardEvent'
local string_len = string.len
local string_sub = string.sub
local format = string.format
-- TextEntry
-- A text frame that gathers keyboard input.
local TextEntry = Class{name='TextEntry',
inherits=Text,
function(self, ...)
Text.construct(self, ...)
InputEvents:register(self, KeyboardEvent)
end
}
-- destructor
function TextEntry:destroy()
self._isEnteringText = nil
-- Frame will unregister all InputEvents
Text.destroy(self)
end
-- override Frame:onRelease()
function TextEntry:onRelease(button, mods)
if self._pressed then
if 'l' == button then
self._isEnteringText = not self._isEnteringText
end
end
end
-- override Frame:onHoverIn()
function TextEntry:onHoverIn(x, y)
if self._isEnteringText then return end
Text.onHoverIn(self, x, y)
end
-- override Frame:onHoverOut()
function TextEntry:onHoverOut(x, y)
if self._isEnteringText then return end
Text.onHoverOut(self, x, y)
end
-- override Frame:switchToNormalStyle()
function TextEntry:switchToNormalStyle()
if self._isEnteringText then return end
Text.switchToNormalStyle(self)
end
-- override Frame:switchToHoverStyle()
function TextEntry:switchToHoverStyle()
if self._isEnteringText then return end
Text.switchToHoverStyle(self)
end
-- capture text input if in editing mode
function TextEntry:KeyboardEvent(e)
if not self._isEnteringText then return end
if self._text then
-- copy the entire text
local text = {}
local numLines = #self._text
for i=1,numLines do text[i] = self._text[i] end
local lineNum = numLines
if lineNum < 1 then lineNum = 1 end
local line = text[lineNum] or ''
local key = e:getKey()
switch(key) {
backspace = function()
line = string_sub(line, 1, -2)
if string.len(line) < 1 then
text[lineNum] = nil
lineNum = lineNum - 1
if lineNum < 1 then lineNum = 1 end
line = text[lineNum] or ''
end
end,
['return'] = function()
local nextLine = lineNum + 1
if nextLine > self._maxLines then nextLine = self._maxLines end
text[nextLine] = text[nextLine] or ''
end,
escape = function()
self._isEnteringText = false
self:_handleMouseRelease(love.mouse.getPosition())
end,
default = function()
local unicode = e:getUnicode()
if unicode then
line = format('%s%s', line, unicode)
end
end,
}
text[lineNum] = line
self:setText(text)
self:_drawFB()
else
warning('Text is missing!')
end
end
-- the class
return TextEntry
|
fix TextEntry to work with latest changes to mouse events
|
fix TextEntry to work with latest changes to mouse events
|
Lua
|
mit
|
scottcs/wyx
|
57c249712a007344c2c554e02eb7af8874027ef6
|
spec/01-unit/013-reports_spec.lua
|
spec/01-unit/013-reports_spec.lua
|
local meta = require "kong.meta"
local helpers = require "spec.helpers"
local reports = require "kong.core.reports"
describe("reports", function()
describe("send()", function()
setup(function()
reports.toggle(true)
end)
it("sends report over UDP", function()
local thread = helpers.udp_server(8189)
reports.send("stub", {
hello = "world",
foo = "bar",
baz = function() return "bat" end,
}, "127.0.0.1", 8189)
local ok, res = thread:join()
assert.True(ok)
assert.matches("^<14>", res)
res = res:sub(5)
assert.matches("cores=%d+", res)
assert.matches("uname=[%w]+", res)
assert.matches("version=" .. meta._VERSION, res, nil, true)
assert.matches("hostname=[%w]+", res)
assert.matches("foo=bar", res, nil, true)
assert.matches("hello=world", res, nil, true)
assert.matches("signal=stub", res, nil, true)
assert.matches("baz=bat", res, nil, true)
end)
it("doesn't send if not enabled", function()
reports.toggle(false)
local thread = helpers.udp_server(8189)
reports.send({
foo = "bar"
}, "127.0.0.1", 8189)
local ok, res, err = thread:join()
assert.True(ok)
assert.is_nil(res)
assert.equal("timeout", err)
end)
end)
describe("retrieve_redis_version()", function()
before_each(function()
package.loaded["kong.core.reports"] = nil
reports = require "kong.core.reports"
reports.toggle(true)
end)
it("does not query Redis if not enabled", function()
reports.toggle(false)
local red_mock = {
info = function() end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_not_called()
end)
it("queries Redis if enabled", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_called_with(red_mock, "server")
end)
it("queries Redis only once", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
reports.retrieve_redis_version(red_mock)
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_called(1)
end)
it("retrieves major.minor version", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("2.4", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (1/3)", function()
local red_mock = {
info = function()
return nil
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (2/3)", function()
local red_mock = {
info = function()
return ngx.null
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (3/3)", function()
local red_mock = {
info = function()
return "hello world"
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
end)
end)
|
local meta = require "kong.meta"
local helpers = require "spec.helpers"
local reports = require "kong.core.reports"
describe("reports", function()
describe("send()", function()
setup(function()
reports.toggle(true)
end)
it("sends report over UDP", function()
local thread = helpers.udp_server(8189)
reports.send("stub", {
hello = "world",
foo = "bar",
baz = function() return "bat" end,
}, "127.0.0.1", 8189)
local ok, res = thread:join()
assert.True(ok)
assert.matches("^<14>", res)
res = res:sub(5)
assert.matches("cores=%d+", res)
assert.matches("uname=[%w]+", res)
assert.matches("version=" .. meta._VERSION, res, nil, true)
assert.matches("hostname=[%w]+", res)
assert.matches("foo=bar", res, nil, true)
assert.matches("hello=world", res, nil, true)
assert.matches("signal=stub", res, nil, true)
assert.matches("baz=bat", res, nil, true)
end)
it("doesn't send if not enabled", function()
reports.toggle(false)
local thread = helpers.udp_server(8189)
reports.send({
foo = "bar"
}, "127.0.0.1", 8189)
local ok, res, err = thread:join()
assert.True(ok)
assert.is_nil(res)
assert.equal("timeout", err)
end)
end)
describe("retrieve_redis_version()", function()
setup(function()
_G.ngx = ngx
_G.ngx.log = function() return end
end)
before_each(function()
package.loaded["kong.core.reports"] = nil
reports = require "kong.core.reports"
reports.toggle(true)
end)
it("does not query Redis if not enabled", function()
reports.toggle(false)
local red_mock = {
info = function() end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_not_called()
end)
it("queries Redis if enabled", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_called_with(red_mock, "server")
end)
it("queries Redis only once", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
local s = spy.on(red_mock, "info")
reports.retrieve_redis_version(red_mock)
reports.retrieve_redis_version(red_mock)
reports.retrieve_redis_version(red_mock)
assert.spy(s).was_called(1)
end)
it("retrieves major.minor version", function()
local red_mock = {
info = function()
return "redis_version:2.4.5\r\nredis_git_sha1:e09e31b1"
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("2.4", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (1/3)", function()
local red_mock = {
info = function()
return nil
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (2/3)", function()
local red_mock = {
info = function()
return ngx.null
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
it("retrieves 'unknown' when the version could not be retrieved (3/3)", function()
local red_mock = {
info = function()
return "hello world"
end,
}
reports.retrieve_redis_version(red_mock)
assert.equal("unknown", reports.get_ping_value("redis_version"))
end)
end)
end)
|
fix(tests) silence unnecessary stderr output in reports tests
|
fix(tests) silence unnecessary stderr output in reports tests
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,jebenexer/kong,Mashape/kong
|
88beaed5eb942904c113c3bb923730b9bcafa55d
|
conf/vertices.lua
|
conf/vertices.lua
|
access = {
["no"] = 0,
["official"] = 0,
["private"] = 0,
["destination"] = 0,
["yes"] = 7,
["permissive"] = 7,
["agricultural"] = 0,
["customers"] = 7
}
motor_vehicle = {
["no"] = 0,
["yes"] = 1,
["agricultural"] = 0,
["destination"] = 0,
["private"] = 0,
["forestry"] = 0,
["designated"] = 1,
["permissive"] = 1
}
bicycle = {
["yes"] = 2,
["designated"] = 2,
["dismount"] = 2,
["no"] = 0,
["lane"] = 2,
["track"] = 2,
["shared"] = 2,
["shared_lane"] = 2,
["sidepath"] = 2,
["share_busway"] = 2,
["none"] = 0
}
foot = {
["no"] = 0,
["yes"] = 4,
["designated"] = 4,
["permissive"] = 4,
["crossing"] = 4
}
function nodes_proc (kv, nokeys)
--normalize a few tags that we care about
local access = access[kv["access"]] or 7
local foot = foot[kv["foot"]] or bit32.band(access, 4)
local bike = bicycle[kv["bicycle"]] or bit32.band(access, 2)
local auto = motor_vehicle[kv["motor_vehicle"]]
if auto == nil then
auto = motor_vehicle[kv["motorcar"]]
end
auto = auto or bit32.band(access, 1)
--check for gates and bollards
local gate = kv["barrier"] == "gate" or kv["barrier"] == "lift_gate"
local bollard = false
if gate == false then
--if there was a bollard cars can't get through it
bollard = kv["barrier"] == "bollard" or kv["barrier"] == "block"
--save the following as gates.
if (bollard and (kv["bollard"] == "rising" or kv["bollard"] == "removable")) then
gate = true
bollard = false
end
auto = bollard and 0 or 1
end
--store the gate and bollard info
kv["gate"] = tostring(gate)
kv["bollard"] = tostring(bollard)
--store a mask denoting which modes of transport are allowed
kv["modes_mask"] = bit32.bor(auto, bike, foot)
return 0, kv
end
function ways_proc (keyvalues, nokeys)
--we dont care about ways at all so filter all of them
return 1, keyvalues, 0, 0
end
function rels_proc (keyvalues, nokeys)
--we dont care about rels at all so filter all of them
return 1, keyvalues
end
function rel_members_proc (keyvalues, keyvaluemembers, roles, membercount)
--because we filter all rels we never call this function
membersuperseeded = {}
for i = 1, membercount do
membersuperseeded[i] = 0
end
return 1, keyvalues, membersuperseeded, 0, 0, 0
end
|
access = {
["no"] = "false",
["official"] = "false",
["private"] = "false",
["destination"] = "false",
["yes"] = "true",
["permissive"] = "true",
["agricultural"] = "false",
["customers"] = "true"
}
motor_vehicle = {
["no"] = 0,
["yes"] = 1,
["agricultural"] = 0,
["destination"] = 0,
["private"] = 0,
["forestry"] = 0,
["designated"] = 1,
["permissive"] = 1
}
bicycle = {
["yes"] = 2,
["designated"] = 2,
["dismount"] = 2,
["no"] = 0,
["lane"] = 2,
["track"] = 2,
["shared"] = 2,
["shared_lane"] = 2,
["sidepath"] = 2,
["share_busway"] = 2,
["none"] = 0
}
foot = {
["no"] = 0,
["yes"] = 4,
["designated"] = 4,
["permissive"] = 4,
["crossing"] = 4
}
function nodes_proc (kv, nokeys)
--normalize a few tags that we care about
local access = access[kv["access"]] or "true"
local foot = foot[kv["foot"]] or 4
local bike = bicycle[kv["bicycle"]] or 2
local auto = motor_vehicle[kv["motor_vehicle"]]
if auto == nil then
auto = motor_vehicle[kv["motorcar"]]
end
auto = auto or 1
if access == "false" then
foot = 0
bike = 0
auto = 0
end
--check for gates and bollards
local gate = kv["barrier"] == "gate" or kv["barrier"] == "lift_gate"
local bollard = false
if gate == false then
--if there was a bollard cars can't get through it
bollard = kv["barrier"] == "bollard" or kv["barrier"] == "block"
--save the following as gates.
if (bollard and (kv["bollard"] == "rising" or kv["bollard"] == "removable")) then
gate = true
bollard = false
end
auto = bollard and 0 or 1
end
--store the gate and bollard info
kv["gate"] = tostring(gate)
kv["bollard"] = tostring(bollard)
if kv["amenity"] == "bicycle_rental" or (kv["shop"] == "bicycle" and kv["service:bicycle:rental"] == "yes") then
kv["bicycle_rental"] = "true"
end
--store a mask denoting which modes of transport are allowed
kv["modes_mask"] = bit32.bor(auto, bike, foot)
return 0, kv
end
function ways_proc (keyvalues, nokeys)
--we dont care about ways at all so filter all of them
return 1, keyvalues, 0, 0
end
function rels_proc (keyvalues, nokeys)
--we dont care about rels at all so filter all of them
return 1, keyvalues
end
function rel_members_proc (keyvalues, keyvaluemembers, roles, membercount)
--because we filter all rels we never call this function
membersuperseeded = {}
for i = 1, membercount do
membersuperseeded[i] = 0
end
return 1, keyvalues, membersuperseeded, 0, 0, 0
end
|
fixed access bug for nodes.
|
fixed access bug for nodes.
|
Lua
|
mit
|
fsaric/mjolnir,fsaric/mjolnir,fsaric/mjolnir
|
32b3258a85545b5fe451ea4eadfdd9156f31a552
|
interface/flow/dynvars.lua
|
interface/flow/dynvars.lua
|
local proto = require "proto.proto"
local dynvar = {}
dynvar.__index = dynvar
local _aliases = {
udpSrc = proto.udp.setSrcPort, udpDst = proto.udp.setDstPort,
tcpSrc = proto.tcp.setSrcPort, tcpDst = proto.tcp.setDstPort,
ethSrc = proto.eth.default.setSrc, ethDst = proto.eth.default.setDst,
ethVlan = proto.eth.vlan.setVlanTag,
ethinnerVlanTag = proto.eth.qinq.setInnerVlanTag,
ethouterVlanId = proto.eth.qinq.setOuterVlanTag,
ethouterVlanTag = proto.eth.qinq.setOuterVlanTag,
}
local function _find_setter(pkt, var)
local alias = _aliases[pkt .. var]
if alias then
return alias
end
return proto[pkt].metatype["set" .. var]
end
local function _new_dynvar(pkt, var, func)
local self = { pkt = pkt, var = var, func = func }
self.applyfn = _find_setter(pkt, var)
assert(self.applyfn, pkt .. var)
self.value = func()
return setmetatable(self, dynvar)
end
function dynvar:update()
local v = self.func()
self.value = v
return v
end
function dynvar:apply(pkt)
self.applyfn(pkt[self.pkt], self.value)
end
function dynvar:updateApply(pkt)
dynvar.update(self)
self.applyfn(pkt[self.pkt], self.value)
end
local dynvars, dv_final = {}, {}
dynvars.__index, dv_final.__index = dynvars, dv_final
function dynvars.new()
local self = {
index = {}, count = 0
}
return setmetatable(self, dynvars)
end
local function _add_dv(self, index, dv)
table.insert(self, dv)
self.index[index] = dv
self.count = self.count + 1
end
function dynvars:add(pkt, var, func)
local dv = _new_dynvar(pkt, var, func)
_add_dv(self, pkt .. var, dv)
return dv
end
function dynvars:inherit(other, fillTbl)
for i,v in pairs(other.index) do
local ftIndex = v.pkt .. v.var
if not self.index[i] and not fillTbl[ftIndex] then
_add_dv(self, i, v)
end
end
end
function dynvars:finalize()
setmetatable(self, dv_final)
end
function dv_final:updateAll()
for i = 1, self.count do
dynvar.update(self[i])
end
end
function dv_final:applyAll(pkt)
for i = 1, self.count do
dynvar.apply(self[i], pkt)
end
end
function dv_final:updateApplyAll(pkt)
for i = 1, self.count do
dynvar.updateApply(self[i], pkt)
end
end
return dynvars
|
local proto = require "proto.proto"
local dynvar = {}
dynvar.__index = dynvar
local _aliases = {
udpSrc = proto.udp.metatype.setSrcPort, udpDst = proto.udp.metatype.setDstPort,
tcpSrc = proto.tcp.metatype.setSrcPort, tcpDst = proto.tcp.metatype.setDstPort,
ethSrc = proto.eth.default.metatype.setSrc, ethDst = proto.eth.default.metatype.setDst,
ethVlan = proto.eth.vlan.metatype.setVlanTag,
ethinnerVlanTag = proto.eth.qinq.metatype.setInnerVlanTag,
ethouterVlanId = proto.eth.qinq.metatype.setOuterVlanTag,
ethouterVlanTag = proto.eth.qinq.metatype.setOuterVlanTag,
}
local function _find_setter(pkt, var)
local alias = _aliases[pkt .. var]
if alias then
return alias
end
return proto[pkt].metatype["set" .. var]
end
local function _new_dynvar(pkt, var, func)
local self = { pkt = pkt, var = var, func = func }
self.applyfn = _find_setter(pkt, var)
assert(self.applyfn, pkt .. var)
self.value = func()
return setmetatable(self, dynvar)
end
function dynvar:update()
local v = self.func()
self.value = v
return v
end
function dynvar:apply(pkt)
self.applyfn(pkt[self.pkt], self.value)
end
function dynvar:updateApply(pkt)
dynvar.update(self)
self.applyfn(pkt[self.pkt], self.value)
end
local dynvars, dv_final = {}, {}
dynvars.__index, dv_final.__index = dynvars, dv_final
function dynvars.new()
local self = {
index = {}, count = 0
}
return setmetatable(self, dynvars)
end
local function _add_dv(self, index, dv)
table.insert(self, dv)
self.index[index] = dv
self.count = self.count + 1
end
function dynvars:add(pkt, var, func)
local dv = _new_dynvar(pkt, var, func)
_add_dv(self, pkt .. var, dv)
return dv
end
function dynvars:inherit(other, fillTbl)
for i,v in pairs(other.index) do
local ftIndex = v.pkt .. v.var
if not self.index[i] and not fillTbl[ftIndex] then
_add_dv(self, i, v)
end
end
end
function dynvars:finalize()
setmetatable(self, dv_final)
end
function dv_final:updateAll()
for i = 1, self.count do
dynvar.update(self[i])
end
end
function dv_final:applyAll(pkt)
for i = 1, self.count do
dynvar.apply(self[i], pkt)
end
end
function dv_final:updateApplyAll(pkt)
for i = 1, self.count do
dynvar.updateApply(self[i], pkt)
end
end
return dynvars
|
Fix aliases.
|
Fix aliases.
|
Lua
|
mit
|
scholzd/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen
|
4a5bca0f878dd358c1722c499889c9866009599f
|
src/backends/littlewire-rgbw.lua
|
src/backends/littlewire-rgbw.lua
|
local Lwdev = {}
function Lwdev:init(device)
self.littlewire = require("littlewire")
local littlewire_devices = littlewire.search()
print("Found ", #littlewire_devices, " littlewire devices.\n")
self.lw_dev = littlewire.connect()
print("Connected to first device.")
print("FW Version: ", littlewire.readFirmwareVersion(self.lw_dev), "\n")
littlewire.softPWM_state(self.lw_dev, 1)
print("Littlewire rgbw backend initialized.")
end
-- FIXME In RGBW mode we are overloading every other pixel to carry W data
function Lwdev:set_pixels(pixels)
local w
if #pixels == 2 then
w = pixels[2][1]
else
w = 0
end
littlewire.softPWM_write(self.lw_dev, pixels[1][1], pixels[1][2], pixels[1][3], w)
end
return Lwdev
|
local Lwdev = {}
function Lwdev:init(device)
self.littlewire = require("littlewire")
local littlewire_devices = self.littlewire.search()
print("Found ", #littlewire_devices, " littlewire devices.\n")
self.lw_dev = self.littlewire.connect()
print("Connected to first device.")
print("FW Version: ", self.littlewire.readFirmwareVersion(self.lw_dev), "\n")
self.littlewire.quadPWM_state(self.lw_dev, 1)
print("Littlewire rgbw backend initialized.")
end
-- FIXME In RGBW mode we are overloading every other pixel to carry W data
function Lwdev:set_pixels(pixels)
local w
if #pixels == 2 then
w = pixels[2][1]
else
w = 0
end
self.littlewire.quadPWM_write(self.lw_dev, pixels[1][1], pixels[1][2], pixels[1][3], w)
end
return Lwdev
|
fix typo
|
fix typo
|
Lua
|
mit
|
evq/opc-lua
|
dc7b89fb75f6940d00f579b956bfe33149ac6f9b
|
test/primitive.lua
|
test/primitive.lua
|
function assignment()
a = 1
b, c, d = nil
e, f, g = 1, 2, 3
local i, k, l = 3, 2, 1
print (a, b, c, d, e, f, g, i, k, l)
end
function vararg(...)
a = ...
c, d = ...
t = {...}
s = {1, 2, 3, ...}
local f, g, h = ...
t.x = ...
assignment(...)
if true then
return a, t, s, ...
end
return ...
end
function tables()
function generator(x, y, z)
return x, y, z
end
t = {
[123.322] = 3,
[3] = {
"a", "b", "c"
},
generator("a", "b", "c"),
generator("d", "e", "f")
}
t.var = 1
t.str = "Nope"
function t:foo(var)
self.var = var;
self.str = "!!!" .. var
end
t:foo(123)
print(t)
end
function logical()
x = 3
print ("No then, only else")
if x == 1 then
else
print ("Not one!")
end
print ("elseifs")
if x == 3 then
print("is three!")
elseif x == 5 then
print("is five!")
elseif x == 8 then
print("is eight!")
else
print("is something else!")
end
print ("ordinary if")
if x == 6 then
print("Is six!")
else
print("Whatever else!")
end
y = 4
print ("normal logical expression")
b = (x and y) or y
print ("precalculated true expression")
c = true or (x and y) or true
print ("precalculated false expression")
d = false and ((x and y) or true)
print ("precalculated false expression with function")
e = error() and false and ((x and y) or true)
print ("precalculated? false expression with variable")
local z = false
f = z and ((x and y) or true)
print ("precalculated false expression with nil")
f = nil and ((x and y) or true)
print(x, y, b, c, d, e, f)
end
function functions()
function func1(x, y)
function sub(z)
return z
end
return x, y, sub
end
x, y, z = func1(1, 2)
print(z(4))
x = func1(1, 2)
func1(1, 2)
function func2(x)
print (x)
end
function func3(x)
return x*2
end
func2(func3(3))
function func4(x, y, z)
print (x, y, z)
end
func4(1, 2, func2(3))
end
function locals(x, y, ...)
local a, b, c = ...
function generator()
return 1, 2, 3
end
local d, e, f = generator()
local g, h, i, k = 4, generator()
local l, m, n = f, e
end
function loops()
function iterate_over(table)
function iterator(table, index)
key, value = next(table, index)
return key, value, 1, 2, 3
end
return iterator, table, nil
end
t = {1, 2, 3}
print ("numeric for without step")
for i=1, 100 do
print(i)
end
print ("numeric for with step")
for i=1, 100, 2 do
print(i)
end
print ("iterator for")
for key, value in pairs(t) do
print(key, value)
end
print("iterator for with another iterator")
for key, value, x, y, z in iterate_over(t) do
print(key, value, x, y, z)
end
print("iterator for with crazy custom iterator")
a, b, c = pairs(t)
for key, value in a, b, c do
print(key, value)
end
print("iterator for with dissected iterator")
local z = false
for key, value in ipairs(t) do
print(key, value)
end
print ("while")
x = 3
while x > 0 do
x = x - 1
end
print ("while with copy check")
y = 0
x = y
while x do
x = y
end
print ("repeat until")
repeat
x = x + 1
until x > 5
print ("repeat until with copy check")
repeat
x = y
until not x
end
function upvalues()
test = 0
function sub(x)
test = test + 1
test = 3
test = "asd"
test = 4.0
return test + x
end
print(sub(3))
end
function subblock()
x = 3
do
local a = 2
print(a + x)
end
y = 4
end
|
function assignment()
a = 1
b, c, d = nil
e, f, g = 1, 2, 3
local i, k, l = 3, 2, 1
print (a, b, c, d, e, f, g, i, k, l)
end
function vararg(...)
a = ...
c, d = ...
t = {...}
s = {1, 2, 3, ...}
local f, g, h = ...
t.x = ...
assignment(...)
if true then
return a, t, s, ...
end
return ...
end
function tables()
function generator(x, y, z)
return x, y, z
end
t = {
[123.322] = 3,
[3] = {
"a", "b", "c"
},
generator("a", "b", "c"),
generator("d", "e", "f")
}
t.var = 1
t.str = "Nope"
function t:foo(var)
self.var = var;
self.str = "!!!" .. var
end
t:foo(123)
print(t)
end
function logical()
x = 3
print ("No then, only else")
if x == 1 then
else
print ("Not one!")
end
print ("elseifs")
if x == 3 then
print("is three!")
elseif x == 5 then
print("is five!")
elseif x == 8 then
print("is eight!")
else
print("is something else!")
end
print ("ordinary if")
if x == 6 then
print("Is six!")
else
print("Whatever else!")
end
y = 4
print ("normal logical expression")
b = (x and y) or y
print ("precalculated true expression")
c = true or (x and y) or true
print ("precalculated false expression")
d = false and ((x and y) or true)
print ("precalculated false expression with function")
e = error() and false and ((x and y) or true)
print ("precalculated? false expression with variable")
local z = false
f = z and ((x and y) or true)
print ("precalculated false expression with nil")
f = nil and ((x and y) or true)
print(x, y, b, c, d, e, f)
end
function functions()
function func1(x, y)
function sub(z)
return z
end
return x, y, sub
end
x, y, z = func1(1, 2)
print(z(4))
x = func1(1, 2)
func1(1, 2)
function func2(x)
print (x)
end
function func3(x)
return x*2
end
func2(func3(3))
function func4(x, y, z)
print (x, y, z)
end
func4(1, 2, func2(3))
end
function locals(x, y, ...)
local a, b, c = ...
function generator()
return 1, 2, 3
end
local d, e, f = generator()
local g, h, i, k = 4, generator()
local l, m, n = f, e
end
function loops()
function iterate_over(table)
function iterator(table, index)
key, value = next(table, index)
return key, value, 1, 2, 3
end
return iterator, table, nil
end
t = {1, 2, 3}
print ("numeric for without step")
for i=1, 100 do
print(i)
end
print ("numeric for with step")
for i=1, 100, 2 do
print(i)
end
print ("iterator for")
for key, value in pairs(t) do
print(key, value)
end
print("iterator for with another iterator")
local z = false
for key, value in ipairs(t) do
print(key, value)
end
print("iterator for with crazy custom iterator")
for key, value, x, y, z in iterate_over(t) do
print(key, value, x, y, z)
end
print("iterator for with dissected iterator")
a, b, c = pairs(t)
for key, value in a, b, c do
print(key, value)
end
print ("while")
x = 3
while x > 0 do
x = x - 1
end
print ("while with copy check")
y = 0
x = y
while x do
x = y
end
print ("repeat until")
repeat
x = x + 1
until x > 5
print ("repeat until with copy check")
repeat
x = y
until not x
end
function upvalues()
test = 0
function sub(x)
test = test + 1
test = 3
test = "asd"
test = 4.0
return test + x
end
print(sub(3))
end
function subblock()
x = 3
do
local a = 2
print(a + x)
end
y = 4
end
|
[primitive.lua] Fix print/loops order
|
[primitive.lua] Fix print/loops order
|
Lua
|
mit
|
NightNord/ljd,mrexodia/ljd,jjdredd/ljd
|
3a81dd9eb9cff297973b3427d96ff1100ae8a31e
|
test/test_spec.lua
|
test/test_spec.lua
|
local fqclient = require("../lua/fqclient.lua")
local function mkreader(exchange, program)
local key_auth = mtev.uuid()
local key_bind = mtev.uuid()
local key_read = mtev.uuid()
local fqc_read = fqclient.new("127.0.0.1", 8765, "busted-user-1", "busted-pw")
fqc_read.auth_cb = function()
mtev.notify(key_auth)
end
fqc_read.bind_cb = function()
mtev.notify(key_bind)
end
fqc_read:bind(exchange, program) -- need to bind before connect
fqc_read:connect()
-- We have to call fq_read:recv() in a loop in order for call backs to execute.
mtev.coroutine_spawn(function()
while true do
local m = { fqc_read:recv() }
if #m > 0 then
mtev.log("error", "RECV: %s\n", mtev.tojson(m):tostring())
mtev.notify(key_read, m[2]) -- just forward payload
else
mtev.sleep(.005)
end
end
end)
assert.truthy(mtev.waitfor(key_auth, 5))
assert.truthy(mtev.waitfor(key_bind, 5))
local reader = function(timeout)
local _, m = mtev.waitfor(key_read, timeout or 5)
return m
end
return reader
end
describe("fq", function()
local fq, api
setup(function()
-- Setup fq process wrapper
fq = mtev.Proc:new {
path = "../fqd",
argv = {
"fqd", "-D",
'-n', '192.168.33.10',
'-c', './fqd.sqlite',
'-p', '8765',
},
boot_match = "Listening on port",
}
-- write stderr output to out.log
fq:logwrite("out.log")
-- Optional: Forward fqd output to error log
-- fq:loglog("error")
api = mtev.Api:http("127.0.0.1", '8765')
end)
teardown(function()
fq:kill()
end)
it("should start", function()
fq:start()
assert.truthy(fq:ready())
end)
it("should allow HTTP requests", function()
assert.truthy(api:get("/stats.json"):check())
end)
local fqc_send
local exchange = "test-exchange"
local program = "prefix:"
local route = "test-route"
local reader
it("should accept connections", function()
fqc_send = fqclient.new("127.0.0.1", 8765, "busted-user-2", "busted-pw")
fqc_send:connect()
reader = mkreader(exchange, "prefix:")
end)
it("should send/recv hello messages", function()
local msg = "Hello!"
local N = 10
for i=1,N do
fqc_send:send(msg, exchange, route)
end
for i=1,N do
assert.equal(msg, reader())
end
end)
it("should send messages via HTTP", function()
-- Submit message via HTTP
-- $ curl -X POST -H "X-Fq-User: web" -H 'X-Fq-Route: user-route' \
-- -H 'X-Fq-Exchange: busted-exchange' 192.168.33.10:8765/submit \
-- --data 'Hello world!'
-- {"routed":1,"dropped":0,"no_route":0,"no_exchange":0}
local payload = "Some HTTP payload"
r = api:post("/submit", payload, {
["X-Fq-User"] = "web",
["X-Fq-Route"] = "web-route",
["X-Fq-Exchange"] = exchange,
}):check()
assert.equals(r:json().routed, 1)
assert.equals(payload, reader())
end)
it("should send messages via fqs", function()
-- quick and dirty way to spin up fqs
mtev.sh(string.format(
[[printf 'hello fqs' | LD_LIBRARY_PATH=../:/opt/circonus/lib ../fqs -x "%s" -r "%s"]],
exchange, route))
assert.equals('hello fqs', reader())
end)
it("should allow multiple readers", function()
local reader2 = mkreader(exchange, "prefix:")
local msg = "hello reader 2!"
fqc_send:send(msg, exchange, route)
assert.equals(msg, reader())
assert.equals(msg, reader2())
end)
it("should filter prefixes", function()
local reader_x = mkreader(exchange, "prefix:x")
fqc_send:send("abc", exchange, "abc")
fqc_send:send("xxx", exchange, "xxx")
assert.equals("abc", reader())
assert.equals("xxx", reader())
assert.equals("xxx", reader_x())
end)
end)
|
local fqclient = require("../lua/fqclient.lua")
local function mkreader(exchange, program)
local key_auth = mtev.uuid()
local key_bind = mtev.uuid()
local key_read = mtev.uuid()
local fqc_read = fqclient.new("127.0.0.1", 18765, "busted-user-1", "busted-pw")
fqc_read.auth_cb = function()
mtev.notify(key_auth, true)
end
fqc_read.bind_cb = function()
mtev.notify(key_bind, true)
end
fqc_read:bind(exchange, program) -- need to bind before connect
fqc_read:connect()
-- We have to call fq_read:recv() in a loop in order for call backs to execute.
mtev.coroutine_spawn(function()
while true do
local m = { fqc_read:recv() }
if #m > 0 then
mtev.log("debug", "RECV: %s\n", mtev.tojson(m):tostring())
mtev.notify(key_read, m[2]) -- just forward payload
else
mtev.sleep(.005)
end
end
end)
assert.truthy(mtev.waitfor(key_auth, 5))
assert.truthy(mtev.waitfor(key_bind, 5))
local reader = function(timeout)
local _, m = mtev.waitfor(key_read, timeout or 5)
return m
end
return reader
end
describe("fq", function()
local fq, api
setup(function()
-- Setup fq process wrapper
fq = mtev.Proc:new {
path = "../fqd",
argv = {
"fqd", "-D",
'-n', '10.254.254.1',
'-c', './fqd.sqlite',
'-p', '18765',
'-v', 'conn,route,msg,io',
},
boot_match = "Listening on port",
}
-- write stderr output to out.log
fq:logwrite("out.log")
-- Optional: Forward fqd output to error log
-- fq:loglog("error")
api = mtev.Api:http("127.0.0.1", '18765')
end)
teardown(function()
fq:kill()
end)
it("should start", function()
fq:start()
assert.truthy(fq:ready())
end)
it("should allow HTTP requests", function()
assert.truthy(api:get("/stats.json"):check())
end)
local fqc_send
local exchange = "test-exchange"
local program = "prefix:"
local route = "test-route"
local reader
it("should accept connections", function()
fqc_send = fqclient.new("127.0.0.1", 18765, "busted-user-2", "busted-pw")
fqc_send:connect()
reader = mkreader(exchange, "prefix:")
end)
it("should send/recv hello messages", function()
local msg = "Hello!"
local N = 10
for i=1,N do
fqc_send:send(msg, exchange, route)
end
for i=1,N do
assert.equal(msg, reader())
end
end)
it("should send messages via HTTP", function()
-- Submit message via HTTP
-- $ curl -X POST -H "X-Fq-User: web" -H 'X-Fq-Route: user-route' \
-- -H 'X-Fq-Exchange: busted-exchange' 192.168.33.10:8765/submit \
-- --data 'Hello world!'
-- {"routed":1,"dropped":0,"no_route":0,"no_exchange":0}
local payload = "Some HTTP payload"
r = api:post("/submit", payload, {
["X-Fq-User"] = "web",
["X-Fq-Route"] = "web-route",
["X-Fq-Exchange"] = exchange,
}):check()
assert.equals(r:json().routed, 1)
assert.equals(payload, reader())
end)
it("should send messages via fqs", function()
-- quick and dirty way to spin up fqs
mtev.sh(string.format(
[[printf 'hello fqs' | LD_LIBRARY_PATH=../:/opt/circonus/lib ../fqs -a 127.0.0.1:18765 -x "%s" -r "%s"]],
exchange, route))
assert.equals('hello fqs', reader())
end)
it("should allow multiple readers", function()
local reader2 = mkreader(exchange, "prefix:")
local msg = "hello reader 2!"
fqc_send:send(msg, exchange, route)
assert.equals(msg, reader())
assert.equals(msg, reader2())
end)
it("should filter prefixes", function()
local reader_x = mkreader(exchange, "prefix:x")
fqc_send:send("abc", exchange, "abc")
fqc_send:send("xxx", exchange, "xxx")
assert.equals("abc", reader())
assert.equals("xxx", reader())
assert.equals("xxx", reader_x())
end)
end)
|
fix test to run on separate port and use value for notify
|
fix test to run on separate port and use value for notify
|
Lua
|
mit
|
circonus-labs/fq,circonus-labs/fq,circonus-labs/fq,circonus-labs/fq,circonus-labs/fq,circonus-labs/fq
|
8d208ec6968049164f1d460bcadc9a36a9c5f666
|
tests/libs/tap.lua
|
tests/libs/tap.lua
|
--[[
Copyright 2014 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.
--]]
exports.name = "luvit/tap"
exports.version = "0.1.0-1"
exports.dependencies = {
"luvit/[email protected]"
}
exports.license = "Apache 2"
exports.homepage = "https://github.com/luvit/luvit/blob/master/tests/libs/tap.lua"
exports.description = "Libuv loop based test runner with tap output."
exports.tags = {"test", "tap"}
local uv = require('uv')
local colorize = require('pretty-print').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.stop()
uv.walk(function (handle)
if preexisting[handle] or uv.is_closing(handle) then return end
uv.close(handle)
end)
-- Wait for the close calls to finish
uv.run()
-- Reset the cwd if the script changed it.
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
|
--[[
Copyright 2014 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.
--]]
exports.name = "luvit/tap"
exports.version = "0.1.0-1"
exports.dependencies = {
"luvit/[email protected]"
}
exports.license = "Apache 2"
exports.homepage = "https://github.com/luvit/luvit/blob/master/tests/libs/tap.lua"
exports.description = "Libuv loop based test runner with tap output."
exports.tags = {"test", "tap"}
local uv = require('uv')
local colorize = require('pretty-print').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 err
local function expect(fn, count)
expected = expected + (count or 1)
return function (...)
expected = expected - 1
local success, ret = pcall(fn, ...)
if not success then err = ret end
collectgarbage()
return ret
end
end
test.fn(expect)
collectgarbage()
uv.run()
collectgarbage()
if err then error(err) end
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.stop()
uv.walk(function (handle)
if preexisting[handle] or uv.is_closing(handle) then return end
uv.close(handle)
end)
-- Wait for the close calls to finish
uv.run()
-- Reset the cwd if the script changed it.
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 uncaught errors in tap
|
Fix uncaught errors in tap
|
Lua
|
apache-2.0
|
luvit/luvit,kaustavha/luvit,kaustavha/luvit,kaustavha/luvit,luvit/luvit,zhaozg/luvit,zhaozg/luvit
|
76bef86c870360aaa3766a9d6e127009519e814c
|
xmake/rules/renderer_plugins.lua
|
xmake/rules/renderer_plugins.lua
|
-- Builds renderer plugins if linked to NazaraRenderer
rule("build_rendererplugins")
on_load(function (target)
local deps = table.wrap(target:get("deps"))
if target:kind() == "binary" and (table.contains(deps, "NazaraRenderer") or table.contains(deps, "NazaraGraphics")) then
for name, _ in pairs(modules) do
local depName = "Nazara" .. name
if name:match("^.+Renderer$") and not table.contains(deps, depName) then -- don't overwrite dependency
target:add("deps", depName, {inherit = false})
end
end
end
end)
|
local modules = NazaraModules
-- Builds renderer plugins if linked to NazaraRenderer
rule("build_rendererplugins")
on_load(function (target)
local deps = table.wrap(target:get("deps"))
if target:kind() == "binary" and (table.contains(deps, "NazaraRenderer") or table.contains(deps, "NazaraGraphics")) then
for name, _ in pairs(modules) do
local depName = "Nazara" .. name
if name:match("^.+Renderer$") and not table.contains(deps, depName) then -- don't overwrite dependency
target:add("deps", depName, {inherit = false})
end
end
end
end)
|
Build: Fix renderer plugins dependencies
|
Build: Fix renderer plugins dependencies
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
1ec0da558a3e149bf241cfe1f80160ca9f0bb238
|
test_scripts/Polices/build_options/ATF_P_TC_PTU_Cycleing_Through_The_URLs_During_Retry_Sequence.lua
|
test_scripts/Polices/build_options/ATF_P_TC_PTU_Cycleing_Through_The_URLs_During_Retry_Sequence.lua
|
---------------------------------------------------------------------------------------------
-- HTTP flow
-- Requirement summary:
-- [PolicyTableUpdate] Cycleing through the URLs during retry sequence
--
-- Description:
-- The policies manager shall cycle through the list of URLs, using the next one in the list
-- for every new policy table request over a retry sequence. In case of the only URL in Local Policy Table,
-- it must always be the destination for a Policy Table Snapshot.
--
-- Preconditions
-- 1. Preapre specific PTU file with additional URLs for app
-- 2. LPT is updated -> SDL.OnStatusUpdate(UP_TO_DATE)
-- Steps:
-- 1. Register new app -> new PTU sequence started and it can't be finished successfully
-- 2. Verify url parameter of OnSystemRequest() notification for each cycle
--
-- Expected result:
-- Url parameter is taken cyclically from list of available URLs
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
--[[ Local Variables ]]
local policy_file_name = "PolicyTableUpdate"
local ptu_file = "files/jsons/Policies/build_options/ptu_18269.json"
local sequence = { }
local attempts = 16
local r_expected = {
"http://policies.domain1.ford.com/api/policies",
"http://policies.domain2.ford.com/api/policies",
"http://policies.domain3.ford.com/api/policies"}
local r_actual = { }
--[[ Local Functions ]]
local function timestamp()
local f = io.popen("date +%H:%M:%S.%3N")
local o = f:read("*all")
f:close()
return (o:gsub("\n", ""))
end
local function log(event, ...)
table.insert(sequence, { ts = timestamp(), e = event, p = {...} })
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
config.defaultProtocolVersion = 2
--[[ Specific Notifications ]]
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate")
:Do(function(_, _)
-- log("SDL->HMI: SDL.OnStatusUpdate()", d.params.status)
end)
:Times(AnyNumber())
:Pin()
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(_, _)
log("SDL->HMI: BC.PolicyUpdate()")
end)
:Times(AnyNumber())
:Pin()
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Update_LPT()
local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = policy_file_name }, ptu_file)
EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" })
end
function Test:RegisterNotification()
self.mobileSession:ExpectNotification("OnSystemRequest")
:Do(function(_, d)
log("SDL->MOB: OnSystemRequest()", d.payload.requestType, d.payload.url)
table.insert(r_actual, d.payload.url)
end)
:Times(AnyNumber())
:Pin()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:StartNewMobileSession()
self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
end
function Test:RegisterNewApp()
EXPECT_HMICALL("BasicCommunication.UpdateAppList")
:Do(function(_, d)
self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { })
self.applications = { }
for _, app in pairs(d.params.applications) do
self.applications[app.appName] = app.appID
end
end)
local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams)
self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
end
Test["Starting waiting cycle [" .. attempts * 5 .. "] sec"] = function() end
for i = 1, attempts do
Test["Waiting " .. i * 5 .. " sec"] = function()
os.execute("sleep 5")
end
end
function Test.ShowSequence()
print("--- Sequence -------------------------------------")
for k, v in pairs(sequence) do
local s = k .. ": " .. v.ts .. ": " .. v.e
for _, val in pairs(v.p) do
if val then s = s .. ": " .. val end
end
print(s)
end
print("--------------------------------------------------")
end
function Test:ValidateResult()
for i = 1, 3 do
if r_expected[i] ~= r_actual[i] then
local m = table.concat({"\nExpected url:\n", r_expected[i], "\nActual:\n", r_actual[i], "\n"})
self:FailTestCase(m)
end
end
end
return Test
|
---------------------------------------------------------------------------------------------
-- HTTP flow
-- Requirement summary:
-- [PolicyTableUpdate] Cycleing through the URLs during retry sequence
--
-- Description:
-- The policies manager shall cycle through the list of URLs, using the next one in the list
-- for every new policy table request over a retry sequence. In case of the only URL in Local Policy Table,
-- it must always be the destination for a Policy Table Snapshot.
--
-- Preconditions
-- 1. Preapre specific PTU file with additional URLs for app
-- 2. LPT is updated -> SDL.OnStatusUpdate(UP_TO_DATE)
-- Steps:
-- 1. Register new app -> new PTU sequence started and it can't be finished successfully
-- 2. Verify url parameter of OnSystemRequest() notification for each cycle
--
-- Expected result:
-- Url parameter is taken cyclically from list of available URLs
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
--[[ Local Variables ]]
local ptu_file = "files/jsons/Policies/build_options/ptu_18269.json"
local sequence = { }
local attempts = 16
local r_expected = {
"http://policies.telematics.ford.com/api/policies",
"http://policies.domain1.ford.com/api/policies",
"http://policies.domain2.ford.com/api/policies",
"http://policies.domain3.ford.com/api/policies",
"http://policies.domain4.ford.com/api/policies"}
local r_actual = { }
--[[ Local Functions ]]
local function timestamp()
local f = io.popen("date +%H:%M:%S.%3N")
local o = f:read("*all")
f:close()
return (o:gsub("\n", ""))
end
local function log(event, ...)
table.insert(sequence, { ts = timestamp(), e = event, p = {...} })
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
config.defaultProtocolVersion = 2
--[[ Specific Notifications ]]
function Test:RegisterNotification()
self.mobileSession:ExpectNotification("OnSystemRequest")
:Do(function(_, d)
if d.payload.requestType == "HTTP" then
log("SDL->MOB1: OnSystemRequest()", d.payload.requestType, d.payload.url)
table.insert(r_actual, d.payload.url)
end
end)
:Times(AnyNumber())
:Pin()
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Update_LPT()
local policy_file_name = "PolicyTableUpdate"
local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = policy_file_name }, ptu_file)
EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" })
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:StartNewMobileSession()
self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
end
function Test:RegisterNotification()
self.mobileSession2:ExpectNotification("OnSystemRequest")
:Do(function(_, d)
if d.payload.requestType == "HTTP" then
log("SDL->MOB2: OnSystemRequest()", d.payload.requestType, d.payload.url)
table.insert(r_actual, d.payload.url)
end
end)
:Times(AnyNumber())
:Pin()
end
function Test:RegisterNewApp()
local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams)
self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
end
Test["Starting waiting cycle [" .. attempts * 5 .. "] sec"] = function() end
for i = 1, attempts do
Test["Waiting " .. i * 5 .. " sec"] = function()
os.execute("sleep 5")
end
end
function Test.ShowSequence()
print("--- Sequence -------------------------------------")
for k, v in pairs(sequence) do
local s = k .. ": " .. v.ts .. ": " .. v.e
for _, val in pairs(v.p) do
if val then s = s .. ": " .. val end
end
print(s)
end
print("--------------------------------------------------")
end
function Test:ValidateResult()
for i = 1, 3 do
if r_expected[i] ~= r_actual[i] then
local m = table.concat({"\nExpected url:\n", tostring(r_expected[i]), "\nActual:\n", tostring(r_actual[i]), "\n"})
self:FailTestCase(m)
end
end
end
return Test
|
Fix issues after clarification
|
Fix issues after clarification
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
d985c00dcdfe856defa462fc157e1ee63e9d09b1
|
MMOCoreORB/bin/scripts/screenplays/dungeon/warren/captain_heff_convo_handler.lua
|
MMOCoreORB/bin/scripts/screenplays/dungeon/warren/captain_heff_convo_handler.lua
|
local ObjectManager = require("managers.object.object_manager")
CaptainHeffConversationHandler = Object:new {}
function CaptainHeffConversationHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNPC, selectedOption, pConversationScreen)
local screen = LuaConversationScreen(pConversationScreen)
local screenID = screen:getScreenID()
if (screenID == "heff_1") then
ObjectManager.withCreaturePlayerObject(pConversingPlayer, function(playerObject)
playerObject:awardBadge(39)
local pDatapad = SceneObject(pConversingPlayer):getSlottedObject("datapad")
if (pDatapad ~= nil) then
for i = 1, 4, 1 do
local pEvidence = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_0" .. i .. ".iff", false)
if (pEvidence ~= nil) then
SceneObject(pEvidence):destroyObjectFromWorld()
SceneObject(pEvidence):destroyObjectFromDatabase()
end
end
local pKey = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_encryption_key.iff", false)
if (pKey ~= nil) then
SceneObject(pKey):destroyObjectFromWorld()
SceneObject(pKey):destroyObjectFromDatabase()
end
end
end)
end
return pConversationScreen
end
function CaptainHeffConversationHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
return ObjectManager.withCreaturePlayerObject(pPlayer, function(playerObject)
if (playerObject:hasBadge(39)) then
return convoTemplate:getScreen("heff_done")
else
local pDatapad = SceneObject(pPlayer):getSlottedObject("datapad")
if (pDatapad ~= nil) then
local pEvidence1 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_01.iff", false)
local pEvidence2 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_02.iff", false)
local pEvidence3 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_03.iff", false)
local pEvidence4 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_04.iff", false)
local pEvidence5 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_encryption_key.iff", false)
if (pEvidence1 ~= nil) and (pEvidence2 ~= nil) and (pEvidence3 ~= nil) and (pEvidence4 ~= nil) and (pEvidence5 ~= nil) then
return convoTemplate:getScreen("heff_start")
end
end
end
return convoTemplate:getScreen("heff_bye")
end)
end
function CaptainHeffConversationHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
|
local ObjectManager = require("managers.object.object_manager")
CaptainHeffConversationHandler = Object:new {}
function CaptainHeffConversationHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNPC, selectedOption, pConversationScreen)
local screen = LuaConversationScreen(pConversationScreen)
local screenID = screen:getScreenID()
if (screenID == "heff_1") then
ObjectManager.withCreaturePlayerObject(pConversingPlayer, function(playerObject)
playerObject:awardBadge(39)
playerObject:increaseFactionStanding("imperial", 500)
local pDatapad = SceneObject(pConversingPlayer):getSlottedObject("datapad")
if (pDatapad ~= nil) then
for i = 1, 4, 1 do
local pEvidence = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_0" .. i .. ".iff", false)
if (pEvidence ~= nil) then
SceneObject(pEvidence):destroyObjectFromWorld()
SceneObject(pEvidence):destroyObjectFromDatabase()
end
end
local pKey = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_encryption_key.iff", false)
if (pKey ~= nil) then
SceneObject(pKey):destroyObjectFromWorld()
SceneObject(pKey):destroyObjectFromDatabase()
end
end
end)
end
return pConversationScreen
end
function CaptainHeffConversationHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
return ObjectManager.withCreaturePlayerObject(pPlayer, function(playerObject)
if (playerObject:hasBadge(39)) then
return convoTemplate:getScreen("heff_done")
else
local pDatapad = SceneObject(pPlayer):getSlottedObject("datapad")
if (pDatapad ~= nil) then
local pEvidence1 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_01.iff", false)
local pEvidence2 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_02.iff", false)
local pEvidence3 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_03.iff", false)
local pEvidence4 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_evidence_04.iff", false)
local pEvidence5 = getContainerObjectByTemplate(pDatapad, "object/intangible/data_item/warren_encryption_key.iff", false)
if (pEvidence1 ~= nil) and (pEvidence2 ~= nil) and (pEvidence3 ~= nil) and (pEvidence4 ~= nil) and (pEvidence5 ~= nil) then
return convoTemplate:getScreen("heff_start")
end
end
end
return convoTemplate:getScreen("heff_bye")
end)
end
function CaptainHeffConversationHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
|
[fixed] final quest turn-in for 'The Warren' to grant proper faction-point reward (Mantis #6811)
|
[fixed] final quest turn-in for 'The Warren' to grant proper
faction-point reward (Mantis #6811)
Change-Id: I352ae8f6c7e9b1c813615f54051f5cd393fb5331
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
0a76fac5ea5298f5bcd7695a0fcfc8d977aecd2c
|
MMOCoreORB/bin/scripts/screenplays/poi/corellia_grand_theater_vreni_island.lua
|
MMOCoreORB/bin/scripts/screenplays/poi/corellia_grand_theater_vreni_island.lua
|
GrandTheaterVreniScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "GrandTheaterVreniScreenPlay",
}
registerScreenPlay("GrandTheaterVreniScreenPlay", true)
function GrandTheaterVreniScreenPlay:start()
if (isZoneEnabled("corellia")) then
self:spawnMobiles()
end
end
function GrandTheaterVreniScreenPlay:spawnMobiles()
spawnMobile("corellia", "businessman",60,-5428.59,24.1812,-6228.31,140.458,0)
spawnMobile("corellia", "cll8_binary_load_lifter",60,-5692.65,14.6,-6151.28,140.406,0)
spawnMobile("corellia", "commoner",60,-5505.69,23.4,-6118.63,272.183,0)
spawnMobile("corellia", "commoner",60,-5468.42,23.4,-6144.87,182.034,0)
spawnMobile("corellia", "commoner",60,-5495.01,23.4,-6190.5,325.039,0)
spawnMobile("corellia", "commoner",60,-5504.22,23.4,-6211.56,1.34408,0)
spawnMobile("corellia", "commoner",60,-5488.87,23.8964,-6242.6,304.866,0)
spawnMobile("corellia", "commoner",60,-5519.68,23.4,-6224.4,134.773,0)
spawnMobile("corellia", "commoner",60,-5551.88,23.4,-6221.48,124.882,0)
spawnMobile("corellia", "commoner",60,-5549.18,23.4,-6189.25,119.296,0)
spawnMobile("corellia", "commoner",60,-5571.88,23.4,-6129.85,97.3312,0)
spawnMobile("corellia", "commoner",60,-5385.68,24,-6239.93,118.359,0)
spawnMobile("corellia", "commoner",60,-5708.22,14.6,-6157.68,63.8572,0)
spawnMobile("corellia", "commoner",60,-5686.69,14.6,-6148.05,214.943,0)
spawnMobile("corellia", "commoner",60,-5693.27,14.6,-6177.12,293.479,0)
spawnMobile("corellia", "corsec_inspector_sergeant",1,24.9055,1.28309,5.31569,360.011,2775414)
spawnMobile("corellia", "corsec_investigator",1,8.4,1.0,10.8,-172,2775413)
spawnMobile("corellia", "corsec_detective",1,8.2,1.0,8.7,7,2775413)
spawnMobile("corellia", "corsec_master_sergeant",1,24.9055,1.28309,6.41569,180.019,2775414)
spawnMobile("corellia", "crackdown_rebel_guardsman",1,-5538.4,16.4902,-6054.7,182.005,0)
spawnMobile("corellia", "crackdown_rebel_cadet",1,-5568.4,23.4,-6199.11,90.254,0)
spawnMobile("corellia", "crackdown_rebel_command_security_guard",1,-5501.09,23.4,-6128.22,142.839,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",1,-5534.1,23.4,-6217.9,138.004,0)
spawnMobile("corellia", "crackdown_rebel_liberator",1,-5549.5,23.4,-6202.1,310.009,0)
spawnMobile("corellia", "crackdown_rebel_comm_operator",1,-5582.42,23.4,-6199.06,90.2331,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",1,-5429.8,24,-6218.9,0,0)
spawnMobile("corellia", "crackdown_rebel_guard_captain",1,-5411.4,24.9599,-6219.3,5.00012,0)
spawnMobile("corellia", "crackdown_rebel_soldier",1,-5320,24,-6237.8,94.0028,0)
spawnMobile("corellia", "crackdown_rebel_soldier",1,-5443.6,24,-6243,282.008,0)
spawnMobile("corellia", "crackdown_rebel_soldier",1,-5716.1,14.6,-6153.1,269.008,0)
spawnMobile("corellia", "crackdown_rebel_liberator",1,-5716.1,14.6,-6147.5,271.008,0)
spawnMobile("corellia", "crackdown_rebel_soldier",1,-5664,14.6,-6179.3,94.0028,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",1,-5664,14.7566,-6185.3,94.0028,0)
spawnMobile("corellia", "eg6_power_droid",60,-5690.7,14.6,-6154.2,-87,0)
spawnMobile("corellia", "farmer",60,-22.5021,1.6,4.63468,179.972,2775415)
spawnMobile("corellia", "gambler",60,-22.5017,1.59973,3.53494,359.971,2775415)
spawnMobile("corellia", "informant_npc_lvl_3",0,-5559,0,-6220,90,0)
spawnMobile("corellia", "karrek_flim",60,-6.11988,1.6,-7.43599,219.682,2775417)
spawnMobile("corellia", "noble",60,-24.96,1.6,-4.79578,14.5444,2775419)
spawnMobile("corellia", "r2",60,-5528,23.4,-6195.05,84.2678,0) -- "R2-P2" When/if option customName is available to spawnMobile function
spawnMobile("corellia", "scientist",60,-5557.29,23.4,-6203.08,226.081,0)
spawnMobile("corellia", "scientist",60,-5691.18,14.6,-6133.32,248.134,0)
spawnMobile("corellia", "trainer_entertainer",0,22.0446,-0.894993,11.7787,189,3005697)
spawnMobile("corellia", "trainer_doctor",0,-2.9,0.7,2.5,132,7615446)
spawnMobile("corellia", "trainer_musician",0,-5408,24.7288,-6260,50,0)
end
|
GrandTheaterVreniScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "GrandTheaterVreniScreenPlay",
}
registerScreenPlay("GrandTheaterVreniScreenPlay", true)
function GrandTheaterVreniScreenPlay:start()
if (isZoneEnabled("corellia")) then
self:spawnMobiles()
end
end
function GrandTheaterVreniScreenPlay:spawnMobiles()
spawnMobile("corellia", "businessman",60,-5428.59,24.1812,-6228.31,140.458,0)
spawnMobile("corellia", "cll8_binary_load_lifter",60,-5692.65,14.6,-6151.28,140.406,0)
spawnMobile("corellia", "commoner",60,-5505.69,23.4,-6118.63,272.183,0)
spawnMobile("corellia", "commoner",60,-5468.42,23.4,-6144.87,182.034,0)
spawnMobile("corellia", "commoner",60,-5495.01,23.4,-6190.5,325.039,0)
spawnMobile("corellia", "commoner",60,-5504.22,23.4,-6211.56,1.34408,0)
spawnMobile("corellia", "commoner",60,-5488.87,23.8964,-6242.6,304.866,0)
spawnMobile("corellia", "commoner",60,-5519.68,23.4,-6224.4,134.773,0)
spawnMobile("corellia", "commoner",60,-5551.88,23.4,-6221.48,124.882,0)
spawnMobile("corellia", "commoner",60,-5549.18,23.4,-6189.25,119.296,0)
spawnMobile("corellia", "commoner",60,-5571.88,23.4,-6129.85,97.3312,0)
spawnMobile("corellia", "commoner",60,-5385.68,24,-6239.93,118.359,0)
spawnMobile("corellia", "commoner",60,-5708.22,14.6,-6157.68,63.8572,0)
spawnMobile("corellia", "commoner",60,-5686.69,14.6,-6148.05,214.943,0)
spawnMobile("corellia", "commoner",60,-5693.27,14.6,-6177.12,293.479,0)
spawnMobile("corellia", "corsec_inspector_sergeant",300,24.9055,1.28309,5.31569,360.011,2775414)
spawnMobile("corellia", "corsec_investigator",300,8.4,1.0,10.8,-172,2775413)
spawnMobile("corellia", "corsec_detective",300,8.2,1.0,8.7,7,2775413)
spawnMobile("corellia", "corsec_master_sergeant",300,24.9055,1.28309,6.41569,180.019,2775414)
spawnMobile("corellia", "crackdown_rebel_guardsman",300,-5538.4,16.4902,-6054.7,182.005,0)
spawnMobile("corellia", "crackdown_rebel_cadet",300,-5568.4,23.4,-6199.11,90.254,0)
spawnMobile("corellia", "crackdown_rebel_command_security_guard",300,-5501.09,23.4,-6128.22,142.839,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",300,-5534.1,23.4,-6217.9,138.004,0)
spawnMobile("corellia", "crackdown_rebel_liberator",300,-5549.5,23.4,-6202.1,310.009,0)
spawnMobile("corellia", "crackdown_rebel_comm_operator",300,-5582.42,23.4,-6199.06,90.2331,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",300,-5429.8,24,-6218.9,0,0)
spawnMobile("corellia", "crackdown_rebel_guard_captain",300,-5411.4,24.9599,-6219.3,5.00012,0)
spawnMobile("corellia", "crackdown_rebel_soldier",300,-5320,24,-6237.8,94.0028,0)
spawnMobile("corellia", "crackdown_rebel_soldier",300,-5443.6,24,-6243,282.008,0)
spawnMobile("corellia", "crackdown_rebel_soldier",300,-5716.1,14.6,-6153.1,269.008,0)
spawnMobile("corellia", "crackdown_rebel_liberator",300,-5716.1,14.6,-6147.5,271.008,0)
spawnMobile("corellia", "crackdown_rebel_soldier",300,-5664,14.6,-6179.3,94.0028,0)
spawnMobile("corellia", "crackdown_rebel_guardsman",300,-5664,14.7566,-6185.3,94.0028,0)
spawnMobile("corellia", "eg6_power_droid",60,-5690.7,14.6,-6154.2,-87,0)
spawnMobile("corellia", "farmer",60,-22.5021,1.6,4.63468,179.972,2775415)
spawnMobile("corellia", "gambler",60,-22.5017,1.59973,3.53494,359.971,2775415)
spawnMobile("corellia", "informant_npc_lvl_3",0,-5559,0,-6220,90,0)
spawnMobile("corellia", "karrek_flim",60,-6.11988,1.6,-7.43599,219.682,2775417)
spawnMobile("corellia", "noble",60,-24.96,1.6,-4.79578,14.5444,2775419)
spawnMobile("corellia", "r2",60,-5528,23.4,-6195.05,84.2678,0) -- "R2-P2" When/if option customName is available to spawnMobile function
spawnMobile("corellia", "scientist",60,-5557.29,23.4,-6203.08,226.081,0)
spawnMobile("corellia", "scientist",60,-5691.18,14.6,-6133.32,248.134,0)
spawnMobile("corellia", "trainer_entertainer",0,22.0446,-0.894993,11.7787,189,3005697)
spawnMobile("corellia", "trainer_doctor",0,-2.9,0.7,2.5,132,7615446)
spawnMobile("corellia", "trainer_musician",0,-5408,24.7288,-6260,50,0)
end
|
[fixed] rebel respawns too fast at grand theater vreni island
|
[fixed] rebel respawns too fast at grand theater vreni island
Change-Id: If3e0f2995cb4c45b244ff4b8dc54c5623088dc88
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
81449c948d060450100f709fc116222f05d20d3f
|
ssbase/gamemode/storeitems/accessories/tails_feline.lua
|
ssbase/gamemode/storeitems/accessories/tails_feline.lua
|
ITEM.ID = "tails_feline" -- Should be a unique string that identifies the item
ITEM.Name = "Tail (Cat)" -- The name the item should display
ITEM.Price = 2000
ITEM.Model = "models/mrgiggles/skeyler/accessories/tails_feline.mdl" -- Model used by the item
ITEM.Type = "tail" -- Also works for stuff like "mask" and such. Used for item compatibility
ITEM.Colorable = false -- Used if the model is colorable via setcolor (or in a models case, setplayercolor)
ITEM.Tintable = false -- Used if the model is colorable, but a translation is needed to $selfillumtint
ITEM.Rotate = 45
ITEM.CamPos = Vector(30, 22, -3) -- Used the modify the position of the camera on DModelPanels
ITEM.LookAt = Vector(-20, 0, -3) -- Used to change the angle at which the camera views the model
ITEM.Fov = 20
ITEM.Functions = {} -- Anything that can be called but not a gmod hook but more of a "store hook" goes here
ITEM.Functions["Equip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Functions["Unequip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Hooks = {} -- Could run some shit in think hook maybe clientside only (e.g. repositioning or HEALTH CALCULATIONS OR SOMETHING LIKE THAT)
ITEM.Hooks["UpdateAnimation"] = function (item,ply)
if CLIENT then
if(SS.STORE.CSModels[ply] && SS.STORE.CSModels[ply][item.ID]) then
local i = SS.STORE.CSModels[ply][item.ID]
if(ply:GetWalkSpeed() == ply:GetRunSpeed()) then
ply.running = false
if(ply:GetVelocity():Length() == 0) then
ply.idle = true
else
ply.idle = false
end
elseif(ply:GetVelocity():Length() > ply:GetWalkSpeed()+25) then
ply.running = true
ply.idle = false
elseif(ply:Speed() == 0) then
ply.idle = true
else
ply.idle = false
ply.running = false
end
local tidle = i:LookupSequence("ACT_IDLE") -- This should eliminate the need to figure out which enumerations are what
--local twalk = i:LookupSequence("ACT_WALK")
--local trun = i:LookupSequence("ACT_RUN")
if ply.idle then
if i:GetSequence() != tidle then
i:SetSequence(tidle)
end
elseif(!ply.running && i:GetSequence() != 5) then
i:SetSequence(5)
elseif(ply.running && i:GetSequence() != 4) then
i:SetSequence(4)
end
if(i.lastthink) then
i:FrameAdvance(RealTime()-i.lastthink) --this function better fucking work I HAD TO FIND THIS IN DMODELPANEL ITS NOT EVEN DOCUMENTED!
end
i.lastthink = CurTime()
end
end
end
/* ACCESSORY VARIABLES */
ITEM.Bone = "ValveBiped.Bip01_Spine" -- Bone the item is attached to. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.BoneMerge = false -- May be used for certain accessories to bonemerge the item instead. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.Models = {}
ITEM.Models["elin"] = { ["0_0_0_0"]= {pos=Vector(0, -2.6, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["miku"] = { ["0_0_0_0"]= {pos=Vector(0, -3.4, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["tron"] = { ["0_0_0_0"]= {pos=Vector(0.2, -3.5, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["usif"] = { ["0_0_0_0"]= {pos=Vector(1.5, -0.75, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["zer0"] = { ["0_0_0_0"]= {pos=Vector(0.35, -5.25, 0), ang=Angle(0, 180, -90), scale=2.0774}}
/* ************* */
|
ITEM.ID = "tails_feline" -- Should be a unique string that identifies the item
ITEM.Name = "Tail (Cat)" -- The name the item should display
ITEM.Price = 2000
ITEM.Model = "models/mrgiggles/skeyler/accessories/tails_feline.mdl" -- Model used by the item
ITEM.Type = "tail" -- Also works for stuff like "mask" and such. Used for item compatibility
ITEM.Colorable = false -- Used if the model is colorable via setcolor (or in a models case, setplayercolor)
ITEM.Tintable = false -- Used if the model is colorable, but a translation is needed to $selfillumtint
ITEM.Rotate = 45
ITEM.CamPos = Vector(30, 22, -3) -- Used the modify the position of the camera on DModelPanels
ITEM.LookAt = Vector(-20, 0, -3) -- Used to change the angle at which the camera views the model
ITEM.Fov = 20
ITEM.Functions = {} -- Anything that can be called but not a gmod hook but more of a "store hook" goes here
ITEM.Functions["Equip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Functions["Unequip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Hooks = {} -- Could run some shit in think hook maybe clientside only (e.g. repositioning or HEALTH CALCULATIONS OR SOMETHING LIKE THAT)
ITEM.Hooks["UpdateAnimation"] = function (item,ply)
if CLIENT then
if(SS.STORE.CSModels[ply] && SS.STORE.CSModels[ply][item.ID]) then
local i = SS.STORE.CSModels[ply][item.ID]
if(ply:GetWalkSpeed() == ply:GetRunSpeed()) then
ply.running = false
if(ply:GetVelocity():Length() == 0) then
ply.idle = true
else
ply.idle = false
end
elseif(ply:GetVelocity():Length() > ply:GetWalkSpeed()+25) then
ply.running = true
ply.idle = false
elseif(ply:Speed() == 0) then
ply.idle = true
else
ply.idle = false
ply.running = false
end
local tidle = i:LookupSequence("ACT_IDLE") -- This should eliminate the need to figure out which enumerations are what
--local twalk = i:LookupSequence("ACT_WALK")
--local trun = i:LookupSequence("ACT_RUN")
if ply.idle then
i:SetSequence(tidle)
elseif(!ply.running && i:GetSequence() != 5) then
i:SetSequence(5)
elseif(ply.running && i:GetSequence() != 4) then
i:SetSequence(4)
end
if(i.lastthink) then
i:FrameAdvance(RealTime()-i.lastthink) --this function better fucking work I HAD TO FIND THIS IN DMODELPANEL ITS NOT EVEN DOCUMENTED!
end
i.lastthink = CurTime()
end
end
end
/* ACCESSORY VARIABLES */
ITEM.Bone = "ValveBiped.Bip01_Spine" -- Bone the item is attached to. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.BoneMerge = false -- May be used for certain accessories to bonemerge the item instead. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.Models = {}
ITEM.Models["elin"] = { ["0_0_0_0"]= {pos=Vector(0, -2.6, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["miku"] = { ["0_0_0_0"]= {pos=Vector(0, -3.4, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["tron"] = { ["0_0_0_0"]= {pos=Vector(0.2, -3.5, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["usif"] = { ["0_0_0_0"]= {pos=Vector(1.5, -0.75, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["zer0"] = { ["0_0_0_0"]= {pos=Vector(0.35, -5.25, 0), ang=Angle(0, 180, -90), scale=2.0774}}
/* ************* */
|
Reverted my stupid fixes
|
Reverted my stupid fixes
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
df446792d696b4b0d3d541064ffc9d4d6b1cdb4c
|
src/lua-factory/sources/grl-appletrailers.lua
|
src/lua-factory/sources/grl-appletrailers.lua
|
--[[
* Copyright (C) 2015 Grilo Project
*
* 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
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-appletrailers-lua",
name = "Apple Movie Trailers",
description = "Apple Trailers",
supported_media = 'video',
supported_keys = { 'author', 'publication-date', 'description', 'duration', 'genre', 'id', 'thumbnail', 'title', 'url', 'certificate', 'studio', 'license', 'performer', 'size' },
config_keys = {
optional = { 'definition' },
},
icon = 'resource:///org/gnome/grilo/plugins/appletrailers/trailers.svg',
tags = { 'country:us', 'cinema', 'net:internet', 'net:plaintext' },
}
-- Global table to store config data
ldata = {}
-- Global table to store parse results
cached_xml = nil
function grl_source_init(configs)
ldata.hd = (configs.definition and configs.definition == 'hd')
return true
end
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
APPLE_TRAILERS_CURRENT_SD = "http://trailers.apple.com/trailers/home/xml/current_480p.xml"
APPLE_TRAILERS_CURRENT_HD = "http://trailers.apple.com/trailers/home/xml/current_720p.xml"
function grl_source_browse()
local skip = grl.get_options("skip")
local count = grl.get_options("count")
-- Make sure to reset the cache when browsing again
if skip == 0 then
cached_xml = nil
end
if cached_xml then
parse_results(cached_xml)
else
local url = APPLE_TRAILERS_CURRENT_SD
if ldata.hd then
url = APPLE_TRAILERS_CURRENT_HD
end
grl.debug('Fetching URL: ' .. url .. ' (count: ' .. count .. ' skip: ' .. skip .. ')')
grl.fetch(url, "fetch_results_cb")
end
end
---------------
-- Utilities --
---------------
-- simili-XML parsing from
-- http://lua-users.org/wiki/LuaXml
function parseargs(s)
local arg = {}
string.gsub(s, "([%-%w]+)=([\"'])(.-)%2", function (w, _, a)
arg[w] = a
end)
return arg
end
function collect(s)
local stack = {}
local top = {}
table.insert(stack, top)
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string.find(s, "<(%/?)([%w:]+)(.-)(%/?)>", i)
if not ni then break end
local text = string.sub(s, i, ni-1)
if not string.find(text, "^%s*$") then
table.insert(top, text)
end
if empty == "/" then -- empty element tag
table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
elseif c == "" then -- start tag
top = {label=label, xarg=parseargs(xarg)}
table.insert(stack, top) -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("nothing to close with "..label)
end
if toclose.label ~= label then
error("trying to close "..toclose.label.." with "..label)
end
table.insert(top, toclose)
end
i = j+1
end
local text = string.sub(s, i)
if not string.find(text, "^%s*$") then
table.insert(stack[#stack], text)
end
if #stack > 1 then
error("unclosed "..stack[#stack].label)
end
return stack[1]
end
function flatten_array(array)
local t = {}
for i, v in ipairs(array) do
if v.label == 'movieinfo' then
v.label = v.xarg.id
end
if v.xarg and v.xarg.filesize then
t['filesize'] = v.xarg.filesize
end
if v.label then
if (type(v) == "table") then
-- t['name'] already exists, append to it
if t[v.label] then
table.insert(t[v.label], v[1])
else
t[v.label] = flatten_array(v)
end
else
t[v.label] = v
end
else
if (type(v) == "table") then
table.insert(t, flatten_array(v))
else
table.insert(t, v)
end
end
end
return t
end
function fetch_results_cb(results)
if not results then
grl.warning('Failed to fetch XML file')
grl.callback()
return
end
local array = collect(results)
cached_xml = flatten_array(array)
parse_results(cached_xml)
end
function parse_results(results)
local count = grl.get_options("count")
local skip = grl.get_options("skip")
for i, item in pairs(results.records) do
local media = {}
media.type = 'video'
media.id = i
if item.cast then media.performer = item.cast.name end
media.genre = item.genre.name
media.license = item.info.copyright[1]
media.description = item.info.description[1]
media.director = item.info.director[1]
media.publication_date = item.info.releasedate[1]
media.certificate = item.info.rating[1]
media.studio = item.info.studio[1]
media.title = item.info.title[1]
media.thumbnail = item.poster.xlarge[1]
media.url = item.preview.large[1]
media.size = item.preview.filesize
local mins, secs = item.info.runtime[1]:match('(%d):(%d)')
media.duration = tonumber(mins) * 60 + tonumber(secs)
if skip > 0 then
skip = skip - 1
else
count = count - 1
grl.callback(media, count)
if count == 0 then
return
end
end
end
if count ~= 0 then
grl.callback()
end
end
|
--[[
* Copyright (C) 2015 Grilo Project
*
* 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
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-appletrailers-lua",
name = "Apple Movie Trailers",
description = "Apple Trailers",
supported_media = 'video',
supported_keys = { 'author', 'publication-date', 'description', 'duration', 'genre', 'id', 'thumbnail', 'title', 'url', 'certificate', 'studio', 'license', 'performer', 'size' },
config_keys = {
optional = { 'definition' },
},
icon = 'resource:///org/gnome/grilo/plugins/appletrailers/trailers.svg',
tags = { 'country:us', 'cinema', 'net:internet', 'net:plaintext' },
}
-- Global table to store config data
ldata = {}
-- Global table to store parse results
cached_xml = nil
function grl_source_init(configs)
ldata.hd = (configs.definition and configs.definition == 'hd')
return true
end
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
APPLE_TRAILERS_CURRENT_SD = "http://trailers.apple.com/trailers/home/xml/current_480p.xml"
APPLE_TRAILERS_CURRENT_HD = "http://trailers.apple.com/trailers/home/xml/current_720p.xml"
function grl_source_browse()
local skip = grl.get_options("skip")
local count = grl.get_options("count")
-- Make sure to reset the cache when browsing again
if skip == 0 then
cached_xml = nil
end
if cached_xml then
parse_results(cached_xml)
else
local url = APPLE_TRAILERS_CURRENT_SD
if ldata.hd then
url = APPLE_TRAILERS_CURRENT_HD
end
grl.debug('Fetching URL: ' .. url .. ' (count: ' .. count .. ' skip: ' .. skip .. ')')
grl.fetch(url, "fetch_results_cb")
end
end
---------------
-- Utilities --
---------------
function fetch_results_cb(results)
if not results then
grl.warning('Failed to fetch XML file')
grl.callback()
return
end
cached_xml = grl.lua.xml.string_to_table(results)
parse_results(cached_xml)
end
function parse_results(results)
local count = grl.get_options("count")
local skip = grl.get_options("skip")
for i, item in pairs(results.records.movieinfo) do
local media = {}
media.type = 'video'
media.id = item.id
if item.cast then
media.performer = {}
for j, cast in pairs(item.cast.name) do
table.insert(media.performer, cast.xml)
end
end
if item.genre then
media.genre = {}
for j, genre in pairs(item.genre.name) do
table.insert(media.genre, genre.xml)
end
end
media.license = item.info.copyright.xml
media.description = item.info.description.xml
media.director = item.info.director.xml
media.publication_date = item.info.releasedate.xml
media.certificate = item.info.rating.xml
media.studio = item.info.studio.xml
media.title = item.info.title.xml
media.thumbnail = item.poster.xlarge.xml
media.url = item.preview.large.xml
media.size = item.preview.large.filesize
local mins, secs = item.info.runtime.xml:match('(%d):(%d)')
media.duration = tonumber(mins) * 60 + tonumber(secs)
if skip > 0 then
skip = skip - 1
else
count = count - 1
grl.callback(media, count)
if count == 0 then
return
end
end
end
if count ~= 0 then
grl.callback()
end
end
|
lua-factory: Port Apple Trailers to new XML parser
|
lua-factory: Port Apple Trailers to new XML parser
https://bugzilla.gnome.org/show_bug.cgi?id=755556
|
Lua
|
lgpl-2.1
|
MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,GNOME/grilo-plugins
|
e0fe6aa2ab2fba71d3414873c1ba048044ee88a0
|
tests/package.lua
|
tests/package.lua
|
assert(nil == package.loaders[5])
local configure_loaders = function()
table.insert(package.loaders, 4, function() end)
assert(package.loaders[1])
assert(package.loaders[2])
assert(package.loaders[3])
assert(package.loaders[4])
assert(package.loaders[5])
print "loaders configured!"
end
configure_loaders()
for k,v in pairs(package.loaders) do
print( k, type(v))
end
lanes = require "lanes"
lanes.configure{with_timers=false, on_state_create = configure_loaders}
|
local loaders = package.loaders or package.searchers
assert(nil == loaders[5])
local configure_loaders = function()
table.insert(loaders, 4, function() end)
assert(loaders[1])
assert(loaders[2])
assert(loaders[3])
assert(loaders[4])
assert(loaders[5])
print "loaders configured!"
end
configure_loaders()
for k,v in pairs(loaders) do
print( k, type(v))
end
lanes = require "lanes"
lanes.configure{with_timers=false, on_state_create = configure_loaders}
|
Fix package test for Lua 5.2 and Lua 5.3
|
Fix package test for Lua 5.2 and Lua 5.3
Starting from Lua 5.2, package.loaders is renamed as package.searchers.
|
Lua
|
mit
|
aryajur/lanes,aryajur/lanes
|
a25e4e1ed89e49b865f3779ea28df2a31cfde931
|
profiles/foot.lua
|
profiles/foot.lua
|
-- Foot profile
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["foot"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "foot" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "foot" }
speed_profile = {
["primary"] = 5,
["primary_link"] = 5,
["secondary"] = 5,
["secondary_link"] = 5,
["tertiary"] = 5,
["tertiary_link"] = 5,
["unclassified"] = 5,
["residential"] = 5,
["road"] = 5,
["living_street"] = 5,
["service"] = 5,
["track"] = 5,
["path"] = 5,
["steps"] = 5,
["ferry"] = 5,
["pedestrian"] = 5,
["footway"] = 5,
["pier"] = 5,
["default"] = 5
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = false
use_restrictions = false
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 2
use_turn_restrictions = false
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if obey_bollards then
--flag node as unpassable if it black listed as unpassable
if access_tag_blacklist[barrier] then
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = false;
end
end
return 1
end
function way_function (way)
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local onewayClass = way.tags:Find("oneway:foot")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration(duration) / math.max(1, numberOfNodesInWay-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
way.speed = speed_profile[highway]
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then
way.direction = Way.oneway
elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then
way.direction = Way.bidirectional
elseif onewayClass == "-1" then
way.direction = Way.opposite
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Foot profile
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["foot"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "foot" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "foot" }
speed_profile = {
["primary"] = 5,
["primary_link"] = 5,
["secondary"] = 5,
["secondary_link"] = 5,
["tertiary"] = 5,
["tertiary_link"] = 5,
["unclassified"] = 5,
["residential"] = 5,
["road"] = 5,
["living_street"] = 5,
["service"] = 5,
["track"] = 5,
["path"] = 5,
["steps"] = 5,
["ferry"] = 5,
["pedestrian"] = 5,
["footway"] = 5,
["pier"] = 5,
["default"] = 5
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = false
use_restrictions = false
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 2
use_turn_restrictions = false
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if obey_bollards then
--flag node as unpassable if it black listed as unpassable
if access_tag_blacklist[barrier] then
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = false;
end
end
return 1
end
function way_function (way)
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local onewayClass = way.tags:Find("oneway:foot")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
way.speed = speed_profile[highway]
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then
way.direction = Way.oneway
elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then
way.direction = Way.bidirectional
elseif onewayClass == "-1" then
way.direction = Way.opposite
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes #737
|
Fixes #737
|
Lua
|
bsd-2-clause
|
deniskoronchik/osrm-backend,ammeurer/osrm-backend,bjtaylor1/osrm-backend,prembasumatary/osrm-backend,stevevance/Project-OSRM,oxidase/osrm-backend,Tristramg/osrm-backend,chaupow/osrm-backend,antoinegiret/osrm-backend,prembasumatary/osrm-backend,hydrays/osrm-backend,beemogmbh/osrm-backend,duizendnegen/osrm-backend,yuryleb/osrm-backend,arnekaiser/osrm-backend,neilbu/osrm-backend,oxidase/osrm-backend,ammeurer/osrm-backend,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,jpizarrom/osrm-backend,stevevance/Project-OSRM,nagyistoce/osrm-backend,neilbu/osrm-backend,felixguendling/osrm-backend,agruss/osrm-backend,frodrigo/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,tkhaxton/osrm-backend,Conggge/osrm-backend,felixguendling/osrm-backend,oxidase/osrm-backend,frodrigo/osrm-backend,agruss/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,Carsten64/OSRM-aux-git,duizendnegen/osrm-backend,raymond0/osrm-backend,KnockSoftware/osrm-backend,Project-OSRM/osrm-backend,Conggge/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,arnekaiser/osrm-backend,KnockSoftware/osrm-backend,alex85k/Project-OSRM,KnockSoftware/osrm-backend,deniskoronchik/osrm-backend,Tristramg/osrm-backend,felixguendling/osrm-backend,atsuyim/osrm-backend,duizendnegen/osrm-backend,arnekaiser/osrm-backend,stevevance/Project-OSRM,antoinegiret/osrm-geovelo,Tristramg/osrm-backend,antoinegiret/osrm-backend,ramyaragupathy/osrm-backend,alex85k/Project-OSRM,skyborla/osrm-backend,atsuyim/osrm-backend,tkhaxton/osrm-backend,bitsteller/osrm-backend,bitsteller/osrm-backend,chaupow/osrm-backend,jpizarrom/osrm-backend,beemogmbh/osrm-backend,skyborla/osrm-backend,Conggge/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,alex85k/Project-OSRM,Conggge/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-geovelo,bjtaylor1/Project-OSRM-Old,bjtaylor1/Project-OSRM-Old,neilbu/osrm-backend,bjtaylor1/osrm-backend,antoinegiret/osrm-backend,frodrigo/osrm-backend,atsuyim/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,antoinegiret/osrm-geovelo,jpizarrom/osrm-backend,Project-OSRM/osrm-backend,Carsten64/OSRM-aux-git,ammeurer/osrm-backend,nagyistoce/osrm-backend,bjtaylor1/Project-OSRM-Old,yuryleb/osrm-backend,bjtaylor1/Project-OSRM-Old,Carsten64/OSRM-aux-git,raymond0/osrm-backend,Project-OSRM/osrm-backend,skyborla/osrm-backend,arnekaiser/osrm-backend,oxidase/osrm-backend,agruss/osrm-backend,ramyaragupathy/osrm-backend,chaupow/osrm-backend,yuryleb/osrm-backend,neilbu/osrm-backend,KnockSoftware/osrm-backend,stevevance/Project-OSRM,yuryleb/osrm-backend,raymond0/osrm-backend,deniskoronchik/osrm-backend,deniskoronchik/osrm-backend,bitsteller/osrm-backend,prembasumatary/osrm-backend,beemogmbh/osrm-backend,tkhaxton/osrm-backend
|
ab319662058fe769de509e90e98ccc2bd5bd7081
|
tests/wow_api.lua
|
tests/wow_api.lua
|
local _G = getfenv(0)
local donothing = function() end
local frames = {} -- Stores globally created frames, and their internal properties.
local FrameClass = {} -- A class for creating frames.
FrameClass.methods = { "SetScript", "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents", "OnShow", "OnHide" }
function FrameClass:New()
local frame = {}
for i,method in ipairs(self.methods) do
frame[method] = self[method]
end
local frameProps = {
events = {},
scripts = {},
timer = GetTime(),
isShow = true
}
return frame, frameProps
end
function FrameClass:SetScript(script,handler)
frames[self].scripts[script] = handler
end
function FrameClass:RegisterEvent(event)
frames[self].events[event] = true
end
function FrameClass:UnregisterEvent(event)
frames[self].events[event] = nil
end
function FrameClass:UnregisterAllEvents(frame)
for event in pairs(frames[self].events) do
frames[self].events[event] = nil
end
end
function FrameClass:Show()
frames[self].isShow = true
end
function FrameClass:Hide()
frames[self].isShow = false
end
function FrameClass:IsShown()
return frames[self].isShow
end
function CreateFrame(kind, name, parent)
local frame,internal = FrameClass:New()
frames[frame] = internal
if name then
_G[name] = frame
end
return frame
end
function UnitName(unit)
return unit
end
function GetRealmName()
return "Realm Name"
end
function UnitClass(unit)
return "Warrior", "WARRIOR"
end
function UnitHealthMax()
return 100
end
function UnitHealth()
return 50
end
function GetNumRaidMembers()
return 1
end
function GetNumPartyMembers()
return 1
end
FACTION_HORDE = "Horde"
FACTION_ALLIANCE = "Alliance"
function UnitFactionGroup(unit)
return "Horde", "Horde"
end
function UnitRace(unit)
return "Undead", "Scourge"
end
GetTime = os.clock
function IsAddOnLoaded() return nil end
SlashCmdList = {}
function __WOW_Input(text)
local a,b = string.find(text, "^/%w+")
local arg, text = string.sub(text, a,b), string.sub(text, b + 2)
for k,handler in pairs(SlashCmdList) do
local i = 0
while true do
i = i + 1
if not _G["SLASH_" .. k .. i] then
break
elseif _G["SLASH_" .. k .. i] == arg then
handler(text)
return
end
end
end;
print("No command found:", text)
end
local ChatFrameTemplate = {
AddMessage = function(self, text)
print((string.gsub(text, "|c%x%x%x%x%x%x%x%x(.-)|r", "%1")))
end
}
for i=1,7 do
local f = {}
for k,v in pairs(ChatFrameTemplate) do
f[k] = v
end
_G["ChatFrame"..i] = f
end
DEFAULT_CHAT_FRAME = ChatFrame1
debugstack = debug.traceback
date = os.date
function GetLocale()
return "enUS"
end
function GetAddOnInfo()
return
end
function GetNumAddOns()
return 0
end
function getglobal(k)
return _G[k]
end
function setglobal(k, v)
_G[k] = v
end
local function _errorhandler(msg)
print("--------- geterrorhandler error -------\n"..msg.."\n-----end error-----\n")
end
function geterrorhandler()
return _errorhandler
end
function InCombatLockdown()
return false
end
function IsLoggedIn()
return false
end
time = os.clock
strmatch = string.match
function SendAddonMessage(prefix, message, distribution, target)
assert(#prefix + #message < 255,
string.format("SendAddonMessage: message too long (%d bytes)",
#prefix + #message))
-- CHAT_MSG_ADDON(prefix, message, distribution, sender)
WoWAPI_FireEvent("CHAT_MSG_ADDON", prefix, message, distribution, "Sender")
end
RED_FONT_COLOR_CODE = ""
GREEN_FONT_COLOR_CODE = ""
StaticPopupDialogs = {}
function WoWAPI_FireEvent(event,...)
for frame, props in pairs(frames) do
if props.events[event] then
if props.scripts["OnEvent"] then
props.scripts["OnEvent"](frame,event,...)
end
end
end
end
function WoWAPI_FireUpdate()
local now = GetTime()
for frame,props in pairs(frames) do
if props.isShow and props.scripts.OnUpdate then
props.scripts.OnUpdate(frame,now-props.timer)
props.timer = now
end
end
end
-- utility function for "dumping" a number of arguments (return a string representation of them)
function dump(...)
local t = {}
for i=1,select("#", ...) do
local v = select(i, ...)
if type(v)=="string" then
tinsert(t, string.format("%q", v))
else
tinsert(t, tostring(v))
end
end
return "<"..table.concat(t, "> <")..">"
end
|
local _G = getfenv(0)
local donothing = function() end
local frames = {} -- Stores globally created frames, and their internal properties.
local FrameClass = {} -- A class for creating frames.
FrameClass.methods = { "SetScript", "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents", "Show", "Hide", "IsShown" }
function FrameClass:New()
local frame = {}
for i,method in ipairs(self.methods) do
frame[method] = self[method]
end
local frameProps = {
events = {},
scripts = {},
timer = GetTime(),
isShow = true
}
return frame, frameProps
end
function FrameClass:SetScript(script,handler)
frames[self].scripts[script] = handler
end
function FrameClass:RegisterEvent(event)
frames[self].events[event] = true
end
function FrameClass:UnregisterEvent(event)
frames[self].events[event] = nil
end
function FrameClass:UnregisterAllEvents(frame)
for event in pairs(frames[self].events) do
frames[self].events[event] = nil
end
end
function FrameClass:Show()
frames[self].isShow = true
end
function FrameClass:Hide()
frames[self].isShow = false
end
function FrameClass:IsShown()
return frames[self].isShow
end
function CreateFrame(kind, name, parent)
local frame,internal = FrameClass:New()
frames[frame] = internal
if name then
_G[name] = frame
end
return frame
end
function UnitName(unit)
return unit
end
function GetRealmName()
return "Realm Name"
end
function UnitClass(unit)
return "Warrior", "WARRIOR"
end
function UnitHealthMax()
return 100
end
function UnitHealth()
return 50
end
function GetNumRaidMembers()
return 1
end
function GetNumPartyMembers()
return 1
end
FACTION_HORDE = "Horde"
FACTION_ALLIANCE = "Alliance"
function UnitFactionGroup(unit)
return "Horde", "Horde"
end
function UnitRace(unit)
return "Undead", "Scourge"
end
GetTime = os.clock
function IsAddOnLoaded() return nil end
SlashCmdList = {}
function __WOW_Input(text)
local a,b = string.find(text, "^/%w+")
local arg, text = string.sub(text, a,b), string.sub(text, b + 2)
for k,handler in pairs(SlashCmdList) do
local i = 0
while true do
i = i + 1
if not _G["SLASH_" .. k .. i] then
break
elseif _G["SLASH_" .. k .. i] == arg then
handler(text)
return
end
end
end;
print("No command found:", text)
end
local ChatFrameTemplate = {
AddMessage = function(self, text)
print((string.gsub(text, "|c%x%x%x%x%x%x%x%x(.-)|r", "%1")))
end
}
for i=1,7 do
local f = {}
for k,v in pairs(ChatFrameTemplate) do
f[k] = v
end
_G["ChatFrame"..i] = f
end
DEFAULT_CHAT_FRAME = ChatFrame1
debugstack = debug.traceback
date = os.date
function GetLocale()
return "enUS"
end
function GetAddOnInfo()
return
end
function GetNumAddOns()
return 0
end
function getglobal(k)
return _G[k]
end
function setglobal(k, v)
_G[k] = v
end
local function _errorhandler(msg)
print("--------- geterrorhandler error -------\n"..msg.."\n-----end error-----\n")
end
function geterrorhandler()
return _errorhandler
end
function InCombatLockdown()
return false
end
function IsLoggedIn()
return false
end
time = os.clock
strmatch = string.match
function SendAddonMessage(prefix, message, distribution, target)
assert(#prefix + #message < 255,
string.format("SendAddonMessage: message too long (%d bytes)",
#prefix + #message))
-- CHAT_MSG_ADDON(prefix, message, distribution, sender)
WoWAPI_FireEvent("CHAT_MSG_ADDON", prefix, message, distribution, "Sender")
end
function hooksecurefunc(func_name, post_hook_func)
local orig_func = _G[func_name]
_G[func_name] = function (...)
orig_func(...)
return post_hook_func(...)
end
end
RED_FONT_COLOR_CODE = ""
GREEN_FONT_COLOR_CODE = ""
StaticPopupDialogs = {}
function WoWAPI_FireEvent(event,...)
for frame, props in pairs(frames) do
if props.events[event] then
if props.scripts["OnEvent"] then
props.scripts["OnEvent"](frame,event,...)
end
end
end
end
function WoWAPI_FireUpdate()
local now = GetTime()
for frame,props in pairs(frames) do
if props.isShow and props.scripts.OnUpdate then
props.scripts.OnUpdate(frame,now-props.timer)
props.timer = now
end
end
end
-- utility function for "dumping" a number of arguments (return a string representation of them)
function dump(...)
local t = {}
for i=1,select("#", ...) do
local v = select(i, ...)
if type(v)=="string" then
tinsert(t, string.format("%q", v))
else
tinsert(t, tostring(v))
end
end
return "<"..table.concat(t, "> <")..">"
end
|
Ace3: fixed frame methods added hooksecurefunc emulation
|
Ace3:
fixed frame methods
added hooksecurefunc emulation
git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@262 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
b255c66c87aa1030f0866dacf5465380e7c02e83
|
test_scripts/Polices/Policy_Table_Update/021_ATF_P_TC_timeout_countdown_start.lua
|
test_scripts/Polices/Policy_Table_Update/021_ATF_P_TC_timeout_countdown_start.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] "timeout" countdown start
--
-- Description:
-- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS
-- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be
-- assigned as "JSON" in mobile app notification.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default")
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID)
-- 2. Performed steps
-- Do not send SystemRequest from <app_ID>
--
-- Expected result:
-- SDL waits for SystemRequest response from <app ID> within 'timeout' value, if no obtained,
-- it starts retry sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_trigger_getting_device_consent()
testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Sending_PTS_to_mobile_application()
local time_update_needed = {}
local time_system_request = {}
local endpoints = {}
local is_test_fail = false
local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local PathToSnapshot = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot")
local file_pts = SystemFilesPath.."/"..PathToSnapshot
local seconds_between_retries = {}
local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
end
local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 2000)
commonTestCases:DelayedExp(time_wait) -- tolerance 10 sec
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil}
end
end
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } )
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" })
--first retry sequence
local function verify_retry_sequence(occurences)
--time_update_needed[#time_update_needed + 1] = testCasesForPolicyTable.time_trigger
time_update_needed[#time_update_needed + 1] = timestamp()
local time_1 = time_update_needed[#time_update_needed]
local time_2 = time_system_request[#time_system_request]
local timeout = (time_1 - time_2)
if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then
is_test_fail = true
commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms")
else
print("timeout is as expected for retry sequence "..occurences..": "..timeout_pts.."ms. real: "..timeout)
end
return true
end
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"})
:Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",
{status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2)
:Do(function(exp_pu, data)
if(data.params.status == "UPDATE_NEEDED") then
verify_retry_sequence(exp_pu.occurences - 1)
end
end)
--TODO(istoimenova): Remove when "[GENIVI] PTU is restarted each 10 sec." is fixed.
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
:Do(function(_,data)
is_test_fail = true
commonFunctions:printError("ERROR: PTU sequence is restarted again!")
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] "timeout" countdown start
--
-- Description:
-- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS
-- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be
-- assigned as "JSON" in mobile app notification.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default")
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID)
-- 2. Performed steps
-- Do not send SystemRequest from <app_ID>
--
-- Expected result:
-- SDL waits for SystemRequest response from <app ID> within 'timeout' value, if no obtained,
-- it starts retry sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_trigger_getting_device_consent()
testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Sending_PTS_to_mobile_application()
local time_update_needed = {}
local time_system_request = {}
local endpoints = {}
local is_test_fail = false
local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local PathToSnapshot = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot")
local file_pts = SystemFilesPath.."/"..PathToSnapshot
local seconds_between_retries = {}
local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
end
local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 2000)
commonTestCases:DelayedExp(time_wait) -- tolerance 10 sec
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil}
end
end
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } )
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" })
--first retry sequence
local function verify_retry_sequence(occurences)
--time_update_needed[#time_update_needed + 1] = testCasesForPolicyTable.time_trigger
time_update_needed[#time_update_needed + 1] = timestamp()
local time_1 = time_update_needed[#time_update_needed]
local time_2 = time_system_request[#time_system_request]
local timeout = (time_1 - time_2)
if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then
is_test_fail = true
commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms")
else
print("timeout is as expected for retry sequence "..occurences..": "..timeout_pts.."ms. real: "..timeout)
end
return true
end
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"})
:Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2):Timeout(64000)
:Do(function(exp_pu, data)
print(exp_pu.occurences..":"..data.params.status)
if(data.params.status == "UPDATE_NEEDED") then
verify_retry_sequence(exp_pu.occurences - 1)
end
end)
--TODO(istoimenova): Remove when "[GENIVI] PTU is restarted each 10 sec." is fixed.
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
:Do(function(_,data)
is_test_fail = true
commonFunctions:printError("ERROR: PTU sequence is restarted again!")
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
Fix issues in script
|
Fix issues in script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
b0aa3b69139ffc540968dd8b37d04e9647253d8b
|
xmake/platforms/android/config.lua
|
xmake/platforms/android/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
--
-- imports
import("core.project.config")
import("core.base.singleton")
import("detect.sdks.find_ndk")
import("detect.sdks.find_android_sdk")
import("private.platform.toolchain")
import("private.platform.check_arch")
import("private.platform.check_toolchain")
-- check the ndk toolchain
function _check_ndk()
local ndk = find_ndk(config.get("ndk"), {force = true, verbose = true})
if ndk then
config.set("ndk", ndk.sdkdir, {force = true, readonly = true}) -- maybe to global
config.set("bin", ndk.bindir, {force = true, readonly = true})
config.set("cross", ndk.cross, {force = true, readonly = true})
config.set("gcc_toolchain", ndk.gcc_toolchain, {force = true, readonly = true})
else
-- failed
cprint("${bright color.error}please run:")
cprint(" - xmake config --ndk=xxx")
cprint("or - xmake global --ndk=xxx")
raise()
end
end
-- check the android sdk
function _check_android_sdk()
local sdk = find_android_sdk(config.get("android_sdk"), {force = true, verbose = true})
if sdk then
config.set("sdk", sdk.sdkdir, {force = true, readonly = true}) -- maybe to global
end
end
-- get toolchains
function _toolchains()
-- get cross
local cross = config.get("cross")
-- get gcc toolchain bin directory
local gcc_toolchain_bin = nil
local gcc_toolchain = config.get("gcc_toolchain")
if gcc_toolchain then
gcc_toolchain_bin = path.join(gcc_toolchain, "bin")
end
-- init toolchains
local cc = toolchain("the c compiler")
local cxx = toolchain("the c++ compiler")
local cpp = toolchain("the c preprocessor")
local ld = toolchain("the linker")
local sh = toolchain("the shared library linker")
local ar = toolchain("the static library archiver")
local ex = toolchain("the static library extractor")
local ranlib = toolchain("the static library index generator")
local as = toolchain("the assember")
local rc = toolchain("the rust compiler")
local rc_ld = toolchain("the rust linker")
local rc_sh = toolchain("the rust shared library linker")
local rc_ar = toolchain("the rust static library archiver")
local toolchains = {cc = cc, cxx = cxx, cpp = cpp, as = as, ld = ld, sh = sh, ar = ar, ex = ex, ranlib = ranlib,
rc = rc, ["rc-ld"] = rc_ld, ["rc-sh"] = rc_sh, ["rc-ar"] = rc_ar}
-- init the c compiler
cc:add({name = "gcc", cross = cross}, "clang")
-- init the c++ compiler
cxx:add({name = "g++", cross = cross}, "clang++")
-- init the c preprocessor
cpp:add({name = "gcc -E", cross = cross}, "clang -E")
-- init the assember
as:add({name = "gcc", cross = cross}, "clang")
-- init the linker
ld:add({name = "gcc", cross = cross})
ld:add({name = "g++", cross = cross})
ld:add("clang", "clang++")
-- init the shared library linker
sh:add({name = "gcc", cross = cross})
sh:add({name = "g++", cross = cross})
sh:add("clang", "clang++")
-- init the static library archiver
ar:add({name = "ar", cross = cross}, "llvm-ar")
-- init the static library extractor
ex:add({name = "ar", cross = cross}, "llvm-ar")
-- init the static library index generator
ranlib:add({name = "ranlib", cross = cross, pathes = gcc_toolchain_bin}, "ranlib")
-- init the rust compiler and linker
rc:add("$(env RC)", "rustc")
rc_ld:add("$(env RC)", "rustc")
rc_sh:add("$(env RC)", "rustc")
rc_ar:add("$(env RC)", "rustc")
return toolchains
end
-- check it
function main(platform, name)
-- only check the given config name?
if name then
local toolchain = singleton.get("android.toolchains", _toolchains)[name]
if toolchain then
check_toolchain(config, name, toolchain)
end
else
-- check arch
check_arch(config, "armv7-a")
-- check ndk
_check_ndk()
-- check android sdk
_check_android_sdk()
-- check ld and sh, @note toolchains must be initialized after calling check_ndk()
local toolchains = singleton.get("android.toolchains", _toolchains)
check_toolchain(config, "ld", toolchains.ld)
check_toolchain(config, "sh", toolchains.sh)
end
end
|
--!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
--
-- imports
import("core.project.config")
import("core.base.singleton")
import("detect.sdks.find_ndk")
import("detect.sdks.find_android_sdk")
import("private.platform.toolchain")
import("private.platform.check_arch")
import("private.platform.check_toolchain")
-- check the ndk toolchain
function _check_ndk()
local ndk = find_ndk(config.get("ndk"), {force = true, verbose = true})
if ndk then
config.set("ndk", ndk.sdkdir, {force = true, readonly = true}) -- maybe to global
config.set("bin", ndk.bindir, {force = true, readonly = true})
config.set("cross", ndk.cross, {force = true, readonly = true})
config.set("gcc_toolchain", ndk.gcc_toolchain, {force = true, readonly = true})
else
-- failed
cprint("${bright color.error}please run:")
cprint(" - xmake config --ndk=xxx")
cprint("or - xmake global --ndk=xxx")
raise()
end
end
-- check the android sdk
function _check_android_sdk()
local sdk = find_android_sdk(config.get("android_sdk"), {force = true, verbose = true})
if sdk then
config.set("sdk", sdk.sdkdir, {force = true, readonly = true}) -- maybe to global
end
end
-- get toolchains
function _toolchains()
-- get cross
local cross = config.get("cross")
-- get gcc toolchain bin directory
local gcc_toolchain_bin = nil
local gcc_toolchain = config.get("gcc_toolchain")
if gcc_toolchain then
gcc_toolchain_bin = path.join(gcc_toolchain, "bin")
end
-- init toolchains
local cc = toolchain("the c compiler")
local cxx = toolchain("the c++ compiler")
local cpp = toolchain("the c preprocessor")
local ld = toolchain("the linker")
local sh = toolchain("the shared library linker")
local ar = toolchain("the static library archiver")
local ex = toolchain("the static library extractor")
local ranlib = toolchain("the static library index generator")
local as = toolchain("the assember")
local rc = toolchain("the rust compiler")
local rc_ld = toolchain("the rust linker")
local rc_sh = toolchain("the rust shared library linker")
local rc_ar = toolchain("the rust static library archiver")
local toolchains = {cc = cc, cxx = cxx, cpp = cpp, as = as, ld = ld, sh = sh, ar = ar, ex = ex, ranlib = ranlib,
rc = rc, ["rc-ld"] = rc_ld, ["rc-sh"] = rc_sh, ["rc-ar"] = rc_ar}
-- init the c compiler
cc:add({name = "gcc", cross = cross}, "clang")
-- init the c++ compiler
cxx:add({name = "g++", cross = cross}, "clang++")
-- init the c preprocessor
cpp:add({name = "gcc -E", cross = cross}, "clang -E")
-- init the assember
as:add({name = "gcc", cross = cross}, "clang")
-- init the linker
ld:add({name = "gcc", cross = cross})
ld:add({name = "g++", cross = cross})
ld:add("clang", "clang++")
-- init the shared library linker
sh:add({name = "gcc", cross = cross})
sh:add({name = "g++", cross = cross})
sh:add("clang", "clang++")
-- init the static library archiver
ar:add({name = "ar", cross = cross, pathes = gcc_toolchain_bin}, "llvm-ar")
-- init the static library extractor
ex:add({name = "ar", cross = cross, pathes = gcc_toolchain_bin}, "llvm-ar")
-- init the static library index generator
ranlib:add({name = "ranlib", cross = cross, pathes = gcc_toolchain_bin}, "ranlib")
-- init the rust compiler and linker
rc:add("$(env RC)", "rustc")
rc_ld:add("$(env RC)", "rustc")
rc_sh:add("$(env RC)", "rustc")
rc_ar:add("$(env RC)", "rustc")
return toolchains
end
-- check it
function main(platform, name)
-- only check the given config name?
if name then
local toolchain = singleton.get("android.toolchains", _toolchains)[name]
if toolchain then
check_toolchain(config, name, toolchain)
end
else
-- check arch
check_arch(config, "armv7-a")
-- check ndk
_check_ndk()
-- check android sdk
_check_android_sdk()
-- check ld and sh, @note toolchains must be initialized after calling check_ndk()
local toolchains = singleton.get("android.toolchains", _toolchains)
check_toolchain(config, "ld", toolchains.ld)
check_toolchain(config, "sh", toolchains.sh)
end
end
|
fix detect ar for android ar
|
fix detect ar for android ar
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
ea5170ee70ae15aaf299de1392d0099fae86b1ac
|
Peripherals/CPU.lua
|
Peripherals/CPU.lua
|
local events = require("Engine.events")
local coreg = require("Engine.coreg")
return function(config) --A function that creates a new CPU peripheral.
local EventStack = {}
local Instant = false
local RawPull = false
local sleepTimer
local function hookEvent(pre,name)
events:register(pre..":"..name,function(...)
if Instant then
Instant = false coreg:resumeCoroutine(true,name,...)
else
--[[local args = {...}
local nargs = {name}
for k,v in ipairs(args) do table.insert(nargs,v) end]]
if RawPull then
RawPull = false coreg:resumeCoroutine(true,name,...)
end
table.insert(EventStack,{name,...})
end
end)
end
hookEvent("love","update")
hookEvent("love","keypressed")
hookEvent("love","keyreleased")
hookEvent("GPU","mousepressed") --So they are translated to the LIKO-12 screen
hookEvent("GPU","mousemoved")
hookEvent("GPU","mousereleased")
hookEvent("GPU","touchpressed")
hookEvent("GPU","touchmoved")
hookEvent("GPU","touchreleased")
hookEvent("GPU","textinput")
events:register("love:update",function(dt)
if sleepTimer then
sleepTimer = sleepTimer-dt
if sleepTimer <=0 then
sleepTimer = nil
coreg:resumeCoroutine(true)
end
end
end)
--The api starts here--
local CPU = {}
function CPU.pullEvent()
if #EventStack == 0 then
Instant = true
return 2 --To quit the coroutine resuming loop
else
local lastEvent = EventStack[1]
local newEventStack = {}
for k,v in ipairs(EventStack) do
if k > 1 then table.insert(newEventStack,v) end --Remove the last event.
end
EventStack = newEventStack
return true, unpack(lastEvent)
end
end
function CPU.rawPullEvent()
RawPull = true
return 2
end
function CPU.triggerEvent(name,...)
if type(name) ~= "string" then
return false, "The event name must be a string, got a "..type(name)
end
table.insert(EventStack,{name,...})
return true
end
function CPU.clearEStack()
EventStack = {}
return true
end
function CPU.getHostOS()
return true, love.system.getOS()
end
function CPU.isMobile()
if love.system.getOS() == "Android" or love.filesystem.getOS() == "iOS" then
return true, true
else
return true, false
end
end
function CPU.clipboard(text)
if text then
love.system.setClipboardText(tostring(text))
return true
else
return true, love.system.getClipboardText()
end
end
function CPU.clearClipboard()
love.system.setClipboardText()
return true
end
function CPU.sleep(t)
if type(t) ~= "number" then return false, "Time must be a number, provided: "..t end
if t < 0 then return false, "Time must be a positive number" end
sleepTimer = t
return 2
end
function CPU.shutdown()
love.event.quit()
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.reboot(hard)
if hard then
love.event.quit( "restart" )
else
events:trigger("love:reboot") --Tell main.lua that we have to soft reboot.
end
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.openAppData(tar)
local tar = tar or "/"
if tar:sub(0,1) ~= "/" then tar = "/"..tar end
love.system.openURL("file://"..love.filesystem.getSaveDirectory()..tar)
return true --It ran successfully
end
return CPU
end
|
local events = require("Engine.events")
local coreg = require("Engine.coreg")
return function(config) --A function that creates a new CPU peripheral.
local EventStack = {}
local Instant = false
local RawPull = false
local sleepTimer
local function hookEvent(pre,name)
events:register(pre..":"..name,function(...)
if Instant then
Instant = false coreg:resumeCoroutine(true,name,...)
else
--[[local args = {...}
local nargs = {name}
for k,v in ipairs(args) do table.insert(nargs,v) end]]
table.insert(EventStack,{name,...})
if RawPull then
RawPull = false coreg:resumeCoroutine(true,name,...)
end
end
end)
end
hookEvent("love","update")
hookEvent("love","keypressed")
hookEvent("love","keyreleased")
hookEvent("GPU","mousepressed") --So they are translated to the LIKO-12 screen
hookEvent("GPU","mousemoved")
hookEvent("GPU","mousereleased")
hookEvent("GPU","touchpressed")
hookEvent("GPU","touchmoved")
hookEvent("GPU","touchreleased")
hookEvent("GPU","textinput")
events:register("love:update",function(dt)
if sleepTimer then
sleepTimer = sleepTimer-dt
if sleepTimer <=0 then
sleepTimer = nil
coreg:resumeCoroutine(true)
end
end
end)
--The api starts here--
local CPU = {}
function CPU.pullEvent()
if #EventStack == 0 then
Instant = true
return 2 --To quit the coroutine resuming loop
else
local lastEvent = EventStack[1]
local newEventStack = {}
for k,v in ipairs(EventStack) do
if k > 1 then table.insert(newEventStack,v) end --Remove the last event.
end
EventStack = newEventStack
return true, unpack(lastEvent)
end
end
function CPU.rawPullEvent()
RawPull = true
return 2
end
function CPU.triggerEvent(name,...)
if type(name) ~= "string" then
return false, "The event name must be a string, got a "..type(name)
end
table.insert(EventStack,{name,...})
return true
end
function CPU.clearEStack()
EventStack = {}
return true
end
function CPU.getHostOS()
return true, love.system.getOS()
end
function CPU.isMobile()
if love.system.getOS() == "Android" or love.filesystem.getOS() == "iOS" then
return true, true
else
return true, false
end
end
function CPU.clipboard(text)
if text then
love.system.setClipboardText(tostring(text))
return true
else
return true, love.system.getClipboardText()
end
end
function CPU.clearClipboard()
love.system.setClipboardText()
return true
end
function CPU.sleep(t)
if type(t) ~= "number" then return false, "Time must be a number, provided: "..t end
if t < 0 then return false, "Time must be a positive number" end
sleepTimer = t
return 2
end
function CPU.shutdown()
love.event.quit()
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.reboot(hard)
if hard then
love.event.quit( "restart" )
else
events:trigger("love:reboot") --Tell main.lua that we have to soft reboot.
end
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.openAppData(tar)
local tar = tar or "/"
if tar:sub(0,1) ~= "/" then tar = "/"..tar end
love.system.openURL("file://"..love.filesystem.getSaveDirectory()..tar)
return true --It ran successfully
end
return CPU
end
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
9fa0f5f288e47f42554d0854df35379c604e1a9c
|
copas.lua
|
copas.lua
|
socket = require('socket')
ambox = require('ambox')
asock = require('asock')
require('util')
-- A reimplementation of the "copas" library API, based on the
-- actor_post_office/actor_socket libraries.
--
-- The standard copas implementation invokes coroutine.yield() with
-- internal copas objects, causing strange interactions with
-- concurrentlua and (the replacement for concurrentlua),
-- actor_post_office. That is, copas wants to monopolize
-- coroutine.yield(), which is doesn't fit our needs.
--
module("copas", package.seeall)
print("loaded ambox-based copas.")
function session_actor(self_addr, handler, skt)
handler(skt)
end
function addserver(server, handler, timeout)
server:settimeout(timeout or 0.1)
ambox.spawn(upstream_accept, server, session_actor, handler)
end
function step(timeout)
ambox.loop_until_empty()
asock.step()
end
function loop(timeout)
while true do
step(timeout)
end
end
-- Wraps a socket to use fake copas methods...
--
local _skt_mt = {
__index = {
send =
function(self, data, from, to)
return asock.send(ambox.self_addr(), self.socket, data, from, to)
end,
receive =
function(self, pattern)
return asock.recv(ambox.self_addr(), self.socket, pattern)
end,
flush =
function(self)
end,
settimeout =
function(self, time)
self.socket:settimeout(time)
end
}}
function wrap(skt)
return setmetatable({ socket = skt }, _skt_mt)
end
function setErrorHandler(err_handler)
-- call like: err_handler(msg, co, skt)
end
|
socket = require('socket')
ambox = require('ambox')
asock = require('asock')
require('util')
-- A reimplementation of the "copas" library API, based on the
-- ambox/asock libraries.
--
-- The standard copas implementation invokes coroutine.yield() with
-- internal copas objects, causing strange interactions with
-- concurrentlua and (the replacement for concurrentlua),
-- ambox. That is, copas wants to monopolize coroutine.yield(),
-- which is doesn't fit our needs.
--
module("copas", package.seeall)
print("loaded ambox-based copas.")
function session_actor(self_addr, handler, skt)
handler(skt)
end
function addserver(server, handler, timeout)
server:settimeout(timeout or 0.1)
ambox.spawn(upstream_accept, server, session_actor, handler)
end
function step(timeout)
ambox.loop_until_empty()
asock.step()
end
function loop(timeout)
while true do
step(timeout)
end
end
-- Wraps a socket to use fake copas methods...
--
local _skt_mt = {
__index = {
send =
function(self, data, from, to)
return asock.send(ambox.self_addr(), self.socket, data, from, to)
end,
receive =
function(self, pattern)
return asock.recv(ambox.self_addr(), self.socket, pattern)
end,
flush =
function(self)
end,
settimeout =
function(self, time)
self.socket:settimeout(time)
end
}}
function wrap(skt)
return setmetatable({ socket = skt }, _skt_mt)
end
function setErrorHandler(err_handler)
-- call like: err_handler(msg, co, skt)
end
|
Comment fixup
|
Comment fixup
|
Lua
|
apache-2.0
|
steveyen/moxilua
|
c2e59b86daf163ba807136440946a06e2f918bc9
|
output/config.lua
|
output/config.lua
|
launch_modes = {
LOCAL = 0,
LOCAL_DETERMINISM_TEST = 1,
ONLY_CLIENT = 2,
ONLY_SERVER = 3,
CLIENT_AND_SERVER = 4,
TWO_CLIENTS_AND_SERVER = 5
}
config_table = {
launch_mode = launch_modes.LOCAL,
recording_replay_speed = 0.5,
determinism_test_cloned_cosmoi_count = 2,
window_name = "example",
fullscreen = 0,
window_border = 1,
window_x = 400,
window_y = 0,
bpp = 24,
resolution_w = 1000,
resolution_h = 800,
doublebuffer = 1,
debug_disable_cursor_clipping = 0,
mouse_sensitivity = vec2(1.5, 1.5),
connect_address = "127.0.0.1",
connect_port = 13372,
server_port = 13372,
alternative_port = 13373,
nickname = "Pythagoras",
debug_second_nickname = "Kartezjan",
tickrate = 60,
jitter_buffer_ms = 50,
client_commands_jitter_buffer_ms = 0,
interpolation_speed = 525,
misprediction_smoothing_multiplier = 0.5,
debug_var = 0,
debug_randomize_entropies_in_client_setup = 1,
debug_randomize_entropies_in_client_setup_once_every_steps = 1,
server_launch_http_daemon = 1,
server_http_daemon_port = 80,
server_http_daemon_html_file_path = "web/session_report.html",
db_path = "P:/Projects/db/",
survey_num_file_path = "survey_num.in",
post_data_file_path = "post.txt",
last_session_update_link = "patrykcysarz.pl/comment-system/web/stats/last-update/set",
}
if config_table.debug_disable_cursor_clipping == 0 then
set_cursor_visible(0)
end
if config_table.fullscreen == 1 then
config_table.resolution_w = get_display().w
config_table.resolution_h = get_display().h
set_display(config_table.resolution_w, config_table.resolution_h, 32)
end
enabled_window_border = 1
if config_table.window_border == 0 or config_table.fullscreen == 1 then
enabled_window_border = 0
end
global_gl_window:create(
rect_xywh_i(config_table.window_x,
config_table.window_y,
config_table.resolution_w,
config_table.resolution_h),
enabled_window_border,
config_table.window_name,
config_table.doublebuffer,
config_table.bpp)
global_gl_window:set_vsync(0)
global_gl_window:set_as_current()
|
launch_modes = {
LOCAL = 0,
LOCAL_DETERMINISM_TEST = 1,
ONLY_CLIENT = 2,
ONLY_SERVER = 3,
CLIENT_AND_SERVER = 4,
TWO_CLIENTS_AND_SERVER = 5
}
config_table = {
launch_mode = launch_modes.LOCAL,
recording_replay_speed = 0.5,
determinism_test_cloned_cosmoi_count = 2,
window_name = "example",
fullscreen = 0,
window_border = 1,
window_x = 400,
window_y = 0,
bpp = 24,
resolution_w = 1000,
resolution_h = 800,
doublebuffer = 1,
debug_disable_cursor_clipping = 0,
mouse_sensitivity = vec2(1.5, 1.5),
connect_address = "127.0.0.1",
connect_port = 13372,
server_port = 13372,
alternative_port = 13373,
nickname = "Pythagoras",
debug_second_nickname = "Kartezjan",
tickrate = 60,
jitter_buffer_ms = 50,
client_commands_jitter_buffer_ms = 0,
interpolation_speed = 525,
misprediction_smoothing_multiplier = 0.5,
debug_var = 0,
debug_randomize_entropies_in_client_setup = 1,
debug_randomize_entropies_in_client_setup_once_every_steps = 1,
server_launch_http_daemon = 1,
server_http_daemon_port = 80,
server_http_daemon_html_file_path = "web/session_report.html",
db_path = "P:/Projects/db/",
survey_num_file_path = "survey_num.in",
post_data_file_path = "post.txt",
last_session_update_link = "patrykcysarz.pl/comment-system/web/stats/last-update/set",
}
if config_table.debug_disable_cursor_clipping == 0 then
set_cursor_visible(0)
end
if config_table.fullscreen == 1 then
config_table.window_x = 0
config_table.window_y = 0
config_table.resolution_w = get_display().w
config_table.resolution_h = get_display().h
set_display(config_table.resolution_w, config_table.resolution_h, 32)
end
enabled_window_border = 1
if config_table.window_border == 0 or config_table.fullscreen == 1 then
enabled_window_border = 0
end
global_gl_window:create(
rect_xywh_i(config_table.window_x,
config_table.window_y,
config_table.resolution_w,
config_table.resolution_h),
enabled_window_border,
config_table.window_name,
config_table.doublebuffer,
config_table.bpp)
global_gl_window:set_vsync(0)
global_gl_window:set_as_current()
|
config fullscreen fix
|
config fullscreen fix
|
Lua
|
agpl-3.0
|
TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Augmentations,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,DaTa-/Hypersomnia
|
cd563caf61d221c982080c3848ce73ea00a204cd
|
output/config.lua
|
output/config.lua
|
config_table = {
window_name = "example",
fullscreen = 0,
window_border = 1,
window_x = 0,
window_y = 0,
bpp = 24,
resolution_w = 1280,
resolution_h = 720,
doublebuffer = 1,
sensitivity = vec2(1.5, 1.5),
server_address = "127.0.0.1",
server_port = 27014,
nickname = "Daedalus",
multiple_clients_view = 0,
divergence_radius = 1,
tickrate = 60,
simulate_lag = 0,
packet_loss = 0.00,
min_latency = 50,
jitter = 0
}
set_cursor_visible(0)
if config_table.fullscreen == 1 then
config_table.resolution_w = get_display().w
config_table.resolution_h = get_display().h
set_display(config_table.resolution_w, config_table.resolution_h, 32)
end
local borders_type = glwindow.ALL_WINDOW_ELEMENTS
if config_table.window_border == 0 or config_table.fullscreen then
borders_type = 0
end
global_gl_window:create(
rect_xywh_i(config_table.window_x,
config_table.window_y,
config_table.resolution_w,
config_table.resolution_h),
borders_type,
config_table.window_name,
config_table.doublebuffer,
config_table.bpp)
global_gl_window:vsync(0)
global_gl_window:current()
|
config_table = {
window_name = "example",
fullscreen = 0,
window_border = 0,
window_x = 0,
window_y = 0,
bpp = 24,
resolution_w = 1280,
resolution_h = 720,
doublebuffer = 1,
sensitivity = vec2(1.5, 1.5),
server_address = "127.0.0.1",
server_port = 27014,
nickname = "Daedalus",
multiple_clients_view = 0,
divergence_radius = 1,
tickrate = 60,
simulate_lag = 0,
packet_loss = 0.00,
min_latency = 50,
jitter = 0
}
set_cursor_visible(0)
if config_table.fullscreen == 1 then
config_table.resolution_w = get_display().w
config_table.resolution_h = get_display().h
set_display(config_table.resolution_w, config_table.resolution_h, 32)
end
enabled_window_border = 1
if config_table.window_border == 0 or config_table.fullscreen == 1 then
enabled_window_border = 0
end
global_gl_window:create(
rect_xywh_i(config_table.window_x,
config_table.window_y,
config_table.resolution_w,
config_table.resolution_h),
enabled_window_border,
config_table.window_name,
config_table.doublebuffer,
config_table.bpp)
global_gl_window:set_vsync(0)
global_gl_window:set_as_current()
|
script fix
|
script fix
|
Lua
|
agpl-3.0
|
TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations,DaTa-/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Augmentations
|
54b4dac6b5930c4c3027264ef058e5c5feaec72e
|
.config/nvim/lua/config/neo-tree.lua
|
.config/nvim/lua/config/neo-tree.lua
|
local status_ok, p = pcall(require, "neo-tree")
if not status_ok then
return
end
p.setup({
use_default_mappings = false,
popup_border_style = "rounded",
default_component_configs = {
git_status = {
symbols = {
-- Change type
added = "", -- or "✚", but this is redundant info if you use git_status_colors on the name
modified = "", -- or "", but this is redundant info if you use git_status_colors on the name
deleted = "✖", -- this can only be used in the git_status source
renamed = "➜", -- this can only be used in the git_status source
-- Status type
untracked = "",
ignored = "◌",
unstaged = "",
staged = "",
conflict = "",
},
},
},
window = {
mappings = {
["u"] = "navigate_up",
["l"] = "open",
["<CR>"] = "open",
["<BS>"] = "close_node",
["h"] = "close_node",
["H"] = "toggle_hidden",
["s"] = "open_split",
["-"] = "open_split",
["v"] = "open_vsplit",
["|"] = "open_vsplit",
["t"] = "open_tabnew",
["f"] = "filter_on_submit",
["<C-]>"] = "set_root",
["<C-c><C-c>"] = "clear_filter",
["i"] = {
"add",
config = {
show_path = "relative",
},
},
["o"] = "add_directory",
["d"] = "delete",
["r"] = "rename",
["c"] = "copy",
["m"] = "move", -- takes text input for destination, also accepts the optional config.show_path option like "add".
["q"] = "close_window",
["R"] = "refresh",
["?"] = "show_help",
["[g"] = "prev_git_modified",
["]g"] = "next_git_modified",
["C"] = "close_all_nodes",
["y"] = function(state)
local node = state.tree:get_node()
local name = node.name
vim.fn.setreg("+", name)
vim.fn.setreg('"', name)
print("Copied: " .. name)
end,
["Y"] = function(state)
local node = state.tree:get_node()
local path = vim.fn.fnamemodify(node.path, ":.")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["gy"] = function(state)
local node = state.tree:get_node()
local path = node.path
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
},
},
filesystem = {
filtered_items = {
hide_dotfiles = false,
hide_hidden = false,
hide_gitignored = false,
},
hijack_netrw_behavior = "open_current",
follow_current_file = true,
use_libuv_file_watcher = true,
},
})
local opts = { noremap = true, silent = true }
local keymap = vim.api.nvim_set_keymap
keymap("n", "-", "<Cmd>Neotree float reveal_force_cwd<CR>", opts)
keymap("n", "<Leader>e", "<Cmd>NeoTreeFocusToggle<CR>", opts)
|
local status_ok, p = pcall(require, "neo-tree")
if not status_ok then
return
end
p.setup({
use_default_mappings = false,
popup_border_style = "rounded",
default_component_configs = {
git_status = {
symbols = {
-- Change type
added = "", -- or "✚", but this is redundant info if you use git_status_colors on the name
modified = "", -- or "", but this is redundant info if you use git_status_colors on the name
deleted = "✖", -- this can only be used in the git_status source
renamed = "➜", -- this can only be used in the git_status source
-- Status type
untracked = "",
ignored = "◌",
unstaged = "",
staged = "",
conflict = "",
},
},
},
window = {
mappings = {
["u"] = "navigate_up",
["l"] = "open",
["<CR>"] = "open",
["<BS>"] = "close_node",
["h"] = "close_node",
["H"] = "toggle_hidden",
["s"] = "open_split",
["-"] = "open_split",
["v"] = "open_vsplit",
["|"] = "open_vsplit",
["t"] = "open_tabnew",
["f"] = "filter_on_submit",
["<C-]>"] = "set_root",
["<C-c><C-c>"] = "clear_filter",
["i"] = {
"add",
config = {
show_path = "relative",
},
},
["o"] = "add_directory",
["d"] = "delete",
["r"] = "rename",
["c"] = "copy",
["m"] = "move", -- takes text input for destination, also accepts the optional config.show_path option like "add".
["q"] = "close_window",
["R"] = "refresh",
["?"] = "show_help",
["[g"] = "prev_git_modified",
["]g"] = "next_git_modified",
["C"] = "close_all_nodes",
["y"] = function(state)
local node = state.tree:get_node()
local name = node.name
vim.fn.setreg("+", name)
vim.fn.setreg('"', name)
print("Copied: " .. name)
end,
["Y"] = function(state)
local node = state.tree:get_node()
local path = vim.fn.fnamemodify(node.path, ":.")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["gy"] = function(state)
local node = state.tree:get_node()
local path = node.path
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
},
},
filesystem = {
filtered_items = {
hide_dotfiles = false,
hide_hidden = false,
hide_gitignored = false,
hide_by_pattern = {
".watchman-cookie-*",
},
},
hijack_netrw_behavior = "open_current",
follow_current_file = true,
use_libuv_file_watcher = true,
},
})
local opts = { noremap = true, silent = true }
local keymap = vim.api.nvim_set_keymap
keymap("n", "-", "<Cmd>Neotree float reveal_force_cwd<CR>", opts)
keymap("n", "<Leader>e", "<Cmd>NeoTreeFocusToggle<CR>", opts)
|
[nvim] Fix neo-tree config
|
[nvim] Fix neo-tree config
|
Lua
|
mit
|
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
|
daeefff741d0ddfec2d2833e361017e5233f8729
|
frontend/document/djvudocument.lua
|
frontend/document/djvudocument.lua
|
local Geom = require("ui/geometry")
local Cache = require("cache")
local CacheItem = require("cacheitem")
local KoptOptions = require("ui/data/koptoptions")
local Document = require("document/document")
local DrawContext = require("ffi/drawcontext")
local Configurable = require("configurable")
local DjvuDocument = Document:new{
_document = false,
-- libdjvulibre manages its own additional cache, default value is hard written in c module.
is_djvu = true,
djvulibre_cache_size = nil,
dc_null = DrawContext.new(),
options = KoptOptions,
koptinterface = nil,
}
-- check DjVu magic string to validate
local function validDjvuFile(filename)
f = io.open(filename, "r")
if not f then return false end
local magic = f:read(8)
f:close()
if not magic or magic ~= "AT&TFORM" then return false end
return true
end
function DjvuDocument:init()
local djvu = require("libs/libkoreader-djvu")
self.koptinterface = require("document/koptinterface")
self.configurable:loadDefaults(self.options)
if not validDjvuFile(self.file) then
error("Not a valid DjVu file")
end
local ok
ok, self._document = pcall(djvu.openDocument, self.file, self.djvulibre_cache_size)
if not ok then
error(self._document) -- will contain error message
end
self.is_open = true
self.info.has_pages = true
self.info.configurable = true
self:_readMetadata()
end
function DjvuDocument:getPageTextBoxes(pageno)
return self._document:getPageText(pageno)
end
function DjvuDocument:getWordFromPosition(spos)
return self.koptinterface:getWordFromPosition(self, spos)
end
function DjvuDocument:getTextFromPositions(spos0, spos1)
return self.koptinterface:getTextFromPositions(self, spos0, spos1)
end
function DjvuDocument:getPageBoxesFromPositions(pageno, ppos0, ppos1)
return self.koptinterface:getPageBoxesFromPositions(self, pageno, ppos0, ppos1)
end
function DjvuDocument:nativeToPageRectTransform(pageno, rect)
return self.koptinterface:nativeToPageRectTransform(self, pageno, rect)
end
function DjvuDocument:getOCRWord(pageno, wbox)
return self.koptinterface:getOCRWord(self, pageno, wbox)
end
function DjvuDocument:getOCRText(pageno, tboxes)
return self.koptinterface:getOCRText(self, pageno, tboxes)
end
function DjvuDocument:getPageRegions(pageno)
return self.koptinterface:getPageRegions(self, pageno)
end
function DjvuDocument:getUsedBBox(pageno)
-- djvu does not support usedbbox, so fake it.
local used = {}
local native_dim = self:getNativePageDimensions(pageno)
used.x0, used.y0, used.x1, used.y1 = 0, 0, native_dim.w, native_dim.h
return used
end
function DjvuDocument:clipPagePNGFile(pos0, pos1, pboxes, drawer, filename)
return self.koptinterface:clipPagePNGFile(self, pos0, pos1, pboxes, drawer, filename)
end
function DjvuDocument:clipPagePNGString(pos0, pos1, pboxes, drawer)
return self.koptinterface:clipPagePNGString(self, pos0, pos1, pboxes, drawer)
end
function DjvuDocument:getPageBBox(pageno)
return self.koptinterface:getPageBBox(self, pageno)
end
function DjvuDocument:getPageDimensions(pageno, zoom, rotation)
return self.koptinterface:getPageDimensions(self, pageno, zoom, rotation)
end
function DjvuDocument:getCoverPageImage()
return self.koptinterface:getCoverPageImage(self)
end
function DjvuDocument:findText(pattern, origin, reverse, caseInsensitive, page)
return self.koptinterface:findText(self, pattern, origin, reverse, caseInsensitive, page)
end
function DjvuDocument:renderPage(pageno, rect, zoom, rotation, gamma, render_mode)
return self.koptinterface:renderPage(self, pageno, rect, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:hintPage(pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:hintPage(self, pageno, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:drawPage(target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:drawPage(self, target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:register(registry)
registry:addProvider("djvu", "application/djvu", self)
end
return DjvuDocument
|
local Geom = require("ui/geometry")
local Cache = require("cache")
local CacheItem = require("cacheitem")
local KoptOptions = require("ui/data/koptoptions")
local Document = require("document/document")
local DrawContext = require("ffi/drawcontext")
local Configurable = require("configurable")
local DjvuDocument = Document:new{
_document = false,
-- libdjvulibre manages its own additional cache, default value is hard written in c module.
is_djvu = true,
djvulibre_cache_size = nil,
dc_null = DrawContext.new(),
options = KoptOptions,
koptinterface = nil,
}
-- check DjVu magic string to validate
local function validDjvuFile(filename)
f = io.open(filename, "r")
if not f then return false end
local magic = f:read(8)
f:close()
if not magic or magic ~= "AT&TFORM" then return false end
return true
end
function DjvuDocument:init()
local djvu = require("libs/libkoreader-djvu")
self.koptinterface = require("document/koptinterface")
self.configurable:loadDefaults(self.options)
if not validDjvuFile(self.file) then
error("Not a valid DjVu file")
end
local ok
ok, self._document = pcall(djvu.openDocument, self.file, self.djvulibre_cache_size)
if not ok then
error(self._document) -- will contain error message
end
self.is_open = true
self.info.has_pages = true
self.info.configurable = true
self:_readMetadata()
end
function DjvuDocument:getPageTextBoxes(pageno)
return self._document:getPageText(pageno)
end
function DjvuDocument:getWordFromPosition(spos)
return self.koptinterface:getWordFromPosition(self, spos)
end
function DjvuDocument:getTextFromPositions(spos0, spos1)
return self.koptinterface:getTextFromPositions(self, spos0, spos1)
end
function DjvuDocument:getPageBoxesFromPositions(pageno, ppos0, ppos1)
return self.koptinterface:getPageBoxesFromPositions(self, pageno, ppos0, ppos1)
end
function DjvuDocument:nativeToPageRectTransform(pageno, rect)
return self.koptinterface:nativeToPageRectTransform(self, pageno, rect)
end
function DjvuDocument:getOCRWord(pageno, wbox)
return self.koptinterface:getOCRWord(self, pageno, wbox)
end
function DjvuDocument:getOCRText(pageno, tboxes)
return self.koptinterface:getOCRText(self, pageno, tboxes)
end
function DjvuDocument:getPageRegions(pageno)
return self.koptinterface:getPageRegions(self, pageno)
end
function DjvuDocument:getUsedBBox(pageno)
-- djvu does not support usedbbox, so fake it.
local used = {}
local native_dim = self:getNativePageDimensions(pageno)
used.x0, used.y0, used.x1, used.y1 = 0, 0, native_dim.w, native_dim.h
return used
end
function DjvuDocument:clipPagePNGFile(pos0, pos1, pboxes, drawer, filename)
return self.koptinterface:clipPagePNGFile(self, pos0, pos1, pboxes, drawer, filename)
end
function DjvuDocument:clipPagePNGString(pos0, pos1, pboxes, drawer)
return self.koptinterface:clipPagePNGString(self, pos0, pos1, pboxes, drawer)
end
function DjvuDocument:getPageBBox(pageno)
return self.koptinterface:getPageBBox(self, pageno)
end
function DjvuDocument:getPageDimensions(pageno, zoom, rotation)
return self.koptinterface:getPageDimensions(self, pageno, zoom, rotation)
end
function DjvuDocument:getCoverPageImage()
return self.koptinterface:getCoverPageImage(self)
end
function DjvuDocument:findText(pattern, origin, reverse, caseInsensitive, page)
return self.koptinterface:findText(self, pattern, origin, reverse, caseInsensitive, page)
end
function DjvuDocument:renderPage(pageno, rect, zoom, rotation, gamma, render_mode)
return self.koptinterface:renderPage(self, pageno, rect, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:hintPage(pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:hintPage(self, pageno, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:drawPage(target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
return self.koptinterface:drawPage(self, target, x, y, rect, pageno, zoom, rotation, gamma, render_mode)
end
function DjvuDocument:register(registry)
registry:addProvider("djvu", "application/djvu", self)
registry:addProvider("djv", "application/djvu", self)
end
return DjvuDocument
|
fix #1433
|
fix #1433
|
Lua
|
agpl-3.0
|
Frenzie/koreader,ashang/koreader,mwoz123/koreader,poire-z/koreader,lgeek/koreader,poire-z/koreader,NickSavage/koreader,Markismus/koreader,apletnev/koreader,houqp/koreader,chrox/koreader,mihailim/koreader,pazos/koreader,NiLuJe/koreader,Frenzie/koreader,robert00s/koreader,noname007/koreader,frankyifei/koreader,chihyang/koreader,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,ashhher3/koreader,koreader/koreader
|
a29ccd4e767b65c0ecc77e2bb35fc108f735a3bb
|
core/servermanager.lua
|
core/servermanager.lua
|
local st = require "util.stanza";
local send = require "core.sessionmanager".send_to_session;
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
require "modulemanager"
-- Handle stanzas that were addressed to the server (whether they came from c2s, s2s, etc.)
function handle_stanza(origin, stanza)
-- Use plugins
if not modulemanager.handle_stanza(origin, stanza) then
if stanza.name == "iq" then
if stanza.attr.type ~= "result" and stanza.attr.type ~= "error" then
send(origin, st.error_reply(stanza, "cancel", "service-unavailable"));
end
elseif stanza.name == "message" then
send(origin, st.error_reply(stanza, "cancel", "service-unavailable"));
elseif stanza.name ~= "presence" then
error("Unknown stanza");
end
end
end
|
local st = require "util.stanza";
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
require "modulemanager"
-- Handle stanzas that were addressed to the server (whether they came from c2s, s2s, etc.)
function handle_stanza(origin, stanza)
-- Use plugins
if not modulemanager.handle_stanza(origin, stanza) then
if stanza.name == "iq" then
if stanza.attr.type ~= "result" and stanza.attr.type ~= "error" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
elseif stanza.name == "message" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
elseif stanza.name ~= "presence" then
error("Unknown stanza");
end
end
end
|
Fixed servermanager to use session.send for sending stanzas
|
Fixed servermanager to use session.send for sending stanzas
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
383b72f48ab1840ef39d746e94a39d825bcaa1bd
|
plugins/doge.lua
|
plugins/doge.lua
|
local doge = {}
local mattata = require('mattata')
local URL = require('socket.url')
function doge:init(configuration)
doge.arguments = 'doge <text>'
doge.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('doge').table
doge.help = configuration.commandPrefix .. 'doge <text> - Doge-ifies the given text. It doesn\'t like emoji!'
end
function doge:onMessageReceive(message, configuration)
local input = mattata.input(message.text)
if not input then
mattata.sendMessage(message.chat.id, doge.help, nil, true, false, message.message_id, nil)
return
end
mattata.sendPhoto(message.chat.id, 'http://dogr.io/' .. input:gsub(' ', ''):gsub('\n', '/') .. '.png')
end
return doge
|
local doge = {}
local mattata = require('mattata')
local URL = require('socket.url')
function doge:init(configuration)
doge.arguments = 'doge <text>'
doge.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('doge').table
doge.help = configuration.commandPrefix .. 'doge <text> - Doge-ifies the given text. Sentences are separated using slashes. Example: ' .. configuration.commandPrefix .. 'doge hello world/this is a test sentence'
end
function doge:onMessageReceive(message, configuration)
local input = mattata.input(message.text)
if not input then
mattata.sendMessage(message.chat.id, doge.help, nil, true, false, message.message_id, nil)
return
end
local url = 'http://dogr.io/' .. input:gsub(' ', '%%20') .. '.png?split=false&.png'
local matches = 'https?://[%%%w-_%.%?%.:/%+=&]+' -- Credit to @yagop for this snippet.
if string.match(url, matches) == url then
mattata.sendPhoto(message.chat.id, url)
return
else
mattata.sendMessage(message.chat.id, 'I could not generate an image with those parameters.', nil, true, false, message.message_id)
return
end
end
return doge
|
Fixed a bug with doge.lua
|
Fixed a bug with doge.lua
The plugin now matches against characters which can't be used as a
parameter in the doge API url, and the help has been improved, with an
example of usage.
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.