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
|
---|---|---|---|---|---|---|---|---|---|
81db4a4fd562780caeb9194db11f85fe932a2bfd
|
src/lua/lzmq/llthreads/ex.lua
|
src/lua/lzmq/llthreads/ex.lua
|
-- Copyright (c) 2011 by Robert G. Jakabosky <[email protected]>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- wraps the low-level threads object.
--
local llthreads = require"llthreads"
local setmetatable = setmetatable
local tonumber = tonumber
local assert = assert
local lua_version_t
local function lua_version()
if not lua_version_t then
local version = rawget(_G,"_VERSION")
local maj,min = version:match("^Lua (%d+)%.(%d+)$")
if maj then lua_version_t = {tonumber(maj),tonumber(min)}
elseif not math.mod then lua_version_t = {5,2}
elseif table.pack and not pack then lua_version_t = {5,2}
else lua_version_t = {5,2} end
end
return lua_version_t[1], lua_version_t[2]
end
local LUA_MAJOR, LUA_MINOR = lua_version()
local IS_LUA_51 = (LUA_MAJOR == 5) and (LUA_MINOR == 1)
local IS_LUA_52 = (LUA_MAJOR == 5) and (LUA_MINOR == 2)
local LUA_INIT = "LUA_INIT"
if not IS_LUA_51 then
LUA_INIT = LUA_INIT .. LUA_MAJOR .. "_" .. LUA_MINOR
end
LUA_INIT = os.getenv( LUA_INIT ) or ""
local thread_mt = {}
thread_mt.__index = thread_mt
function thread_mt:start(detached)
return self.thread:start(detached)
end
function thread_mt:join(...)
return self.thread:join(...)
end
function thread_mt:kill()
return self.thread:kill()
end
local bootstrap_pre = [[
local action, action_arg = ...
local lua_init = ]] .. ("%q"):format(LUA_INIT) .. [[
if lua_init and #lua_init > 0 then
if lua_init:sub(1,1) == '@' then
dofile(lua_init:sub(2))
else
assert((loadstring or load)(lua_init))()
end
end
-- create global 'arg'
local argc = select("#", ...)
arg = { n = argc - 2, select(3, ...) }
]]
local bootstrap_post = [[
local loadstring = loadstring or load
local unpack = table.unpack or unpack
local func
-- load Lua code.
if action == 'runfile' then
func = assert(loadfile(action_arg))
-- script name
arg[0] = action_arg
elseif action == 'runstring' then
func = assert(loadstring(action_arg))
-- fake script name
arg[0] = '=(loadstring)'
end
argc = arg.n or #arg
-- run loaded code.
return func(unpack(arg, 1, argc))
]]
local bootstrap_code = bootstrap_pre..bootstrap_post
local function new_thread(bootstrap_code, action, action_arg, ...)
local thread = llthreads.new(bootstrap_code, action, action_arg, ...)
return setmetatable({
thread = thread,
}, thread_mt)
end
local M = {}
M.set_bootstrap_prelude = function (code)
bootstrap_code = bootstrap_pre .. code .. bootstrap_post
end;
M.runfile = function (file, ...)
return new_thread(bootstrap_code, 'runfile', file, ...)
end;
M.runstring = function (code, ...)
return new_thread(bootstrap_code, 'runstring', code, ...)
end;
M.runfile_ex = function (prelude, file, ...)
local bootstrap_code = bootstrap_pre .. prelude .. bootstrap_post
return new_thread(bootstrap_code, 'runfile', file, ...)
end;
M.runstring_ex = function (prelude, code, ...)
local bootstrap_code = bootstrap_pre .. prelude .. bootstrap_post
return new_thread(bootstrap_code, 'runstring', code, ...)
end;
return M
|
-- Copyright (c) 2011 by Robert G. Jakabosky <[email protected]>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- wraps the low-level threads object.
--
local llthreads = require"llthreads"
local setmetatable = setmetatable
local tonumber = tonumber
local assert = assert
local lua_version_t
local function lua_version()
if not lua_version_t then
local version = rawget(_G,"_VERSION")
local maj,min = version:match("^Lua (%d+)%.(%d+)$")
if maj then lua_version_t = {tonumber(maj),tonumber(min)}
elseif not math.mod then lua_version_t = {5,2}
elseif table.pack and not pack then lua_version_t = {5,2}
else lua_version_t = {5,2} end
end
return lua_version_t[1], lua_version_t[2]
end
local LUA_MAJOR, LUA_MINOR = lua_version()
local IS_LUA_51 = (LUA_MAJOR == 5) and (LUA_MINOR == 1)
local IS_LUA_52 = (LUA_MAJOR == 5) and (LUA_MINOR == 2)
local LUA_INIT = "LUA_INIT"
local LUA_INIT_VER
if not IS_LUA_51 then
LUA_INIT_VER = LUA_INIT .. "_" .. LUA_MAJOR .. "_" .. LUA_MINOR
end
LUA_INIT = LUA_INIT_VER and os.getenv( LUA_INIT_VER ) or os.getenv( LUA_INIT ) or ""
local thread_mt = {}
thread_mt.__index = thread_mt
function thread_mt:start(detached)
return self.thread:start(detached)
end
function thread_mt:join(...)
return self.thread:join(...)
end
function thread_mt:kill()
return self.thread:kill()
end
local bootstrap_pre = [[
local action, action_arg = ...
local lua_init = ]] .. ("%q"):format(LUA_INIT) .. [[
if lua_init and #lua_init > 0 then
if lua_init:sub(1,1) == '@' then
dofile(lua_init:sub(2))
else
assert((loadstring or load)(lua_init))()
end
end
-- create global 'arg'
local argc = select("#", ...)
arg = { n = argc - 2, select(3, ...) }
]]
local bootstrap_post = [[
local loadstring = loadstring or load
local unpack = table.unpack or unpack
local func
-- load Lua code.
if action == 'runfile' then
func = assert(loadfile(action_arg))
-- script name
arg[0] = action_arg
elseif action == 'runstring' then
func = assert(loadstring(action_arg))
-- fake script name
arg[0] = '=(loadstring)'
end
argc = arg.n or #arg
-- run loaded code.
return func(unpack(arg, 1, argc))
]]
local bootstrap_code = bootstrap_pre..bootstrap_post
local function new_thread(bootstrap_code, action, action_arg, ...)
local thread = llthreads.new(bootstrap_code, action, action_arg, ...)
return setmetatable({
thread = thread,
}, thread_mt)
end
local M = {}
M.set_bootstrap_prelude = function (code)
bootstrap_code = bootstrap_pre .. code .. bootstrap_post
end;
M.runfile = function (file, ...)
return new_thread(bootstrap_code, 'runfile', file, ...)
end;
M.runstring = function (code, ...)
return new_thread(bootstrap_code, 'runstring', code, ...)
end;
M.runfile_ex = function (prelude, file, ...)
local bootstrap_code = bootstrap_pre .. prelude .. bootstrap_post
return new_thread(bootstrap_code, 'runfile', file, ...)
end;
M.runstring_ex = function (prelude, code, ...)
local bootstrap_code = bootstrap_pre .. prelude .. bootstrap_post
return new_thread(bootstrap_code, 'runstring', code, ...)
end;
return M
|
Fix. Use correct $LUA_INIT variable when create new thread.
|
Fix. Use correct $LUA_INIT variable when create new thread.
|
Lua
|
mit
|
LuaDist/lzmq,LuaDist/lzmq-ffi,moteus/lzmq,zeromq/lzmq,moteus/lzmq,bsn069/lzmq,zeromq/lzmq,moteus/lzmq,zeromq/lzmq,LuaDist/lzmq-ffi,LuaDist/lzmq,bsn069/lzmq
|
6cf9dab6e5092e7c12a69623c7481ec198f3783e
|
item/id_164_emptybottle.lua
|
item/id_164_emptybottle.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/>.
]]
-- Merung 2011: fill stock or potion into bottle
-- UPDATE items SET itm_script='item.id_164_emptybottle' WHERE itm_id IN (164);
local common = require("base.common")
local alchemy = require("alchemy.base.alchemy")
local licence = require("base.licence")
local granorsHut = require("content.granorsHut")
local M = {}
function M.UseItem(User, SourceItem, ltstate)
-- alchemy
-- infront of a cauldron?
local cauldron = alchemy.GetCauldronInfront(User)
if cauldron then
if cauldron:getData("granorsHut") ~= "" then
granorsHut.fillingFromCauldron(User, ltstate)
return
end
if licence.licence(User) then --checks if user is citizen or has a licence
return -- avoids crafting if user is neither citizen nor has a licence
end
if not CheckWaterEmpty(User, SourceItem, cauldron) then
return
end
if not alchemy.checkFood(User) then
return
end
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
if (ltstate == Action.none) then
User:startAction(20,21,5,15,25);
return
end
M.FillIntoBottle(User, SourceItem, cauldron)
alchemy.lowerFood(User)
end
-- The Glutinous Tree
local frontItem = common.GetFrontItem(User)
if frontItem and frontItem.id == 589 and frontItem.pos == position(376,288,0) then
GetSlimeFromTree(User, SourceItem, ltstate)
end
end
function CheckWaterEmpty(User, SourceItem, cauldron)
if (cauldron:getData("filledWith") == "water") then -- water belongs into a bucket, not a potion bottle!
common.InformNLS( User,
"Es ist zu viel Wasser im Kessel, als dass es in die Flaschen passen wrde. Ein Eimer wre hilfreicher.",
"There is too much water in the cauldron to bottle it. Better use a bucket.")
return nil ;
-- no stock, no potion, not essence brew -> nothing we could fil into the bottle
elseif cauldron:getData("filledWith") == "" then
common.InformNLS( User,
"Es befindet sich nichts zum Abfllen im Kessel.",
"There is nothing to be bottled in the cauldron.")
return nil;
end
return true
end
function M.FillIntoBottle(User, SourceItem, cauldron)
-- stock, essence brew or potion; fill it up
if (cauldron:getData("filledWith") == "stock") or (cauldron:getData("filledWith") == "essenceBrew") or (cauldron:getData("filledWith") == "potion") then
local reGem, reGemdust, reCauldron, reBottle = alchemy.GemDustBottleCauldron(nil, nil, cauldron.id, nil, User)
if SourceItem.number > 1 then -- stack!
if cauldron:getData("filledWith") == "stock" then
local data = {}
data.AdrazinConcentration=cauldron:getData("AdrazinConcentration")
data.IllidriumConcentration=cauldron:getData("IllidriumConcentration")
data.CaprazinConcentration=cauldron:getData("CaprazinConcentration")
data.HyperboreliumConcentration=cauldron:getData("HyperboreliumConcentration")
data.EcholonConcentration=cauldron:getData("EcholonConcentration")
data.DracolinConcentration=cauldron:getData("DracolinConcentration")
data.OrcanolConcentration=cauldron:getData("OrcanolConcentration")
data.FenolinConcentration=cauldron:getData("FenolinConcentration")
data.filledWith="stock"
common.CreateItem(User, reBottle, 1, 0, data)
elseif cauldron:getData("filledWith") == "essenceBrew" then
local data = {}
data.essenceHerb1=cauldron:getData("essenceHerb1")
data.essenceHerb2=cauldron:getData("essenceHerb2")
data.essenceHerb3=cauldron:getData("essenceHerb3")
data.essenceHerb4=cauldron:getData("essenceHerb4")
data.essenceHerb5=cauldron:getData("essenceHerb5")
data.essenceHerb6=cauldron:getData("essenceHerb6")
data.essenceHerb7=cauldron:getData("essenceHerb7")
data.essenceHerb8=cauldron:getData("essenceHerb8")
data.filledWith="essenceBrew"
common.CreateItem(User, reBottle, 1, 0, data)
elseif cauldron:getData("filledWith") == "potion" then
local data = {}
data.potionEffectId=cauldron:getData("potionEffectId")
data.filledWith="potion"
common.CreateItem(User, reBottle, 1, tonumber(cauldron:getData("potionQuality")), data)
end
world:erase(SourceItem,1)
else
SourceItem.id = reBottle
alchemy.FillFromTo(cauldron,SourceItem)
world:changeItem(SourceItem)
end
alchemy.RemoveAll(cauldron)
end
world:changeItem(cauldron)
world:makeSound(10,cauldron.pos)
end
function GetSlimeFromTree(User, SourceItem, ltstate)
if ( ltstate == Action.abort ) then
return
end
if (ltstate == Action.none) then
User:startAction(50,21,5,0,0);
return
end
if SourceItem.number > 1 then
local data = {}
data.filledWith="meraldilised slime"
common.CreateItem(User, 327, 1, 0, data)
else
SourceItem.id = 327
SourceItem:setData("filledWith","meraldilised slime")
world:changeItem(SourceItem)
end
end
return M
|
--[[
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/>.
]]
-- Merung 2011: fill stock or potion into bottle
-- UPDATE items SET itm_script='item.id_164_emptybottle' WHERE itm_id IN (164);
local common = require("base.common")
local alchemy = require("alchemy.base.alchemy")
local licence = require("base.licence")
local granorsHut = require("content.granorsHut")
local M = {}
function M.UseItem(User, SourceItem, ltstate)
-- alchemy
-- infront of a cauldron?
local cauldron = alchemy.GetCauldronInfront(User)
if cauldron then
if cauldron:getData("granorsHut") ~= "" then
granorsHut.fillingFromCauldron(User, ltstate)
return
end
if licence.licence(User) then --checks if user is citizen or has a licence
return -- avoids crafting if user is neither citizen nor has a licence
end
if not CheckWaterEmpty(User, SourceItem, cauldron) then
return
end
if not alchemy.checkFood(User) then
return
end
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
if (ltstate == Action.none) then
User:startAction(20,21,5,15,25);
return
end
M.FillIntoBottle(User, SourceItem, cauldron)
alchemy.lowerFood(User)
end
-- The Glutinous Tree
local frontItem = common.GetFrontItem(User)
if frontItem and frontItem.id == 589 and frontItem.pos == position(376,288,0) then
GetSlimeFromTree(User, SourceItem, ltstate)
end
end
function CheckWaterEmpty(User, SourceItem, cauldron)
if (cauldron:getData("filledWith") == "water") then -- water belongs into a bucket, not a potion bottle!
common.InformNLS( User,
"Es ist zu viel Wasser im Kessel, als dass es in die Flaschen passen wrde. Ein Eimer wre hilfreicher.",
"There is too much water in the cauldron to bottle it. Better use a bucket.")
return nil ;
-- no stock, no potion, not essence brew -> nothing we could fil into the bottle
elseif cauldron:getData("filledWith") == "" then
common.InformNLS( User,
"Es befindet sich nichts zum Abfllen im Kessel.",
"There is nothing to be bottled in the cauldron.")
return nil;
end
return true
end
function M.FillIntoBottle(User, SourceItem, cauldron)
-- stock, essence brew or potion; fill it up
if (cauldron:getData("filledWith") == "stock") or (cauldron:getData("filledWith") == "essenceBrew") or (cauldron:getData("filledWith") == "potion") then
local reGem, reGemdust, reCauldron, reBottle = alchemy.GemDustBottleCauldron(nil, nil, cauldron.id, nil, User)
if SourceItem.number > 1 then -- stack!
if cauldron:getData("filledWith") == "stock" then
local data = {}
data.AdrazinConcentration=cauldron:getData("AdrazinConcentration")
data.IllidriumConcentration=cauldron:getData("IllidriumConcentration")
data.CaprazinConcentration=cauldron:getData("CaprazinConcentration")
data.HyperboreliumConcentration=cauldron:getData("HyperboreliumConcentration")
data.EcholonConcentration=cauldron:getData("EcholonConcentration")
data.DracolinConcentration=cauldron:getData("DracolinConcentration")
data.OrcanolConcentration=cauldron:getData("OrcanolConcentration")
data.FenolinConcentration=cauldron:getData("FenolinConcentration")
data.filledWith="stock"
common.CreateItem(User, reBottle, 1, 333, data)
elseif cauldron:getData("filledWith") == "essenceBrew" then
local data = {}
data.essenceHerb1=cauldron:getData("essenceHerb1")
data.essenceHerb2=cauldron:getData("essenceHerb2")
data.essenceHerb3=cauldron:getData("essenceHerb3")
data.essenceHerb4=cauldron:getData("essenceHerb4")
data.essenceHerb5=cauldron:getData("essenceHerb5")
data.essenceHerb6=cauldron:getData("essenceHerb6")
data.essenceHerb7=cauldron:getData("essenceHerb7")
data.essenceHerb8=cauldron:getData("essenceHerb8")
data.filledWith="essenceBrew"
common.CreateItem(User, reBottle, 1, 333, data)
elseif cauldron:getData("filledWith") == "potion" then
local data = {}
data.potionEffectId=cauldron:getData("potionEffectId")
data.filledWith="potion"
common.CreateItem(User, reBottle, 1, tonumber(cauldron:getData("potionQuality")), data)
end
world:erase(SourceItem,1)
else
SourceItem.id = reBottle
alchemy.FillFromTo(cauldron,SourceItem)
world:changeItem(SourceItem)
end
alchemy.RemoveAll(cauldron)
end
world:changeItem(cauldron)
world:makeSound(10,cauldron.pos)
end
function GetSlimeFromTree(User, SourceItem, ltstate)
if ( ltstate == Action.abort ) then
return
end
if (ltstate == Action.none) then
User:startAction(50,21,5,0,0);
return
end
if SourceItem.number > 1 then
local data = {}
data.filledWith="meraldilised slime"
common.CreateItem(User, 327, 1, 333, data)
User:eraseItem(SourceItem.id, 1)
else
SourceItem.id = 327
SourceItem:setData("filledWith","meraldilised slime")
world:changeItem(SourceItem)
end
end
return M
|
set quality of items to 333 explicitly, rather than rely on server to interpret 0 as 333
|
set quality of items to 333 explicitly, rather than rely on server to interpret 0 as 333
While here fix erase of an empty bottle
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
|
242be864d3e0a1c287ac0c3ecac4566cf79d5ad3
|
src_trunk/resources/item-system/s_move_items.lua
|
src_trunk/resources/item-system/s_move_items.lua
|
local function openInventory( element, ax, ay )
triggerEvent( "subscribeToInventoryChanges", source, element )
triggerClientEvent( source, "openElementInventory", element, ax, ay )
end
addEvent( "openFreakinInventory", true )
addEventHandler( "openFreakinInventory", getRootElement(), openInventory )
--
local function closeInventory( element )
triggerEvent( "unsubscribeFromInventoryChanges", source, element )
end
addEvent( "closeFreakinInventory", true )
addEventHandler( "closeFreakinInventory", getRootElement(), closeInventory )
--
local function moveToElement( element, slot, ammo )
if not hasSpaceForItem( element ) then
outputChatBox( "The Inventory is full.", source, 255, 0, 0 )
else
if not ammo then
local item = getItems( source )[ slot ]
if item then
moveItem( source, element, slot )
end
else
exports.global:takeWeapon( source, slot )
giveItem( element, -slot, ammo )
end
end
end
addEvent( "moveToElement", true )
addEventHandler( "moveToElement", getRootElement(), moveToElement )
local function moveFromElement( element, slot, ammo )
local item = getItems( element )[slot]
if item then
if item[1] > 0 then
moveItem( element, source, slot )
else
takeItemFromSlot( element, slot )
if ammo < item[2] then
exports.global:giveWeapon( source, -item[1], ammo )
giveItem( element, item[1], item[2] - ammo )
else
exports.global:giveWeapon( source, -item[1], item[2] )
end
triggerClientEvent( source, "forceElementMoveUpdate", source )
end
end
end
addEvent( "moveFromElement", true )
addEventHandler( "moveFromElement", getRootElement(), moveFromElement )
|
local function openInventory( element, ax, ay )
triggerEvent( "subscribeToInventoryChanges", source, element )
triggerClientEvent( source, "openElementInventory", element, ax, ay )
end
addEvent( "openFreakinInventory", true )
addEventHandler( "openFreakinInventory", getRootElement(), openInventory )
--
local function closeInventory( element )
triggerEvent( "unsubscribeFromInventoryChanges", source, element )
end
addEvent( "closeFreakinInventory", true )
addEventHandler( "closeFreakinInventory", getRootElement(), closeInventory )
--
local function moveToElement( element, slot, ammo )
if not hasSpaceForItem( element ) then
outputChatBox( "The Inventory is full.", source, 255, 0, 0 )
else
if not ammo then
local item = getItems( source )[ slot ]
if item then
moveItem( source, element, slot )
end
else
local name = "Safe"
if getElementType( element ) == "vehicle" then
name = "Vehicle"
end
if slot == 16 or slot == 18 or ( slot >= 35 and slot <= 40 ) then
outputChatBox("You can't put those weapons into a " .. name .. ".", source, 255, 0, 0)
elseif tonumber(getElementData(source, "duty")) > 0 then
outputChatBox("You can't put your weapons in a " .. name .. " while being on duty.", source, 255, 0, 0)
elseif tonumber(getElementData(source, "job")) == 4 and slot == 41 then
outputChatBox("You can't put this spray can into a " .. name .. ".", source, 255, 0, 0)
else
exports.global:takeWeapon( source, slot )
giveItem( element, -slot, ammo )
end
end
end
end
addEvent( "moveToElement", true )
addEventHandler( "moveToElement", getRootElement(), moveToElement )
local function moveFromElement( element, slot, ammo )
local item = getItems( element )[slot]
if item then
if item[1] > 0 then
moveItem( element, source, slot )
else
takeItemFromSlot( element, slot )
if ammo < item[2] then
exports.global:giveWeapon( source, -item[1], ammo )
giveItem( element, item[1], item[2] - ammo )
else
exports.global:giveWeapon( source, -item[1], item[2] )
end
triggerClientEvent( source, "forceElementMoveUpdate", source )
end
end
end
addEvent( "moveFromElement", true )
addEventHandler( "moveFromElement", getRootElement(), moveFromElement )
|
moving weapons fix
|
moving weapons fix
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1681 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
23eec4877efc7ed4d20b5673d47acfc29d8d73ef
|
kong/api/routes/plugins.lua
|
kong/api/routes/plugins.lua
|
local kong = kong
local null = ngx.null
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.reports"
local endpoints = require "kong.api.endpoints"
local arguments = require "kong.api.arguments"
local singletons = require "kong.singletons"
local type = type
local pairs = pairs
local get_plugin = endpoints.get_entity_endpoint(kong.db.plugins.schema)
local put_plugin = endpoints.put_entity_endpoint(kong.db.plugins.schema)
local delete_plugin = endpoints.delete_entity_endpoint(kong.db.plugins.schema)
local function before_plugin_for_entity(entity_name, plugin_field)
return function(self, db, helpers)
local entity = endpoints.select_entity(self, db, kong.db[entity_name].schema)
if not entity then
return kong.response.exit(404, { message = "Not found" })
end
local plugin = db.plugins:select({ id = self.params.id })
if not plugin
or type(plugin[plugin_field]) ~= "table"
or plugin[plugin_field].id ~= entity.id then
return kong.response.exit(404, { message = "Not found" })
end
self.plugin = plugin
self.params.plugins = self.params.id
end
end
local function fill_plugin_data(args, plugin)
local post = args.post
post.name = post.name or plugin.name
-- Only now we can decode the 'config' table for form-encoded values
post = arguments.decode(post, kong.db.plugins.schema)
-- While we're at it, get values for composite uniqueness check
post.route = post.route or plugin.route
post.service = post.service or plugin.service
post.consumer = post.consumer or plugin.consumer
args.post = post
end
local patch_plugin
do
local patch_plugin_endpoint = endpoints.patch_entity_endpoint(kong.db.plugins.schema)
patch_plugin = function(self, db, helpers)
local plugin = self.plugin
fill_plugin_data(self.args, plugin)
return patch_plugin_endpoint(self, db, helpers)
end
end
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local schema_to_jsonable
do
local function fdata_to_jsonable(fdata)
local out = {}
for k, v in pairs(fdata) do
if k == "schema" then
out[k] = schema_to_jsonable(v)
elseif type(v) == "table" then
out[k] = fdata_to_jsonable(v)
elseif type(v) ~= "function" then
out[k] = v
end
end
return out
end
local insert = table.insert
local ipairs = ipairs
local next = next
schema_to_jsonable = function(schema)
local fields = {}
for _, field in ipairs(schema.fields) do
local fname = next(field)
local fdata = field[fname]
insert(fields, { [fname] = fdata_to_jsonable(fdata) })
end
return { fields = fields }
end
end
local function post_process(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
if data.service ~= null and data.service.id then
r_data.e = "s"
elseif data.route ~= null and data.route.id then
r_data.e = "r"
elseif data.consumer ~= null and data.consumer.id then
r_data.e = "c"
end
reports.send("api", r_data)
return data
end
return {
["/plugins"] = {
POST = function(_, _, _, parent)
return parent(post_process)
end,
},
["/plugins/:plugins"] = {
PATCH = function(self, db, helpers, parent)
local post = self.args and self.args.post
-- Read-before-write only if necessary
if post and (post.name == nil or
post.route == nil or
post.service == nil or
post.consumer == nil) then
-- We need the name, otherwise we don't know what type of
-- plugin this is and we can't perform *any* validations.
local plugin = db.plugins:select({ id = self.params.plugins })
if not plugin then
return kong.response.exit(404, { message = "Not found" })
end
fill_plugin_data(self.args, plugin)
end
return parent()
end,
},
["/plugins/schema/:name"] = {
GET = function(self, db, helpers)
local subschema = db.plugins.schema.subschemas[self.params.name]
if not subschema then
return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" })
end
local copy = schema_to_jsonable(subschema.fields.config)
return kong.response.exit(200, copy)
end
},
["/plugins/enabled"] = {
GET = function(_, _, helpers)
local enabled_plugins = setmetatable({}, cjson.empty_array_mt)
for k in pairs(singletons.configuration.loaded_plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return kong.response.exit(200, {
enabled_plugins = enabled_plugins
})
end
},
-- Available for backward compatibility
["/consumers/:consumers/plugins/:id"] = {
before = before_plugin_for_entity("consumers", "consumer"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/routes/:routes/plugins/:id"] = {
before = before_plugin_for_entity("routes", "route"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/services/:services/plugins/:id"] = {
before = before_plugin_for_entity("services", "service"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
}
|
local kong = kong
local null = ngx.null
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.reports"
local endpoints = require "kong.api.endpoints"
local arguments = require "kong.api.arguments"
local singletons = require "kong.singletons"
local type = type
local pairs = pairs
local get_plugin = endpoints.get_entity_endpoint(kong.db.plugins.schema)
local put_plugin = endpoints.put_entity_endpoint(kong.db.plugins.schema)
local delete_plugin = endpoints.delete_entity_endpoint(kong.db.plugins.schema)
local function before_plugin_for_entity(entity_name, plugin_field)
return function(self, db, helpers)
local entity = endpoints.select_entity(self, db, kong.db[entity_name].schema)
if not entity then
return kong.response.exit(404, { message = "Not found" })
end
local plugin = db.plugins:select({ id = self.params.id })
if not plugin
or type(plugin[plugin_field]) ~= "table"
or plugin[plugin_field].id ~= entity.id then
return kong.response.exit(404, { message = "Not found" })
end
self.plugin = plugin
self.params.plugins = self.params.id
end
end
local function fill_plugin_data(args, plugin)
local post = args.post
post.name = post.name or plugin.name
-- Only now we can decode the 'config' table for form-encoded values
post = arguments.decode(post, kong.db.plugins.schema)
-- While we're at it, get values for composite uniqueness check
post.route = post.route or plugin.route
post.service = post.service or plugin.service
post.consumer = post.consumer or plugin.consumer
args.post = post
end
local patch_plugin
do
local patch_plugin_endpoint = endpoints.patch_entity_endpoint(kong.db.plugins.schema)
patch_plugin = function(self, db, helpers)
local plugin = self.plugin
fill_plugin_data(self.args, plugin)
return patch_plugin_endpoint(self, db, helpers)
end
end
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local schema_to_jsonable
do
local function fdata_to_jsonable(fdata)
local out = {}
for k, v in pairs(fdata) do
if k == "schema" then
out[k] = schema_to_jsonable(v)
elseif type(v) == "table" then
out[k] = fdata_to_jsonable(v)
elseif type(v) == "number" then
if v ~= v then
out[k] = "nan"
elseif v == math.huge then
out[k] = "inf"
elseif v == -math.huge then
out[k] = "-inf"
else
out[k] = v
end
elseif type(v) ~= "function" then
out[k] = v
end
end
return out
end
local insert = table.insert
local ipairs = ipairs
local next = next
schema_to_jsonable = function(schema)
local fields = {}
for _, field in ipairs(schema.fields) do
local fname = next(field)
local fdata = field[fname]
insert(fields, { [fname] = fdata_to_jsonable(fdata) })
end
return { fields = fields }
end
end
local function post_process(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
if data.service ~= null and data.service.id then
r_data.e = "s"
elseif data.route ~= null and data.route.id then
r_data.e = "r"
elseif data.consumer ~= null and data.consumer.id then
r_data.e = "c"
end
reports.send("api", r_data)
return data
end
return {
["/plugins"] = {
POST = function(_, _, _, parent)
return parent(post_process)
end,
},
["/plugins/:plugins"] = {
PATCH = function(self, db, helpers, parent)
local post = self.args and self.args.post
-- Read-before-write only if necessary
if post and (post.name == nil or
post.route == nil or
post.service == nil or
post.consumer == nil) then
-- We need the name, otherwise we don't know what type of
-- plugin this is and we can't perform *any* validations.
local plugin = db.plugins:select({ id = self.params.plugins })
if not plugin then
return kong.response.exit(404, { message = "Not found" })
end
fill_plugin_data(self.args, plugin)
end
return parent()
end,
},
["/plugins/schema/:name"] = {
GET = function(self, db, helpers)
local subschema = db.plugins.schema.subschemas[self.params.name]
if not subschema then
return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" })
end
local copy = schema_to_jsonable(subschema.fields.config)
return kong.response.exit(200, copy)
end
},
["/plugins/enabled"] = {
GET = function(_, _, helpers)
local enabled_plugins = setmetatable({}, cjson.empty_array_mt)
for k in pairs(singletons.configuration.loaded_plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return kong.response.exit(200, {
enabled_plugins = enabled_plugins
})
end
},
-- Available for backward compatibility
["/consumers/:consumers/plugins/:id"] = {
before = before_plugin_for_entity("consumers", "consumer"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/routes/:routes/plugins/:id"] = {
before = before_plugin_for_entity("routes", "route"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/services/:services/plugins/:id"] = {
before = before_plugin_for_entity("services", "service"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
}
|
fix(api) encode non-JSON-representable numbers as strings
|
fix(api) encode non-JSON-representable numbers as strings
Unlike Lua tables, the JSON standard does not support NaN and infinities. When
representing plugin schemas, we now convert these special numbers to strings
(case in point: the datadog plugin had a validator using `between = {1,
math.huge}` and this was causing the `/plugins/schemas/datadog` endpoint to
fail).
|
Lua
|
apache-2.0
|
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
|
bf4cada8517e3041b9713437bcbb02ebec1cfaaf
|
src/Ninja.lua
|
src/Ninja.lua
|
local P = {}
local System = require 'System'
local format = string.format
local concat = table.concat
local function indent(n)
return string.rep(' ', n or 4)
end
local function indented(line, n)
return concat { indent(n), line }
end
local function separated(str)
if not string.empty(str) then
return str..(suffix or ' ')
else
return ''
end
end
local function join(list)
return concat(list)
end
local function join_space(list)
return concat(list, ' ')
end
local function join_nl(list)
return concat(list, '\n')
end
local function join_escaped(list)
return concat(list, ' $\n')
end
local function quote(s)
return format("'%s'", string.gsub(s or '', "%$", "$$"))
end
local function escape(s)
s = string.gsub(s, "%$", "$$")
s = string.gsub(s, " ", "$ ")
s = string.gsub(s, ":", "$:")
return s
end
local function binding(k, v)
return format('%s = %s', assert(k), assert(v))
end
local function format_rule(name, command)
return format('rule %s\n%scommand = %s', name, indent(4), command)
end
local function format_build(build)
local lines = { '' }
local function format_outputs(outputs)
local lines = { outputs[1] }
if #outputs > 1 then
extend(lines, map(function (x)
return indented(escape(x), 8)
end, sort(table.rest(outputs, 2))))
append(lines, indent(12))
end
return join_escaped(lines)
end
local function format_inputs(inputs)
local lines = { '' }
extend(lines, sort(map(function (x)
return indented(escape(tostring(x)), 16)
end, inputs)))
return join_escaped(lines)
end
append(lines, format('build %s: %s%s',
format_outputs(build.outputs),
assert(build.rule),
format_inputs(build.inputs)))
extend(lines, map(function (key)
return indented(binding(key, build.vars[key]))
end, sort(table.keys(build.vars))))
return join_nl(lines)
end
local function format_stage(target)
local function get_outputs()
local outputs = { tostring(target) }
return extend(outputs, target.outputs or {})
end
local function format_args()
local command = { target.name, target.stage,
target.config or quote('')
}
if target.arg then
append(command, quote(target.arg))
end
return join_space(command)
end
return format_build {
rule = 'stage',
inputs = target.inputs,
outputs = get_outputs(),
vars = {
description = target:__tostring(' '),
args = format_args()
}
}
end
local function format_package(name, pkg)
local lines = {}
for stage in pkg:each() do
append(lines, format_stage(stage))
end
return join(lines)
end
local function find_sources()
local sources = {}
local pipe = System.popen([[find "$jagen_dir" "$jagen_project_dir" \
-type f "(" \
-path "$jagen_dir/bin/*" -o \
-path "$jagen_dir/lib/*" -o \
-path "$jagen_dir/src/*" -o \
-path "$jagen_dir/usr/*" -o \
-path "$jagen_dir/env.sh" -o \
-path "$jagen_dir/init-project" -o \
-path "$jagen_project_dir/env.sh" -o \
-path "$jagen_project_dir/config.sh" -o \
-path "$jagen_project_dir/lib/*" \
")" | sort]])
for line in pipe:lines() do
table.insert(sources, line)
end
pipe:close()
return sources
end
function P.generate(out_file, rules)
local file = assert(io.open(out_file, 'w'))
local packages = {}
for k, v in pairs(rules) do
table.insert(packages, v)
end
table.sort(packages, function (a, b)
return a.name < b.name
end)
local lines = {
binding('builddir', assert(Jagen.build_dir)),
format_rule('refresh', 'jagen refresh'),
format_rule('stage', join {
separated(Jagen.shell), 'jagen-pkg $args && touch $out'
})
}
append(lines, format_build {
rule = 'refresh',
inputs = find_sources(),
outputs = { 'build.ninja' },
})
extend(lines, pmap(format_package, packages))
file:write(join_nl(lines))
file:write('\n')
file:close()
end
return P
|
local P = {}
local System = require 'System'
local format = string.format
local concat = table.concat
local function indent(n)
return string.rep(' ', n or 4)
end
local function indented(line, n)
return concat { indent(n), line }
end
local function separated(str)
if not string.empty(str) then
return str..(suffix or ' ')
else
return ''
end
end
local function join(list)
return concat(list)
end
local function join_space(list)
return concat(list, ' ')
end
local function join_nl(list)
return concat(list, '\n')
end
local function join_escaped(list)
return concat(list, ' $\n')
end
local function quote(s)
return format("'%s'", string.gsub(s or '', "%$", "$$"))
end
local function escape(s)
s = string.gsub(s, "%$", "$$")
s = string.gsub(s, " ", "$ ")
s = string.gsub(s, ":", "$:")
return s
end
local function binding(k, v)
return format('%s = %s', assert(k), assert(v))
end
local function format_rule(name, command)
return format('rule %s\n%scommand = %s', name, indent(4), command)
end
local function format_build(build)
local lines = { '' }
local function format_outputs(outputs)
local lines = { outputs[1] }
if #outputs > 1 then
extend(lines, map(function (x)
return indented(escape(x), 8)
end, sort(table.rest(outputs, 2))))
append(lines, indent(12))
end
return join_escaped(lines)
end
local function format_inputs(inputs)
local lines = { '' }
extend(lines, sort(map(function (x)
return indented(escape(tostring(x)), 16)
end, inputs)))
return join_escaped(lines)
end
append(lines, format('build %s: %s%s',
format_outputs(build.outputs),
assert(build.rule),
format_inputs(build.inputs)))
extend(lines, map(function (key)
return indented(binding(key, build.vars[key]))
end, sort(table.keys(build.vars))))
return join_nl(lines)
end
local function format_stage(target)
local function get_outputs()
local outputs = { tostring(target) }
return extend(outputs, target.outputs or {})
end
local function format_args()
local command = { target.name, target.stage,
target.config or quote('')
}
if target.arg then
append(command, quote(target.arg))
end
return join_space(command)
end
local vars = {
description = target:__tostring(' '),
args = format_args(),
}
-- Do not rebuild the outputs if the command line changes. In this case it
-- means that adding or removing patches from the list will not cause full
-- rebuild.
if target.stage == 'provide_patches' then
vars.generator = true
end
return format_build {
rule = 'stage',
inputs = target.inputs,
outputs = get_outputs(),
vars = vars
}
end
local function format_package(name, pkg)
local lines = {}
for stage in pkg:each() do
append(lines, format_stage(stage))
end
return join(lines)
end
local function find_sources()
local sources = {}
local pipe = System.popen([[find "$jagen_dir" "$jagen_project_dir" \
-type f "(" \
-path "$jagen_dir/bin/*" -o \
-path "$jagen_dir/lib/*" -o \
-path "$jagen_dir/src/*" -o \
-path "$jagen_dir/usr/*" -o \
-path "$jagen_dir/env.sh" -o \
-path "$jagen_dir/init-project" -o \
-path "$jagen_project_dir/env.sh" -o \
-path "$jagen_project_dir/config.sh" -o \
-path "$jagen_project_dir/lib/*" \
")" | sort]])
for line in pipe:lines() do
table.insert(sources, line)
end
pipe:close()
return sources
end
function P.generate(out_file, rules)
local file = assert(io.open(out_file, 'w'))
local packages = {}
for k, v in pairs(rules) do
table.insert(packages, v)
end
table.sort(packages, function (a, b)
return a.name < b.name
end)
local lines = {
binding('builddir', assert(Jagen.build_dir)),
format_rule('refresh', 'jagen refresh'),
format_rule('stage', join {
separated(Jagen.shell), 'jagen-pkg $args && touch $out'
})
}
append(lines, format_build {
rule = 'refresh',
inputs = find_sources(),
outputs = { 'build.ninja' },
})
extend(lines, pmap(format_package, packages))
file:write(join_nl(lines))
file:write('\n')
file:close()
end
return P
|
Consider 'provide patches' stages to be generators
|
Consider 'provide patches' stages to be generators
This fixes the unnecessary full rebuild when patches are added or
removed to the list.
|
Lua
|
mit
|
bazurbat/jagen
|
f9f2cdda488d48a0714f8915c979405686f569c4
|
config/vcfanno/hg38-gemini.lua
|
config/vcfanno/hg38-gemini.lua
|
function mean(vals)
local sum=0
for i=1,#vals do
sum = sum + vals[i]
end
return sum / #vals
end
function loc(chrom, start, stop)
return chrom .. ":" .. start .. "-" .. stop
end
CLINVAR_LOOKUP = {}
CLINVAR_LOOKUP['0'] = 'unknown'
CLINVAR_LOOKUP['1'] = 'germline'
CLINVAR_LOOKUP['2'] = 'somatic'
CLINVAR_LOOKUP['4'] = 'inherited'
CLINVAR_LOOKUP['8'] = 'paternal'
CLINVAR_LOOKUP['16'] = 'maternal'
CLINVAR_LOOKUP['32'] = 'de-novo'
CLINVAR_LOOKUP['64'] = 'biparental'
CLINVAR_LOOKUP['128'] = 'uniparental'
CLINVAR_LOOKUP['256'] = 'not-tested'
CLINVAR_LOOKUP['512'] = 'tested-inconclusive'
CLINVAR_LOOKUP['1073741824'] = 'other'
CLINVAR_SIG = {}
CLINVAR_SIG['0'] = 'uncertain'
CLINVAR_SIG['1'] = 'not-provided'
CLINVAR_SIG['2'] = 'benign'
CLINVAR_SIG['3'] = 'likely-benign'
CLINVAR_SIG['4'] = 'likely-pathogenic'
CLINVAR_SIG['5'] = 'pathogenic'
CLINVAR_SIG['6'] = 'drug-response'
CLINVAR_SIG['7'] = 'histocompatibility'
CLINVAR_SIG['255'] = 'other'
CLINVAR_SIG['.'] = '.'
function intotbl(ud)
local tbl = {}
for i=1,#ud do
tbl[i] = ud[i]
end
return tbl
end
-- from lua-users wiki
function split(str, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function contains(str, tok)
return string.find(str, tok) ~= nil
end
function div2(a, b)
if(a == 0) then return "0.0" end
return string.format("%.9f", (a + 0) / b)
end
function ratio(vals)
vals = vals[1] -- get 2 values per element. alt and ref counts.
if vals[2] == 0 then return "0.0" end
return string.format("%.9f", vals[1] / (vals[1] + vals[2]))
end
function clinvar_sig(vals)
local t = type(vals)
-- just a single-value
if(t == "string" or t == "number") and not contains(vals, "|") then
return CLINVAR_SIG[vals]
elseif t ~= "table" then
if not contains(t, "userdata") then
if t == "string" then
vals = split(vals, ",")
else
vals = {vals}
end
else
vals = intotbl(vals)
end
end
local ret = {}
for i=1,#vals do
if not contains(vals[i], "|") then
ret[#ret+1] = CLINVAR_SIG[vals[i]]
else
local invals = split(vals[i], "|")
local inret = {}
for j=1,#invals do
inret[#inret+1] = CLINVAR_SIG[invals[j]]
end
ret[#ret+1] = join(inret, "|")
end
end
return join(ret, ",")
end
join = table.concat
function check_clinvar_aaf(clinvar_sig, max_aaf_all, aaf_cutoff)
-- didn't find an aaf for this so can't be common
if max_aaf_all == nil or clinvar_sig == nil then
return false
end
if type(clinvar_sig) ~= "string" then
clinvar_sig = join(clinvar_sig, ",")
end
return contains(clinvar_sig, "pathogenic") and max_aaf_all > aaf_cutoff
end
|
function mean(vals)
local sum=0
for i=1,#vals do
sum = sum + vals[i]
end
return sum / #vals
end
function loc(chrom, start, stop)
return chrom .. ":" .. start .. "-" .. stop
end
CLINVAR_LOOKUP = {}
CLINVAR_LOOKUP['0'] = 'unknown'
CLINVAR_LOOKUP['1'] = 'germline'
CLINVAR_LOOKUP['2'] = 'somatic'
CLINVAR_LOOKUP['4'] = 'inherited'
CLINVAR_LOOKUP['8'] = 'paternal'
CLINVAR_LOOKUP['16'] = 'maternal'
CLINVAR_LOOKUP['32'] = 'de-novo'
CLINVAR_LOOKUP['64'] = 'biparental'
CLINVAR_LOOKUP['128'] = 'uniparental'
CLINVAR_LOOKUP['256'] = 'not-tested'
CLINVAR_LOOKUP['512'] = 'tested-inconclusive'
CLINVAR_LOOKUP['1073741824'] = 'other'
CLINVAR_SIG = {}
CLINVAR_SIG['0'] = 'uncertain'
CLINVAR_SIG['1'] = 'not-provided'
CLINVAR_SIG['2'] = 'benign'
CLINVAR_SIG['3'] = 'likely-benign'
CLINVAR_SIG['4'] = 'likely-pathogenic'
CLINVAR_SIG['5'] = 'pathogenic'
CLINVAR_SIG['6'] = 'drug-response'
CLINVAR_SIG['7'] = 'histocompatibility'
CLINVAR_SIG['255'] = 'other'
CLINVAR_SIG['.'] = '.'
function intotbl(ud)
local tbl = {}
for i=1,#ud do
tbl[i] = ud[i]
end
return tbl
end
-- from lua-users wiki
function split(str, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function contains(str, tok)
return string.find(str, tok) ~= nil
end
function div2(a, b)
if(a == 0) then return "0.0" end
return string.format("%.9f", (a + 0) / b)
end
function ratio(vals)
vals = vals[1] -- get 2 values per element. alt and ref counts.
if vals[2] == 0 then return "0.0" end
return string.format("%.9f", vals[1] / (vals[1] + vals[2]))
end
function clinvar_sig(vals)
local t = type(vals)
-- just a single-value
if(t == "string" or t == "number") and not contains(vals, "|") then
return CLINVAR_SIG[vals]
elseif t ~= "table" then
if not contains(t, "userdata") then
if t == "string" then
vals = split(vals, ",")
else
vals = {vals}
end
else
vals = intotbl(vals)
end
end
local ret = {}
for i=1,#vals do
if not contains(vals[i], "|") then
ret[#ret+1] = CLINVAR_SIG[vals[i]]
else
local invals = split(vals[i], "|")
local inret = {}
for j=1,#invals do
inret[#inret+1] = CLINVAR_SIG[invals[j]]
end
ret[#ret+1] = join(inret, "|")
end
end
return join(ret, ",")
end
join = table.concat
function check_clinvar_aaf(clinvar_sig, max_aaf_all, aaf_cutoff)
-- didn't find an aaf for this so can't be common
if max_aaf_all == nil or clinvar_sig == nil then
return false
end
if type(clinvar_sig) ~= "string" then
clinvar_sig = join(clinvar_sig, ",")
end
if false == contains(clinvar_sig, "pathogenic") then
return false
end
if type(max_aaf_all) ~= "table" then
return max_aaf_all > aaf_cutoff
end
for i, aaf in pairs(max_aaf_all) do
if aaf > aaf_cutoff then
return true
end
end
return false
end
|
vcfanno clinvar fix https://github.com/brentp/vcfanno/commit/5fcce8db2aeee016ab927c8ca36a715c02f982f9
|
vcfanno clinvar fix https://github.com/brentp/vcfanno/commit/5fcce8db2aeee016ab927c8ca36a715c02f982f9
|
Lua
|
mit
|
chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,biocyberman/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen
|
56424931bb72b38151fb359d5d5f862a23fea5b8
|
applications/luci-app-samba/luasrc/model/cbi/samba.lua
|
applications/luci-app-samba/luasrc/model/cbi/samba.lua
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2008 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
m = Map("samba", translate("Network Shares"))
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("template", translate("Edit Template"))
s:taboption("general", Value, "name", translate("Hostname"))
s:taboption("general", Value, "description", translate("Description"))
s:taboption("general", Value, "workgroup", translate("Workgroup"))
h = s:taboption("general", Flag, "homes", translate("Share home-directories"),
translate("Allow system users to reach their home directories via " ..
"network shares"))
h.rmempty = false
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the samba configuration."),
translate("This is the content of the file '/etc/samba/smb.conf.template' from which your samba configuration will be generated. " ..
"Values enclosed by pipe symbols ('|') should not be changed. They get their values from the 'General Settings' tab."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/samba/smb.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("//etc/samba/smb.conf.template", value)
end
s = m:section(TypedSection, "sambashare", translate("Shared Directories"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("Name"))
pth = s:option(Value, "path", translate("Path"))
if nixio.fs.access("/etc/config/fstab") then
pth.titleref = luci.dispatcher.build_url("admin", "system", "fstab")
end
s:option(Value, "users", translate("Allowed users")).rmempty = true
ro = s:option(Flag, "read_only", translate("Read-only"))
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"
br = s:option(Flag, "browseable", translate("Browseable"))
br.rmempty = false
br.default = "yes"
br.enabled = "yes"
br.disabled = "no"
go = s:option(Flag, "guest_ok", translate("Allow guests"))
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask", translate("Create mask"),
translate("Mask for new files"))
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask", translate("Directory mask"),
translate("Mask for new directories"))
dm.rmempty = true
dm.size = 4
return m
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2008 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
m = Map("samba", translate("Network Shares"))
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("template", translate("Edit Template"))
s:taboption("general", Value, "name", translate("Hostname"))
s:taboption("general", Value, "description", translate("Description"))
s:taboption("general", Value, "workgroup", translate("Workgroup"))
h = s:taboption("general", Flag, "homes", translate("Share home-directories"),
translate("Allow system users to reach their home directories via " ..
"network shares"))
h.rmempty = false
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the samba configuration."),
translate("This is the content of the file '/etc/samba/smb.conf.template' from which your samba configuration will be generated. " ..
"Values enclosed by pipe symbols ('|') should not be changed. They get their values from the 'General Settings' tab."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/samba/smb.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("//etc/samba/smb.conf.template", value)
end
s = m:section(TypedSection, "sambashare", translate("Shared Directories")
, translate("Please add directories to share. Each directory refers to a folder on a mounted device."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("Name"))
pth = s:option(Value, "path", translate("Path"))
if nixio.fs.access("/etc/config/fstab") then
pth.titleref = luci.dispatcher.build_url("admin", "system", "fstab")
end
s:option(Value, "users", translate("Allowed users")).rmempty = true
ro = s:option(Flag, "read_only", translate("Read-only"))
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"
br = s:option(Flag, "browseable", translate("Browseable"))
br.rmempty = false
br.default = "yes"
br.enabled = "yes"
br.disabled = "no"
go = s:option(Flag, "guest_ok", translate("Allow guests"))
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask", translate("Create mask"),
translate("Mask for new files"))
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask", translate("Directory mask"),
translate("Mask for new directories"))
dm.rmempty = true
dm.size = 4
return m
|
luci-app-samba: Shared directory help text.
|
luci-app-samba: Shared directory help text.
A forum.lede-project.org member had trouble understanding how to configure Samba.
This is help text for Shared Directories.
Signed-off-by: Bob Meizlik <[email protected]>
[whitespace fixed]
Signed-off-by: Jo-Philipp Wich <[email protected]>
|
Lua
|
apache-2.0
|
hnyman/luci,kuoruan/luci,artynet/luci,openwrt-es/openwrt-luci,remakeelectric/luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,chris5560/openwrt-luci,artynet/luci,kuoruan/luci,Wedmer/luci,Wedmer/luci,openwrt/luci,Noltari/luci,Noltari/luci,openwrt-es/openwrt-luci,nmav/luci,wongsyrone/luci-1,wongsyrone/luci-1,981213/luci-1,openwrt/luci,kuoruan/luci,Wedmer/luci,openwrt/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,remakeelectric/luci,kuoruan/lede-luci,oneru/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,nmav/luci,nmav/luci,artynet/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,chris5560/openwrt-luci,remakeelectric/luci,tobiaswaldvogel/luci,remakeelectric/luci,nmav/luci,chris5560/openwrt-luci,Noltari/luci,openwrt/luci,wongsyrone/luci-1,Noltari/luci,wongsyrone/luci-1,remakeelectric/luci,openwrt/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,artynet/luci,rogerpueyo/luci,rogerpueyo/luci,981213/luci-1,remakeelectric/luci,wongsyrone/luci-1,oneru/luci,rogerpueyo/luci,hnyman/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,oneru/luci,nmav/luci,openwrt/luci,hnyman/luci,hnyman/luci,kuoruan/luci,Noltari/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,lbthomsen/openwrt-luci,981213/luci-1,wongsyrone/luci-1,kuoruan/lede-luci,oneru/luci,kuoruan/lede-luci,981213/luci-1,openwrt/luci,Noltari/luci,tobiaswaldvogel/luci,oneru/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,artynet/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,Noltari/luci,hnyman/luci,Wedmer/luci,kuoruan/luci,Wedmer/luci,oneru/luci,openwrt/luci,artynet/luci,981213/luci-1,artynet/luci,Noltari/luci,hnyman/luci,hnyman/luci,nmav/luci,kuoruan/lede-luci,oneru/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/luci,rogerpueyo/luci,kuoruan/lede-luci,981213/luci-1,hnyman/luci,kuoruan/luci,remakeelectric/luci,tobiaswaldvogel/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,Wedmer/luci,nmav/luci,wongsyrone/luci-1,kuoruan/luci,tobiaswaldvogel/luci,remakeelectric/luci,Wedmer/luci,nmav/luci,oneru/luci,Wedmer/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,kuoruan/lede-luci,lbthomsen/openwrt-luci,981213/luci-1
|
cc7b91030c9f23f3d36d7d9ca70603a9b7b9d6a7
|
testserver/item/base/music.lua
|
testserver/item/base/music.lua
|
-- Standardskript fr Instrumente
-- Nitram
require("base.common")
module("item.base.music", package.seeall)
TalkTexts={[Character.flute] = {}, [Character.lute] = {}, [Character.horn] = {}, [Character.harp] = {}, [Character.panpipe] = {}, [Character.drum] = {}};
function addTalkText(eText,gText, Skill)
table.insert(TalkTexts[Skill],{eText,gText});
end
function PlayInstrument(User,Item,Skill)
local Skl=User:getSkill(Skill);
local Qual=math.floor(Item.quality/100);
local PlayVal=base.common.Limit(math.floor((Skl+(Qual*5))/120*table.getn(TalkTexts[Skill])*(math.random(8,13)/10)),1,table.getn(TalkTexts[Skill]));
User:talkLanguage( Character.say, Player.german, TalkTexts[Skill][PlayVal][2]);
User:talkLanguage( Character.say, Player.english, TalkTexts[Skill][PlayVal][1]);
User:learn(Skill,30,100,User:increaseAttrib("dexterity",0));
User.movepoints=User.movepoints-30;
end
|
-- Standardskript fr Instrumente
-- Nitram
require("base.common")
module("item.base.music", package.seeall)
TalkTexts={[Character.flute] = {}, [Character.lute] = {}, [Character.horn] = {}, [Character.harp] = {}, [Character.panpipe] = {}, [Character.drum] = {}};
function addTalkText(eText,gText, Skill)
table.insert(TalkTexts[Skill],{eText,gText});
end
function PlayInstrument(User,Item,Skill)
local Skl=User:getSkill(Skill);
local Qual=math.floor(Item.quality/100);
local PlayVal=base.common.Limit(math.floor((Skl+(Qual*5))/120*table.getn(TalkTexts[Skill])*(math.random(8,13)/10)),1,table.getn(TalkTexts[Skill]));
User:talkLanguage( Character.say, Player.german, TalkTexts[Skill][PlayVal][2]);
User:talkLanguage( Character.say, Player.english, TalkTexts[Skill][PlayVal][1]);
User:learn(Skill,30,100)
User.movepoints=User.movepoints-30;
end
|
Fix instrument learning
|
Fix instrument learning
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
|
40ffdd3355f14b43830f48a497d3960a52e26ffc
|
modules/commotion/root/usr/lib/lua/commotion_helpers.lua
|
modules/commotion/root/usr/lib/lua/commotion_helpers.lua
|
function DIE(str)
luci.http.status(500, "Internal Server Error")
luci.http.write(str)
luci.http.close()
end
--- Redirects a page to https if the path is within the "node" path.
-- @param node node path to check. format as such -> "/NODE/"
-- @param env A table containing the REQUEST_URI and the SERVER_NAME. Can take full luci.http.getenv()
-- @return True if page is to be redirected. False if path does not include node or if https is already on.
function check_https(node, env)
if string.match(env.REQUEST_URI, node) then
if env.HTTPS ~= "on" then
luci.http.redirect("https://"..env.SERVER_NAME..env.REQUEST_URI)
return true
end
return false
end
return false
end
--- Gives the md5 and sha1 fingerprints of uhttpd server.
--- Call as such: md5, sha1 = ssl_cert_fingerprints() If you only give one var name it will only give you md5. Call like: _, sha1 = to throw away md5
-- @return md5 and sha1 hash of uhttpd.
function ssl_cert_fingerprints()
--get cert file from /etc/config/uhttpd
local uci = luci.model.uci.cursor()
local cert = uci:get('uhttpd','main','cert')
--get md5 and sha1 hash's of cert file
local md5 = luci.sys.exec("md5sum "..cert)
local sha1 = luci.sys.exec("sha1sum "..cert)
-- remove the filename and extra spaces then uppercase the cert string
sha1 = string.upper(sha1:match("(%w*)%s*"..cert))
md5 = string.upper(md5:match("(%w*)%s*"..cert))
--add colons between pairs of two chars
sha1 = sha1:gsub("(%w%w)", "%1:")
md5 = md5:gsub("(%w%w)", "%1:")
--remove the final colon
sha1 = sha1:sub(1, -2)
md5 = md5:sub(1,-2)
return md5, sha1
end
function uci_encode(str)
if (str) then
str = string.gsub (str, "([^%w])", function(c) return '_' .. tostring(string.byte(c)) end)
end
return str
end
function html_encode(str)
return string.gsub(str,"[<>&\n\r\"]",function(c) return html_replacements[c] or c end)
end
function url_encode(str)
return string.gsub(str,"[<>%s]",function(c) return url_replacements[c] or c end)
end
function printf(tmpl,t)
return (tmpl:gsub('($%b{})', function(w) return t[w:sub(3, -2)] or w end))
end
function log(msg)
if (type(msg) == "table") then
for key, val in pairs(msg) do
log('{')
log(key)
log(':')
log(val)
log('}')
end
else
luci.sys.exec("logger -t luci \"" .. tostring(msg) .. '"')
end
end
function is_ip4addr(str)
local i,j, _1, _2, _3, _4 = string.find(str, '^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$')
if (i and
(tonumber(_1) >= 0 and tonumber(_1) <= 255) and
(tonumber(_2) >= 0 and tonumber(_2) <= 255) and
(tonumber(_3) >= 0 and tonumber(_3) <= 255) and
(tonumber(_4) >= 0 and tonumber(_4) <= 255)) then
return true
end
return false
end
function is_ip4addr_cidr(str)
local i,j, _1, _2 = string.find(str, '^(.+)/(%d+)$')
if i and is_ip4addr(_1) and tonumber(_2) >= 0 and tonumber(_2) <= 32 then
return true
end
return false
end
function is_ssid(str)
-- SSID can have almost anything in it
if #tostring(str) < 32 then
return tostring(str):match("[%w%p]+[%s]*[%w%p]*]*")
else
return nil
end
end
function is_mode(str)
-- Modes are simple, but also match the "-" in Ad-Hoc
return tostring(str):match("[%w%-]*")
end
function is_chan(str)
-- Channels are plain digits
return tonumber(string.match(str, "[%d]+"))
end
function is_bitRate(br)
-- Bitrate can start with a space and we want to display Mb/s
return br:match("[%s]?[%d%.]*[%s][%/%a]+")
end
function is_email(email)
return tostring(email):match("[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?")
end
function is_hostname(str)
--alphanumeric and hyphen Less than 63 chars
--cannot start or end with a hyphen
if #tostring(str) < 63 then
return tostring(str):match("^%w[%w%-]*%w$")
else
return nil
end
end
function is_fqdn(str)
-- alphanumeric and hyphen less than 255 chars
-- each label must be less than 63 chars
if #tostring(str) < 255 then
-- Should check that each label is < 63 chars --
return tostring(str):match("^[%w%.%-]+$")
else
return nil
end
end
function is_macaddr(str)
local i,j, _1, _2, _3, _4, _5, _6 = string.find(str, '^(%x%x):(%x%x):(%x%x):(%x%x):(%x%x):(%x%x)$')
if i then return true end
return false
end
function is_uint(str)
return str:find("^%d+$")
end
function is_hex(str)
return str:find("^%x+$")
end
function is_port(str)
return is_uint(str) and tonumber(str) >= 0 and tonumber(str) <= 65535
end
function is_valid_uci(str)
return str:find("^[%w_]+$")
end
function pass_to_shell(str)
return str:gsub("$(","\\$"):gsub("`","\\`")
end
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function list_ifaces()
local uci = luci.model.uci.cursor()
local r = {zone_to_iface = {}, iface_to_zone = {}}
uci:foreach("network", "interface",
function(zone)
if zone['.name'] == 'loopback' then return end
local iface = luci.sys.exec("ubus call network.interface." .. zone['.name'] .. " status |grep '\"device\"' | cut -d '\"' -f 4"):gsub("%s$","")
r.zone_to_iface[zone['.name']]=iface
r.iface_to_zone[iface]=zone['.name']
end
)
return r
end
html_replacements = {
["<"] = "<",
[">"] = ">",
["&"] = "&",
["\n"] = " ",
["\r"] = " ",
["\""] = """
}
url_replacements = {
["<"] = "%3C",
[">"] = "%3E",
[" "] = "%20",
['"'] = "%22"
}
|
function DIE(str)
luci.http.status(500, "Internal Server Error")
luci.http.write(str)
luci.http.close()
end
--- Redirects a page to https if the path is within the "node" path.
-- @param node node path to check. format as such -> "/NODE/"
-- @param env A table containing the REQUEST_URI and the SERVER_NAME. Can take full luci.http.getenv()
-- @return True if page is to be redirected. False if path does not include node or if https is already on.
function check_https(node, env)
if string.match(env.REQUEST_URI, node) then
if env.HTTPS ~= "on" then
luci.http.redirect("https://"..env.SERVER_NAME..env.REQUEST_URI)
return true
end
return false
end
return false
end
--- Gives the md5 and sha1 fingerprints of uhttpd server.
--- Call as such: md5, sha1 = ssl_cert_fingerprints() If you only give one var name it will only give you md5. Call like: _, sha1 = to throw away md5
-- @return md5 and sha1 hash of uhttpd.
function ssl_cert_fingerprints()
--get cert file from /etc/config/uhttpd
local uci = luci.model.uci.cursor()
local cert = uci:get('uhttpd','main','cert')
--get md5 and sha1 hash's of cert file
local md5 = luci.sys.exec("md5sum "..cert)
local sha1 = luci.sys.exec("sha1sum "..cert)
-- remove the filename and extra spaces then uppercase the cert string
sha1 = string.upper(sha1:match("(%w*)%s*"..cert))
md5 = string.upper(md5:match("(%w*)%s*"..cert))
--add colons between pairs of two chars
sha1 = sha1:gsub("(%w%w)", "%1:")
md5 = md5:gsub("(%w%w)", "%1:")
--remove the final colon
sha1 = sha1:sub(1, -2)
md5 = md5:sub(1,-2)
return md5, sha1
end
function uci_encode(str)
if (str) then
str = string.gsub (str, "([^%w])", function(c) return '_' .. tostring(string.byte(c)) end)
end
return str
end
function html_encode(str)
if (str) then
str = string.gsub(str,"[<>&\n\r\"]",function(c) return html_replacements[c] or c end)
end
return str
end
function url_encode(str)
if (str) then
str = string.gsub(str,"[<>%s]",function(c) return url_replacements[c] or c end)
end
return str
end
function printf(tmpl,t)
return (tmpl:gsub('($%b{})', function(w) return t[w:sub(3, -2)] or w end))
end
function log(msg)
if (type(msg) == "table") then
for key, val in pairs(msg) do
log('{')
log(key)
log(':')
log(val)
log('}')
end
else
luci.sys.exec("logger -t luci \"" .. tostring(msg) .. '"')
end
end
function is_ip4addr(str)
local i,j, _1, _2, _3, _4 = string.find(str, '^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$')
if (i and
(tonumber(_1) >= 0 and tonumber(_1) <= 255) and
(tonumber(_2) >= 0 and tonumber(_2) <= 255) and
(tonumber(_3) >= 0 and tonumber(_3) <= 255) and
(tonumber(_4) >= 0 and tonumber(_4) <= 255)) then
return true
end
return false
end
function is_ip4addr_cidr(str)
local i,j, _1, _2 = string.find(str, '^(.+)/(%d+)$')
if i and is_ip4addr(_1) and tonumber(_2) >= 0 and tonumber(_2) <= 32 then
return true
end
return false
end
function is_ssid(str)
-- SSID can have almost anything in it
if #tostring(str) < 32 then
return tostring(str):match("[%w%p]+[%s]*[%w%p]*]*")
else
return nil
end
end
function is_mode(str)
-- Modes are simple, but also match the "-" in Ad-Hoc
return tostring(str):match("[%w%-]*")
end
function is_chan(str)
-- Channels are plain digits
return tonumber(string.match(str, "[%d]+"))
end
function is_bitRate(br)
-- Bitrate can start with a space and we want to display Mb/s
return br:match("[%s]?[%d%.]*[%s][%/%a]+")
end
function is_email(email)
return tostring(email):match("[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?")
end
function is_hostname(str)
--alphanumeric and hyphen Less than 63 chars
--cannot start or end with a hyphen
if #tostring(str) < 63 then
return tostring(str):match("^%w[%w%-]*%w$")
else
return nil
end
end
function is_fqdn(str)
-- alphanumeric and hyphen less than 255 chars
-- each label must be less than 63 chars
if #tostring(str) < 255 then
-- Should check that each label is < 63 chars --
return tostring(str):match("^[%w%.%-]+$")
else
return nil
end
end
function is_macaddr(str)
local i,j, _1, _2, _3, _4, _5, _6 = string.find(str, '^(%x%x):(%x%x):(%x%x):(%x%x):(%x%x):(%x%x)$')
if i then return true end
return false
end
function is_uint(str)
return str:find("^%d+$")
end
function is_hex(str)
return str:find("^%x+$")
end
function is_port(str)
return is_uint(str) and tonumber(str) >= 0 and tonumber(str) <= 65535
end
function is_valid_uci(str)
return str:find("^[%w_]+$")
end
function pass_to_shell(str)
return str:gsub("$(","\\$"):gsub("`","\\`")
end
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function list_ifaces()
local uci = luci.model.uci.cursor()
local r = {zone_to_iface = {}, iface_to_zone = {}}
uci:foreach("network", "interface",
function(zone)
if zone['.name'] == 'loopback' then return end
local iface = luci.sys.exec("ubus call network.interface." .. zone['.name'] .. " status |grep '\"device\"' | cut -d '\"' -f 4"):gsub("%s$","")
r.zone_to_iface[zone['.name']]=iface
r.iface_to_zone[iface]=zone['.name']
end
)
return r
end
html_replacements = {
["<"] = "<",
[">"] = ">",
["&"] = "&",
["\n"] = " ",
["\r"] = " ",
["\""] = """
}
url_replacements = {
["<"] = "%3C",
[">"] = "%3E",
[" "] = "%20",
['"'] = "%22"
}
|
fixes to commotion_helpers
|
fixes to commotion_helpers
|
Lua
|
apache-2.0
|
opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux
|
492e2d76881522aa303890b268a53fb9c8cd9f0f
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with a fixed hostname while having a dynamically changing IP-Address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s:option(Flag, "enabled", translate("enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
svc:value("")
svc:value("dyndns.org")
svc:value("changeip.com")
svc:value("zoneedit.com")
svc:value("no-ip.com")
svc:value("freedns.afraid.org")
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
src = s:option(ListValue, "ip_source")
src:value("network", translate("Network"))
src:value("interface", translate("Interface"))
src:value("web", "URL")
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", "URL")
web:depends("ip_source", "web")
web.rmempty = true
s:option(Value, "update_url").optional = true
s:option(Value, "check_interval").default = 10
unit = s:option(ListValue, "check_unit")
unit.default = "minutes"
unit:value("minutes", "min")
unit:value("hours", "h")
s:option(Value, "force_interval").default = 72
unit = s:option(ListValue, "force_unit")
unit.default = "hours"
unit:value("minutes", "min")
unit:value("hours", "h")
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with a fixed hostname while having a dynamically changing IP-Address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s:option(Flag, "enabled", translate("enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
svc:value("")
svc:value("dyndns.org")
svc:value("changeip.com")
svc:value("zoneedit.com")
svc:value("no-ip.com")
svc:value("freedns.afraid.org")
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
src = s:option(ListValue, "ip_source", translate("Source of IP-Address"))
src:value("network", translate("Network"))
src:value("interface", translate("Interface"))
src:value("web", "URL")
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", "URL")
web:depends("ip_source", "web")
web.rmempty = true
s:option(Value, "update_url", translate("Custom Update-URL")).optional = true
s:option(Value, "check_interval", translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-Time unit"))
unit.default = "minutes"
unit:value("minutes", "min")
unit:value("hours", "h")
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-Time unit"))
unit.default = "hours"
unit:value("minutes", "min")
unit:value("hours", "h")
return m
|
applications/luci-ddns: fix dyndns config page
|
applications/luci-ddns: fix dyndns config page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5463 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
Flexibity/luci,freifunk-gluon/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Flexibity/luci,ch3n2k/luci,8devices/carambola2-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,phi-psi/luci,stephank/luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,jschmidlapp/luci,Flexibity/luci,Canaan-Creative/luci,saraedum/luci-packages-old,gwlim/luci,ThingMesh/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,stephank/luci,vhpham80/luci,jschmidlapp/luci,ch3n2k/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,Canaan-Creative/luci,phi-psi/luci,ch3n2k/luci,vhpham80/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,vhpham80/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,gwlim/luci,stephank/luci,projectbismark/luci-bismark,freifunk-gluon/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,gwlim/luci,8devices/carambola2-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,ch3n2k/luci,ch3n2k/luci,phi-psi/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,stephank/luci,projectbismark/luci-bismark,jschmidlapp/luci,zwhfly/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,jschmidlapp/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,vhpham80/luci,saraedum/luci-packages-old,Flexibity/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Canaan-Creative/luci,Canaan-Creative/luci,stephank/luci,stephank/luci,Canaan-Creative/luci,jschmidlapp/luci
|
e11be4362d3c13db1cab2d93269c5faa268d4b8f
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local lineEmitter = LineEmitter:new()
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
response.target = payload.source
response.source = payload.target
response.id = payload.id
log("Sending response:")
p(response)
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
tls.createServer(options, function (client)
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
respond(log, client, payload)
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end):listen(port)
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local lineEmitter = LineEmitter:new()
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
set_option(opts, "listen_ip", '127.0.0.1')
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
response.target = payload.source
response.source = payload.target
response.id = payload.id
log("Sending response:")
p(response)
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
tls.createServer(options, function (client)
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
respond(log, client, payload)
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end):listen(port, opts.listen_ip)
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
monitoring: fixtures: server: add listen_ip option
|
monitoring: fixtures: server: add listen_ip option
make it possible to run this thing over the internet
|
Lua
|
apache-2.0
|
cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base
|
a9119dc198db95a34a2193e342d07e81ba2b43ce
|
Mjolnir/setup.lua
|
Mjolnir/setup.lua
|
os.exit = mj._exit
local function pack(...)
return {n = select("#", ...), ...}
end
function mj.runstring(s)
local fn, err = loadstring("return " .. s)
if not fn then fn, err = loadstring(s) end
if not fn then return tostring(err) end
local str = ""
local results = pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function mj.showerror(err)
mj._notify("Mjolnir error occurred")
print(err)
end
do
local r = debug.getregistry()
r.__mj_debug_traceback = debug.traceback
r.__mj_showerror = mj.showerror
end
local rawprint = print
function print(...)
rawprint(...)
local vals = pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
local str = table.concat(vals, "\t") .. "\n"
mj._logmessage(str)
end
--- mj.print = print
--- The original print function, before Mjolnir overrides it.
mj.print = rawprint
-- load user's init-file
local fn, err = loadfile "init.lua"
if fn then
if mj.pcall(fn) then
print "-- Loading ~/.mjolnir/init.lua; success."
end
elseif err:find "No such file or directory" then
print "-- Loading ~/.mjolnir/init.lua; file not found, skipping."
else
print(tostring(err))
mj._notify("Syntax error in ~/.mjolnir/init.lua")
end
|
os.exit = mj._exit
local function pack(...)
return {n = select("#", ...), ...}
end
function mj.runstring(s)
local fn, err = loadstring("return " .. s)
if not fn then fn, err = loadstring(s) end
if not fn then return tostring(err) end
local str = ""
local results = pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function mj.showerror(err)
mj._notify("Mjolnir error occurred")
print(err)
end
do
local r = debug.getregistry()
r.__mj_debug_traceback = debug.traceback
r.__mj_showerror = mj.showerror
end
local rawprint = print
function print(...)
rawprint(...)
local vals = pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
local str = table.concat(vals, "\t") .. "\n"
mj._logmessage(str)
end
--- mj.print = print
--- The original print function, before Mjolnir overrides it.
mj.print = rawprint
-- load user's init-file
local fn, err = loadfile "init.lua"
if fn then
local ok, err = xpcall(fn, debug.traceback)
if ok then
print "-- Loading ~/.mjolnir/init.lua; success."
else
mj.showerror(err)
end
elseif err:find "No such file or directory" then
print "-- Loading ~/.mjolnir/init.lua; file not found, skipping."
else
print(tostring(err))
mj._notify("Syntax error in ~/.mjolnir/init.lua")
end
|
Fixing use of non-existent function.
|
Fixing use of non-existent function.
|
Lua
|
mit
|
wvierber/hammerspoon,nkgm/hammerspoon,wsmith323/hammerspoon,peterhajas/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,heptal/hammerspoon,trishume/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,knu/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,chrisjbray/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,tmandry/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,CommandPost/CommandPost-App,kkamdooong/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,junkblocker/hammerspoon,hypebeast/hammerspoon,Stimim/hammerspoon,heptal/hammerspoon,dopcn/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,knu/hammerspoon,emoses/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,tmandry/hammerspoon,knl/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,Habbie/hammerspoon
|
254cdded77a1a05d7f16d0a677374cdc55349c66
|
packages/dnsmasq-lease-share/src/dnsmasq-lease-share.lua
|
packages/dnsmasq-lease-share/src/dnsmasq-lease-share.lua
|
#!/usr/bin/lua
--[[
Copyright (C) 2013 Gioacchino Mazzurco <[email protected]>
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this file. If not, see <http://www.gnu.org/licenses/>.
]]--
-- PLEASE USE TAB NOT SPACE JUST FOR INDENTATION
--! dhcp lease file lines format
--! <Time of lease expiry, in epoch time (seconds since 1970)> <Client MAC Address> <Client IP> <Client unqualified hostname if provided, * if not provided> <Client-ID, if known. The client-ID is used as the computer's unique-ID in preference to the MAC address, if it's available>
--! root at OpenWrt:~# cat /var/dhcp.leases
--! 946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05
--! 946689351 00:0f:b0:3a:b5:0b 192.168.1.208 colinux *
--! 946689493 02:0f:b0:3a:b5:0b 192.168.1.199 * 01:02:0f:b0:3a:b5:0b
require("uci");
local local_lease_file = "/tmp/dnsmasq-lease-share-local-lease"
local alfred_shared_lease_num = "65"
local command = arg[1];
local client_mac = arg[2];
--! Tell alfred local dhcp lease changed
function update_alfred()
local lease_file = io.open(local_lease_file, "r+");
local stdin = io.popen("alfred -s " .. alfred_shared_lease_num,"w");
stdin:write(lease_file:read("*all"));
lease_file:close();
stdin:close();
end
function get_hostname()
local hostfile = io.open("/proc/sys/kernel/hostname", "r");
local ret_string = hostfile:read();
hostfile:close();
return ret_string;
end
function get_if_mac(ifname)
local macfile = io.open("/sys/class/net/" .. ifname .. "/address");
local ret_string = macfile:read();
macfile:close();
return ret_string;
end
if command == "add" then
local lease_expiration = os.getenv("DNSMASQ_LEASE_EXPIRES");
local client_ip = arg[3];
local client_hostname;
if (arg[4] and (arg[4]:len() > 0)) then client_hostname = arg[4] else client_hostname = "*" end;
local client_id = os.getenv("DNSMASQ_CLIENT_ID");
if ((not client_id) or (client_id:len() <= 0)) then client_id = client_mac end;
local lease_line = lease_expiration .. " " .. client_mac .. " " .. client_ip .. " " .. client_hostname .. " " .. client_id .. "\n";
local lease_file = io.open(local_lease_file, "a");
lease_file:write(lease_line);
lease_file:close();
update_alfred()
elseif command == "del" then
local leases = "";
local lease_file = io.open(local_lease_file, "r");
while lease_file:read(0) do
local lease_line = lease_file:read();
if not string.find(lease_line, client_mac) then leases = leases .. lease_line .. "\n" end
end
lease_file:close()
lease_file = io.open(local_lease_file, "w");
lease_file:write(leases);
lease_file:close();
update_alfred();
elseif command == "init" then
local stdout = io.popen("alfred -r " .. alfred_shared_lease_num,"r");
local raw_output = stdout:read("*a");
stdout:close();
local uci_conf = uci.cursor();
local own_hostname = get_hostname();
local own_ipv4 = uci_conf:get("network", "lan", "ipaddr");
local disposable_mac = get_if_mac("br-lan");
print("999999999 " .. disposable_mac .. " " .. own_ipv4 .. " " .. own_hostname .. " " .. disposable_mac);
if (not raw_output) then exit(0); end
json_output = {};
local lease_table = {};
-------------------------------- { added because alfred doesn't output valid json yet }
assert(loadstring("json_output = {" .. raw_output .. "}"))()
for _, row in ipairs(json_output) do
local node_mac, value = unpack(row)
table.insert(lease_table, value:gsub("\x0a", "\n") .. "\n")
end
print(table.concat(lease_table));
end
|
#!/usr/bin/lua
--[[
Copyright (C) 2013 Gioacchino Mazzurco <[email protected]>
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this file. If not, see <http://www.gnu.org/licenses/>.
]]--
-- PLEASE USE TAB NOT SPACE JUST FOR INDENTATION
--! dhcp lease file lines format
--! <Time of lease expiry, in epoch time (seconds since 1970)> <Client MAC Address> <Client IP> <Client unqualified hostname if provided, * if not provided> <Client-ID, if known. The client-ID is used as the computer's unique-ID in preference to the MAC address, if it's available>
--! root at OpenWrt:~# cat /var/dhcp.leases
--! 946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05
--! 946689351 00:0f:b0:3a:b5:0b 192.168.1.208 colinux *
--! 946689493 02:0f:b0:3a:b5:0b 192.168.1.199 * 01:02:0f:b0:3a:b5:0b
require("uci");
local local_lease_file = "/tmp/dnsmasq-lease-share-local-lease"
local alfred_shared_lease_num = "65"
local own_lease_lifetime = "600" -- in seconds
local command = arg[1];
local client_mac = arg[2];
--! Tell alfred local dhcp lease changed
function update_alfred()
local lease_file = io.open(local_lease_file, "r+");
local stdin = io.popen("alfred -s " .. alfred_shared_lease_num,"w");
stdin:write(lease_file:read("*all"));
lease_file:close();
stdin:close();
end
function get_hostname()
local hostfile = io.open("/proc/sys/kernel/hostname", "r");
local ret_string = hostfile:read();
hostfile:close();
return ret_string;
end
function get_if_mac(ifname)
local macfile = io.open("/sys/class/net/" .. ifname .. "/address");
local ret_string = macfile:read();
macfile:close();
return ret_string;
end
if command == "add" then
local lease_expiration = os.getenv("DNSMASQ_LEASE_EXPIRES");
local client_ip = arg[3];
local client_hostname;
if (arg[4] and (arg[4]:len() > 0)) then client_hostname = arg[4] else client_hostname = "*" end;
local client_id = os.getenv("DNSMASQ_CLIENT_ID");
if ((not client_id) or (client_id:len() <= 0)) then client_id = client_mac end;
local lease_line = lease_expiration .. " " .. client_mac .. " " .. client_ip .. " " .. client_hostname .. " " .. client_id .. "\n";
local lease_file = io.open(local_lease_file, "a");
lease_file:write(lease_line);
lease_file:close();
update_alfred()
elseif command == "del" then
local leases = "";
local lease_file = io.open(local_lease_file, "r");
while lease_file:read(0) do
local lease_line = lease_file:read();
if not string.find(lease_line, client_mac) then leases = leases .. lease_line .. "\n" end
end
lease_file:close()
lease_file = io.open(local_lease_file, "w");
lease_file:write(leases);
lease_file:close();
update_alfred();
elseif command == "init" then
local stdout = io.popen("alfred -r " .. alfred_shared_lease_num,"r");
local raw_output = stdout:read("*a");
stdout:close();
local uci_conf = uci.cursor();
local own_hostname = get_hostname();
local own_ipv4 = uci_conf:get("network", "lan", "ipaddr");
local disposable_mac = get_if_mac("br-lan");
print(os.time()+own_lease_lifetime .. " " .. disposable_mac .. " " .. own_ipv4 .. " " .. own_hostname .. " " .. disposable_mac);
if (not raw_output) then exit(0); end
json_output = {};
local lease_table = {};
-------------------------------- { added because alfred doesn't output valid json yet }
assert(loadstring("json_output = {" .. raw_output .. "}"))()
for _, row in ipairs(json_output) do
local node_mac, value = unpack(row)
table.insert(lease_table, value:gsub("\x0a", "\n") .. "\n")
end
print(table.concat(lease_table));
end
|
own lease had an expiry time in the past, fix that and set it to 10 minutes in the future
|
own lease had an expiry time in the past, fix that and set it to 10 minutes in the future
|
Lua
|
agpl-3.0
|
p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages
|
085c778b4cbc15c075fa4a81fd01a3f1d877744c
|
lib/resty/auto-ssl/storage_adapters/redis.lua
|
lib/resty/auto-ssl/storage_adapters/redis.lua
|
local redis = require "resty.redis"
local _M = {}
local function prefixed_key(self, key)
if self.options["prefix"] then
return self.options["prefix"] .. ":" .. key
else
return key
end
end
function _M.new(auto_ssl_instance)
local options = auto_ssl_instance:get("redis") or {}
if not options["host"] then
options["host"] = "127.0.0.1"
end
if not options["port"] then
options["port"] = 6379
end
return setmetatable({ options = options }, { __index = _M })
end
function _M.get_connection(self)
local connection = ngx.ctx.auto_ssl_redis_connection
if connection then
return connection
end
connection = redis:new()
local ok, err
if self.options["socket"] then
ok, err = connection:connect(self.options["socket"], self.options["connect_options"])
else
ok, err = connection:connect(self.options["host"], self.options["port"], self.options["connect_options"])
end
if not ok then
return false, err
end
if self.options["auth"] then
ok, err = connection:auth(self.options["auth"])
if not ok then
return false, err
end
end
if self.options["db"] then
ok, err = connection:select(self.options["db"])
if not ok then
return false, err
end
end
ngx.ctx.auto_ssl_redis_connection = connection
return connection
end
function _M.setup()
end
function _M.get(self, key)
local connection, connection_err = self:get_connection()
if connection_err then
return nil, connection_err
end
local res, err = connection:get(prefixed_key(self, key))
if res == ngx.null then
res = nil
end
return res, err
end
function _M.set(self, key, value, options)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
key = prefixed_key(self, key)
local ok, err = connection:set(key, value)
if ok then
if options and options["exptime"] then
local _, expire_err = connection:expire(key, options["exptime"])
if expire_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set expire: ", expire_err)
end
end
end
return ok, err
end
function _M.delete(self, key)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
return connection:del(prefixed_key(self, key))
end
function _M.keys_with_suffix(self, suffix)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
local keys, err = connection:keys(prefixed_key(self, "*" .. suffix))
if keys and self.options["prefix"] then
local unprefixed_keys = {}
-- First character past the prefix and a colon
local offset = string.len(self.options["prefix"]) + 2
for _, key in ipairs(keys) do
local unprefixed = string.sub(key, offset)
table.insert(unprefixed_keys, unprefixed)
end
keys = unprefixed_keys
end
return keys, err
end
return _M
|
local redis = require "resty.redis"
local _M = {}
local function prefixed_key(self, key)
if self.options["prefix"] then
return self.options["prefix"] .. ":" .. key
else
return key
end
end
function _M.new(auto_ssl_instance)
local options = auto_ssl_instance:get("redis") or {}
if not options["host"] then
options["host"] = "127.0.0.1"
end
if not options["port"] then
options["port"] = 6379
end
return setmetatable({ options = options }, { __index = _M })
end
function _M.get_connection(self)
local connection = ngx.ctx.auto_ssl_redis_connection
if connection then
return connection
end
connection = redis:new()
local ok, err
local connect_options = self.options["connect_options"] or {}
if self.options["socket"] then
ok, err = connection:connect(self.options["socket"], connect_options)
else
ok, err = connection:connect(self.options["host"], self.options["port"], connect_options)
end
if not ok then
return false, err
end
if self.options["auth"] then
ok, err = connection:auth(self.options["auth"])
if not ok then
return false, err
end
end
if self.options["db"] then
ok, err = connection:select(self.options["db"])
if not ok then
return false, err
end
end
ngx.ctx.auto_ssl_redis_connection = connection
return connection
end
function _M.setup()
end
function _M.get(self, key)
local connection, connection_err = self:get_connection()
if connection_err then
return nil, connection_err
end
local res, err = connection:get(prefixed_key(self, key))
if res == ngx.null then
res = nil
end
return res, err
end
function _M.set(self, key, value, options)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
key = prefixed_key(self, key)
local ok, err = connection:set(key, value)
if ok then
if options and options["exptime"] then
local _, expire_err = connection:expire(key, options["exptime"])
if expire_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set expire: ", expire_err)
end
end
end
return ok, err
end
function _M.delete(self, key)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
return connection:del(prefixed_key(self, key))
end
function _M.keys_with_suffix(self, suffix)
local connection, connection_err = self:get_connection()
if connection_err then
return false, connection_err
end
local keys, err = connection:keys(prefixed_key(self, "*" .. suffix))
if keys and self.options["prefix"] then
local unprefixed_keys = {}
-- First character past the prefix and a colon
local offset = string.len(self.options["prefix"]) + 2
for _, key in ipairs(keys) do
local unprefixed = string.sub(key, offset)
table.insert(unprefixed_keys, unprefixed)
end
keys = unprefixed_keys
end
return keys, err
end
return _M
|
Fix custom redis connect options in older OpenResty versions.
|
Fix custom redis connect options in older OpenResty versions.
Fix for our OpenResty 1.11.2 tests, where `nil` options seem to cause
issues, but an empty table works as expected.
|
Lua
|
mit
|
GUI/lua-resty-auto-ssl
|
1dcfe0d19a8c47d87b8afbe800abdfb9bdbfed67
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.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.tools.webadmin")
m = Map("olsrd", translate("olsrd", "OLSR Daemon"))
s = m:section(TypedSection, "olsrd", translate("olsrd_general"))
s.dynamic = true
s.anonymous = true
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
debug.optional = true
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
noint.optional = true
s:option(Value, "Pollrate").optional = true
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsrd_olsrd_tcredundancy_0"))
tcr:value("1", translate("olsrd_olsrd_tcredundancy_1"))
tcr:value("2", translate("olsrd_olsrd_tcredundancy_2"))
tcr.optional = true
s:option(Value, "MprCoverage").optional = true
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1"))
lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2"))
lql.optional = true
s:option(Value, "LinkQualityAging").optional = true
lqa = s:option(ListValue, "LinkQualityAlgorithm")
lqa.optional = true
lqa:value("etx_fpm", translate("olsrd_etx_fpm"))
lqa:value("etx_float", translate("olsrd_etx_float"))
lqa:value("etx_ff", translate("olsrd_etx_ff"))
lqa.optional = true
lqfish = s:option(Flag, "LinkQualityFishEye")
lqfish.optional = true
s:option(Value, "LinkQualityWinSize").optional = true
s:option(Value, "LinkQualityDijkstraLimit").optional = true
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
hyst.optional = true
fib = s:option(ListValue, "FIBMetric")
fib.optional = true
fib:value("flat")
fib:value("correct")
fib:value("approx")
fib.optional = true
clrscr = s:option(Flag, "ClearScreen")
clrscr.enabled = "yes"
clrscr.disabled = "no"
clrscr.optional = true
willingness = s:option(ListValue, "Willingness")
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
ign = i:option(Flag, "ignore", "Enable")
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
network = i:option(ListValue, "interface", translate("network"))
luci.tools.webadmin.cbi_add_networks(network)
i:option(Value, "Ip4Broadcast").optional = true
ip6t = i:option(ListValue, "Ip6AddrType")
ip6t:value("", translate("cbi_select"))
ip6t:value("auto")
ip6t:value("site-local")
ip6t:value("unique-local")
ip6t:value("global")
ip6t.optional = true
i:option(Value, "HelloInterval").optional = true
i:option(Value, "HelloValidityTime").optional = true
i:option(Value, "TcInterval").optional = true
i:option(Value, "TcValidityTime").optional = true
i:option(Value, "MidInterval").optional = true
i:option(Value, "MidValidityTime").optional = true
i:option(Value, "HnaInterval").optional = true
i:option(Value, "HnaValidityTime").optional = true
adc = i:option(Flag, "AutoDetectChanges")
adc.enabled = "yes"
adc.disabled = "no"
adc.optional = true
--[[
ipc = m:section(TypedSection, "IpcConnect")
ipc.anonymous = true
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.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.tools.webadmin")
m = Map("olsrd", translate("olsrd", "OLSR Daemon"))
s = m:section(TypedSection, "olsrd", translate("olsrd_general"))
s.dynamic = true
s.anonymous = true
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
debug.optional = true
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
noint.optional = true
s:option(Value, "Pollrate").optional = true
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsrd_olsrd_tcredundancy_0"))
tcr:value("1", translate("olsrd_olsrd_tcredundancy_1"))
tcr:value("2", translate("olsrd_olsrd_tcredundancy_2"))
tcr.optional = true
s:option(Value, "MprCoverage").optional = true
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1"))
lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2"))
lql.optional = true
s:option(Value, "LinkQualityAging").optional = true
lqa = s:option(ListValue, "LinkQualityAlgorithm")
lqa.optional = true
lqa:value("etx_fpm", translate("olsrd_etx_fpm"))
lqa:value("etx_float", translate("olsrd_etx_float"))
lqa:value("etx_ff", translate("olsrd_etx_ff"))
lqa.optional = true
lqfish = s:option(Flag, "LinkQualityFishEye")
lqfish.optional = true
s:option(Value, "LinkQualityWinSize").optional = true
s:option(Value, "LinkQualityDijkstraLimit").optional = true
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
hyst.optional = true
fib = s:option(ListValue, "FIBMetric")
fib.optional = true
fib:value("flat")
fib:value("correct")
fib:value("approx")
fib.optional = true
clrscr = s:option(Flag, "ClearScreen")
clrscr.enabled = "yes"
clrscr.disabled = "no"
clrscr.optional = true
willingness = s:option(ListValue, "Willingness")
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
ign = i:option(Flag, "ignore", "Enable")
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
network = i:option(ListValue, "interface", translate("network"))
luci.tools.webadmin.cbi_add_networks(network)
i:option(Value, "Ip4Broadcast").optional = true
ip6t = i:option(ListValue, "Ip6AddrType")
ip6t:value("", translate("cbi_select"))
ip6t:value("auto")
ip6t:value("site-local")
ip6t:value("unique-local")
ip6t:value("global")
ip6t.optional = true
i:option(Value, "HelloInterval").optional = true
i:option(Value, "HelloValidityTime").optional = true
i:option(Value, "TcInterval").optional = true
i:option(Value, "TcValidityTime").optional = true
i:option(Value, "MidInterval").optional = true
i:option(Value, "MidValidityTime").optional = true
i:option(Value, "HnaInterval").optional = true
i:option(Value, "HnaValidityTime").optional = true
adc = i:option(Flag, "AutoDetectChanges")
adc.enabled = "yes"
adc.disabled = "no"
adc.optional = true
--[[
ipc = m:section(TypedSection, "IpcConnect")
ipc.anonymous = true
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
]]
return m
|
[applications] luci-olsr: Fix enable option for interfaces
|
[applications] luci-olsr: Fix enable option for interfaces
|
Lua
|
apache-2.0
|
aa65535/luci,oneru/luci,keyidadi/luci,openwrt/luci,opentechinstitute/luci,marcel-sch/luci,Hostle/luci,mumuqz/luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,palmettos/test,palmettos/cnLuCI,slayerrensky/luci,oyido/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,wongsyrone/luci-1,Noltari/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,mumuqz/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,urueedi/luci,nwf/openwrt-luci,tcatm/luci,david-xiao/luci,schidler/ionic-luci,forward619/luci,rogerpueyo/luci,hnyman/luci,Wedmer/luci,rogerpueyo/luci,slayerrensky/luci,sujeet14108/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,aa65535/luci,dismantl/luci-0.12,thesabbir/luci,oyido/luci,dwmw2/luci,Noltari/luci,male-puppies/luci,openwrt/luci,palmettos/cnLuCI,nmav/luci,cshore/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,MinFu/luci,Wedmer/luci,marcel-sch/luci,tcatm/luci,Wedmer/luci,slayerrensky/luci,taiha/luci,jchuang1977/luci-1,sujeet14108/luci,Hostle/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,bright-things/ionic-luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,Kyklas/luci-proto-hso,cshore/luci,LuttyYang/luci,NeoRaider/luci,MinFu/luci,harveyhu2012/luci,sujeet14108/luci,slayerrensky/luci,thess/OpenWrt-luci,male-puppies/luci,Kyklas/luci-proto-hso,artynet/luci,oyido/luci,kuoruan/lede-luci,tcatm/luci,jchuang1977/luci-1,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,keyidadi/luci,cshore/luci,bright-things/ionic-luci,zhaoxx063/luci,deepak78/new-luci,bittorf/luci,lbthomsen/openwrt-luci,MinFu/luci,Noltari/luci,palmettos/test,deepak78/new-luci,oyido/luci,obsy/luci,lbthomsen/openwrt-luci,schidler/ionic-luci,Kyklas/luci-proto-hso,nmav/luci,thess/OpenWrt-luci,male-puppies/luci,wongsyrone/luci-1,nwf/openwrt-luci,jorgifumi/luci,urueedi/luci,dismantl/luci-0.12,artynet/luci,bittorf/luci,tobiaswaldvogel/luci,fkooman/luci,aa65535/luci,shangjiyu/luci-with-extra,kuoruan/luci,chris5560/openwrt-luci,cshore/luci,chris5560/openwrt-luci,artynet/luci,ollie27/openwrt_luci,david-xiao/luci,chris5560/openwrt-luci,Wedmer/luci,Hostle/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,MinFu/luci,NeoRaider/luci,lcf258/openwrtcn,opentechinstitute/luci,jchuang1977/luci-1,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,tcatm/luci,lbthomsen/openwrt-luci,nmav/luci,remakeelectric/luci,thess/OpenWrt-luci,artynet/luci,schidler/ionic-luci,bittorf/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,dismantl/luci-0.12,thess/OpenWrt-luci,aa65535/luci,lcf258/openwrtcn,MinFu/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,oneru/luci,daofeng2015/luci,maxrio/luci981213,kuoruan/luci,oneru/luci,dwmw2/luci,dwmw2/luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,teslamint/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,joaofvieira/luci,RuiChen1113/luci,thess/OpenWrt-luci,openwrt/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,aa65535/luci,remakeelectric/luci,harveyhu2012/luci,schidler/ionic-luci,obsy/luci,bright-things/ionic-luci,keyidadi/luci,LuttyYang/luci,kuoruan/lede-luci,david-xiao/luci,ff94315/luci-1,openwrt-es/openwrt-luci,zhaoxx063/luci,forward619/luci,Sakura-Winkey/LuCI,thesabbir/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,nmav/luci,lcf258/openwrtcn,joaofvieira/luci,maxrio/luci981213,oneru/luci,taiha/luci,wongsyrone/luci-1,MinFu/luci,remakeelectric/luci,mumuqz/luci,marcel-sch/luci,schidler/ionic-luci,nmav/luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,jlopenwrtluci/luci,rogerpueyo/luci,wongsyrone/luci-1,florian-shellfire/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,ff94315/luci-1,opentechinstitute/luci,palmettos/cnLuCI,tcatm/luci,tobiaswaldvogel/luci,981213/luci-1,fkooman/luci,openwrt-es/openwrt-luci,mumuqz/luci,rogerpueyo/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,lbthomsen/openwrt-luci,fkooman/luci,taiha/luci,LuttyYang/luci,remakeelectric/luci,aa65535/luci,artynet/luci,fkooman/luci,obsy/luci,teslamint/luci,wongsyrone/luci-1,RuiChen1113/luci,RuiChen1113/luci,artynet/luci,jorgifumi/luci,obsy/luci,zhaoxx063/luci,joaofvieira/luci,hnyman/luci,rogerpueyo/luci,palmettos/test,jlopenwrtluci/luci,nmav/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,keyidadi/luci,thesabbir/luci,fkooman/luci,LuttyYang/luci,openwrt-es/openwrt-luci,NeoRaider/luci,ff94315/luci-1,wongsyrone/luci-1,cshore/luci,RuiChen1113/luci,kuoruan/luci,kuoruan/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,bittorf/luci,palmettos/cnLuCI,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,daofeng2015/luci,cshore/luci,david-xiao/luci,Hostle/luci,oneru/luci,Noltari/luci,maxrio/luci981213,NeoRaider/luci,sujeet14108/luci,bittorf/luci,lbthomsen/openwrt-luci,Wedmer/luci,deepak78/new-luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,kuoruan/luci,tobiaswaldvogel/luci,981213/luci-1,urueedi/luci,cappiewu/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,981213/luci-1,bright-things/ionic-luci,kuoruan/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,dismantl/luci-0.12,Noltari/luci,fkooman/luci,male-puppies/luci,nwf/openwrt-luci,sujeet14108/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,shangjiyu/luci-with-extra,kuoruan/luci,maxrio/luci981213,ff94315/luci-1,schidler/ionic-luci,dwmw2/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,shangjiyu/luci-with-extra,jorgifumi/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,mumuqz/luci,cappiewu/luci,thesabbir/luci,obsy/luci,florian-shellfire/luci,joaofvieira/luci,hnyman/luci,joaofvieira/luci,Sakura-Winkey/LuCI,marcel-sch/luci,oyido/luci,NeoRaider/luci,deepak78/new-luci,marcel-sch/luci,tcatm/luci,david-xiao/luci,ff94315/luci-1,joaofvieira/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,oyido/luci,urueedi/luci,Sakura-Winkey/LuCI,harveyhu2012/luci,Wedmer/luci,palmettos/cnLuCI,keyidadi/luci,jchuang1977/luci-1,oneru/luci,lcf258/openwrtcn,florian-shellfire/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,cappiewu/luci,nmav/luci,981213/luci-1,rogerpueyo/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,remakeelectric/luci,taiha/luci,jchuang1977/luci-1,daofeng2015/luci,jorgifumi/luci,forward619/luci,maxrio/luci981213,mumuqz/luci,chris5560/openwrt-luci,thess/OpenWrt-luci,shangjiyu/luci-with-extra,forward619/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,Hostle/luci,nwf/openwrt-luci,urueedi/luci,jlopenwrtluci/luci,opentechinstitute/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,cappiewu/luci,kuoruan/lede-luci,deepak78/new-luci,cappiewu/luci,ollie27/openwrt_luci,palmettos/test,keyidadi/luci,kuoruan/lede-luci,LuttyYang/luci,Sakura-Winkey/LuCI,forward619/luci,jchuang1977/luci-1,chris5560/openwrt-luci,ollie27/openwrt_luci,david-xiao/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,hnyman/luci,NeoRaider/luci,RuiChen1113/luci,fkooman/luci,openwrt/luci,zhaoxx063/luci,hnyman/luci,Noltari/luci,taiha/luci,RuiChen1113/luci,openwrt/luci,cshore/luci,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,marcel-sch/luci,NeoRaider/luci,thesabbir/luci,teslamint/luci,fkooman/luci,marcel-sch/luci,remakeelectric/luci,NeoRaider/luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,urueedi/luci,forward619/luci,Hostle/luci,schidler/ionic-luci,keyidadi/luci,deepak78/new-luci,oyido/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,teslamint/luci,daofeng2015/luci,cappiewu/luci,cshore/luci,taiha/luci,daofeng2015/luci,teslamint/luci,nwf/openwrt-luci,lcf258/openwrtcn,LuttyYang/luci,Hostle/luci,lcf258/openwrtcn,jorgifumi/luci,bittorf/luci,ollie27/openwrt_luci,palmettos/cnLuCI,981213/luci-1,sujeet14108/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,bittorf/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,Hostle/luci,remakeelectric/luci,forward619/luci,lcf258/openwrtcn,lcf258/openwrtcn,slayerrensky/luci,wongsyrone/luci-1,nmav/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,palmettos/test,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,slayerrensky/luci,wongsyrone/luci-1,ff94315/luci-1,bright-things/ionic-luci,maxrio/luci981213,maxrio/luci981213,zhaoxx063/luci,florian-shellfire/luci,florian-shellfire/luci,thesabbir/luci,sujeet14108/luci,slayerrensky/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,cappiewu/luci,obsy/luci,cshore-firmware/openwrt-luci,openwrt/luci,taiha/luci,remakeelectric/luci,rogerpueyo/luci,nwf/openwrt-luci,joaofvieira/luci,male-puppies/luci,lbthomsen/openwrt-luci,Noltari/luci,opentechinstitute/luci,harveyhu2012/luci,dismantl/luci-0.12,obsy/luci,RuiChen1113/luci,kuoruan/luci,harveyhu2012/luci,obsy/luci,david-xiao/luci,nwf/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,Noltari/luci,RedSnake64/openwrt-luci-packages,artynet/luci,cshore-firmware/openwrt-luci,dwmw2/luci,taiha/luci,urueedi/luci,tcatm/luci,deepak78/new-luci,dismantl/luci-0.12,palmettos/test,thess/OpenWrt-luci,dwmw2/luci,artynet/luci,chris5560/openwrt-luci,hnyman/luci,hnyman/luci,Wedmer/luci,palmettos/test,hnyman/luci,teslamint/luci,Kyklas/luci-proto-hso,deepak78/new-luci,oyido/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,ollie27/openwrt_luci,teslamint/luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,chris5560/openwrt-luci,mumuqz/luci,bright-things/ionic-luci,florian-shellfire/luci,david-xiao/luci,Sakura-Winkey/LuCI,openwrt/luci,opentechinstitute/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,slayerrensky/luci,joaofvieira/luci,thesabbir/luci,oneru/luci
|
60d91b48c93059ca68e06decabd7e02cc36b88d6
|
kong/cmd/utils/migrations.lua
|
kong/cmd/utils/migrations.lua
|
local log = require "kong.cmd.utils.log"
local MIGRATIONS_MUTEX_KEY = "migrations"
local NOT_LEADER_MSG = "aborted: another node is performing database changes"
local NEEDS_BOOTSTRAP_MSG = "Database needs bootstrapping or is older than Kong 1.0.\n\n" ..
"To start a new installation from scratch, run 'kong migrations bootstrap'.\n\n" ..
"To migrate from a version older than 1.0, migrated to Kong 1.5.0 first. \n" ..
"If you still have 'apis' entities, you can convert them to Routes and Services\n" ..
"using the 'kong migrations migrate-apis' command in Kong 1.5.0.\n\n"
local function check_state(schema_state)
if not schema_state:is_up_to_date() then
if schema_state.needs_bootstrap then
error(NEEDS_BOOTSTRAP_MSG)
end
if schema_state.new_migrations then
error("New migrations available; run 'kong migrations up' to proceed")
end
end
end
local function bootstrap(schema_state, db, ttl)
if schema_state.needs_bootstrap then
log("Bootstrapping database...")
assert(db:schema_bootstrap())
else
log("Database already bootstrapped")
return
end
local opts = {
ttl = ttl,
no_wait = true, -- exit the mutex if another node acquired it
}
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
assert(db:run_migrations(schema_state.new_migrations, {
run_up = true,
run_teardown = true,
}))
log("Database is up-to-date")
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
end
local function up(schema_state, db, opts)
if schema_state.needs_bootstrap then
-- fresh install: must bootstrap (which will run migrations up)
error("Cannot run migrations: " .. NEEDS_BOOTSTRAP_MSG)
end
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
schema_state = assert(db:schema_state())
if not opts.force and schema_state.pending_migrations then
error("Database has pending migrations; run 'kong migrations finish'")
end
if opts.force and schema_state.executed_migrations then
log.debug("forcing re-execution of these migrations:\n%s",
schema_state.executed_migrations)
assert(db:run_migrations(schema_state.executed_migrations, {
run_up = true,
run_teardown = true,
skip_teardown_migrations = schema_state.pending_migrations
}))
schema_state = assert(db:schema_state())
if schema_state.pending_migrations then
log("\nDatabase has pending migrations; run 'kong migrations finish' when ready")
return
end
end
if not schema_state.new_migrations then
if not opts.force then
log("Database is already up-to-date")
end
return
end
log.debug("migrations to run:\n%s", schema_state.new_migrations)
assert(db:run_migrations(schema_state.new_migrations, {
run_up = true,
}))
schema_state = assert(db:schema_state())
if schema_state.pending_migrations then
log("\nDatabase has pending migrations; run 'kong migrations finish' when ready")
return
end
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
return ok
end
local function finish(schema_state, db, opts)
if schema_state.needs_bootstrap then
error("Cannot run migrations: " .. NEEDS_BOOTSTRAP_MSG)
end
opts.no_wait = true -- exit the mutex if another node acquired it
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
local schema_state = assert(db:schema_state())
if opts.force and schema_state.executed_migrations then
assert(db:run_migrations(schema_state.executed_migrations, {
run_up = true,
run_teardown = true,
}))
schema_state = assert(db:schema_state())
end
if schema_state.pending_migrations then
log.debug("pending migrations to finish:\n%s",
schema_state.pending_migrations)
assert(db:run_migrations(schema_state.pending_migrations, {
run_teardown = true,
}))
schema_state = assert(db:schema_state())
end
if schema_state.new_migrations then
log("\nNew migrations available; run 'kong migrations up' to proceed")
return
end
if not opts.force and not schema_state.pending_migrations then
log("No pending migrations to finish")
end
return
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
end
local function reset(schema_state, db, ttl)
if schema_state.needs_bootstrap then
log("Database not bootstrapped, nothing to reset")
return false
end
local opts = {
ttl = ttl,
no_wait = true,
no_cleanup = true,
}
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
log("Resetting database...")
assert(db:schema_reset())
log("Database successfully reset")
end)
if err then
-- failed to acquire locks - maybe locks table was dropped?
log.error(err .. " - retrying without cluster lock")
log("Resetting database...")
assert(db:schema_reset())
log("Database successfully reset")
return true
end
if not ok then
log(NOT_LEADER_MSG)
return false
end
return true
end
return {
up = up,
reset = reset,
finish = finish,
bootstrap = bootstrap,
check_state = check_state,
NEEDS_BOOTSTRAP_MSG = NEEDS_BOOTSTRAP_MSG,
}
|
local log = require "kong.cmd.utils.log"
local MIGRATIONS_MUTEX_KEY = "migrations"
local NOT_LEADER_MSG = "aborted: another node is performing database changes"
local NEEDS_BOOTSTRAP_MSG = "Database needs bootstrapping or is older than Kong 1.0.\n\n" ..
"To start a new installation from scratch, run 'kong migrations bootstrap'.\n\n" ..
"To migrate from a version older than 1.0, migrated to Kong 1.5.0 first. \n" ..
"If you still have 'apis' entities, you can convert them to Routes and Services\n" ..
"using the 'kong migrations migrate-apis' command in Kong 1.5.0.\n\n"
local function check_state(schema_state)
if not schema_state:is_up_to_date() then
if schema_state.needs_bootstrap then
error(NEEDS_BOOTSTRAP_MSG)
end
if schema_state.new_migrations then
error("New migrations available; run 'kong migrations up' to proceed")
end
end
end
local function bootstrap(schema_state, db, ttl)
if schema_state.needs_bootstrap then
log("Bootstrapping database...")
assert(db:schema_bootstrap())
else
log("Database already bootstrapped")
return
end
local opts = {
ttl = ttl,
no_wait = true, -- exit the mutex if another node acquired it
}
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
assert(db:run_migrations(schema_state.new_migrations, {
run_up = true,
run_teardown = true,
}))
log("Database is up-to-date")
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
end
local function up(schema_state, db, opts)
if schema_state.needs_bootstrap then
-- fresh install: must bootstrap (which will run migrations up)
error("Cannot run migrations: " .. NEEDS_BOOTSTRAP_MSG)
end
-- see #6105 for background, this is a workaround that gives a better
-- error message (one w/o the long stacktrace) when the pending
-- migration checks failed
if not opts.force and schema_state.pending_migrations then
error("Database has pending migrations; run 'kong migrations finish'")
end
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
schema_state = assert(db:schema_state())
if not opts.force and schema_state.pending_migrations then
error("Database has pending migrations; run 'kong migrations finish'")
end
if opts.force and schema_state.executed_migrations then
log.debug("forcing re-execution of these migrations:\n%s",
schema_state.executed_migrations)
assert(db:run_migrations(schema_state.executed_migrations, {
run_up = true,
run_teardown = true,
skip_teardown_migrations = schema_state.pending_migrations
}))
schema_state = assert(db:schema_state())
if schema_state.pending_migrations then
log("\nDatabase has pending migrations; run 'kong migrations finish' when ready")
return
end
end
if not schema_state.new_migrations then
if not opts.force then
log("Database is already up-to-date")
end
return
end
log.debug("migrations to run:\n%s", schema_state.new_migrations)
assert(db:run_migrations(schema_state.new_migrations, {
run_up = true,
}))
schema_state = assert(db:schema_state())
if schema_state.pending_migrations then
log("\nDatabase has pending migrations; run 'kong migrations finish' when ready")
return
end
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
return ok
end
local function finish(schema_state, db, opts)
if schema_state.needs_bootstrap then
error("Cannot run migrations: " .. NEEDS_BOOTSTRAP_MSG)
end
opts.no_wait = true -- exit the mutex if another node acquired it
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
local schema_state = assert(db:schema_state())
if opts.force and schema_state.executed_migrations then
assert(db:run_migrations(schema_state.executed_migrations, {
run_up = true,
run_teardown = true,
}))
schema_state = assert(db:schema_state())
end
if schema_state.pending_migrations then
log.debug("pending migrations to finish:\n%s",
schema_state.pending_migrations)
assert(db:run_migrations(schema_state.pending_migrations, {
run_teardown = true,
}))
schema_state = assert(db:schema_state())
end
if schema_state.new_migrations then
log("\nNew migrations available; run 'kong migrations up' to proceed")
return
end
if not opts.force and not schema_state.pending_migrations then
log("No pending migrations to finish")
end
return
end)
if err then
error(err)
end
if not ok then
log(NOT_LEADER_MSG)
end
end
local function reset(schema_state, db, ttl)
if schema_state.needs_bootstrap then
log("Database not bootstrapped, nothing to reset")
return false
end
local opts = {
ttl = ttl,
no_wait = true,
no_cleanup = true,
}
local ok, err = db:cluster_mutex(MIGRATIONS_MUTEX_KEY, opts, function()
log("Resetting database...")
assert(db:schema_reset())
log("Database successfully reset")
end)
if err then
-- failed to acquire locks - maybe locks table was dropped?
log.error(err .. " - retrying without cluster lock")
log("Resetting database...")
assert(db:schema_reset())
log("Database successfully reset")
return true
end
if not ok then
log(NOT_LEADER_MSG)
return false
end
return true
end
return {
up = up,
reset = reset,
finish = finish,
bootstrap = bootstrap,
check_state = check_state,
NEEDS_BOOTSTRAP_MSG = NEEDS_BOOTSTRAP_MSG,
}
|
fix(cli) do not print out stacktraces when running `kong migrations up` with pending migrations
|
fix(cli) do not print out stacktraces when running `kong migrations up` with pending migrations
Fixes #6105 reported by @jeremyjpj0916. The stacktrace is not necessary as it is not a real error, but just a way for us to get out of the cluster mutex callback.
In the future we may want to allow cluster mutex to handle error messages more gracefully, but for now this change is sufficient without significant modification to the cluster mutex helper.
Before this commit:
```
$ kong migrations up
Error: [PostgreSQL error] cluster_mutex callback threw an error: kong/cmd/utils/migrations.lua:67: Database has pending migrations; run 'kong migrations finish'
stack traceback:
[C]: in function 'error'
kong/cmd/utils/migrations.lua:67: in function <kong/cmd/utils/migrations.lua:63>
[C]: in function 'xpcall'
kong/db/init.lua:364: in function <kong/db/init.lua:314>
[C]: in function 'pcall'
kong/concurrency.lua:45: in function 'cluster_mutex'
kong/cmd/utils/migrations.lua:63: in function 'up'
kong/cmd/migrations.lua:177: in function 'cmd_exec'
kong/cmd/init.lua:88: in function <kong/cmd/init.lua:88>
[C]: in function 'xpcall'
kong/cmd/init.lua:88: in function <kong/cmd/init.lua:45>
bin/kong:9: in function 'file_gen'
init_worker_by_lua:47: in function <init_worker_by_lua:45>
[C]: in function 'xpcall'
init_worker_by_lua:54: in function <init_worker_by_lua:52>
Run with --v (verbose) or --vv (debug) for more details
```
After this commit:
```
$ kong migrations up
Error: Database has pending migrations; run 'kong migrations finish'
Run with --v (verbose) or --vv (debug) for more details
```
Co-authored-by: Datong Sun <[email protected]>
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
1ecc7698aa5861a2a2c4be4cf0f7b0090309eee9
|
game/scripts/vscripts/modules/attributes/attributes.lua
|
game/scripts/vscripts/modules/attributes/attributes.lua
|
ModuleRequire(..., "data")
for propName, propValue in pairs(ATTRIBUTE_LIST) do
if propValue.recalculate == nil then
ModuleLinkLuaModifier(..., "modifier_attribute_" .. propName, "modifiers")
end
end
if not Attributes then
Attributes = class({})
Attributes.Applier = CreateItem("item_dummy", nil, nil)
end
function Attributes:Init()
local gameModeEntity = GameRules:GetGameModeEntity()
for _, v in pairs(ATTRIBUTE_LIST) do
if v.attributeDerivedStat ~= nil then
gameModeEntity:SetCustomAttributeDerivedStatValue(v.attributeDerivedStat, v.default)
end
end
end
function Attributes:SetPropValue(hero, prop, value)
if not hero.attributes_adjustments then hero.attributes_adjustments = {} end
local propValue = ATTRIBUTE_LIST[prop]
if not propValue then error('Not found property named "' .. prop .. '"') end
hero.attributes_adjustments[prop] = value - (propValue.default / (propValue.stack or 1))
end
function Attributes:GetTotalPropValue(arg1, prop)
local hero = type(arg1) == "table" and arg1
local attributeValue = type(arg1) == "number" and arg1
local propValue = ATTRIBUTE_LIST[prop]
if not propValue then error('Not found property named "' .. prop .. '"') end
if not attributeValue then
attributeValue = hero:GetAttribute(propValue.attribute)
end
local adjustment = Attributes:GetAdjustmentForProp(hero, prop)
local perPoint = adjustment + (propValue.default / (propValue.stack or 1))
return attributeValue * perPoint
end
function Attributes:GetAdjustmentForProp(hero, prop)
if hero and hero.attributes_adjustments and hero.attributes_adjustments[prop] then
return hero.attributes_adjustments[prop]
end
return 0
end
function Attributes:CheckAttributeModifier(hero, modifier)
if not hero:HasModifier(modifier) then
hero:AddNewModifier(hero, self.Applier, modifier, nil)
end
end
|
ModuleRequire(..., "data")
for propName, propValue in pairs(ATTRIBUTE_LIST) do
if propValue.recalculate == nil then
ModuleLinkLuaModifier(..., "modifier_attribute_" .. propName, "modifiers")
end
end
if not Attributes then
Attributes = class({})
Attributes.Applier = CreateItem("item_dummy", nil, nil)
end
function Attributes:Init()
local gameModeEntity = GameRules:GetGameModeEntity()
for _, v in pairs(ATTRIBUTE_LIST) do
if v.attributeDerivedStat ~= nil then
gameModeEntity:SetCustomAttributeDerivedStatValue(v.attributeDerivedStat, v.default)
end
end
end
function Attributes:SetPropValue(hero, prop, value)
if not hero.attributes_adjustments then hero.attributes_adjustments = {} end
local propValue = ATTRIBUTE_LIST[prop]
if not propValue then error('Not found property named "' .. prop .. '"') end
hero.attributes_adjustments[prop] = value - propValue.default
end
function Attributes:GetTotalPropValue(arg1, prop)
local hero = type(arg1) == "table" and arg1
local attributeValue = type(arg1) == "number" and arg1
local propValue = ATTRIBUTE_LIST[prop]
if not propValue then error('Not found property named "' .. prop .. '"') end
if not attributeValue then
attributeValue = hero:GetAttribute(propValue.attribute)
end
local adjustment = Attributes:GetAdjustmentForProp(hero, prop)
local perPoint = adjustment + propValue.default
return attributeValue * perPoint
end
function Attributes:GetAdjustmentForProp(hero, prop)
if hero and hero.attributes_adjustments and hero.attributes_adjustments[prop] then
return hero.attributes_adjustments[prop]
end
return 0
end
function Attributes:CheckAttributeModifier(hero, modifier)
if not hero:HasModifier(modifier) then
hero:AddNewModifier(hero, self.Applier, modifier, nil)
end
end
|
fix(attributes): GetTotalPropValue returns amount of stacks instead of actual number
|
fix(attributes): GetTotalPropValue returns amount of stacks instead of actual number
Also fixes wrong before-spell amplify damage calculation
|
Lua
|
mit
|
ark120202/aabs
|
bba06d7d7e88d37ea8d8e5dfe84b61a80f1b0579
|
lua/entities/gmod_wire_expression2/core/custom/wiring.lua
|
lua/entities/gmod_wire_expression2/core/custom/wiring.lua
|
-- Originally by Jeremydeath, updated by Nebual + Natrim's wirelink
E2Lib.RegisterExtension("wiring", false)
__e2setcost(30)
--- Creates an invisible wire between the input <inputname> of <this> and the output <outputname> of <ent2>
e2function number entity:createWire(entity ent2, string inputname, string outputname)
if not IsValid(this) or not IsValid(ent2) then return 0 end
if not isOwner(self, this) or not isOwner(self, ent2) then return 0 end
if not this.Inputs or not ent2.Outputs then return 0 end
if inputname == "" or outputname == "" then return 0 end
if not this.Inputs[inputname] or not ent2.Outputs[outputname] then return 0 end
if this.Inputs[inputname].Src then
local CheckInput = this.Inputs[inputname]
if CheckInput.SrcId == outputname and CheckInput.Src == ent2 then return 0 end -- Already wired
end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire creation doesn't execute the E2 immediately because an input changed
Wire_Link_Start(self.player:UniqueID(), this, this:WorldToLocal(this:GetPos()), inputname, "cable/rope", Vector(255,255,255), 0)
Wire_Link_End(self.player:UniqueID(), ent2, ent2:WorldToLocal(ent2:GetPos()), outputname, self.player)
self.entity.trigger = trigger
return 1
end
local ValidWireMat = {"cable/rope", "cable/cable2", "cable/xbeam", "cable/redlaser", "cable/blue_elec", "cable/physbeam", "cable/hydra", "arrowire/arrowire", "arrowire/arrowire2"}
--- Creates a wire between the input <input> of <this> and the output <outputname> of <ent2>, using the <width>, <color>, <mat>
e2function number entity:createWire(entity ent2, string inputname, string outputname, width, vector color, string mat)
if not IsValid(this) or not IsValid(ent2) then return 0 end
if not isOwner(self, this) or not isOwner(self, ent2) then return 0 end
if not this.Inputs or not ent2.Outputs then return 0 end
if inputname == "" or outputname == "" then return 0 end
if not this.Inputs[inputname] or not ent2.Outputs[outputname] then return 0 end
if this.Inputs[inputname].Src then
local CheckInput = this.Inputs[inputname]
if CheckInput.SrcId == outputname and CheckInput.Src == ent2 then return 0 end -- Already wired
end
if(!table.HasValue(ValidWireMat,mat)) then
if(table.HasValue(ValidWireMat,"cable/"..mat)) then
mat = "cable/"..mat
elseif(table.HasValue(ValidWireMat,"arrowire/"..mat)) then
mat = "arrowire/"..mat
else
return 0
end
end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire creation doesn't execute the E2 immediately because an input changed
Wire_Link_Start(self.player:UniqueID(), this, this:WorldToLocal(this:GetPos()), input, mat, Vector(color[1],color[2],color[3]), width or 1)
Wire_Link_End(self.player:UniqueID(), ent2, ent2:WorldToLocal(ent2:GetPos()), outputname, self.player)
self.entity.trigger = trigger
return 1
end
--- Deletes wire leading to <this>'s input <input>
e2function number entity:deleteWire(string inputname)
if not IsValid(this) or not isOwner(self, this) or inputname == "" then return 0 end
if not this.Inputs or not this.Inputs[inputname] or not this.Inputs[inputname].Src then return 0 end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire deletion doesn't execute the E2 immediately because an input zero'd
Wire_Link_Clear(this, inputname)
self.entity.trigger = trigger
return 1
end
__e2setcost(10)
--- Returns an array of <this>'s wire input names
e2function array entity:getWireInputs()
if not IsValid(this) or not isOwner(self, this) or not this.Inputs then return {} end
local ret = {}
for k,v in pairs(this.Inputs) do
if k != "" then
table.insert(ret, k)
end
end
return ret
end
--- Returns an array of <this>'s wire output names
e2function array entity:getWireOutputs()
if not IsValid(this) or not isOwner(self, this) or not this.Outputs then return {} end
local ret = {}
for k,v in pairs(this.Outputs) do
if k != "" then
table.insert(ret, k)
end
end
return ret
end
__e2setcost(25)
--- Returns <this>'s entity wirelink
e2function wirelink entity:wirelink()
if not IsValid(this) then return nil end
if not isOwner(self, this) then return nil end
if not this.IsWire then return nil end -- dont do it on non-wire
if !this.extended then
this.extended = true
RefreshSpecialOutputs(this)
end
return this
end
--- Removes <this>'s entity wirelink
e2function number entity:removeWirelink()
if not IsValid(this) then return 0 end
if not isOwner(self, this) then return 0 end
if not this.IsWire then return 0 end -- dont do it on non-wire
if !this.extended then return 0 end
this.extended = false
RefreshSpecialOutputs(this)
return 1
end
__e2setcost(nil) -- temporary
|
-- Originally by Jeremydeath, updated by Nebual + Natrim's wirelink
E2Lib.RegisterExtension("wiring", false)
__e2setcost(30)
--- Creates an invisible wire between the input <inputname> of <this> and the output <outputname> of <ent2>
e2function number entity:createWire(entity ent2, string inputname, string outputname)
if not IsValid(this) or not IsValid(ent2) then return 0 end
if not isOwner(self, this) or not isOwner(self, ent2) then return 0 end
if not this.Inputs or not ent2.Outputs then return 0 end
if inputname == "" or outputname == "" then return 0 end
if not this.Inputs[inputname] or not ent2.Outputs[outputname] then return 0 end
if this.Inputs[inputname].Src then
local CheckInput = this.Inputs[inputname]
if CheckInput.SrcId == outputname and CheckInput.Src == ent2 then return 0 end -- Already wired
end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire creation doesn't execute the E2 immediately because an input changed
Wire_Link_Start(self.player:UniqueID(), this, this:WorldToLocal(this:GetPos()), inputname, "cable/rope", Vector(255,255,255), 0)
Wire_Link_End(self.player:UniqueID(), ent2, ent2:WorldToLocal(ent2:GetPos()), outputname, self.player)
self.entity.trigger = trigger
return 1
end
local ValidWireMat = {"cable/rope", "cable/cable2", "cable/xbeam", "cable/redlaser", "cable/blue_elec", "cable/physbeam", "cable/hydra", "arrowire/arrowire", "arrowire/arrowire2"}
--- Creates a wire between the input <input> of <this> and the output <outputname> of <ent2>, using the <width>, <color>, <mat>
e2function number entity:createWire(entity ent2, string inputname, string outputname, width, vector color, string mat)
if not IsValid(this) or not IsValid(ent2) then return 0 end
if not isOwner(self, this) or not isOwner(self, ent2) then return 0 end
if not this.Inputs or not ent2.Outputs then return 0 end
if inputname == "" or outputname == "" then return 0 end
if not this.Inputs[inputname] or not ent2.Outputs[outputname] then return 0 end
if this.Inputs[inputname].Src then
local CheckInput = this.Inputs[inputname]
if CheckInput.SrcId == outputname and CheckInput.Src == ent2 then return 0 end -- Already wired
end
if(!table.HasValue(ValidWireMat,mat)) then
if(table.HasValue(ValidWireMat,"cable/"..mat)) then
mat = "cable/"..mat
elseif(table.HasValue(ValidWireMat,"arrowire/"..mat)) then
mat = "arrowire/"..mat
else
return 0
end
end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire creation doesn't execute the E2 immediately because an input changed
Wire_Link_Start(self.player:UniqueID(), this, this:WorldToLocal(this:GetPos()), input, mat, Vector(color[1],color[2],color[3]), width or 1)
Wire_Link_End(self.player:UniqueID(), ent2, ent2:WorldToLocal(ent2:GetPos()), outputname, self.player)
self.entity.trigger = trigger
return 1
end
--- Deletes wire leading to <this>'s input <input>
e2function number entity:deleteWire(string inputname)
if not IsValid(this) or not isOwner(self, this) or inputname == "" then return 0 end
if not this.Inputs or not this.Inputs[inputname] or not this.Inputs[inputname].Src then return 0 end
local trigger = self.entity.trigger
self.entity.trigger = { false, {} } -- So the wire deletion doesn't execute the E2 immediately because an input zero'd
Wire_Link_Clear(this, inputname)
self.entity.trigger = trigger
return 1
end
__e2setcost(10)
--- Returns an array of <this>'s wire input names
e2function array entity:getWireInputs()
if not IsValid(this) or not isOwner(self, this) or not this.Inputs then return {} end
local ret = {}
for k,v in pairs(this.Inputs) do
if k != "" then
table.insert(ret, k)
end
end
return ret
end
--- Returns an array of <this>'s wire output names
e2function array entity:getWireOutputs()
if not IsValid(this) or not isOwner(self, this) or not this.Outputs then return {} end
local ret = {}
for k,v in pairs(this.Outputs) do
if k != "" then
table.insert(ret, k)
end
end
return ret
end
__e2setcost(25)
--- Returns <this>'s entity wirelink
e2function wirelink entity:wirelink()
if not IsValid(this) then return nil end
if not isOwner(self, this) then return nil end
if not this.Inputs and not this.Outputs then return nil end
if !this.extended then
this.extended = true
RefreshSpecialOutputs(this)
end
return this
end
--- Removes <this>'s entity wirelink
e2function number entity:removeWirelink()
if not IsValid(this) then return 0 end
if not isOwner(self, this) then return 0 end
if not this.Inputs and not this.Outputs then return 0 end
if !this.extended then return 0 end
this.extended = false
RefreshSpecialOutputs(this)
return 1
end
__e2setcost(nil)
|
E2: wiring - allow entity:wirelink() on other ENTS
|
E2: wiring - allow entity:wirelink() on other ENTS
that have outputs or inputs
- fixes CAF wirelink problem
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,CaptainPRICE/wire,wiremod/wire,Grocel/wire,Python1320/wire,mms92/wire,rafradek/wire,plinkopenguin/wiremod,bigdogmat/wire,sammyt291/wire,notcake/wire,garrysmodlua/wire,mitterdoo/wire,immibis/wiremod,dvdvideo1234/wire,thegrb93/wire
|
81020e3d088a4058a6e9a6369338a5b256f959bd
|
lua/starfall/libs_sh/hook.lua
|
lua/starfall/libs_sh/hook.lua
|
-------------------------------------------------------------------------------
-- Hook library
-------------------------------------------------------------------------------
--- Deals with hooks
-- @shared
local hook_library, _ = SF.Libraries.Register("hook")
local registered_instances = {}
--- Sets a hook function
function hook_library.add(hookname, name, func)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
if func then SF.CheckType(func,"function") else return end
local inst = SF.instance
local hooks = inst.hooks[hookname:lower()]
if not hooks then
hooks = {}
inst.hooks[hookname:lower()] = hooks
end
hooks[name] = func
registered_instances[inst] = true
end
--- Run a hook
-- @shared
-- @param hookname The hook name
-- @param ... arguments
function hook_library.run(hookname, ...)
SF.CheckType(hookname,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
for k,v in pairs( instance.hooks[lower] ) do
local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v )
if not ok and instance.runOnError then
instance.runOnError( tbl[1] )
hook_library.remove( hookname, k )
elseif next(tbl) ~= nil then
return unpack( tbl )
end
end
end
end
--- Remove a hook
-- @shared
-- @param hookname The hook name
-- @param name The unique name for this hook
function hook_library.remove( hookname, name )
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
instance.hooks[lower][name] = nil
if not next(instance.hooks[lower]) then
instance.hooks[lower] = nil
end
end
if not next(instance.hooks) then
registered_instances[instance] = nil
end
end
SF.Libraries.AddHook("deinitialize",function(instance)
registered_instances[instance] = nil
end)
SF.Libraries.AddHook("cleanup",function(instance)
if instance.error then
registered_instances[instance] = nil
instance.hooks = {}
end
end)
--[[
local blocked_types = {
PhysObj = true,
NPC = true,
}
local function wrap( value )
if type(value) == "table" then
return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} )
elseif blocked_types[type(value)] then
return nil
else
return SF.WrapObject( value ) or value
end
end
-- Helper function for hookAdd
local function wrapArguments( ... )
local t = {...}
return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6])
end
]]
local wrapArguments = SF.Sanitize
--local run = SF.RunScriptHook
local function run( hookname, customfunc, ... )
for instance,_ in pairs( registered_instances ) do
if instance.hooks[hookname] then
for name, func in pairs( instance.hooks[hookname] ) do
local ok, ret = instance:runFunctionT( func, ... )
if ok and customfunc then
return customfunc( instance, ret )
end
end
end
end
end
local hooks = {}
--- Add a GMod hook so that SF gets access to it
-- @shared
-- @param hookname The hook name. In-SF hookname will be lowercased
-- @param customfunc Optional custom function
function SF.hookAdd( hookname, customfunc )
hooks[#hooks+1] = hookname
local lower = hookname:lower()
hook.Add( hookname, "SF_" .. hookname, function(...)
return run( lower, customfunc, wrapArguments( ... ) )
end)
end
--- Gets a list of all available hooks
-- @shared
function hook_library.getList()
return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end})
end
local add = SF.hookAdd
if SERVER then
-- Server hooks
add( "GravGunOnPickedUp" )
add( "GravGunOnDropped" )
add( "OnPhysgunFreeze" )
add( "OnPhysgunReload" )
add( "PlayerDeath" )
add( "PlayerDisconnected" )
add( "PlayerInitialSpawn" )
add( "PlayerSpawn" )
add( "PlayerLeaveVehicle" )
add( "PlayerSay", function( instance, args ) if args then return args[1] end end )
add( "PlayerSpray" )
add( "PlayerUse" )
add( "PlayerSwitchFlashlight" )
else
-- Client hooks
-- todo
end
-- Shared hooks
-- Player hooks
add( "PlayerHurt" )
add( "PlayerNoClip" )
add( "KeyPress" )
add( "KeyRelease" )
add( "GravGunPunt" )
add( "PhysgunPickup" )
add( "PhysgunDrop" )
-- Entity hooks
add( "OnEntityCreated" )
add( "EntityRemoved" )
-- Other
add( "EndEntityDriving" )
add( "StartEntityDriving" )
|
-------------------------------------------------------------------------------
-- Hook library
-------------------------------------------------------------------------------
--- Deals with hooks
-- @shared
local hook_library, _ = SF.Libraries.Register("hook")
local registered_instances = {}
--- Sets a hook function
function hook_library.add(hookname, name, func)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
if func then SF.CheckType(func,"function") else return end
local inst = SF.instance
local hooks = inst.hooks[hookname:lower()]
if not hooks then
hooks = {}
inst.hooks[hookname:lower()] = hooks
end
hooks[name] = func
registered_instances[inst] = true
end
--- Run a hook
-- @shared
-- @param hookname The hook name
-- @param ... arguments
function hook_library.run(hookname, ...)
SF.CheckType(hookname,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
for k,v in pairs( instance.hooks[lower] ) do
local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v )
if not ok and instance.runOnError then
instance.runOnError( tbl[1] )
hook_library.remove( hookname, k )
elseif next(tbl) ~= nil then
return unpack( tbl )
end
end
end
end
--- Remove a hook
-- @shared
-- @param hookname The hook name
-- @param name The unique name for this hook
function hook_library.remove( hookname, name )
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
instance.hooks[lower][name] = nil
if not next(instance.hooks[lower]) then
instance.hooks[lower] = nil
end
end
if not next(instance.hooks) then
registered_instances[instance] = nil
end
end
SF.Libraries.AddHook("deinitialize",function(instance)
registered_instances[instance] = nil
end)
SF.Libraries.AddHook("cleanup",function(instance,name,func,err)
if name == "_runFunction" and err == true then
registered_instances[instance] = nil
instance.hooks = {}
end
end)
--[[
local blocked_types = {
PhysObj = true,
NPC = true,
}
local function wrap( value )
if type(value) == "table" then
return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} )
elseif blocked_types[type(value)] then
return nil
else
return SF.WrapObject( value ) or value
end
end
-- Helper function for hookAdd
local function wrapArguments( ... )
local t = {...}
return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6])
end
]]
local wrapArguments = SF.Sanitize
--local run = SF.RunScriptHook
local function run( hookname, customfunc, ... )
for instance,_ in pairs( registered_instances ) do
if instance.hooks[hookname] then
for name, func in pairs( instance.hooks[hookname] ) do
local ok, ret = instance:runFunctionT( func, ... )
if ok and customfunc then
return customfunc( instance, ret )
end
end
end
end
end
local hooks = {}
--- Add a GMod hook so that SF gets access to it
-- @shared
-- @param hookname The hook name. In-SF hookname will be lowercased
-- @param customfunc Optional custom function
function SF.hookAdd( hookname, customfunc )
hooks[#hooks+1] = hookname
local lower = hookname:lower()
hook.Add( hookname, "SF_" .. hookname, function(...)
return run( lower, customfunc, wrapArguments( ... ) )
end)
end
--- Gets a list of all available hooks
-- @shared
function hook_library.getList()
return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end})
end
local add = SF.hookAdd
if SERVER then
-- Server hooks
add( "GravGunOnPickedUp" )
add( "GravGunOnDropped" )
add( "OnPhysgunFreeze" )
add( "OnPhysgunReload" )
add( "PlayerDeath" )
add( "PlayerDisconnected" )
add( "PlayerInitialSpawn" )
add( "PlayerSpawn" )
add( "PlayerLeaveVehicle" )
add( "PlayerSay", function( instance, args ) if args then return args[1] end end )
add( "PlayerSpray" )
add( "PlayerUse" )
add( "PlayerSwitchFlashlight" )
else
-- Client hooks
-- todo
end
-- Shared hooks
-- Player hooks
add( "PlayerHurt" )
add( "PlayerNoClip" )
add( "KeyPress" )
add( "KeyRelease" )
add( "GravGunPunt" )
add( "PhysgunPickup" )
add( "PhysgunDrop" )
-- Entity hooks
add( "OnEntityCreated" )
add( "EntityRemoved" )
-- Other
add( "EndEntityDriving" )
add( "StartEntityDriving" )
|
working fix for errored starfall chips still calling hooks
|
working fix for errored starfall chips still calling hooks
working fix for errored starfall chips still calling hooks
|
Lua
|
bsd-3-clause
|
Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall
|
346719dd9765647b7334387b1ac657acebc7c874
|
packages/lime-system/files/usr/lib/lua/lime/network.lua
|
packages/lime-system/files/usr/lib/lua/lime/network.lua
|
#!/usr/bin/lua
network = {}
local bit = require "nixio".bit
local ip = require "luci.ip"
local config = require "lime.config"
local utils = require "lime.utils"
function network.get_mac(ifname)
local mac = assert(fs.readfile("/sys/class/net/"..ifname.."/address")):gsub("\n","")
return utils.split(mac, ":")
end
function network.primary_interface()
return config:get("network", "primary_interface")
end
function network.primary_mac()
return network.get_mac(network.primary_interface())
end
function network.primary_address()
local ipv4_template = config:get("network", "ipv4_address")
local ipv6_template = config:get("network", "ipv6_address")
local pm = network.primary_mac()
for i=1,6,1 do
ipv6_template = ipv6_template:gsub("M" .. i, pm[i])
ipv4_template = ipv4_template:gsub("M" .. i, tonumber(pm[i], 16))
end
return ip.IPv4(ipv4_template), ip.IPv6(ipv6_template)
end
function network.eui64(mac)
local function flip_7th_bit(x) return utils.hex(bit.bxor(tonumber(x, 16), 2)) end
local t = utils.split(mac, ":")
t[1] = flip_7th_bit(t[1])
return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6])
end
--@DEPRECATED We should implement a proto for this too
function network.setup_lan(ipv4, ipv6)
uci:set("network", "lan", "ip6addr", ipv6:string())
uci:set("network", "lan", "ipaddr", ipv4:host():string())
uci:set("network", "lan", "netmask", ipv4:mask():string())
uci:set("network", "lan", "ifname", "eth0 bat0")
uci:save("network")
end
--@DEPRECATED We should implement a proto for this too
function network.setup_anygw(ipv4, ipv6)
local n1, n2, n3 = network_id()
-- anygw macvlan interface
print("Adding macvlan interface to uci network...")
local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3)
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC
anygw_ipv4[3] = ipv4:prefix()
uci:set("network", "lm_anygw_dev", "device")
uci:set("network", "lm_anygw_dev", "type", "macvlan")
uci:set("network", "lm_anygw_dev", "name", "anygw")
uci:set("network", "lm_anygw_dev", "ifname", "@lan")
uci:set("network", "lm_anygw_dev", "macaddr", anygw_mac)
uci:set("network", "lm_anygw_if", "interface")
uci:set("network", "lm_anygw_if", "proto", "static")
uci:set("network", "lm_anygw_if", "ifname", "anygw")
uci:set("network", "lm_anygw_if", "ip6addr", anygw_ipv6:string())
uci:set("network", "lm_anygw_if", "ipaddr", anygw_ipv4:host():string())
uci:set("network", "lm_anygw_if", "netmask", anygw_ipv4:mask():string())
local content = { insert = table.insert, concat = table.concat }
for line in io.lines("/etc/firewall.user") do
if not line:match("^ebtables ") then content:insert(line) end
end
content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac)
content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac)
fs.writefile("/etc/firewall.user", content:concat("\n").."\n")
-- IPv6 router advertisement for anygw interface
print("Enabling RA in dnsmasq...")
local content = { }
table.insert(content, "enable-ra")
table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string()))
table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan")
table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string()))
table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string()))
table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string()))
table.insert(content, "dhcp-broadcast=tag:anygw")
table.insert(content, "no-dhcp-interface=br-lan")
fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n")
-- and disable 6relayd
print("Disabling 6relayd...")
fs.writefile("/etc/config/6relayd", "")
end
function network.setup_rp_filter()
local sysctl_file_path = "/etc/sysctl.conf";
local sysctl_options = "";
local sysctl_file = io.open(sysctl_file_path, "r");
while sysctl_file:read(0) do
local sysctl_line = sysctl_file:read();
if not string.find(sysctl_line, ".rp_filter") then sysctl_options = sysctl_options .. sysctl_line .. "\n" end
end
sysctl_file:close()
sysctl_options = sysctl_options .. "net.ipv4.conf.default.rp_filter=2\nnet.ipv4.conf.all.rp_filter=2\n";
sysctl_file = io.open(sysctl_file_path, "w");
sysctl_file:write(sysctl_options);
sysctl_file:close();
end
function network.clean()
print("Clearing network config...")
uci:delete("network", "globals", "ula_prefix")
uci:foreach("network", "interface", function(s)
if s[".name"]:match("^lm_") then
uci:delete("network", s[".name"])
end
end)
end
function network.scandevices()
devices = {}
local devList = {}
local devInd = 0
-- Scan for plain ethernet interface
devList = utils.split(io.popen("ls -1 /sys/class/net/"):read("*a"), "\n")
for i=1,#devList do
if devList[i]:match("eth%d") then
devices[devInd] = devList[i]
devInd = devInd + 1
end
end
-- Scan for mac80211 wifi devices
devList = utils.split(io.popen("ls -1 /sys/class/ieee80211/"):read("*a"), "\n")
for i=1,#devList do
if devList[i]:match("phy%d") then
devices[devInd] = devList[i]
devInd = devInd + 1
end
end
-- When we will support other device type just scan for them here
return devices
end
function network.configure()
network.clean()
local protocols = config:get("network", "protocols")
local ipv4, ipv6 = network.primary_address() -- for br-lan
network.setup_rp_filter()
network.setup_lan(ipv4, ipv6)
network.setup_anygw(ipv4, ipv6)
local specificIfaces = {};
config.foreach("net", function(iface) specificIfaces[iface[".name"]] = iface end)
-- Scan for fisical devices, if there is a specific config apply that otherwise apply general config
local fisDev = network.scandevices()
for i=1,#fisDev do
local pif = specificIfaces[fisDev[i]]
if pif then
for j=1,#pif["protocols"] do
local args = utils.split(pif["protocols"][j], ":")
if args[1] == "manual" then break end -- If manual is specified do not configure interface
local proto = require("lime.proto."..args[1])
proto.setup_interface(fisDev[i], args)
end
else
local protos = config.get("net","protocols")
for p=1,#protos do
local args = utils.split(protos[p], ":")
local proto = require("lime.proto."..args[1])
proto.setup_interface(fisDev[i], args)
end
end
end
end
function network.apply()
-- TODO (i.e. /etc/init.d/network restart)
end
function network.init()
-- TODO
end
return network
|
#!/usr/bin/lua
network = {}
local bit = require "nixio".bit
local ip = require "luci.ip"
local config = require "lime.config"
local utils = require "lime.utils"
network.limeIfNamePrefix="lm_"
function network.get_mac(ifname)
local mac = assert(fs.readfile("/sys/class/net/"..ifname.."/address")):gsub("\n","")
return utils.split(mac, ":")
end
function network.primary_interface()
return config:get("network", "primary_interface")
end
function network.primary_mac()
return network.get_mac(network.primary_interface())
end
function network.primary_address()
local ipv4_template = config:get("network", "ipv4_address")
local ipv6_template = config:get("network", "ipv6_address")
local pm = network.primary_mac()
for i=1,6,1 do
ipv6_template = ipv6_template:gsub("M" .. i, pm[i])
ipv4_template = ipv4_template:gsub("M" .. i, tonumber(pm[i], 16))
end
return ip.IPv4(ipv4_template), ip.IPv6(ipv6_template)
end
function network.eui64(mac)
local function flip_7th_bit(x) return utils.hex(bit.bxor(tonumber(x, 16), 2)) end
local t = utils.split(mac, ":")
t[1] = flip_7th_bit(t[1])
return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6])
end
--@DEPRECATED We should implement a proto for this too
function network.setup_lan(ipv4, ipv6)
uci:set("network", "lan", "ip6addr", ipv6:string())
uci:set("network", "lan", "ipaddr", ipv4:host():string())
uci:set("network", "lan", "netmask", ipv4:mask():string())
uci:set("network", "lan", "ifname", "eth0 bat0")
uci:save("network")
end
--@DEPRECATED We should implement a proto for this too
function network.setup_anygw(ipv4, ipv6)
-- anygw macvlan interface
print("Adding macvlan interface to uci network...")
local n1, n2, n3 = network_id()
local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3)
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC
anygw_ipv4[3] = ipv4:prefix()
local pfr = network.limeIfNamePrefix
uci:set("network", pfr.."anygw_dev", "device")
uci:set("network", pfr.."anygw_dev", "type", "macvlan")
uci:set("network", pfr.."anygw_dev", "name", "anygw")
uci:set("network", pfr.."anygw_dev", "ifname", "@lan")
uci:set("network", pfr.."anygw_dev", "macaddr", anygw_mac)
uci:set("network", pfr.."anygw_if", "interface")
uci:set("network", pfr.."anygw_if", "proto", "static")
uci:set("network", pfr.."anygw_if", "ifname", "anygw")
uci:set("network", pfr.."anygw_if", "ip6addr", anygw_ipv6:string())
uci:set("network", pfr.."anygw_if", "ipaddr", anygw_ipv4:host():string())
uci:set("network", pfr.."anygw_if", "netmask", anygw_ipv4:mask():string())
local content = { insert = table.insert, concat = table.concat }
for line in io.lines("/etc/firewall.user") do
if not line:match("^ebtables ") then content:insert(line) end
end
content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac)
content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac)
fs.writefile("/etc/firewall.user", content:concat("\n").."\n")
-- IPv6 router advertisement for anygw interface
print("Enabling RA in dnsmasq...")
local content = { }
table.insert(content, "enable-ra")
table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string()))
table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan")
table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string()))
table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string()))
table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string()))
table.insert(content, "dhcp-broadcast=tag:anygw")
table.insert(content, "no-dhcp-interface=br-lan")
fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n")
-- and disable 6relayd
print("Disabling 6relayd...")
fs.writefile("/etc/config/6relayd", "")
end
function network.setup_rp_filter()
local sysctl_file_path = "/etc/sysctl.conf";
local sysctl_options = "";
local sysctl_file = io.open(sysctl_file_path, "r");
while sysctl_file:read(0) do
local sysctl_line = sysctl_file:read();
if not string.find(sysctl_line, ".rp_filter") then sysctl_options = sysctl_options .. sysctl_line .. "\n" end
end
sysctl_file:close()
sysctl_options = sysctl_options .. "net.ipv4.conf.default.rp_filter=2\nnet.ipv4.conf.all.rp_filter=2\n";
sysctl_file = io.open(sysctl_file_path, "w");
sysctl_file:write(sysctl_options);
sysctl_file:close();
end
function network.clean()
print("Clearing network config...")
uci:delete("network", "globals", "ula_prefix")
-- Delete interfaces generated by LiMe
uci:foreach("network", "interface", function(s) if s[".name"]:match(network.limeIfNamePrefix) then uci:delete("network", s[".name"]) end end)
end
function network.scandevices()
devices = {}
local devList = {}
local devInd = 0
-- Scan for plain ethernet interface
devList = utils.split(io.popen("ls -1 /sys/class/net/"):read("*a"), "\n")
for i=1,#devList do
if devList[i]:match("eth%d") then
devices[devInd] = devList[i]
devInd = devInd + 1
end
end
-- Scan for mac80211 wifi devices
devList = utils.split(io.popen("ls -1 /sys/class/ieee80211/"):read("*a"), "\n")
for i=1,#devList do
if devList[i]:match("phy%d") then
devices[devInd] = devList[i]
devInd = devInd + 1
end
end
-- When we will support other device type just scan for them here
return devices
end
function network.configure()
network.clean()
local protocols = config:get("network", "protocols")
local ipv4, ipv6 = network.primary_address() -- for br-lan
network.setup_rp_filter()
network.setup_lan(ipv4, ipv6)
network.setup_anygw(ipv4, ipv6)
local specificIfaces = {};
config.foreach("net", function(iface) specificIfaces[iface[".name"]] = iface end)
-- Scan for fisical devices, if there is a specific config apply that otherwise apply general config
local fisDev = network.scandevices()
for i=1,#fisDev do
local pif = specificIfaces[fisDev[i]]
if pif then
for j=1,#pif["protocols"] do
local args = utils.split(pif["protocols"][j], ":")
if args[1] == "manual" then break end -- If manual is specified do not configure interface
local proto = require("lime.proto."..args[1])
proto.setup_interface(fisDev[i], args)
end
else
local protos = config.get("net","protocols")
for p=1,#protos do
local args = utils.split(protos[p], ":")
local proto = require("lime.proto."..args[1])
proto.setup_interface(fisDev[i], args)
end
end
end
end
function network.apply()
-- TODO (i.e. /etc/init.d/network restart)
end
function network.init()
-- TODO
end
return network
|
Use network.limeIfNamePrefix instead of repeat lm_ around the code
|
Use network.limeIfNamePrefix instead of repeat lm_ around the code
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages
|
e501f5ed76eb64e8a696cf8a8ca5159b8db9a100
|
module/admin-core/src/model/cbi/admin_index/luci.lua
|
module/admin-core/src/model/cbi/admin_index/luci.lua
|
-- ToDo: Translate, Add descriptions and help texts
m = Map("luci", "FFLuCI")
c = m:section(NamedSection, "main", "core", "Allgemein")
c:option(Value, "lang", "Sprache")
c:option(Value, "mediaurlbase", "Mediaverzeichnis")
f = m:section(NamedSection, "flash", "extern", "Firmwareupgrade")
f:option(Value, "keep", "Übernehme Dateien").size = 64
p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien")
p.dynamic = true
u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden")
u.dynamic = true
return m
|
-- ToDo: Translate, Add descriptions and help texts
m = Map("luci", "FFLuCI")
c = m:section(NamedSection, "main", "core", "Allgemein")
c:option(Value, "lang", "Sprache")
c:option(Value, "mediaurlbase", "Mediaverzeichnis")
f = m:section(NamedSection, "flash_keep", "extern", "Zu übernehmende Dateien bei Firmwareupgrade")
f.dynamic = true
p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien")
p.dynamic = true
u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden")
u.dynamic = true
return m
|
* Fixed changed layout of flash_keep in admin > index
|
* Fixed changed layout of flash_keep in admin > index
|
Lua
|
apache-2.0
|
joaofvieira/luci,lbthomsen/openwrt-luci,tcatm/luci,openwrt-es/openwrt-luci,palmettos/test,NeoRaider/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,slayerrensky/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,david-xiao/luci,hnyman/luci,hnyman/luci,rogerpueyo/luci,oyido/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,kuoruan/luci,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,lcf258/openwrtcn,taiha/luci,dwmw2/luci,bright-things/ionic-luci,dwmw2/luci,keyidadi/luci,maxrio/luci981213,fkooman/luci,male-puppies/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,bittorf/luci,obsy/luci,cshore-firmware/openwrt-luci,oyido/luci,dwmw2/luci,cshore-firmware/openwrt-luci,cappiewu/luci,teslamint/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,bright-things/ionic-luci,taiha/luci,Sakura-Winkey/LuCI,hnyman/luci,kuoruan/luci,ollie27/openwrt_luci,NeoRaider/luci,joaofvieira/luci,palmettos/cnLuCI,marcel-sch/luci,chris5560/openwrt-luci,urueedi/luci,shangjiyu/luci-with-extra,nmav/luci,palmettos/cnLuCI,ff94315/luci-1,maxrio/luci981213,slayerrensky/luci,artynet/luci,thess/OpenWrt-luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,artynet/luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,remakeelectric/luci,daofeng2015/luci,urueedi/luci,schidler/ionic-luci,forward619/luci,981213/luci-1,jorgifumi/luci,nwf/openwrt-luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,male-puppies/luci,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,urueedi/luci,oneru/luci,aa65535/luci,nmav/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,hnyman/luci,fkooman/luci,LuttyYang/luci,openwrt/luci,bright-things/ionic-luci,cshore/luci,kuoruan/lede-luci,rogerpueyo/luci,Noltari/luci,981213/luci-1,male-puppies/luci,bright-things/ionic-luci,nmav/luci,hnyman/luci,cshore/luci,cshore/luci,forward619/luci,chris5560/openwrt-luci,male-puppies/luci,NeoRaider/luci,florian-shellfire/luci,kuoruan/luci,thess/OpenWrt-luci,remakeelectric/luci,palmettos/test,david-xiao/luci,fkooman/luci,openwrt/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,taiha/luci,RuiChen1113/luci,NeoRaider/luci,fkooman/luci,NeoRaider/luci,Kyklas/luci-proto-hso,urueedi/luci,ollie27/openwrt_luci,palmettos/cnLuCI,RuiChen1113/luci,teslamint/luci,zhaoxx063/luci,maxrio/luci981213,deepak78/new-luci,remakeelectric/luci,joaofvieira/luci,mumuqz/luci,thess/OpenWrt-luci,nwf/openwrt-luci,keyidadi/luci,shangjiyu/luci-with-extra,cshore/luci,MinFu/luci,LuttyYang/luci,sujeet14108/luci,palmettos/test,joaofvieira/luci,Wedmer/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,rogerpueyo/luci,openwrt/luci,ff94315/luci-1,981213/luci-1,zhaoxx063/luci,schidler/ionic-luci,slayerrensky/luci,sujeet14108/luci,aa65535/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,marcel-sch/luci,keyidadi/luci,cappiewu/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,daofeng2015/luci,taiha/luci,tobiaswaldvogel/luci,ff94315/luci-1,opentechinstitute/luci,tcatm/luci,bittorf/luci,florian-shellfire/luci,jchuang1977/luci-1,taiha/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,remakeelectric/luci,david-xiao/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,oyido/luci,daofeng2015/luci,openwrt-es/openwrt-luci,teslamint/luci,palmettos/cnLuCI,cappiewu/luci,ff94315/luci-1,tcatm/luci,wongsyrone/luci-1,NeoRaider/luci,harveyhu2012/luci,aa65535/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,dwmw2/luci,Hostle/luci,thesabbir/luci,david-xiao/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,palmettos/test,keyidadi/luci,urueedi/luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,jorgifumi/luci,mumuqz/luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,mumuqz/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,nwf/openwrt-luci,rogerpueyo/luci,ff94315/luci-1,obsy/luci,jorgifumi/luci,aa65535/luci,urueedi/luci,nmav/luci,jlopenwrtluci/luci,cappiewu/luci,obsy/luci,wongsyrone/luci-1,male-puppies/luci,jchuang1977/luci-1,zhaoxx063/luci,Hostle/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,schidler/ionic-luci,jorgifumi/luci,tcatm/luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,cappiewu/luci,jchuang1977/luci-1,oyido/luci,Wedmer/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,mumuqz/luci,palmettos/test,opentechinstitute/luci,artynet/luci,opentechinstitute/luci,deepak78/new-luci,oneru/luci,Wedmer/luci,ollie27/openwrt_luci,teslamint/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,daofeng2015/luci,Noltari/luci,fkooman/luci,deepak78/new-luci,cappiewu/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,sujeet14108/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,zhaoxx063/luci,mumuqz/luci,tcatm/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,bittorf/luci,dwmw2/luci,NeoRaider/luci,dismantl/luci-0.12,sujeet14108/luci,slayerrensky/luci,harveyhu2012/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,NeoRaider/luci,Kyklas/luci-proto-hso,aa65535/luci,hnyman/luci,tobiaswaldvogel/luci,taiha/luci,florian-shellfire/luci,openwrt-es/openwrt-luci,ff94315/luci-1,david-xiao/luci,aa65535/luci,jlopenwrtluci/luci,oyido/luci,dismantl/luci-0.12,Wedmer/luci,artynet/luci,aa65535/luci,Hostle/luci,remakeelectric/luci,obsy/luci,kuoruan/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,deepak78/new-luci,david-xiao/luci,lcf258/openwrtcn,Hostle/luci,LuttyYang/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,opentechinstitute/luci,nwf/openwrt-luci,palmettos/test,db260179/openwrt-bpi-r1-luci,forward619/luci,RedSnake64/openwrt-luci-packages,bittorf/luci,maxrio/luci981213,sujeet14108/luci,jlopenwrtluci/luci,maxrio/luci981213,jorgifumi/luci,dwmw2/luci,forward619/luci,keyidadi/luci,palmettos/cnLuCI,schidler/ionic-luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,florian-shellfire/luci,openwrt/luci,lbthomsen/openwrt-luci,remakeelectric/luci,dismantl/luci-0.12,chris5560/openwrt-luci,palmettos/test,thess/OpenWrt-luci,joaofvieira/luci,tobiaswaldvogel/luci,urueedi/luci,thess/OpenWrt-luci,Noltari/luci,palmettos/test,thesabbir/luci,zhaoxx063/luci,artynet/luci,harveyhu2012/luci,981213/luci-1,kuoruan/luci,artynet/luci,RuiChen1113/luci,oneru/luci,Wedmer/luci,lbthomsen/openwrt-luci,hnyman/luci,kuoruan/luci,Hostle/luci,marcel-sch/luci,RedSnake64/openwrt-luci-packages,981213/luci-1,MinFu/luci,oyido/luci,slayerrensky/luci,deepak78/new-luci,kuoruan/lede-luci,cappiewu/luci,Hostle/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,daofeng2015/luci,obsy/luci,zhaoxx063/luci,bright-things/ionic-luci,wongsyrone/luci-1,jorgifumi/luci,oneru/luci,thesabbir/luci,obsy/luci,cshore/luci,thesabbir/luci,RuiChen1113/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,openwrt/luci,nwf/openwrt-luci,opentechinstitute/luci,shangjiyu/luci-with-extra,male-puppies/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,oyido/luci,keyidadi/luci,sujeet14108/luci,openwrt-es/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,mumuqz/luci,RuiChen1113/luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,marcel-sch/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,Noltari/luci,fkooman/luci,thesabbir/luci,artynet/luci,oneru/luci,slayerrensky/luci,joaofvieira/luci,981213/luci-1,forward619/luci,dwmw2/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,schidler/ionic-luci,opentechinstitute/luci,oyido/luci,ff94315/luci-1,ollie27/openwrt_luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,openwrt/luci,rogerpueyo/luci,cshore/luci,aa65535/luci,Noltari/luci,maxrio/luci981213,kuoruan/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,cshore/luci,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,keyidadi/luci,forward619/luci,palmettos/cnLuCI,teslamint/luci,Sakura-Winkey/LuCI,mumuqz/luci,openwrt/luci,bittorf/luci,oneru/luci,981213/luci-1,thesabbir/luci,Kyklas/luci-proto-hso,obsy/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,mumuqz/luci,kuoruan/lede-luci,male-puppies/luci,nmav/luci,Noltari/luci,keyidadi/luci,joaofvieira/luci,Noltari/luci,kuoruan/lede-luci,harveyhu2012/luci,jorgifumi/luci,bright-things/ionic-luci,MinFu/luci,ollie27/openwrt_luci,thesabbir/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,jchuang1977/luci-1,daofeng2015/luci,LuttyYang/luci,rogerpueyo/luci,thess/OpenWrt-luci,bright-things/ionic-luci,marcel-sch/luci,remakeelectric/luci,hnyman/luci,lbthomsen/openwrt-luci,Wedmer/luci,LuttyYang/luci,forward619/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,LuttyYang/luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,schidler/ionic-luci,Kyklas/luci-proto-hso,jorgifumi/luci,marcel-sch/luci,nwf/openwrt-luci,florian-shellfire/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,artynet/luci,bittorf/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,male-puppies/luci,harveyhu2012/luci,palmettos/cnLuCI,fkooman/luci,jlopenwrtluci/luci,MinFu/luci,lbthomsen/openwrt-luci,tcatm/luci,lbthomsen/openwrt-luci,Hostle/luci,deepak78/new-luci,thess/OpenWrt-luci,kuoruan/lede-luci,nwf/openwrt-luci,obsy/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,jchuang1977/luci-1,jchuang1977/luci-1,kuoruan/lede-luci,wongsyrone/luci-1,zhaoxx063/luci,MinFu/luci,daofeng2015/luci,taiha/luci,palmettos/cnLuCI,zhaoxx063/luci,Wedmer/luci,wongsyrone/luci-1,urueedi/luci,teslamint/luci,schidler/ionic-luci,MinFu/luci,MinFu/luci,bittorf/luci,remakeelectric/luci,slayerrensky/luci,harveyhu2012/luci,maxrio/luci981213,kuoruan/lede-luci,ollie27/openwrt_luci,taiha/luci,oneru/luci,ff94315/luci-1,jchuang1977/luci-1,cshore/luci,joaofvieira/luci,nmav/luci,florian-shellfire/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,deepak78/new-luci,tcatm/luci,lcf258/openwrtcn
|
ccadbc91d176d419cf9891a0d03e8a7b5ff3b158
|
scripts/shaderc.lua
|
scripts/shaderc.lua
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "shaderc"
uuid "f3cd2e90-52a4-11e1-b86c-0800200c9a66"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
"3rdparty/dxsdk/include",
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
FCPP_DIR,
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
strip()
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "shaderc"
uuid "f3cd2e90-52a4-11e1-b86c-0800200c9a66"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
FCPP_DIR,
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
strip()
|
shaderc: Fixed DXSDK include path.
|
shaderc: Fixed DXSDK include path.
|
Lua
|
bsd-2-clause
|
kondrak/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,aonorin/bgfx,elmindreda/bgfx,aonorin/bgfx,Synxis/bgfx,MikePopoloski/bgfx,bkaradzic/bgfx,attilaz/bgfx,Synxis/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx,v3n/bgfx,marco-we/bgfx,andr3wmac/bgfx,attilaz/bgfx,jdryg/bgfx,mendsley/bgfx,andr3wmac/bgfx,0-wiz-0/bgfx,mmicko/bgfx,aonorin/bgfx,kondrak/bgfx,mendsley/bgfx,v3n/bgfx,elmindreda/bgfx,fluffyfreak/bgfx,0-wiz-0/bgfx,jpcy/bgfx,emoon/bgfx,mendsley/bgfx,emoon/bgfx,andr3wmac/bgfx,septag/bgfx,fluffyfreak/bgfx,marco-we/bgfx,mmicko/bgfx,Synxis/bgfx,elmindreda/bgfx,jdryg/bgfx,attilaz/bgfx,septag/bgfx,jdryg/bgfx,bkaradzic/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,emoon/bgfx,mmicko/bgfx,kondrak/bgfx,bkaradzic/bgfx,jpcy/bgfx,v3n/bgfx,jdryg/bgfx,jpcy/bgfx,0-wiz-0/bgfx,MikePopoloski/bgfx,fluffyfreak/bgfx,LWJGL-CI/bgfx,marco-we/bgfx,septag/bgfx,jpcy/bgfx
|
0354dbe8891fa970046de70ae62561e92d49c28a
|
resources/prosody-plugins/mod_token_verification.lua
|
resources/prosody-plugins/mod_token_verification.lua
|
-- Token authentication
-- Copyright (C) 2015 Atlassian
local log = module._log;
local host = module.host;
local st = require "util.stanza";
local is_admin = require "core.usermanager".is_admin;
local parentHostName = string.gmatch(tostring(host), "%w+.(%w.+)")();
if parentHostName == nil then
log("error", "Failed to start - unable to get parent hostname");
return;
end
local parentCtx = module:context(parentHostName);
if parentCtx == nil then
log("error",
"Failed to start - unable to get parent context for host: %s",
tostring(parentHostName));
return;
end
local token_util = module:require "token/util".new(parentCtx);
-- no token configuration
if token_util == nil then
return;
end
log("debug",
"%s - starting MUC token verifier app_id: %s app_secret: %s allow empty: %s",
tostring(host), tostring(token_util.appId), tostring(token_util.appSecret),
tostring(token_util.allowEmptyToken));
-- option to disable room modification (sending muc config form) for guest that do not provide token
local require_token_for_moderation;
local function load_config()
require_token_for_moderation = module:get_option_boolean("token_verification_require_token_for_moderation");
end
load_config();
local function verify_user(session, stanza)
log("debug", "Session token: %s, session room: %s",
tostring(session.auth_token),
tostring(session.jitsi_meet_room));
-- token not required for admin users
local user_jid = stanza.attr.from;
if is_admin(user_jid) then
log("debug", "Token not required from admin user: %s", user_jid);
return nil;
end
log("debug",
"Will verify token for user: %s, room: %s ", user_jid, stanza.attr.to);
if not token_util:verify_room(session, stanza.attr.to) then
log("error", "Token %s not allowed to join: %s",
tostring(session.auth_token), tostring(stanza.attr.to));
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room and token mismatched"));
return false; -- we need to just return non nil
end
log("debug",
"allowed: %s to enter/create room: %s", user_jid, stanza.attr.to);
end
module:hook("muc-room-pre-create", function(event)
local origin, stanza = event.origin, event.stanza;
log("debug", "pre create: %s %s", tostring(origin), tostring(stanza));
return verify_user(origin, stanza);
end);
module:hook("muc-occupant-pre-join", function(event)
local origin, room, stanza = event.origin, event.room, event.stanza;
log("debug", "pre join: %s %s", tostring(room), tostring(stanza));
return verify_user(origin, stanza);
end);
for event_name, method in pairs {
-- Normal room interactions
["iq-set/bare/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
-- Host room
["iq-set/host/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
} do
module:hook(event_name, function (event)
local session, stanza = event.origin, event.stanza;
-- if we do not require token we pass it through(default behaviour)
-- or the request is coming from admin (focus)
if not require_token_for_moderation or is_admin(stanza.attr.from) then
return;
end
-- jitsi_meet_room is set after the token had been verified
if not session.auth_token or not session.jitsi_meet_room then
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room modification disabled for guests"));
return true;
end
end, -1); -- the default prosody hook is on -2
end
module:hook_global('config-reloaded', load_config);
|
-- Token authentication
-- Copyright (C) 2015 Atlassian
local log = module._log;
local host = module.host;
local st = require "util.stanza";
local is_admin = require "core.usermanager".is_admin;
local parentHostName = string.gmatch(tostring(host), "%w+.(%w.+)")();
if parentHostName == nil then
log("error", "Failed to start - unable to get parent hostname");
return;
end
local parentCtx = module:context(parentHostName);
if parentCtx == nil then
log("error",
"Failed to start - unable to get parent context for host: %s",
tostring(parentHostName));
return;
end
local token_util = module:require "token/util".new(parentCtx);
-- no token configuration
if token_util == nil then
return;
end
log("debug",
"%s - starting MUC token verifier app_id: %s app_secret: %s allow empty: %s",
tostring(host), tostring(token_util.appId), tostring(token_util.appSecret),
tostring(token_util.allowEmptyToken));
-- option to disable room modification (sending muc config form) for guest that do not provide token
local require_token_for_moderation;
local function load_config()
require_token_for_moderation = module:get_option_boolean("token_verification_require_token_for_moderation");
end
load_config();
-- verify user and whether he is allowed to join a room based on the token information
local function verify_user(session, stanza)
log("debug", "Session token: %s, session room: %s",
tostring(session.auth_token),
tostring(session.jitsi_meet_room));
-- token not required for admin users
local user_jid = stanza.attr.from;
if is_admin(user_jid) then
log("debug", "Token not required from admin user: %s", user_jid);
return true;
end
log("debug",
"Will verify token for user: %s, room: %s ", user_jid, stanza.attr.to);
if not token_util:verify_room(session, stanza.attr.to) then
log("error", "Token %s not allowed to join: %s",
tostring(session.auth_token), tostring(stanza.attr.to));
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room and token mismatched"));
return false; -- we need to just return non nil
end
log("debug",
"allowed: %s to enter/create room: %s", user_jid, stanza.attr.to);
return true;
end
module:hook("muc-room-pre-create", function(event)
local origin, stanza = event.origin, event.stanza;
log("debug", "pre create: %s %s", tostring(origin), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
module:hook("muc-occupant-pre-join", function(event)
local origin, room, stanza = event.origin, event.room, event.stanza;
log("debug", "pre join: %s %s", tostring(room), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
for event_name, method in pairs {
-- Normal room interactions
["iq-set/bare/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
-- Host room
["iq-set/host/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
} do
module:hook(event_name, function (event)
local session, stanza = event.origin, event.stanza;
-- if we do not require token we pass it through(default behaviour)
-- or the request is coming from admin (focus)
if not require_token_for_moderation or is_admin(stanza.attr.from) then
return;
end
-- jitsi_meet_room is set after the token had been verified
if not session.auth_token or not session.jitsi_meet_room then
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room modification disabled for guests"));
return true;
end
end, -1); -- the default prosody hook is on -2
end
module:hook_global('config-reloaded', load_config);
|
fix: Updates docs and verification to halt joining process.
|
fix: Updates docs and verification to halt joining process.
When returning the error and showing to user not allowed screen we were not completely halting the prejoin operation when token verification fails on room join and the token is valid in general.
|
Lua
|
apache-2.0
|
gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet
|
f427433d6df48858ed447474a704c4fb69720380
|
src/plugins/finalcutpro/timeline/commandsetactions.lua
|
src/plugins/finalcutpro/timeline/commandsetactions.lua
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C O M M A N D P O S T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.timeline.commandsetactions ===
---
--- Adds Actions to the Console for triggering Final Cut Pro shortcuts as defined in the Command Set files.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local log = require("hs.logger").new("commandsetactions")
local timer = require("hs.timer")
local dialog = require("cp.dialog")
local fcp = require("cp.apple.finalcutpro")
local plist = require("cp.plist")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local GROUP = "fcpx"
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
function mod.init()
--------------------------------------------------------------------------------
-- Add Action Handler:
--------------------------------------------------------------------------------
mod._handler = mod._actionmanager.addHandler(GROUP .. "_shortcuts", GROUP)
:onChoices(function(choices)
local fcpPath = fcp:getPath()
local currentLanguage = fcp:currentLanguage()
if fcpPath and currentLanguage then
local namePath = fcpPath .. "/Contents/Resources/" .. currentLanguage .. ".lproj/NSProCommandNames.strings"
local descriptionPath = fcpPath .. "/Contents/Resources/" .. currentLanguage .. ".lproj/NSProCommandDescriptions.strings"
local nameData = plist.fileToTable(namePath)
local descriptionData = plist.fileToTable(descriptionPath)
if nameData and descriptionData then
for id, name in pairs(nameData) do
local subText = descriptionData[id] or i18n("commandEditorShortcut")
choices
:add(name)
:subText(subText)
:params(id)
:id(id)
end
end
end
end)
:onExecute(function(action)
local result = fcp:performShortcut(action)
if not result then
dialog.displayMessage(i18n("shortcutCouldNotBeTriggered"), i18n("ok"))
end
end)
:onActionId(function(action)
return "fcpxShortcuts"
end)
--------------------------------------------------------------------------------
-- Reset the handler choices when the Final Cut Pro language changes:
--------------------------------------------------------------------------------
fcp.currentLanguage:watch(function(value)
mod._handler:reset()
timer.doAfter(0.01, function() mod._handler.choices:update() end)
end)
return mod
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.commandsetactions",
group = "finalcutpro",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
mod._actionmanager = deps.actionmanager
return mod.init()
end
return plugin
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C O M M A N D P O S T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.timeline.commandsetactions ===
---
--- Adds Actions to the Console for triggering Final Cut Pro shortcuts as defined in the Command Set files.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local log = require("hs.logger").new("commandsetactions")
local timer = require("hs.timer")
local dialog = require("cp.dialog")
local fcp = require("cp.apple.finalcutpro")
local plist = require("cp.plist")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local GROUP = "fcpx"
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
function mod.init()
--------------------------------------------------------------------------------
-- Add Action Handler:
--------------------------------------------------------------------------------
mod._handler = mod._actionmanager.addHandler(GROUP .. "_shortcuts", GROUP)
:onChoices(function(choices)
local fcpPath = fcp:getPath()
local currentLanguage = fcp:currentLanguage()
if fcpPath and currentLanguage then
local namePath = fcpPath .. "/Contents/Resources/" .. currentLanguage .. ".lproj/NSProCommandNames.strings"
local descriptionPath = fcpPath .. "/Contents/Resources/" .. currentLanguage .. ".lproj/NSProCommandDescriptions.strings"
local nameData = plist.fileToTable(namePath)
local descriptionData = plist.fileToTable(descriptionPath)
if nameData and descriptionData then
for id, name in pairs(nameData) do
local subText = descriptionData[id] or i18n("commandEditorShortcut")
choices
:add(name)
:subText(subText)
:params(id)
:id(id)
end
end
end
end)
:onExecute(function(action)
if type(action) == "table" then
--------------------------------------------------------------------------------
-- Used by URL Handler:
--------------------------------------------------------------------------------
action = action.id
end
local result = fcp:performShortcut(action)
if not result then
dialog.displayMessage(i18n("shortcutCouldNotBeTriggered"), i18n("ok"))
log.ef("Failed to trigger shortcut with action: %s", action and hs.inspect(action))
end
end)
:onActionId(function(action)
return "fcpxShortcuts"
end)
--------------------------------------------------------------------------------
-- Reset the handler choices when the Final Cut Pro language changes:
--------------------------------------------------------------------------------
fcp.currentLanguage:watch(function(value)
mod._handler:reset()
timer.doAfter(0.01, function() mod._handler.choices:update() end)
end)
return mod
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.commandsetactions",
group = "finalcutpro",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
mod._actionmanager = deps.actionmanager
return mod.init()
end
return plugin
|
Bug Fix
|
Bug Fix
- `fcpx_shortcuts` didn’t work with URL Handler
|
Lua
|
mit
|
cailyoung/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,cailyoung/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
|
d87b3ba69a43b4e5281e75e09253dd985e922def
|
love2d/mapGenerator.lua
|
love2d/mapGenerator.lua
|
require('math')
MapGenerator = {}
MAP_PLAIN = 0
MAP_MOUNTAIN = 1
MAP_OBJ_NOTHING = 0
MAP_OBJ_WATER = 1
MAP_OBJ_TREE = 2
MAP_OBJ_START = 3
MAP_OBJ_FIREPLACE = 4
MAP_WATER_PERCENTAGE = 0.15
MAP_TREE_PERCENTAGE = 0.1
MAP_FIREPLACE_PERCENTAGE = 0.1
function MapGenerator.newMap(width, height)
local map = {}
local plain = {}
local mountain = {}
local countPlain = 0
for x = 1, width do
map[x] = {}
for y = 1, height do
if y/width < 0.5 * math.cos((x / height) * 2 * math.pi - 2*math.pi/3) -math.abs(0.5 * math.cos((x / height) * 4 * math.pi - 2*math.pi/3)) + 0.5 then
map[x][y] = {MAP_PLAIN, MAP_OBJ_NOTHING}
countPlain = countPlain + 1
plain[#plain + 1] = {x, y}
else
map[x][y] = {MAP_MOUNTAIN, MAP_OBJ_NOTHING}
mountain[#mountain + 1] = {x, y}
end
end
end
local numPlain = #plain
local numMountains = #mountain
-- create trees
local numTrees = MAP_TREE_PERCENTAGE * countPlain
for i = 1, numTrees do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_TREE
print("Tree: ", pos[1], pos[2])
end
-- create start point
local numUnits = 1
for i = 1, numUnits do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_START
print("Unit: ", pos[1], pos[2])
end
-- create water
local numWater = MAP_WATER_PERCENTAGE * width * height
local waterToPlace = numWater
while waterToPlace > 0 do
local pos
local maxSize = math.random(1, math.min(15, waterToPlace))
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
else
local idx = math.random(#mountain)
pos = mountain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
end
print("Water: ", pos[1], pos[2], "@", maxSize)
end
--create fire places
local numFirePlaces = MAP_FIREPLACE_PERCENTAGE * width * height
for i = 1, numFirePlaces do
local pos
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
else
local idx = math.random(#mountain)
pos = mountain[idx]
table.remove(mountain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
end
print("Fire place: ", pos[1], pos[2])
end
MapGenerator.printMap(map)
print("Trees: ", numTrees, "Water: ", numWater, "Units: ", numUnits)
return map
end
function MapGenerator.removePosFromTables(tables, x, y)
for idx, tab in pairs(tables) do
for i, v in pairs(tab) do
if x == v[1] and y == v[2] then
table.remove(tab, i)
return
end
end
end
end
function MapGenerator.canPlaceWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
return true
else
return false
end
end
function MapGenerator.placeWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
map[x][y][2] = MAP_OBJ_WATER
return true
else
return false
end
end
function MapGenerator.isValidPosition(x, y, width, height)
if x < 1 or x > width then
return false
end
if y < 1 or y > height then
return false
end
return true
end
function MapGenerator.checkWaterTarget(map, x, y, width, height)
if MapGenerator.isValidPosition(x, y, width, height) then
return MapGenerator.canPlaceWater(map, x, y)
end
return false
end
function MapGenerator.generateWater(x, y, tables, map, width, height, maxSize)
local placed = 0
if MapGenerator.placeWater(map, x, y) then
MapGenerator.removePosFromTables(tables, x, y)
placed = placed + 1
else
return placed
end
for i = 1, maxSize - 1 do
-- locate possible targets
local neighbours = {}
if MapGenerator.checkWaterTarget(map, x - 1, y , width, height) then neighbours[#neighbours + 1] = {x - 1, y } end
if MapGenerator.checkWaterTarget(map, x + 1, y , width, height) then neighbours[#neighbours + 1] = {x + 1, y } end
if MapGenerator.checkWaterTarget(map, x , y - 1, width, height) then neighbours[#neighbours + 1] = {x , y - 1} end
if MapGenerator.checkWaterTarget(map, x , y + 1, width, height) then neighbours[#neighbours + 1] = {x , y + 1} end
if #neighbours < 1 then
return placed
end
local idx = math.random(#neighbours)
local pos = neighbours[idx]
if MapGenerator.placeWater(map, pos[1], pos[2]) then
MapGenerator.removePosFromTables(tables, pos[1], pos[2])
placed = placed + 1
x = pos[1]
y = pos[2]
else
return placed
end
end
return placed
end
function MapGenerator.printMap(map)
for i,v in pairs(map) do
local line = ""
for j, v in pairs(v) do
line = line .. (v[1] + 2 * v[2]) .. " "
end
print(line)
end
end
function MapGenerator.getID(map, x, y)
return map[x][y][1] + 2 * map[x][y][2]
end
|
require('math')
MapGenerator = {}
MAP_UNDEFINED = 0
MAP_PLAIN = 1
MAP_MOUNTAIN = 2
MAP_OBJ_NOTHING = 0
MAP_OBJ_WATER = 1
MAP_OBJ_TREE = 2
MAP_OBJ_START = 3
MAP_OBJ_FIREPLACE = 4
MAP_WATER_PERCENTAGE = 0.15
MAP_TREE_PERCENTAGE = 0.1
MAP_FIREPLACE_PERCENTAGE = 0.1
function MapGenerator.newMap(width, height)
local map = {}
local plain = {}
local mountain = {}
local countPlain = 0
for x = 1, width do
map[x] = {}
for y = 1, height do
if y/width < 0.5 * math.cos((x / height) * 2 * math.pi - 2*math.pi/3) -math.abs(0.5 * math.cos((x / height) * 4 * math.pi - 2*math.pi/3)) + 0.5 then
map[x][y] = {MAP_PLAIN, MAP_OBJ_NOTHING}
countPlain = countPlain + 1
plain[#plain + 1] = {x, y}
else
map[x][y] = {MAP_MOUNTAIN, MAP_OBJ_NOTHING}
mountain[#mountain + 1] = {x, y}
end
end
end
local numPlain = #plain
local numMountains = #mountain
-- create trees
local numTrees = MAP_TREE_PERCENTAGE * countPlain
for i = 1, numTrees do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_TREE
print("Tree: ", pos[1], pos[2])
end
-- create start point
local numUnits = 1
for i = 1, numUnits do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_START
print("Unit: ", pos[1], pos[2])
end
-- create water
local numWater = MAP_WATER_PERCENTAGE * width * height
local waterToPlace = numWater
while waterToPlace > 0 do
local pos
local maxSize = math.random(1, math.min(15, waterToPlace))
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
else
local idx = math.random(#mountain)
pos = mountain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
end
print("Water: ", pos[1], pos[2], "@", maxSize)
end
--create fire places
local numFirePlaces = MAP_FIREPLACE_PERCENTAGE * width * height
for i = 1, numFirePlaces do
local pos
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
else
local idx = math.random(#mountain)
pos = mountain[idx]
table.remove(mountain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
end
print("Fire place: ", pos[1], pos[2])
end
MapGenerator.printMap(map)
print("Trees: ", numTrees, "Water: ", numWater, "Units: ", numUnits)
return map
end
function MapGenerator.removePosFromTables(tables, x, y)
for idx, tab in pairs(tables) do
for i, v in pairs(tab) do
if x == v[1] and y == v[2] then
table.remove(tab, i)
return
end
end
end
end
function MapGenerator.canPlaceWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
return true
else
return false
end
end
function MapGenerator.placeWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
map[x][y][2] = MAP_OBJ_WATER
return true
else
return false
end
end
function MapGenerator.isValidPosition(x, y, width, height)
if x < 1 or x > width then
return false
end
if y < 1 or y > height then
return false
end
return true
end
function MapGenerator.checkWaterTarget(map, x, y, width, height)
if MapGenerator.isValidPosition(x, y, width, height) then
return MapGenerator.canPlaceWater(map, x, y)
end
return false
end
function MapGenerator.generateWater(x, y, tables, map, width, height, maxSize)
local placed = 0
if MapGenerator.placeWater(map, x, y) then
MapGenerator.removePosFromTables(tables, x, y)
placed = placed + 1
else
return placed
end
for i = 1, maxSize - 1 do
-- locate possible targets
local neighbours = {}
if MapGenerator.checkWaterTarget(map, x - 1, y , width, height) then neighbours[#neighbours + 1] = {x - 1, y } end
if MapGenerator.checkWaterTarget(map, x + 1, y , width, height) then neighbours[#neighbours + 1] = {x + 1, y } end
if MapGenerator.checkWaterTarget(map, x , y - 1, width, height) then neighbours[#neighbours + 1] = {x , y - 1} end
if MapGenerator.checkWaterTarget(map, x , y + 1, width, height) then neighbours[#neighbours + 1] = {x , y + 1} end
if #neighbours < 1 then
return placed
end
local idx = math.random(#neighbours)
local pos = neighbours[idx]
if MapGenerator.placeWater(map, pos[1], pos[2]) then
MapGenerator.removePosFromTables(tables, pos[1], pos[2])
placed = placed + 1
x = pos[1]
y = pos[2]
else
return placed
end
end
return placed
end
function MapGenerator.printMap(map)
for i,v in pairs(map) do
local line = ""
for j, v in pairs(v) do
line = line .. (v[1] + 2 * v[2]) .. " "
end
print(line)
end
end
function MapGenerator.getID(map, x, y)
return map[x][y][1]
end
function MapGenerator.getObject(map, x, y)
return map[x][y][2]
end
|
Fixed map generator
|
Fixed map generator
|
Lua
|
mit
|
nczempin/lizard-journey
|
e9e85583295a4cdf4aeb760e4f35ce8ac1921af8
|
lua/entities/gmod_wire_egp/lib/objects/boxoutline.lua
|
lua/entities/gmod_wire_egp/lib/objects/boxoutline.lua
|
-- Author: Divran
local Obj = EGP:NewObject( "BoxOutline" )
Obj.size = 1
Obj.angle = 0
Obj.CanTopLeft = true
local function rotate( x, y, a )
local a = a * math.pi / 180
local _x = math.cos(a) * x - math.sin(a) * y
local _y = math.sin(a) * x + math.cos(a) * y
return _x, _y
end
Obj.Draw = function( self )
if (self.a>0 and self.w > 0 and self.h > 0) then
surface.SetDrawColor( self.r, self.g, self.b, self.a )
local x, y, w, h, a, s = self.x, self.y, self.w, self.h, self.angle, self.size
local x1, y1 = rotate( w / 2 - s / 2, 0, -a )
local x2, y2 = rotate( -w / 2 + s / 2, 0, -a )
local x3, y3 = rotate( 0, h / 2 - s / 2, -a )
local x4, y4 = rotate( 0, -h / 2 + s / 2, -a )
if (h - s*2 > 0) then
surface.DrawTexturedRectRotated( x + math.ceil(x1), y + math.ceil(y1), h - s*2, s, a - 90 )
surface.DrawTexturedRectRotated( x + math.ceil(x2), y + math.ceil(y2), h - s*2, s, a + 90 )
end
surface.DrawTexturedRectRotated( x + math.ceil(x3), y + math.ceil(y3), w, s, a + 180 )
surface.DrawTexturedRectRotated( x + math.ceil(x4), y + math.ceil(y4), w, s, a )
end
end
Obj.Transmit = function( self )
net.WriteInt( self.size, 16 )
net.WriteInt( (self.angle%360)*20, 16 )
self.BaseClass.Transmit( self )
end
Obj.Receive = function( self )
local tbl = {}
tbl.size = net.ReadInt(16)
tbl.angle = net.ReadInt(16)/20
table.Merge( tbl, self.BaseClass.Receive( self ) )
return tbl
end
Obj.DataStreamInfo = function( self )
local tbl = {}
tbl.size = self.size
tbl.angle = self.angle
table.Merge( tbl, self.BaseClass.DataStreamInfo( self ) )
return tbl
end
|
-- Author: Divran
local Obj = EGP:NewObject( "BoxOutline" )
Obj.size = 1
Obj.angle = 0
Obj.CanTopLeft = true
local function rotate( x, y, a )
local a = a * math.pi / 180
local _x = math.cos(a) * x - math.sin(a) * y
local _y = math.sin(a) * x + math.cos(a) * y
return _x, _y
end
Obj.Draw = function( self, egp )
if (self.a>0 and self.w > 0 and self.h > 0) then
surface.SetDrawColor( self.r, self.g, self.b, self.a )
local x, y, w, h, a, s = self.x, self.y, self.w, self.h, self.angle, self.size
local x1, y1 = rotate( w / 2 - s / 2, 0, -a )
local x2, y2 = rotate( -w / 2 + s / 2, 0, -a )
local x3, y3 = rotate( 0, h / 2 - s / 2, -a )
local x4, y4 = rotate( 0, -h / 2 + s / 2, -a )
if egp.gmod_wire_egp_emitter then -- is emitter
if (h - s*2 > 0) then
-- Right
surface.DrawTexturedRectRotated( x + math.ceil(x1), y + math.Round(y1), h - s*2, s, a - 90 )
-- Left
surface.DrawTexturedRectRotated( x + math.floor(x2), y + math.Round(y2), h - s*2, s, a + 90 )
end
-- Bottom
surface.DrawTexturedRectRotated( x + math.Round(x3), y + math.floor(y3), w, s, a + 180 )
-- Top
surface.DrawTexturedRectRotated( x + math.Round(x4), y + math.ceil(y4), w, s, a )
else -- is not emitter
if (h - s*2 > 0) then
-- Right
surface.DrawTexturedRectRotated( x + math.ceil(x1), y + math.ceil(y1), h - s*2, s, a - 90 )
-- Left
surface.DrawTexturedRectRotated( x + math.ceil(x2), y + math.ceil(y2), h - s*2, s, a + 90 )
end
-- Bottom
surface.DrawTexturedRectRotated( x + math.ceil(x3), y + math.ceil(y3), w, s, a + 180 )
-- Top
surface.DrawTexturedRectRotated( x + math.ceil(x4), y + math.ceil(y4), w, s, a )
end
end
end
Obj.Transmit = function( self )
net.WriteInt( self.size, 16 )
net.WriteInt( (self.angle%360)*20, 16 )
self.BaseClass.Transmit( self )
end
Obj.Receive = function( self )
local tbl = {}
tbl.size = net.ReadInt(16)
tbl.angle = net.ReadInt(16)/20
table.Merge( tbl, self.BaseClass.Receive( self ) )
return tbl
end
Obj.DataStreamInfo = function( self )
local tbl = {}
tbl.size = self.size
tbl.angle = self.angle
table.Merge( tbl, self.BaseClass.DataStreamInfo( self ) )
return tbl
end
|
Fixing boxOutline rouding errors on emitter as much as possible
|
Fixing boxOutline rouding errors on emitter as much as possible
Fixes #775
|
Lua
|
apache-2.0
|
Grocel/wire,plinkopenguin/wiremod,dvdvideo1234/wire,garrysmodlua/wire,immibis/wiremod,bigdogmat/wire,CaptainPRICE/wire,rafradek/wire,wiremod/wire,sammyt291/wire,thegrb93/wire,Python1320/wire,NezzKryptic/Wire,mitterdoo/wire,notcake/wire,mms92/wire
|
ff211a99d0853f6ac5f45c7a49bac0b9303d6d0e
|
test/tests/03-timestamping.lua
|
test/tests/03-timestamping.lua
|
EXPORT_ASSERTS_TO_GLOBALS = true
local luaunit = require "luaunit"
local dpdk = require "dpdk"
local ts = require "timestamping"
local hist = require "histogram"
local device = require "device"
local timer = require "timer"
local tconfig = require "tconfig"
local PKT_SIZE = 124
Tests = {}
function master()
local cards = tconfig.cards()
local pairs = tconfig.pairs()
local devs = {}
for i=1, #pairs, 2 do
devs[i] = device.config{ port = cards[pairs[i][1]+1][1], rxQueues = 2, txQueues = 3}
devs[i+1] = device.config{ port = cards[pairs[i][2]+1][1], rxQueues = 2, txQueues = 3}
end
device.waitForLinks()
for i=1, #devs, 2 do
slave(devs[i+1]:getRxQueue(0), devs[i]:getTxQueue(0))
slave(devs[i]:getRxQueue(0), devs[i+1]:getTxQueue(0))
end
os.exit(luaunit.LuaUnit.run())
end
function slave(rxQueue, txQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
local runtime = timer:new(10)
while runtime:running() and dpdk.running() do
hist:update(timestamper:measureLatency())
end
hist:print()
return 1
end
|
EXPORT_ASSERTS_TO_GLOBALS = true
local luaunit = require "luaunit"
local dpdk = require "dpdk"
local ts = require "timestamping"
local hist = require "histogram"
local device = require "device"
local timer = require "timer"
local tconfig = require "tconfig"
local PKT_SIZE = 124
Tests = {}
function master()
local cards = tconfig.cards()
local pairs = tconfig.pairs()
local devs = {}
for i=1, #pairs, 2 do
devs[i] = device.config{ port = cards[pairs[i][1]+1][1], rxQueues = 2, txQueues = 3}
devs[i+1] = device.config{ port = cards[pairs[i][2]+1][1], rxQueues = 2, txQueues = 3}
end
device.waitForLinks()
for i=1, #devs, 2 do
Tests["TestNic" .. i] = function ()
luaunit.assertTrue(slave(devs[i+1]:getRxQueue(0), devs[i]:getTxQueue(0)))
luaunit.assertTrue(slave(devs[i]:getRxQueue(0), devs[i+1]:getTxQueue(0)))
end
end
os.exit(luaunit.LuaUnit.run())
end
function slave(rxQueue, txQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
local runtime = timer:new(10)
while runtime:running() and dpdk.running() do
hist:update(timestamper:measureLatency())
end
hist:print()
return 1
end
|
Fixed Timestamping.lua fatal error
|
Fixed Timestamping.lua fatal error
|
Lua
|
mit
|
gallenmu/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,bmichalo/MoonGen,dschoeffm/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,dschoeffm/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,atheurer/MoonGen,scholzd/MoonGen,emmericp/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,scholzd/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen
|
7f81efd07e27d00d33eed5223adae1bdd54ce4a5
|
plugins/likecounter.lua
|
plugins/likecounter.lua
|
local function like(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] + 1)
save_data(_config.likecounter.db, likedata)
end
local function dislike(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] -1)
save_data(_config.likecounter.db, likedata)
end
local function like_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
like(extra.likedata, extra.chat, result.peer_id)
end
local function like_by_reply(extra, success, result)
like(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function like_from(extra, success, result)
like(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function dislike_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
dislike(extra.likedata, extra.chat, result.peer_id)
end
local function dislike_by_reply(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function dislike_from(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function likes_leaderboard(users, lbtype)
local users_info = { }
-- Get user name and param
for k, user in pairs(users) do
if user then
local user_info = get_name(k)
user_info.param = tonumber(user)
table.insert(users_info, user_info)
end
end
-- Sort users by param
table.sort(users_info, function(a, b)
if a.param and b.param then
return a.param > b.param
end
end )
local text = lang_text('likesLeaderboard')
local i = 0
for k, user in pairs(users_info) do
if user.name and user.param then
i = i + 1
text = text .. i .. '. ' .. user.name .. ' => ' .. user.param .. '\n'
end
end
return text
end
local function run(msg, matches)
if msg.to.type ~= 'user' then
if matches[1]:lower() == 'createlikesdb' then
if is_sudo(msg) then
local f = io.open(_config.likecounter.db, 'w+')
f:write('{}')
f:close()
reply_msg(msg.id, lang_text('likesdbCreated'), ok_cb, false)
else
return lang_text('require_sudo')
end
return
end
local chat = tostring(msg.to.id)
local user = tostring(msg.from.id)
local likedata = load_data(_config.likecounter.db)
if not likedata[chat] then
likedata[chat] = { }
save_data(_config.likecounter.db, likedata)
end
if matches[1]:lower() == 'addlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] + matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if matches[1]:lower() == 'remlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] - matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if (matches[1]:lower() == 'likes') then
send_large_msg(get_receiver(msg), likes_leaderboard(likedata[chat]))
return
end
if msg.fwd_from then
reply_msg(msg.id, lang_text('forwardingLike'), ok_cb, false)
else
if matches[1]:lower() == 'like' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, like_from, { likedata = likedata })
return
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
like(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), like_by_username, { chat = chat, likedata = likedata })
end
elseif matches[1]:lower() == 'dislike' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, dislike_from, { likedata = likedata })
return
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
dislike(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), dislike_by_username, { chat = chat, likedata = likedata })
end
end
end
end
end
return {
description = "LIKECOUNTER",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Ll][Ii][Kk][Ee][Ss][Dd][Bb])$",
"^[#!/]([Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Ll][Ii][Kk][Ee])$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee])$",
"^[#!/]([Ll][Ii][Kk][Ee][Ss])$",
"^[#!/]([Aa][Dd][Dd][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
"^[#!/]([Rr][Ee][Mm][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
},
run = run,
min_rank = 0
-- usage
-- #like <id>|<username>|<reply>|from
-- #dislike <id>|<username>|<reply>|from
-- #likes
-- SUDO
-- #createlikesdb
-- #addlikes <id> <value>
-- #remlikes <id> <value>
}
|
local function like(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] + 1)
save_data(_config.likecounter.db, likedata)
end
local function dislike(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] -1)
save_data(_config.likecounter.db, likedata)
end
local function like_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
like(extra.likedata, extra.chat, result.peer_id)
end
local function like_by_reply(extra, success, result)
like(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function like_from(extra, success, result)
like(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function dislike_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
dislike(extra.likedata, extra.chat, result.peer_id)
end
local function dislike_by_reply(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function dislike_from(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
-- Returns a table with `name`
local function get_name(user_id)
local user_info = { }
local uhash = 'user:' .. user_id
local user = redis:hgetall(uhash)
user_info.name = user_print_name(user):gsub('_', ' ')
return user_info
end
local function likes_leaderboard(users, lbtype)
local users_info = { }
-- Get user name and param
for k, user in pairs(users) do
if user then
local user_info = get_name(k)
user_info.param = tonumber(user)
table.insert(users_info, user_info)
end
end
-- Sort users by param
table.sort(users_info, function(a, b)
if a.param and b.param then
return a.param > b.param
end
end )
local text = lang_text('likesLeaderboard')
local i = 0
for k, user in pairs(users_info) do
if user.name and user.param then
i = i + 1
text = text .. i .. '. ' .. user.name .. ' => ' .. user.param .. '\n'
end
end
return text
end
local function run(msg, matches)
if msg.to.type ~= 'user' then
if matches[1]:lower() == 'createlikesdb' then
if is_sudo(msg) then
local f = io.open(_config.likecounter.db, 'w+')
f:write('{}')
f:close()
reply_msg(msg.id, lang_text('likesdbCreated'), ok_cb, false)
else
return lang_text('require_sudo')
end
return
end
local chat = tostring(msg.to.id)
local user = tostring(msg.from.id)
local likedata = load_data(_config.likecounter.db)
if not likedata[chat] then
likedata[chat] = { }
save_data(_config.likecounter.db, likedata)
end
if matches[1]:lower() == 'addlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] + matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if matches[1]:lower() == 'remlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] - matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if (matches[1]:lower() == 'likes') then
send_large_msg(get_receiver(msg), likes_leaderboard(likedata[chat]))
return
end
if msg.fwd_from then
reply_msg(msg.id, lang_text('forwardingLike'), ok_cb, false)
else
if matches[1]:lower() == 'like' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, like_from, { likedata = likedata })
return
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
like(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), like_by_username, { chat = chat, likedata = likedata })
end
elseif matches[1]:lower() == 'dislike' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, dislike_from, { likedata = likedata })
return
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
dislike(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), dislike_by_username, { chat = chat, likedata = likedata })
end
end
end
end
end
return {
description = "LIKECOUNTER",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Ll][Ii][Kk][Ee][Ss][Dd][Bb])$",
"^[#!/]([Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Ll][Ii][Kk][Ee])$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee])$",
"^[#!/]([Ll][Ii][Kk][Ee][Ss])$",
"^[#!/]([Aa][Dd][Dd][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
"^[#!/]([Rr][Ee][Mm][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
},
run = run,
min_rank = 0
-- usage
-- #like <id>|<username>|<reply>|from
-- #dislike <id>|<username>|<reply>|from
-- #likes
-- SUDO
-- #createlikesdb
-- #addlikes <id> <value>
-- #remlikes <id> <value>
}
|
fix missing get_name method
|
fix missing get_name method
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
990832f6b3dc3f154eea2bccae64557e24d88cf7
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s").isnumber = true
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung").isinteger = true
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße").isinteger = true
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
i:option(Value, "Interface", "Netzwerkschnittstellen")
i:option(Value, "HelloInterval", "Hello-Intervall").isnumber = true
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit").isnumber = true
i:option(Value, "TcInterval", "TC-Intervall").isnumber = true
i:option(Value, "TcValidityTime", "TC-Gültigkeit").isnumber = true
i:option(Value, "MidInterval", "MID-Intervall").isnumber = true
i:option(Value, "MidValidityTime", "MID-Gültigkeit").isnumber = true
i:option(Value, "HnaInterval", "HNA-Intervall").isnumber = true
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit").isnumber = true
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s")
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung")
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße")
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", "Netzwerkschnittstellen")
network:value("")
for k, v in pairs(ffluci.model.uci.show("network").network) do
if v[".type"] == "interface" and k ~= "loopback" then
network:value(k)
end
end
i:option(Value, "HelloInterval", "Hello-Intervall")
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit")
i:option(Value, "TcInterval", "TC-Intervall")
i:option(Value, "TcValidityTime", "TC-Gültigkeit")
i:option(Value, "MidInterval", "MID-Intervall")
i:option(Value, "MidValidityTime", "MID-Gültigkeit")
i:option(Value, "HnaInterval", "HNA-Intervall")
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit")
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@1899 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
8devices/carambola2-luci,Flexibity/luci,alxhh/piratenluci,Canaan-Creative/luci,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,jschmidlapp/luci,zwhfly/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,phi-psi/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,phi-psi/luci,phi-psi/luci,gwlim/luci,ch3n2k/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,vhpham80/luci,vhpham80/luci,jschmidlapp/luci,gwlim/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,stephank/luci,ch3n2k/luci,jschmidlapp/luci,stephank/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,Flexibity/luci,jschmidlapp/luci,gwlim/luci,alxhh/piratenluci,jschmidlapp/luci,ch3n2k/luci,saraedum/luci-packages-old,8devices/carambola2-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,Canaan-Creative/luci,gwlim/luci,yeewang/openwrt-luci,Flexibity/luci,phi-psi/luci,yeewang/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,vhpham80/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,projectbismark/luci-bismark,Canaan-Creative/luci,Flexibity/luci,jschmidlapp/luci,freifunk-gluon/luci,phi-psi/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,stephank/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,alxhh/piratenluci,alxhh/piratenluci,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,8devices/carambola2-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,gwlim/luci,ch3n2k/luci,ch3n2k/luci,Canaan-Creative/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,gwlim/luci,saraedum/luci-packages-old,Flexibity/luci,gwlim/luci,projectbismark/luci-bismark
|
0552ce8324fb9a2ee388328def546d8dfc580cd3
|
src/rosmongolog.lua
|
src/rosmongolog.lua
|
#!/usr/bin/lua
----------------------------------------------------------------------------
-- skillenv.lua - Skiller skill environment functions
--
-- Created: Wed Nov 03 17:34:31 2010
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
----------------------------------------------------------------------------
-- 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 Library General Public License for more details.
--
-- Read the full text in the LICENSE.GPL file in the doc directory.
require("roslua")
roslua.assert_version(0,4,1)
roslua.init_node{master_uri=os.getenv("ROS_MASTER_URI"),
node_name="/rosmongolog"}
local dbname = "rosmongolog"
local dbhost = "localhost"
local topics = { {name = "/chatter", type = "std_msgs/String"} }
require("mongo")
local db = mongo.Connection.New()
db:connect("localhost")
for _, t in ipairs(topics) do
local s = roslua.subscriber(t.name, t.type)
local subcolname = t.name:gsub("/", "_")
if subcolname:match("_.*") then subcolname = subcolname:sub(2) end
local collection_name = dbname .. "." .. subcolname
s:add_listener(function (message)
local doc = message:plain_value_table()
db:insert(collection_name, doc)
end)
t.subscriber = s
end
roslua.run()
|
#!/usr/bin/lua
----------------------------------------------------------------------------
-- rosmongolog.lua - Lua based ROS to MongoDB logger
--
-- Created: Wed Nov 03 17:34:31 2010
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
-- Carnegie Mellon University
-- Intel Labs Pittsburgh
----------------------------------------------------------------------------
-- 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 Library General Public License for more details.
--
-- Read the full text in the LICENSE.GPL file in the doc directory.
-- ************************************************************************
-- Note: this script is working and short, but it has been retired in favor
-- of the Python version, because that can write multiple messages
-- concurrently to the database which is beneficial on heavy traffic
-- topics.
--
-- It is however a very good start if you want to write a custom logger for
-- low-traffic topics and where you need to do special preprocessing etc.
-- ************************************************************************
require("roslua")
roslua.assert_version(0,4,1)
roslua.init_node{master_uri=os.getenv("ROS_MASTER_URI"),
node_name="/rosmongolog"}
local dbname = "rosmongolog"
local dbhost = "localhost"
local topics = { {name = "/chatter", type = "std_msgs/String"} }
require("mongo")
local db = mongo.Connection.New()
db:connect("localhost")
for _, t in ipairs(topics) do
local s = roslua.subscriber(t.name, t.type)
local subcolname = t.name:gsub("/", "_"):sub(2)
local collection_name = dbname .. "." .. subcolname
s:add_listener(function (message)
local doc = message:plain_value_table()
db:insert(collection_name, doc)
end)
t.subscriber = s
end
roslua.run()
|
rosmongolog.lua: add note that it has been retired
|
rosmongolog.lua: add note that it has been retired
And fix header, add CMU/Intel copyrights.
|
Lua
|
bsd-3-clause
|
Jailander/mongodb_store,jeansebbaklouti/mongodb_store,strands-project/mongodb_store,cburbridge/mongodb_store,nilsbore/mongodb_store,jeansebbaklouti/mongodb_store,hawesie/mongodb_store,sevenbitbyte/mongodb_store,cburbridge/mongodb_store,sevenbitbyte/mongodb_store,hawesie/mongodb_store,nilsbore/mongodb_store,strands-project/mongodb_store,Jailander/mongodb_store
|
e36a131856117facff531451d731d6b3d7184f66
|
src/kong/plugins/authentication/schema.lua
|
src/kong/plugins/authentication/schema.lua
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
fixing constant value
|
fixing constant value
|
Lua
|
apache-2.0
|
Kong/kong,ind9/kong,li-wl/kong,kyroskoh/kong,smanolache/kong,ajayk/kong,akh00/kong,kyroskoh/kong,jerizm/kong,ccyphers/kong,Kong/kong,rafael/kong,streamdataio/kong,Vermeille/kong,streamdataio/kong,rafael/kong,isdom/kong,vzaramel/kong,Kong/kong,vzaramel/kong,icyxp/kong,jebenexer/kong,salazar/kong,ejoncas/kong,ind9/kong,xvaara/kong,isdom/kong,shiprabehera/kong,Mashape/kong,beauli/kong,ejoncas/kong
|
dc72917c75d348437b3130272e9f105ea696ce47
|
packages/pirania/tests/test_portal.lua
|
packages/pirania/tests/test_portal.lua
|
local test_utils = require 'tests.utils'
local portal = require('portal.portal')
local uci
describe('Pirania portal tests #portal', function()
local snapshot -- to revert luassert stubs and spies
it('get and set config', function()
stub(utils, "unsafe_shell", function () return end)
local default_cfg = io.open('./packages/pirania/files/etc/config/pirania'):read("*all")
test_utils.write_uci_file(uci, 'pirania', default_cfg)
local portal_cfg = portal.get_config()
assert.is_false(portal_cfg.activated)
local activated = true
local with_vouchers = true
local status = portal.set_config(activated, with_vouchers)
assert.stub.spy(utils.unsafe_shell).was.called_with('captive-portal start')
assert.is_true(status)
portal_cfg = portal.get_config()
assert.is_true(portal_cfg.activated)
local activated = false
status = portal.set_config(activated, with_vouchers)
assert.is_true(status)
assert.stub.spy(utils.unsafe_shell).was.called_with('captive-portal stop')
portal_cfg = portal.get_config()
assert.is_false(portal_cfg.activated)
with_vouchers = false
status, message = portal.set_config(activated, with_vouchers)
assert.is_nil(status)
end)
it('get and set portal page', function()
stub(utils, "read_obj_store", function() return {title = "Pirania"} end)
local content = portal.get_page_content()
assert.is.equal('Pirania', content.title)
local title, main_text, logo, link_title, link_url, bgcolor = 'My Portal', 'my text', 'mylogo', 'linktitle', 'http://foo', '#aabbcc'
portal.set_page_content(title, main_text, logo, link_title, link_url, bgcolor)
local content = portal.get_page_content()
assert.are.same({title=title, background_color=bgcolor, link_title=link_title, link_url=link_url, logo=logo}, content)
end)
before_each('', function()
snapshot = assert:snapshot()
test_dir = test_utils.setup_test_dir()
shared_state.PERSISTENT_DATA_DIR = test_dir
shared_state.DATA_DIR = test_dir
uci = test_utils.setup_test_uci()
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_dir()
test_utils.teardown_test_uci(uci)
end)
end)
|
local test_utils = require 'tests.utils'
local shared_state = require('shared-state')
local portal = require('portal.portal')
local uci
describe('Pirania portal tests #portal', function()
local snapshot -- to revert luassert stubs and spies
it('get and set config', function()
stub(utils, "unsafe_shell", function () return end)
local default_cfg = io.open('./packages/pirania/files/etc/config/pirania'):read("*all")
test_utils.write_uci_file(uci, 'pirania', default_cfg)
local portal_cfg = portal.get_config()
assert.is_false(portal_cfg.activated)
local activated = true
local with_vouchers = true
local status = portal.set_config(activated, with_vouchers)
assert.stub.spy(utils.unsafe_shell).was.called_with('captive-portal start')
assert.is_true(status)
portal_cfg = portal.get_config()
assert.is_true(portal_cfg.activated)
local activated = false
status = portal.set_config(activated, with_vouchers)
assert.is_true(status)
assert.stub.spy(utils.unsafe_shell).was.called_with('captive-portal stop')
portal_cfg = portal.get_config()
assert.is_false(portal_cfg.activated)
with_vouchers = false
status, message = portal.set_config(activated, with_vouchers)
assert.is_nil(status)
end)
it('get and set portal page', function()
stub(utils, "read_obj_store", function() return {title = "Pirania"} end)
local content = portal.get_page_content()
assert.is.equal('Pirania', content.title)
local title, main_text, logo, link_title, link_url, bgcolor = 'My Portal', 'my text', 'mylogo', 'linktitle', 'http://foo', '#aabbcc'
portal.set_page_content(title, main_text, logo, link_title, link_url, bgcolor)
local content = portal.get_page_content()
assert.are.same({title=title, background_color=bgcolor, link_title=link_title, link_url=link_url, logo=logo}, content)
end)
before_each('', function()
snapshot = assert:snapshot()
test_dir = test_utils.setup_test_dir()
shared_state.PERSISTENT_DATA_DIR = test_dir
shared_state.DATA_DIR = test_dir
uci = test_utils.setup_test_uci()
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_dir()
test_utils.teardown_test_uci(uci)
end)
end)
|
pirania: fix missing import
|
pirania: fix missing import
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
ef17f13f1efddab9f4c83d0b347dbdc049ec8210
|
MMOCoreORB/bin/scripts/managers/faction_manager.lua
|
MMOCoreORB/bin/scripts/managers/faction_manager.lua
|
--Factional Relationships determine enemies and allies of factions.
--If you kill a factional NPC, and it is allied with another faction, then you also lose faction with the ally.
--If you kill a factional NPC, and it is enemies with another faction, then you gain faction with the enemy.
--AddFaction
-- faction - This is the string key faction that the relationship describes.
-- enemies - This is a comma delimited list of string key factions that this faction is enemies with.
-- allies - This is a comma delimited list of string key factions that this faction is allies with.
addFaction("rebel","imperial","")
addFaction("imperial","rebel","")
addFaction("aakuans","binayre,fed_dub,liberation_party","")
addFaction("afarathu","corsec","")
addFaction("alkhara","tusken_raider","")
addFaction("bandit","townsperson","")
addFaction("beldonnas_league","followers_of_lord_nyax,lost_aqualish","corsec")
addFaction("binayre","aakuans,corsec,fed_dub","")
addFaction("bloodrazor","canyon_corsair,nym","")
addFaction("borvo","gungan,jabba,trade_federation","")
addFaction("canyon_corsair","bloodrazor,nym","")
addFaction("cobral","restuss","")
addFaction("cor_swoop","smashball","")
addFaction("corsec","afarathu,followers_of_lord_nyax,monumenter,rogue_corsec,lost_aqualish","beldonnas_league")
addFaction("dantari_raiders","kunga_tribe,mokk_tribe,janta_tribe","")
addFaction("desert_demon","swoop","")
addFaction("donkuwah_tribe","gondula_tribe,panshee_tribe","")
addFaction("drall","corsec,fed_dub","")
addFaction("endor_marauder","gondula_tribe,panshee_tribe","")
addFaction("fed_dub","binayre,drall,liberation_party,lost_aqualish","")
addFaction("flail","hidden_daggers","")
addFaction("followers_of_lord_nyax","beldonnas_league,corsec","")
addFaction("fs_villager","sith_shadow","")
addFaction("garyn","restuss","")
addFaction("gondula_tribe","donkuwah_tribe,korga_tribe,pubam,endor_marauder","panshee_tribe")
addFaction("gungan","borvo,plasma_thief,swamp_rat","")
addFaction("hidden_daggers","beldonnas_league,corsec,flail","rogue_corsec")
addFaction("hutt","naboo_security_force,narmle,nym,imperial,corsec","jabba,borvo")
addFaction("jabba","borvo,valarian","hutt")
addFaction("janta_tribe","kunga_tribe,dantari_raiders","")
addFaction("jawa","tusken_raider","")
addFaction("kobola","narmle,spice_collective","")
addFaction("korga_tribe","gondula_tribe,panshee_tribe","")
addFaction("kunga_tribe","dantari_raiders,mokk_tribe","")
addFaction("liberation_party","corsec,fed_dub","")
addFaction("lok_mercenaries","bloodrazor,canyon_corsair","")
addFaction("lost_aqualish","beldonnas_league,corsec,fed_dub","")
addFaction("meatlump","beldonnas_league,corsec,rogue_corsec","")
addFaction("mokk","dantari_raiders,janta_tribe","")
addFaction("monumenter","beldonnas_league,corsec","")
addFaction("naboo","borvo","")
addFaction("naboo_pirate","naboo_security_force","")
addFaction("naboo_security_force","borvo,naboo_pirate,plasma_thief,swamp_rat,trade_federation","")
addFaction("narmle","kobola,spice_collective","restuss")
addFaction("nightsister","mtn_clan","")
addFaction("nym","bloodrazor,canyon_corsair","")
addFaction("olag_grek","beldonnas_league,corsec","")
addFaction("panshee_tribe","donkuwah_tribe,korga_tribe,pubam,endor_marauder","gondula_tribe")
addFaction("pirate","","")
addFaction("plasma_thief","gungan","")
addFaction("pubam","gondula_tribe,panshee_tribe","")
addFaction("restuss","cobral,garyn","narmle")
addFaction("rogue_corsec","corsec","hidden_daggers")
addFaction("rorgungan","spice_collective","")
addFaction("sif","imperial,rebel","hutt")
addFaction("mtn_clan","nightsister","")
addFaction("sith_shadow","fs_villager","imperial,rebel")
addFaction("sith_shadow_nonaggro","fs_villager","imperial,rebel")
addFaction("smashball","cor_swoop,corsec","")
addFaction("spice_collective","narmle,kobola,rorgungan","")
addFaction("spider_nightsister","mtn_clan","")
addFaction("swamp_rat","gungan","")
addFaction("swoop","desert_demon","")
addFaction("thug","townsperson","")
addFaction("townsperson","bandit,thug","imperial,rebel")
addFaction("trade_federation","borvo,naboo_security_force","")
addFaction("tusken_raider","alkhara,jawa","")
addFaction("valarian","jabba","")
|
--Factional Relationships determine enemies and allies of factions.
--If you kill a factional NPC, and it is allied with another faction, then you also lose faction with the ally.
--If you kill a factional NPC, and it is enemies with another faction, then you gain faction with the enemy.
--AddFaction
-- faction - This is the string key faction that the relationship describes.
-- enemies - This is a comma delimited list of string key factions that this faction is enemies with.
-- allies - This is a comma delimited list of string key factions that this faction is allies with.
addFaction("rebel","imperial","")
addFaction("imperial","rebel","")
addFaction("aakuans","binayre,fed_dub,liberation_party","")
addFaction("afarathu","corsec","")
addFaction("alkhara","tusken_raider","")
addFaction("bandit","townsperson","")
addFaction("beldonnas_league","followers_of_lord_nyax,lost_aqualish","corsec")
addFaction("binayre","aakuans,corsec,fed_dub","")
addFaction("bloodrazor","canyon_corsair,nym","")
addFaction("borvo","gungan,jabba,trade_federation","")
addFaction("canyon_corsair","bloodrazor,nym","")
addFaction("cobral","restuss","")
addFaction("cor_swoop","smashball","")
addFaction("corsec","afarathu,followers_of_lord_nyax,monumenter,rogue_corsec,lost_aqualish","beldonnas_league")
addFaction("dantari_raiders","kunga_tribe,mokk_tribe,janta_tribe","")
addFaction("desert_demon","swoop","")
addFaction("donkuwah_tribe","gondula_tribe,panshee_tribe","")
addFaction("drall","corsec,fed_dub","")
addFaction("endor_marauder","gondula_tribe,panshee_tribe","")
addFaction("fed_dub","binayre,drall,liberation_party,lost_aqualish","")
addFaction("flail","hidden_daggers","")
addFaction("followers_of_lord_nyax","beldonnas_league,corsec","")
addFaction("fs_villager","sith_shadow","")
addFaction("garyn","restuss","")
addFaction("gondula_tribe","donkuwah_tribe,korga_tribe,pubam,endor_marauder","panshee_tribe")
addFaction("gungan","borvo,plasma_thief,swamp_rat","")
addFaction("hidden_daggers","beldonnas_league,corsec,flail","rogue_corsec")
addFaction("hutt","naboo_security_force,narmle,nym,corsec","jabba,borvo")
addFaction("jabba","borvo,valarian","hutt")
addFaction("janta_tribe","kunga_tribe,dantari_raiders","")
addFaction("jawa","tusken_raider","")
addFaction("kobola","narmle,spice_collective","")
addFaction("korga_tribe","gondula_tribe,panshee_tribe","")
addFaction("kunga_tribe","dantari_raiders,mokk_tribe","")
addFaction("liberation_party","corsec,fed_dub","")
addFaction("lok_mercenaries","bloodrazor,canyon_corsair","")
addFaction("lost_aqualish","beldonnas_league,corsec,fed_dub","")
addFaction("meatlump","beldonnas_league,corsec,rogue_corsec","")
addFaction("mokk","dantari_raiders,janta_tribe","")
addFaction("monumenter","beldonnas_league,corsec","")
addFaction("naboo","borvo","")
addFaction("naboo_pirate","naboo_security_force","")
addFaction("naboo_security_force","borvo,naboo_pirate,plasma_thief,swamp_rat,trade_federation","")
addFaction("narmle","kobola,spice_collective","restuss")
addFaction("nightsister","mtn_clan","")
addFaction("nym","bloodrazor,canyon_corsair","")
addFaction("olag_grek","beldonnas_league,corsec","")
addFaction("panshee_tribe","donkuwah_tribe,korga_tribe,pubam,endor_marauder","gondula_tribe")
addFaction("pirate","","")
addFaction("plasma_thief","gungan","")
addFaction("pubam","gondula_tribe,panshee_tribe","")
addFaction("restuss","cobral,garyn","narmle")
addFaction("rogue_corsec","corsec","hidden_daggers")
addFaction("rorgungan","spice_collective","")
addFaction("sif","","hutt")
addFaction("mtn_clan","nightsister","")
addFaction("sith_shadow","fs_villager","")
addFaction("sith_shadow_nonaggro","fs_villager","")
addFaction("smashball","cor_swoop,corsec","")
addFaction("spice_collective","narmle,kobola,rorgungan","")
addFaction("spider_nightsister","mtn_clan","")
addFaction("swamp_rat","gungan","")
addFaction("swoop","desert_demon","")
addFaction("thug","townsperson","")
addFaction("townsperson","bandit,thug","")
addFaction("trade_federation","borvo,naboo_security_force","")
addFaction("tusken_raider","alkhara,jawa","")
addFaction("valarian","jabba","")
|
[Fixed] killing some non-gcw faction targets increasing/reducing gcw faction - mantis 4382
|
[Fixed] killing some non-gcw faction targets increasing/reducing gcw
faction - mantis 4382
Change-Id: Ib5385454c203b82d0ee3e215898c2fb867c54a84
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
75f2c2774fd24edbe305a1a61199f460bcd9a4a2
|
reader.lua
|
reader.lua
|
#!./kpdfview
package.path = "./frontend/?.lua"
require "ui/ui"
require "ui/readerui"
require "ui/filechooser"
require "ui/infomessage"
require "document/document"
require "alt_getopt"
function showReader(file, pass)
local document = DocumentRegistry:openDocument(file)
if not document then
UIManager:show(InfoMessage:new{ text = "No reader engine for this file" })
return
end
local readerwindow = FrameContainer:new{
dimen = Screen:getSize(),
background = 0,
margin = 0,
padding = 0,
bordersize = 0
}
local reader = ReaderUI:new{
dialog = readerwindow,
dimen = Screen:getSize(),
document = document,
password = pass
}
readerwindow[1] = reader
UIManager:show(readerwindow)
end
function showFileManager(path)
local FileManager = FileChooser:new{
path = path,
dimen = Screen:getSize(),
is_borderless = true,
filter = function(filename)
if DocumentRegistry:getProvider(filename) then
return true
end
end
}
function FileManager:onFileSelect(file)
showReader(file)
return true
end
function FileManager:onClose()
UIManager:quit()
return true
end
UIManager:show(FileManager)
end
-- option parsing:
longopts = {
password = "p",
goto = "g",
gamma = "G",
debug = "d",
help = "h",
}
function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the GPLv3.")
print("See http://github.com/hwhw/kindlepdfviewer for more info.")
return
end
optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:dg:", longopts)
if ARGV[1] == "-h" then
return showusage()
end
local argidx = 1
if ARGV[1] == "-d" then
argidx = argidx + 1
else
DEBUG = function() end
end
if Device.isKindle4() then
-- remove menu item shortcut for K4
Menu.is_enable_shortcut = false
end
-- set up reader's setting: font
G_reader_settings = DocSettings:open(".reader")
fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
local last_file = G_reader_settings:readSetting("lastfile")
Screen:updateRotationMode()
Screen.native_rotation_mode = Screen.cur_rotation_mode
--@TODO we can read version here, refer to commit in master tree: (houqp)
--87712cf0e43fed624f8a9f610be42b1fe174b9fe
if ARGV[argidx] then
if lfs.attributes(ARGV[argidx], "mode") == "directory" then
showFileManager(ARGV[argidx])
elseif lfs.attributes(ARGV[argidx], "mode") == "file" then
showReader(ARGV[argidx], optarg["p"])
end
UIManager:run()
elseif last_file and lfs.attributes(last_file, "mode") == "file" then
showReader(last_file, optarg["p"])
UIManager:run()
else
return showusage()
end
if ARGV[optind] then
if lfs.attributes(ARGV[optind], "mode") == "directory" then
showFileManager(ARGV[optind])
elseif lfs.attributes(ARGV[optind], "mode") == "file" then
showReader(ARGV[optind], optarg["p"])
end
UIManager:run()
elseif last_file and lfs.attributes(last_file, "mode") == "file" then
showReader(last_file, optarg["p"])
UIManager:run()
else
return showusage()
end
-- @TODO dirty workaround, find a way to force native system poll
-- screen orientation and upside down mode 09.03 2012
Screen:setRotationMode(Screen.native_rotation_mode)
input.closeAll()
if util.isEmulated()==0 then
os.execute("killall -cont cvm")
-- send double menu key press events to trigger screen refresh
os.execute("echo 'send 139' > /proc/keypad;echo 'send 139' > /proc/keypad")
end
|
#!./kpdfview
package.path = "./frontend/?.lua"
require "ui/ui"
require "ui/readerui"
require "ui/filechooser"
require "ui/infomessage"
require "document/document"
function showReader(file, pass)
local document = DocumentRegistry:openDocument(file)
if not document then
UIManager:show(InfoMessage:new{ text = "No reader engine for this file" })
return
end
local readerwindow = FrameContainer:new{
dimen = Screen:getSize(),
background = 0,
margin = 0,
padding = 0,
bordersize = 0
}
local reader = ReaderUI:new{
dialog = readerwindow,
dimen = Screen:getSize(),
document = document,
password = pass
}
readerwindow[1] = reader
UIManager:show(readerwindow)
end
function showFileManager(path)
local FileManager = FileChooser:new{
path = path,
dimen = Screen:getSize(),
is_borderless = true,
filter = function(filename)
if DocumentRegistry:getProvider(filename) then
return true
end
end
}
function FileManager:onFileSelect(file)
showReader(file)
return true
end
function FileManager:onClose()
UIManager:quit()
return true
end
UIManager:show(FileManager)
end
-- option parsing:
longopts = {
password = "p",
goto = "g",
gamma = "G",
debug = "d",
help = "h",
}
function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the GPLv3.")
print("See http://github.com/hwhw/kindlepdfviewer for more info.")
return
end
if ARGV[1] == "-h" then
return showusage()
end
local argidx = 1
if ARGV[1] == "-d" then
argidx = argidx + 1
else
DEBUG = function() end
end
if Device.isKindle4() then
-- remove menu item shortcut for K4
Menu.is_enable_shortcut = false
end
-- set up reader's setting: font
G_reader_settings = DocSettings:open(".reader")
fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
local last_file = G_reader_settings:readSetting("lastfile")
Screen:updateRotationMode()
Screen.native_rotation_mode = Screen.cur_rotation_mode
--@TODO we can read version here, refer to commit in master tree: (houqp)
--87712cf0e43fed624f8a9f610be42b1fe174b9fe
if ARGV[argidx] then
if lfs.attributes(ARGV[argidx], "mode") == "directory" then
showFileManager(ARGV[argidx])
elseif lfs.attributes(ARGV[argidx], "mode") == "file" then
showReader(ARGV[argidx], optarg["p"])
end
UIManager:run()
elseif last_file and lfs.attributes(last_file, "mode") == "file" then
showReader(last_file, optarg["p"])
UIManager:run()
else
return showusage()
end
if ARGV[optind] then
if lfs.attributes(ARGV[optind], "mode") == "directory" then
showFileManager(ARGV[optind])
elseif lfs.attributes(ARGV[optind], "mode") == "file" then
showReader(ARGV[optind], optarg["p"])
end
UIManager:run()
elseif last_file and lfs.attributes(last_file, "mode") == "file" then
showReader(last_file, optarg["p"])
UIManager:run()
else
return showusage()
end
-- @TODO dirty workaround, find a way to force native system poll
-- screen orientation and upside down mode 09.03 2012
Screen:setRotationMode(Screen.native_rotation_mode)
input.closeAll()
if util.isEmulated()==0 then
os.execute("killall -cont cvm")
-- send double menu key press events to trigger screen refresh
os.execute("echo 'send 139' > /proc/keypad;echo 'send 139' > /proc/keypad")
end
|
fix getopt module clearance in reader.lua
|
fix getopt module clearance in reader.lua
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,houqp/koreader,houqp/koreader-base,koreader/koreader,apletnev/koreader-base,Frenzie/koreader-base,ashang/koreader,chrox/koreader,Hzj-jie/koreader-base,Frenzie/koreader,Hzj-jie/koreader,mwoz123/koreader,Markismus/koreader,Frenzie/koreader,houqp/koreader-base,NiLuJe/koreader,frankyifei/koreader-base,apletnev/koreader,robert00s/koreader,houqp/koreader-base,lgeek/koreader,poire-z/koreader,koreader/koreader-base,koreader/koreader-base,houqp/koreader-base,apletnev/koreader-base,koreader/koreader,poire-z/koreader,noname007/koreader,frankyifei/koreader,apletnev/koreader-base,mihailim/koreader,koreader/koreader-base,Frenzie/koreader-base,pazos/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,NickSavage/koreader,Hzj-jie/koreader-base,frankyifei/koreader-base,NiLuJe/koreader,Frenzie/koreader-base,ashhher3/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,chihyang/koreader,Hzj-jie/koreader-base
|
b4574a735966ba8b3c82a234c11803e47be0839f
|
reader.lua
|
reader.lua
|
#!./luajit
-- load default settings
require "defaults"
pcall(dofile, "defaults.persistent.lua")
-- set search path for 'require()'
package.path = "common/?.lua;frontend/?.lua;" .. package.path
package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;" .. package.cpath
-- set search path for 'ffi.load()'
local ffi = require("ffi")
local util = require("ffi/util")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
int _putenv(const char *envvar);
]]
if ffi.os == "Windows" then
ffi.C._putenv("PATH=libs;common;")
else
ffi.C.putenv("LD_LIBRARY_PATH="
.. util.realpath("libs") .. ":"
.. util.realpath("common") ..":"
.. ffi.string(ffi.C.getenv("LD_LIBRARY_PATH")))
end
local DocSettings = require("docsettings")
local _ = require("gettext")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = DocSettings:open(".reader")
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
return
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local DEBUG = require("dbg")
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
DEBUG:turnOn()
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = require("device").screen
local Font = require("ui/font")
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") ~= "file" then
last_file = nil
end
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
-- night mode
if G_reader_settings:readSetting("night_mode") then
Screen:toggleNightMode()
end
-- restore kobo frontlight settings
if Device:isKobo() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
local intensity = G_reader_settings:readSetting("frontlight_intensity")
intensity = intensity or powerd.flIntensity
powerd:setIntensityWithoutHW(intensity)
-- powerd:setIntensity(intensity)
end
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set true
-- the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(file)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
FileManager:showFiles(ARGV[argidx])
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(last_file)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
#!./luajit
-- load default settings
require "defaults"
pcall(dofile, "defaults.persistent.lua")
-- set search path for 'require()'
package.path = "common/?.lua;frontend/?.lua;" .. package.path
package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;" .. package.cpath
-- set search path for 'ffi.load()'
local ffi = require("ffi")
local util = require("ffi/util")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
int _putenv(const char *envvar);
]]
if ffi.os == "Windows" then
ffi.C._putenv("PATH=libs;common;")
end
local DocSettings = require("docsettings")
local _ = require("gettext")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = DocSettings:open(".reader")
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
return
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local DEBUG = require("dbg")
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
DEBUG:turnOn()
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = require("device").screen
local Font = require("ui/font")
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") ~= "file" then
last_file = nil
end
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
-- night mode
if G_reader_settings:readSetting("night_mode") then
Screen:toggleNightMode()
end
-- restore kobo frontlight settings
if Device:isKobo() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
local intensity = G_reader_settings:readSetting("frontlight_intensity")
intensity = intensity or powerd.flIntensity
powerd:setIntensityWithoutHW(intensity)
-- powerd:setIntensity(intensity)
end
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set true
-- the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(file)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
FileManager:showFiles(ARGV[argidx])
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(last_file)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
fix crash on kindle
|
fix crash on kindle
|
Lua
|
agpl-3.0
|
koreader/koreader,pazos/koreader,mihailim/koreader,poire-z/koreader,apletnev/koreader,lgeek/koreader,NiLuJe/koreader,chrox/koreader,koreader/koreader,frankyifei/koreader,mwoz123/koreader,NiLuJe/koreader,NickSavage/koreader,Frenzie/koreader,ashhher3/koreader,noname007/koreader,robert00s/koreader,houqp/koreader,Frenzie/koreader,chihyang/koreader,Markismus/koreader,poire-z/koreader,ashang/koreader,Hzj-jie/koreader
|
1332d5d4f5bc5a6c0b3e22623f1779f56854399c
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.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.tools.webadmin")
m = Map("olsrd", translate("olsrd", "OLSR Daemon"))
s = m:section(TypedSection, "olsrd", translate("olsrd_general"))
s.dynamic = true
s.anonymous = true
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
debug.optional = true
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
noint.optional = true
s:option(Value, "Pollrate").optional = true
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsrd_olsrd_tcredundancy_0"))
tcr:value("1", translate("olsrd_olsrd_tcredundancy_1"))
tcr:value("2", translate("olsrd_olsrd_tcredundancy_2"))
tcr.optional = true
s:option(Value, "MprCoverage").optional = true
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1"))
lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2"))
lql.optional = true
s:option(Value, "LinkQualityAging").optional = true
lqa = s:option(ListValue, "LinkQualityAlgorithm")
lqa.optional = true
lqa:value("etx_fpm", translate("olsrd_etx_fpm"))
lqa:value("etx_float", translate("olsrd_etx_float"))
lqa:value("etx_ff", translate("olsrd_etx_ff"))
lqa.optional = true
lqfish = s:option(Flag, "LinkQualityFishEye")
lqfish.optional = true
s:option(Value, "LinkQualityWinSize").optional = true
s:option(Value, "LinkQualityDijkstraLimit").optional = true
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
hyst.optional = true
fib = s:option(ListValue, "FIBMetric")
fib.optional = true
fib:value("flat")
fib:value("correct")
fib:value("approx")
fib.optional = true
clrscr = s:option(Flag, "ClearScreen")
clrscr.enabled = "yes"
clrscr.disabled = "no"
clrscr.optional = true
willingness = s:option(ListValue, "Willingness")
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
ign = i:option(Flag, "ignore", "Enable")
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
network = i:option(ListValue, "interface", translate("network"))
luci.tools.webadmin.cbi_add_networks(network)
i:option(Value, "Ip4Broadcast").optional = true
ip6t = i:option(ListValue, "Ip6AddrType")
ip6t:value("", translate("cbi_select"))
ip6t:value("auto")
ip6t:value("site-local")
ip6t:value("unique-local")
ip6t:value("global")
ip6t.optional = true
i:option(Value, "HelloInterval").optional = true
i:option(Value, "HelloValidityTime").optional = true
i:option(Value, "TcInterval").optional = true
i:option(Value, "TcValidityTime").optional = true
i:option(Value, "MidInterval").optional = true
i:option(Value, "MidValidityTime").optional = true
i:option(Value, "HnaInterval").optional = true
i:option(Value, "HnaValidityTime").optional = true
adc = i:option(Flag, "AutoDetectChanges")
adc.enabled = "yes"
adc.disabled = "no"
adc.optional = true
--[[
ipc = m:section(TypedSection, "IpcConnect")
ipc.anonymous = true
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.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.tools.webadmin")
m = Map("olsrd", translate("olsrd", "OLSR Daemon"))
s = m:section(TypedSection, "olsrd", translate("olsrd_general"))
s.dynamic = true
s.anonymous = true
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
debug.optional = true
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
noint.optional = true
s:option(Value, "Pollrate").optional = true
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsrd_olsrd_tcredundancy_0"))
tcr:value("1", translate("olsrd_olsrd_tcredundancy_1"))
tcr:value("2", translate("olsrd_olsrd_tcredundancy_2"))
tcr.optional = true
s:option(Value, "MprCoverage").optional = true
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1"))
lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2"))
lql.optional = true
s:option(Value, "LinkQualityAging").optional = true
lqa = s:option(ListValue, "LinkQualityAlgorithm")
lqa.optional = true
lqa:value("etx_fpm", translate("olsrd_etx_fpm"))
lqa:value("etx_float", translate("olsrd_etx_float"))
lqa:value("etx_ff", translate("olsrd_etx_ff"))
lqa.optional = true
lqfish = s:option(Flag, "LinkQualityFishEye")
lqfish.optional = true
s:option(Value, "LinkQualityWinSize").optional = true
s:option(Value, "LinkQualityDijkstraLimit").optional = true
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
hyst.optional = true
fib = s:option(ListValue, "FIBMetric")
fib.optional = true
fib:value("flat")
fib:value("correct")
fib:value("approx")
fib.optional = true
clrscr = s:option(Flag, "ClearScreen")
clrscr.enabled = "yes"
clrscr.disabled = "no"
clrscr.optional = true
willingness = s:option(ListValue, "Willingness")
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
ign = i:option(Flag, "ignore", "Enable")
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
network = i:option(ListValue, "interface", translate("network"))
luci.tools.webadmin.cbi_add_networks(network)
i:option(Value, "Ip4Broadcast").optional = true
ip6t = i:option(ListValue, "Ip6AddrType")
ip6t:value("", translate("cbi_select"))
ip6t:value("auto")
ip6t:value("site-local")
ip6t:value("unique-local")
ip6t:value("global")
ip6t.optional = true
i:option(Value, "HelloInterval").optional = true
i:option(Value, "HelloValidityTime").optional = true
i:option(Value, "TcInterval").optional = true
i:option(Value, "TcValidityTime").optional = true
i:option(Value, "MidInterval").optional = true
i:option(Value, "MidValidityTime").optional = true
i:option(Value, "HnaInterval").optional = true
i:option(Value, "HnaValidityTime").optional = true
adc = i:option(Flag, "AutoDetectChanges")
adc.enabled = "yes"
adc.disabled = "no"
adc.optional = true
--[[
ipc = m:section(TypedSection, "IpcConnect")
ipc.anonymous = true
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
]]
return m
|
[applications] luci-olsr: Fix enable option for interfaces
|
[applications] luci-olsr: Fix enable option for interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4740 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,Flexibity/luci,alxhh/piratenluci,Flexibity/luci,alxhh/piratenluci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,8devices/carambola2-luci,Flexibity/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,eugenesan/openwrt-luci,alxhh/piratenluci,ch3n2k/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,ch3n2k/luci,ch3n2k/luci,Flexibity/luci,jschmidlapp/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,stephank/luci,phi-psi/luci,Flexibity/luci,ch3n2k/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,saraedum/luci-packages-old,freifunk-gluon/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Canaan-Creative/luci,alxhh/piratenluci,projectbismark/luci-bismark,alxhh/piratenluci,8devices/carambola2-luci,gwlim/luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,jschmidlapp/luci,Canaan-Creative/luci,8devices/carambola2-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,yeewang/openwrt-luci,vhpham80/luci,vhpham80/luci,gwlim/luci,ThingMesh/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,stephank/luci,8devices/carambola2-luci,phi-psi/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,gwlim/luci,Canaan-Creative/luci,vhpham80/luci,8devices/carambola2-luci,freifunk-gluon/luci,yeewang/openwrt-luci,stephank/luci,jschmidlapp/luci,saraedum/luci-packages-old,stephank/luci,phi-psi/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,vhpham80/luci,gwlim/luci,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,gwlim/luci,gwlim/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,vhpham80/luci,alxhh/piratenluci,yeewang/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci
|
b0bde07c534e87d188911ccb505dc9aedda60f05
|
post_receive.lua
|
post_receive.lua
|
#!/usr/bin/lua
local JSON = require "JSON"
local socket = require "socket"
local lfs = require "lfs"
local old = arg[1] or "??"
local new = arg[2] or "??"
local ref = arg[3] or "(master?)"
local commit = {repository="git", ref=ref}
local pwd = lfs.currentdir()
local project = pwd:match("([^/]+)$") or "unknown"
local pipe = io.popen("git show --name-only " .. new or "??")
commit.hash = new
commit.shortHash = commit.hash:sub(1,7)
commit.project = project
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
local key, val = line:match("^(%S+):%s+(.+)$")
if key and val then
key = key:lower()
if key == "author" then
local author, email = val:match("^(.-) <(.-)>$")
commit.author = author or "(uknown)"
commit.email = email or "(unknown)"
else
commit[key] = val
end
end
end
commit.log = ""
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
commit.log = commit.log .. line:gsub("^ ", "") .. "\n"
end
commit.log = commit.log:gsub("\n$", "")
commit.files = {}
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
table.insert(commit.files, line)
end
pipe:close()
if #commit.files == 1 then
commit.changes = commit.files[1]
else
commit.changes = #commit.files .. " files"
end
local out = JSON:encode({commit=commit})
local s = socket.tcp()
s:settimeout(0.5)
local success, err = s:connect("127.0.0.1", 2069)
if not success then
os.exit()
end
while true do
local line = s:receive("*l")
if not line or line:len() == 0 then break end
end
s:send("POST /json HTTP/1.1\r\n")
s:send("Host: localhost\r\n\r\n")
s:send(out .."\r\n")
s:shutdown()
s:close()
|
#!/usr/bin/lua
local JSON = require "JSON"
local socket = require "socket"
local lfs = require "lfs"
local old = arg[1]
local new = arg[2]
local ref = arg[3] or "(no ref)"
if not old or not new then
print("Usage: post-receive [old] [new] [ref]")
os.exit()
end
local commit = {repository="git", ref=ref}
local pwd = lfs.currentdir()
local project = pwd:match("([^/]+)$") or "unknown"
local pipe = io.popen("git show --name-only " .. new)
commit.hash = new
commit.shortHash = commit.hash:sub(1,7)
commit.project = project
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
local key, val = line:match("^(%S+):%s+(.+)$")
if key and val then
key = key:lower()
if key == "author" then
local author, email = val:match("^(.-) <(.-)>$")
commit.author = author or "(uknown)"
commit.email = email or "(unknown)"
else
commit[key] = val
end
end
end
commit.log = ""
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
commit.log = commit.log .. line:gsub("^ ", "") .. "\n"
end
commit.log = commit.log:gsub("\n$", "")
commit.files = {}
while true do
local line = pipe:read("*l")
if not line or line:len() == 0 then break end
table.insert(commit.files, line)
end
pipe:close()
if #commit.files == 1 then
commit.changes = commit.files[1]
else
commit.changes = #commit.files .. " files"
end
local out = JSON:encode({commit=commit})
local s = socket.tcp()
s:settimeout(0.5)
local success, err = s:connect("127.0.0.1", 2069)
if not success then
os.exit()
end
s:send("POST /json HTTP/1.1\r\n")
s:send("Host: localhost\r\n\r\n")
s:send(out .."\r\n")
s:shutdown()
s:close()
|
Fix up post-receive hook
|
Fix up post-receive hook
|
Lua
|
apache-2.0
|
Humbedooh/gitpubsub
|
7c54d4e62fc84b29915dc618fd3dba2962752e92
|
profiles/car.lua
|
profiles/car.lua
|
-- Begin of globals
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["default"] = 50
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
--find first tag in access hierachy which is set
local function find_access_tag(source)
for i,v in ipairs(access_tags_hierachy) do
if source.tags:Holds(v) then
local tag = source.tags:Find(v)
if tag ~= '' then --and tag ~= "" then
return tag
end
end
end
return nil
end
local function find_in_keyvals(keyvals, tag)
if keyvals:Holds(tag) then
return keyvals:Find(tag)
else
return nil
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source)
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = find_access_tag(node)
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
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- 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 = parse_maxspeed(way.tags:Find ( "maxspeed") )
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = find_access_tag(way)
-- 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] then
return 0
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( 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;
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
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed 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 oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
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
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
-- Begin of globals
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["default"] = 50
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
--find first tag in access hierachy which is set
local function find_access_tag(source)
for i,v in ipairs(access_tags_hierachy) do
if source.tags:Holds(v) then
local tag = source.tags:Find(v)
if tag ~= '' then --and tag ~= "" then
return tag
end
end
end
return nil
end
local function find_in_keyvals(keyvals, tag)
if keyvals:Holds(tag) then
return keyvals:Find(tag)
else
return nil
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
io.write("speed: "..n.."\n")
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = find_access_tag(node)
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
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- 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 = parse_maxspeed(way.tags:Find ( "maxspeed") )
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = find_access_tag(way)
-- 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] then
return 0
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( 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;
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
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed 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 oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
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
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
Fixes the Birminingham speed limit bug reported by Philip Barnes
|
Fixes the Birminingham speed limit bug reported by Philip Barnes
|
Lua
|
bsd-2-clause
|
antoinegiret/osrm-geovelo,nagyistoce/osrm-backend,alex85k/Project-OSRM,bjtaylor1/osrm-backend,skyborla/osrm-backend,arnekaiser/osrm-backend,antoinegiret/osrm-backend,Project-OSRM/osrm-backend,arnekaiser/osrm-backend,agruss/osrm-backend,stevevance/Project-OSRM,arnekaiser/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-backend,oxidase/osrm-backend,Carsten64/OSRM-aux-git,tkhaxton/osrm-backend,ammeurer/osrm-backend,beemogmbh/osrm-backend,keesklopt/matrix,atsuyim/osrm-backend,bjtaylor1/Project-OSRM-Old,KnockSoftware/osrm-backend,alex85k/Project-OSRM,arnekaiser/osrm-backend,oxidase/osrm-backend,beemogmbh/osrm-backend,frodrigo/osrm-backend,ibikecph/osrm-backend,duizendnegen/osrm-backend,neilbu/osrm-backend,chaupow/osrm-backend,tkhaxton/osrm-backend,frodrigo/osrm-backend,nagyistoce/osrm-backend,bjtaylor1/Project-OSRM-Old,ibikecph/osrm-backend,Tristramg/osrm-backend,ammeurer/osrm-backend,prembasumatary/osrm-backend,keesklopt/matrix,agruss/osrm-backend,atsuyim/osrm-backend,Conggge/osrm-backend,felixguendling/osrm-backend,tkhaxton/osrm-backend,Project-OSRM/osrm-backend,ramyaragupathy/osrm-backend,Project-OSRM/osrm-backend,deniskoronchik/osrm-backend,bjtaylor1/osrm-backend,ammeurer/osrm-backend,Conggge/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,felixguendling/osrm-backend,yuryleb/osrm-backend,stevevance/Project-OSRM,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,alex85k/Project-OSRM,bitsteller/osrm-backend,keesklopt/matrix,atsuyim/osrm-backend,ibikecph/osrm-backend,neilbu/osrm-backend,antoinegiret/osrm-backend,jpizarrom/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,Carsten64/OSRM-aux-git,raymond0/osrm-backend,bjtaylor1/Project-OSRM-Old,ramyaragupathy/osrm-backend,Conggge/osrm-backend,agruss/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,stevevance/Project-OSRM,chaupow/osrm-backend,bjtaylor1/Project-OSRM-Old,jpizarrom/osrm-backend,frodrigo/osrm-backend,keesklopt/matrix,antoinegiret/osrm-geovelo,deniskoronchik/osrm-backend,raymond0/osrm-backend,Project-OSRM/osrm-backend,hydrays/osrm-backend,KnockSoftware/osrm-backend,hydrays/osrm-backend,prembasumatary/osrm-backend,ammeurer/osrm-backend,jpizarrom/osrm-backend,frodrigo/osrm-backend,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,oxidase/osrm-backend,prembasumatary/osrm-backend,ammeurer/osrm-backend,nagyistoce/osrm-backend,KnockSoftware/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,Tristramg/osrm-backend,skyborla/osrm-backend,antoinegiret/osrm-geovelo,felixguendling/osrm-backend,yuryleb/osrm-backend,bjtaylor1/osrm-backend,Tristramg/osrm-backend,beemogmbh/osrm-backend,raymond0/osrm-backend,oxidase/osrm-backend,bitsteller/osrm-backend,neilbu/osrm-backend,stevevance/Project-OSRM,Conggge/osrm-backend,raymond0/osrm-backend,hydrays/osrm-backend,neilbu/osrm-backend,ammeurer/osrm-backend,bitsteller/osrm-backend,beemogmbh/osrm-backend,chaupow/osrm-backend,yuryleb/osrm-backend
|
d82a758556d879bfaa6372835e591699b3bfb525
|
MMOCoreORB/bin/scripts/object/building/base/base_building.lua
|
MMOCoreORB/bin/scripts/object/building/base/base_building.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_building_base_base_building = object_building_base_shared_base_building:new {
containerComponent = {"cpp", "StructureContainerComponent"}
}
ObjectTemplates:addTemplate(object_building_base_base_building, "object/building/base/base_building.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_building_base_base_building = object_building_base_shared_base_building:new {
containerComponent = {"cpp", "StructureContainerComponent"},
lotSize = 0,
baseMaintenanceRate = 0,
--What zones can this building be built by a player on.
--Default is corellia, dantooine, lok, naboo, rori, talus, tatooine
allowedZones = {"corellia", "dantooine", "lok", "naboo", "rori", "talus", "tatooine"},
--The minimum rank of a player city required for this structure to be placed.
cityRankRequired = 0,
--Skills required to place this structure object. String value of the particular skill box.
skillRequired = "",
--Abilities required to place this structure object. String value of the ability.
abilityRequired = "",
--Sign is a childObject for the default sign of this structure.
sign = {templateFile = "", x = 0, z = 0, y = 0, ox = 0, oy = 0, oz = 0, ow = 0, cellid = -1, containmentType = 0},
--Should the structure be public by default?
publicStructure = 1,
--Can the structure ever be private?
alwaysPublic = 0,
--The object that is placed during the construction phase.
constructionMarker = "",
--Elevator Terminals format is template_path, cell#, x, z, y, qx, qy, qz, qw, dz - where dz is the delta z.
elevatorTerminals = {},
length = 1,
width = 1
}
ObjectTemplates:addTemplate(object_building_base_base_building, "object/building/base/base_building.iff")
|
[fixed] default values for building object tempates
|
[fixed] default values for building object tempates
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4258 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/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,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
d09ffe195832a3ae8f4170faabff5f230522c7d4
|
kong/api/routes/clustering.lua
|
kong/api/routes/clustering.lua
|
local endpoints = require "kong.api.endpoints"
local kong = kong
local dp_collection_endpoint = endpoints.get_collection_endpoint(kong.db.clustering_data_planes.schema)
return {
["/clustering/data-planes"] = {
schema = kong.db.clustering_data_planes.schema,
methods = {
GET = function(self, dao, helpers)
if kong.configuration.role ~= "control_plane" then
return kong.response.exit(400, {
message = "this endpoint is only available when Kong is " ..
"configured to run as Control Plane for the cluster"
})
end
return dp_collection_endpoint(self, dao, helpers)
end,
},
},
["/clustering/status"] = {
schema = kong.db.clustering_data_planes.schema,
methods = {
GET = function(self, db, helpers)
if kong.configuration.role ~= "control_plane" then
return kong.response.exit(400, {
message = "this endpoint is only available when Kong is " ..
"configured to run as Control Plane for the cluster"
})
end
local data = {}
for row, err in kong.db.clustering_data_planes:each() do
if err then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error happened" })
end
local id = row.id
row.id = nil
data[id] = row
end
return kong.response.exit(200, data, {
["Deprecation"] = "true" -- see: https://tools.ietf.org/html/draft-dalal-deprecation-header-03
})
end,
},
},
}
|
local endpoints = require "kong.api.endpoints"
local kong = kong
local dp_collection_endpoint = endpoints.get_collection_endpoint(kong.db.clustering_data_planes.schema)
return {
["/clustering/data-planes"] = {
schema = kong.db.clustering_data_planes.schema,
methods = {
GET = function(self, dao, helpers)
if kong.configuration.role ~= "control_plane" then
return kong.response.exit(400, {
message = "this endpoint is only available when Kong is " ..
"configured to run as Control Plane for the cluster"
})
end
return dp_collection_endpoint(self, dao, helpers)
end,
},
},
["/clustering/status"] = {
schema = kong.db.clustering_data_planes.schema,
methods = {
GET = function(self, db, helpers)
if kong.configuration.role ~= "control_plane" then
return kong.response.exit(400, {
message = "this endpoint is only available when Kong is " ..
"configured to run as Control Plane for the cluster"
})
end
local data = {}
for row, err in kong.db.clustering_data_planes:each() do
if err then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error happened" })
end
data[row.id] = {
config_hash = row.config_hash,
hostname = row.hostname,
ip = row.ip,
last_seen = row.last_seen,
}
end
return kong.response.exit(200, data, {
["Deprecation"] = "true" -- see: https://tools.ietf.org/html/draft-dalal-deprecation-header-03
})
end,
},
},
}
|
fix(clustering) do not include the new fields in the deprecated `/clustering/status` endpoint
|
fix(clustering) do not include the new fields in the deprecated
`/clustering/status` endpoint
Since we have announced the deprecation of the `/clustering/status` endpoint,
we should not make new database fields available from it. This
encourages people to switch over, but also because we no longer provide any
documentation update to the old endpoint.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
6983868f5eb3391dcf21172e771eae1d5a9ecdd5
|
nonsence_web.lua
|
nonsence_web.lua
|
--[[
"Nonsence" Lua web server
Author: John Abrahamsen ([email protected]).
License: MIT.
The ultra fast cached web server written in Lua.
.;''-.
.' | `._
/` ; `'.
.' \ \
,'\| `| |
| -'_ \ `'.__,J
;' `. `'.__.'
| `"-.___ ,'
'-, /
|.-`-.______-|
} __.--'L
; _,- _.-"`\ ___
`7-;" ' _,,--._ ,-'`__ `.
|/ ,'- .7'.-"--.7 | _.-'
; ,' .' .' .-. \/ .'
; / / .'.- ` |__ .'
\ | .' / | \_)- `'/ _.-'``
_,.--../ .' \_) '`_ \'`
'`f-'``'.`\;;' ''` '-` |
\`.__. ;;;, ) /
`-._,|;;;,, /\ ,'
/ /<_;;;;' `-._ _,-'
| '- /;;;;;, `t'` \. I like nonsence.
`'-'`_.|,';;;, '._/| It wakes up the brain cells!
,_.-' \ |;;;;; `-._/
/ `;\ |;;;, `" - Theodor Seuss Geisel -
.' `'`\;;, /
' ;;;'|
.--. ;.:`\ _.--,
| `'./;' _ '_.' |
\_ `"7f `) /
|` _.-'`t-'`"-.,__.'
`'-'`/;; | | \ mx
;;; ,' | `
/ '
]]--
local web = {}
local epoll = assert(require('epoll'), [[Missing required module: Lua Epoll. (https://github.com/Neopallium/lua-epoll)]])
local nixio = assert(require('nixio'), [[Missing required module: Nixio (https://github.com/Neopallium/nixio)]])
local mime = require('nonsence_mime') -- Require MIME module for document types.
local http_status_codes = require('nonsence_codes') -- Require codes module for HTTP status codes.
local json = require('json') -- Require JSON for automagic writing of Lua tables with self:write().
local type = type
------------------------------------------------
---
--
-- Application Class.
--
---
------------------------------------------------
web.Application = {}
function web.Application:new(routinglist)
application = application or {}
setmetatable(application, self)
self.__index = self
self.routinglist = assert(routinglist, 'Please provide a routinglist when using web.Application:new(routinglist)')
---*
--
-- Adds the application to the applications table.
-- Method: listen()
-- Description: Sets the port to be used for socket.
--
---*
self.listen = function (self, port)
self.port = assert(port, 'Please provide a port number when using web.Application:listen(port)')
nonsence_applications[#nonsence_applications + 1] = { port = port, routinglist = routinglist }
end
return application
end
------------------------------------------------
---
--
-- RequestHandler Class.
--
---
------------------------------------------------
web.RequestHandler = {}
function web.RequestHandler:new(requesthandler)
requesthandler = requesthandler or {}
setmetatable(requesthandler, self)
self.__index = self
self.headers = {}
self.headers.http_version = "HTTP/1.1"
self.headers.status_code = 200
self.headers.server_name = "nonsence version 0.1"
--self.headers.keep_alive = "Keep-Alive: timeout=3, max=199"
self.headers.connection = "Close"
self.headers.content_type = "text/html"
self.headers.date = os.date("!%a, %d %b %Y %H:%M:%S GMT")
self.arguments = {}
local function _write_headers(content_length)
local headers = self.headers
local write_to_buffer = write_to_buffer
write_to_buffer(headers.http_version .. " ")
write_to_buffer(headers.status_code .. " " .. http_status_codes[headers.status_code] .. "\r\n")
write_to_buffer("Server: " .. headers.server_name .. "\r\n")
write_to_buffer("Connection: " .. headers.connection .. "\r\n")
write_to_buffer("Content-Type: " .. headers.content_type .. "\r\n")
write_to_buffer("Content-Length: " .. content_length or 0)
write_to_buffer("\r\n\r\n")
end
function self.set_status_code(self, code)
if code and type(code) == 'number' then
self.headers.status_code = code
else
error('self.status_code() expects type number got: ' .. type(code))
end
end
function self._set_arguments(self, args_string)
local args_string = args_string or ''
local args_table = {}
for key, value in args_string:gmatch("([^=?]*)=?([^&?]*)") do
args_table[key] = value
end
self.arguments = args_table
end
function self.get_arguments(self)
return self.arguments
end
function self.get_argument(self, key)
if self.arguments[key] then
return self.arguments[key]
else
-- Die?
end
end
function self.write(self, data)
if data then
local write_to_buffer = write_to_buffer
if type(data) == 'string' or type(data) == 'number' then
_write_headers(data:len())
write_to_buffer(data)
elseif type(data) == 'table' then
local stringified = json.encode(data)
self.headers.content_type = 'application/json' -- Set correct JSON type.
_write_headers(stringified:len())
write_to_buffer(stringified)
elseif type(data) == 'function' then
-- What to do here?
end
else
_write_headers(0)
end
end
return requesthandler
end
------------------------------------------------
---
--
-- Tools
--
---
------------------------------------------------
web.parse_headers = function(raw_headers)
local HTTPHeader = raw_headers
if HTTPHeader then
-- Fetch HTTP Method.
local method, uri = HTTPHeader:match("([%a*%-*]+)%s+(.-)%s")
-- Fetch all header values by key and value
local request_header_table = {}
for key, value in HTTPHeader:gmatch("([%a*%-*]+):%s?(.-)[\r?\n]+") do
request_header_table[key] = value
end
return { method = method, uri = uri, extras = request_header_table }
end
end
return web
|
--[[
"Nonsence" Lua web server
Author: John Abrahamsen ([email protected]).
License: MIT.
The ultra fast cached web server written in Lua.
.;''-.
.' | `._
/` ; `'.
.' \ \
,'\| `| |
| -'_ \ `'.__,J
;' `. `'.__.'
| `"-.___ ,'
'-, /
|.-`-.______-|
} __.--'L
; _,- _.-"`\ ___
`7-;" ' _,,--._ ,-'`__ `.
|/ ,'- .7'.-"--.7 | _.-'
; ,' .' .' .-. \/ .'
; / / .'.- ` |__ .'
\ | .' / | \_)- `'/ _.-'``
_,.--../ .' \_) '`_ \'`
'`f-'``'.`\;;' ''` '-` |
\`.__. ;;;, ) /
`-._,|;;;,, /\ ,'
/ /<_;;;;' `-._ _,-'
| '- /;;;;;, `t'` \. I like nonsence.
`'-'`_.|,';;;, '._/| It wakes up the brain cells!
,_.-' \ |;;;;; `-._/
/ `;\ |;;;, `" - Theodor Seuss Geisel -
.' `'`\;;, /
' ;;;'|
.--. ;.:`\ _.--,
| `'./;' _ '_.' |
\_ `"7f `) /
|` _.-'`t-'`"-.,__.'
`'-'`/;; | | \ mx
;;; ,' | `
/ '
]]--
local web = {}
local epoll = assert(require('epoll'), [[Missing required module: Lua Epoll. (https://github.com/Neopallium/lua-epoll)]])
local nixio = assert(require('nixio'), [[Missing required module: Nixio (https://github.com/Neopallium/nixio)]])
local mime = require('nonsence_mime') -- Require MIME module for document types.
local http_status_codes = require('nonsence_codes') -- Require codes module for HTTP status codes.
local json = require('json') -- Require JSON for automagic writing of Lua tables with self:write().
local type = type
------------------------------------------------
---
--
-- Application Class.
--
---
------------------------------------------------
web.Application = {}
function web.Application:new(routinglist)
application = application or {}
setmetatable(application, self)
self.__index = self
self.routinglist = assert(routinglist, 'Please provide a routinglist when using web.Application:new(routinglist)')
---*
--
-- Adds the application to the applications table.
-- Method: listen()
-- Description: Sets the port to be used for socket.
--
---*
self.listen = function (self, port)
self.port = assert(port, 'Please provide a port number when using web.Application:listen(port)')
nonsence_applications[#nonsence_applications + 1] = { port = port, routinglist = routinglist }
end
return application
end
------------------------------------------------
---
--
-- RequestHandler Class.
--
---
------------------------------------------------
web.RequestHandler = {}
function web.RequestHandler:new(requesthandler)
requesthandler = requesthandler or {}
setmetatable(requesthandler, self)
self.__index = self
self.headers = {}
self.headers.http_version = "HTTP/1.1"
self.headers.status_code = 200
self.headers.server_name = "nonsence version 0.1"
--self.headers.keep_alive = "Keep-Alive: timeout=3, max=199"
self.headers.connection = "Close"
self.headers.content_type = "text/html"
self.headers.date = os.date("!%a, %d %b %Y %H:%M:%S GMT")
self.arguments = {}
local function _write_headers(content_length)
local headers = self.headers
local write_to_buffer = write_to_buffer
write_to_buffer(headers.http_version .. " ")
write_to_buffer(headers.status_code .. " " .. http_status_codes[headers.status_code] .. "\r\n")
write_to_buffer("Server: " .. headers.server_name .. "\r\n")
write_to_buffer("Connection: " .. headers.connection .. "\r\n")
write_to_buffer("Content-Type: " .. headers.content_type .. "\r\n")
write_to_buffer("Content-Length: " .. content_length or 0)
write_to_buffer("\r\n\r\n")
end
function self.set_status_code(self, code)
if code and type(code) == 'number' then
self.headers.status_code = code
else
error('self.status_code() expects type number got: ' .. type(code))
end
end
function self._set_arguments(self, args_string)
local args_string = args_string or ''
local arguments = {}
local noDoS = 0;
for k, v in string.gmatch(args_string, "([^&=]+)=([^&]+)") do
noDoS = noDoS + 1;
if (noDoS > 256) then break; end -- hashing DoS attack ;O
v = v:gsub("+", " "):gsub("%%(%w%w)", function(s) return string.char(tonumber(s,16)) end);
if (not arguments[k]) then
arguments[k] = v;
else
if ( type(arguments[k]) == "string") then
local tmp = arguments[k];
arguments[k] = {tmp};
end
table.insert(arguments[k], v);
end
end
--
-- Set arguments to RequestHandler.
--
self.arguments = arguments
end
function self.get_arguments(self)
return self.arguments
end
function self.get_argument(self, key)
if self.arguments[key] then
return self.arguments[key]
else
-- Die?
end
end
function self.write(self, data)
if data then
local write_to_buffer = write_to_buffer
if type(data) == 'string' or type(data) == 'number' then
_write_headers(data:len())
write_to_buffer(data)
elseif type(data) == 'table' then
local stringified = json.encode(data)
self.headers.content_type = 'application/json' -- Set correct JSON type.
_write_headers(stringified:len())
write_to_buffer(stringified)
elseif type(data) == 'function' then
-- What to do here?
end
else
_write_headers(0)
end
end
return requesthandler
end
------------------------------------------------
---
--
-- Tools
--
---
------------------------------------------------
web.parse_headers = function(raw_headers)
local HTTPHeader = raw_headers
if HTTPHeader then
-- Fetch HTTP Method.
local method, uri = HTTPHeader:match("([%a*%-*]+)%s+(.-)%s")
-- Fetch all header values by key and value
local request_header_table = {}
for key, value in HTTPHeader:gmatch("([%a*%-*]+):%s?(.-)[\r?\n]+") do
request_header_table[key] = value
end
return { method = method, uri = uri, extras = request_header_table }
end
end
return web
|
Fixed GET argument parsing :)
|
Fixed GET argument parsing :)
|
Lua
|
apache-2.0
|
luastoned/turbo,ddysher/turbo,zcsteele/turbo,mniestroj/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,kernelsauce/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo
|
fee70f8fc3a109a6ba4e5252baca586721a2867f
|
mods/mobs/npc.lua
|
mods/mobs/npc.lua
|
-- Npc by TenPlus1
mobs.npc_drops = { "farming:meat", "farming:donut", "farming:bread", "default:apple", "default:sapling", "default:junglesapling",
"shields:shield_enhanced_wood", "3d_armor:chestplate_cactus", "3d_armor:boots_bronze",
"default:sword_steel", "default:sword_gold", "default:pick_steel", "default:shovel_steel",
"default:bronze_ingot", "bucket:bucket_water" }
mobs:register_mob("mobs:npc", {
-- animal, monster, npc
type = "npc",
-- aggressive, deals 6 damage to player/monster when hit
passive = false,
damage = 6,
attack_type = "dogfight",
attacks_monsters = true,
-- health & armor
hp_min = 20, hp_max = 20, armor = 100,
-- textures and model
collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35},
visual = "mesh",
mesh = "character.b3d",
drawtype = "front",
available_textures = {
total = 1,
texture_1 = {"mobs_npc.png"},
},
visual_size = {x=1, y=1},
-- sounds
makes_footstep_sound = true,
sounds = {},
-- speed and jump
walk_velocity = 1.5,
run_velocity = 2.5,
jump = true,
step = 1,
-- drops wood and chance of apples when dead
drops = {
{name = "default:wood",
chance = 1, min = 1, max = 3},
{name = "default:apple",
chance = 2, min = 1, max = 2},
{name = "default:axe_stone",
chance = 3, min = 1, max = 1},
{name = "maptools:copper_coin",
chance = 2, min = 2, max = 4,},
},
-- damaged by
water_damage = 0,
lava_damage = 2,
light_damage = 0,
-- follow diamond
follow = "default:diamond",
view_range = 16,
-- model animation
animation = {
speed_normal = 30, speed_run = 30,
stand_start = 0, stand_end = 79,
walk_start = 168, walk_end = 187,
run_start = 168, run_end = 187,
punch_start = 200, punch_end = 219,
},
-- right clicking with "cooked meat" or "bread" will give npc more health
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item:get_name() == "mobs:meat" or item:get_name() == "farming:bread" then
local hp = self.object:get_hp()
if hp + 4 > self.hp_max then return end
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
self.object:set_hp(hp+4)
-- right clicking with gold lump drops random item from mobs.npc_drops
elseif item:get_name() == "default:gold_lump" then
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local pos = self.object:getpos()
pos.y = pos.y + 0.5
minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]})
end
end,
})
-- spawning enable for now
mobs:register_spawn("mobs:npc", {"default:dirt_with_grass"}, 20, -1, 20000, 1, 31000)
-- register spawn egg
mobs:register_egg("mobs:npc", "Npc", "default_brick.png", 1)
|
-- Npc by TenPlus1
mobs.npc_drops = { "farming:meat", "farming:donut", "farming:bread", "default:apple", "default:sapling", "default:junglesapling",
"shields:shield_enhanced_wood", "3d_armor:chestplate_cactus", "3d_armor:boots_bronze",
"default:sword_steel", "default:sword_gold", "default:pick_steel", "default:shovel_steel",
"default:bronze_ingot", "bucket:bucket_water" }
mobs:register_mob("mobs:npc", {
-- animal, monster, npc
type = "npc",
-- aggressive, deals 6 damage to player/monster when hit
passive = false,
damage = 6,
attack_type = "dogfight",
attacks_monsters = true,
-- health & armor
hp_min = 20, hp_max = 20, armor = 100,
-- textures and model
collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35},
visual = "mesh",
mesh = "character.b3d",
drawtype = "front",
available_textures = {
total = 1,
texture_1 = {"mobs_npc.png"},
},
visual_size = {x=1, y=1},
-- sounds
makes_footstep_sound = true,
sounds = {},
-- speed and jump
walk_velocity = 1.5,
run_velocity = 2.5,
jump = true,
step = 1,
-- drops wood and chance of apples when dead
drops = {
{name = "default:wood",
chance = 1, min = 1, max = 3},
{name = "default:apple",
chance = 2, min = 1, max = 2},
{name = "default:axe_stone",
chance = 3, min = 1, max = 1},
{name = "maptools:copper_coin",
chance = 2, min = 2, max = 4,},
},
-- damaged by
water_damage = 0,
lava_damage = 2,
light_damage = 0,
-- follow diamond
follow = "default:diamond",
view_range = 16,
-- model animation
animation = {
speed_normal = 30, speed_run = 30,
stand_start = 0, stand_end = 79,
walk_start = 168, walk_end = 187,
run_start = 168, run_end = 187,
punch_start = 200, punch_end = 219,
},
-- right clicking with "cooked meat" or "bread" will give npc more health
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item:get_name() == "mobs:meat" or item:get_name() == "farming:bread" then
local hp = self.object:get_hp()
if hp >= self.hp_max then return end
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local n = hp + 4
if n > self.hp_max then n = self.hp_max end
self.object:set_hp(n)
-- right clicking with gold lump drops random item from mobs.npc_drops
elseif item:get_name() == "default:gold_lump" then
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local pos = self.object:getpos()
pos.y = pos.y + 0.5
minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]})
end
end,
})
-- spawning enable for now
mobs:register_spawn("mobs:npc", {"default:dirt_with_grass"}, 20, -1, 20000, 1, 31000)
-- register spawn egg
mobs:register_egg("mobs:npc", "Npc", "default_brick.png", 1)
|
fixed NPC feed
|
fixed NPC feed
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server
|
aa0f710867cc4333df4efa3fdb45ae2ed51e9c50
|
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
|
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 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$
]]--
local sys = require "luci.sys"
local dsp = require "luci.dispatcher"
arg[1] = arg[1] or ""
m = Map("firewall", translate("Traffic Redirection"),
translate("Traffic redirection allows you to change the " ..
"destination address of forwarded packets."))
m.redirect = dsp.build_url("admin", "network", "firewall")
if not m.uci:get(arg[1]) == "redirect" then
luci.http.redirect(m.redirect)
return
end
local has_v2 = nixio.fs.access("/lib/firewall/fw.sh")
local wan_zone = nil
m.uci:foreach("firewall", "zone",
function(s)
local n = s.network or s.name
if n then
local i
for i in n:gmatch("%S+") do
if i == "wan" then
wan_zone = s.name
return false
end
end
end
end)
s = m:section(NamedSection, arg[1], "redirect", "")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
back = s:taboption("general", DummyValue, "_overview", translate("Overview"))
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect")
name = s:taboption("general", Value, "_name", translate("Name"))
name.rmempty = true
name.size = 10
src = s:taboption("general", Value, "src", translate("Source zone"))
src.nocreate = true
src.default = "wan"
src.template = "cbi/firewall_zonelist"
proto = s:taboption("general", ListValue, "proto", translate("Protocol"))
proto.optional = true
proto:value("tcpudp", "TCP+UDP")
proto:value("tcp", "TCP")
proto:value("udp", "UDP")
dport = s:taboption("general", Value, "src_dport", translate("External port"),
translate("Match incoming traffic directed at the given " ..
"destination port or port range on this host"))
dport.datatype = "portrange"
dport:depends("proto", "tcp")
dport:depends("proto", "udp")
dport:depends("proto", "tcpudp")
to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"),
translate("Redirect matched incoming traffic to the specified " ..
"internal host"))
to.datatype = "ip4addr"
for i, dataset in ipairs(luci.sys.net.arptable()) do
to:value(dataset["IP address"])
end
toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"),
translate("Redirect matched incoming traffic to the given port on " ..
"the internal host"))
toport.optional = true
toport.placeholder = "0-65535"
target = s:taboption("advanced", ListValue, "target", translate("Redirection type"))
target:value("DNAT")
target:value("SNAT")
dest = s:taboption("advanced", Value, "dest", translate("Destination zone"))
dest.nocreate = true
dest.default = "lan"
dest.template = "cbi/firewall_zonelist"
src_dip = s:taboption("advanced", Value, "src_dip",
translate("Intended destination address"),
translate(
"For DNAT, match incoming traffic directed at the given destination "..
"ip address. For SNAT rewrite the source address to the given address."
))
src_dip.optional = true
src_dip.datatype = "ip4addr"
src_dip.placeholder = translate("any")
src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address"))
src_mac.optional = true
src_mac.datatype = "macaddr"
src_mac.placeholder = translate("any")
src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address"))
src_ip.optional = true
src_ip.datatype = "ip4addr"
src_ip.placeholder = translate("any")
sport = s:taboption("advanced", Value, "src_port", translate("Source port"),
translate("Match incoming traffic originating from the given " ..
"source port or port range on the client host"))
sport.optional = true
sport.datatype = "portrange"
sport.placeholder = "0-65536"
sport:depends("proto", "tcp")
sport:depends("proto", "udp")
sport:depends("proto", "tcpudp")
reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback"))
reflection.rmempty = true
reflection:depends({ target = "DNAT", src = wan_zone })
reflection.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 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$
]]--
local sys = require "luci.sys"
local dsp = require "luci.dispatcher"
arg[1] = arg[1] or ""
m = Map("firewall", translate("Traffic Redirection"),
translate("Traffic redirection allows you to change the " ..
"destination address of forwarded packets."))
m.redirect = dsp.build_url("admin", "network", "firewall")
if not m.uci:get(arg[1]) == "redirect" then
luci.http.redirect(m.redirect)
return
end
local has_v2 = nixio.fs.access("/lib/firewall/fw.sh")
local wan_zone = nil
m.uci:foreach("firewall", "zone",
function(s)
local n = s.network or s.name
if n then
local i
for i in n:gmatch("%S+") do
if i == "wan" then
wan_zone = s.name
return false
end
end
end
end)
s = m:section(NamedSection, arg[1], "redirect", "")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
back = s:taboption("general", DummyValue, "_overview", translate("Overview"))
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect")
name = s:taboption("general", Value, "_name", translate("Name"))
name.rmempty = true
name.size = 10
src = s:taboption("general", Value, "src", translate("Source zone"))
src.nocreate = true
src.default = "wan"
src.template = "cbi/firewall_zonelist"
proto = s:taboption("general", Value, "proto", translate("Protocol"))
proto.optional = true
proto:value("tcpudp", "TCP+UDP")
proto:value("tcp", "TCP")
proto:value("udp", "UDP")
dport = s:taboption("general", Value, "src_dport", translate("External port"),
translate("Match incoming traffic directed at the given " ..
"destination port or port range on this host"))
dport.datatype = "portrange"
dport:depends("proto", "tcp")
dport:depends("proto", "udp")
dport:depends("proto", "tcpudp")
to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"),
translate("Redirect matched incoming traffic to the specified " ..
"internal host"))
to.datatype = "ip4addr"
for i, dataset in ipairs(luci.sys.net.arptable()) do
to:value(dataset["IP address"])
end
toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"),
translate("Redirect matched incoming traffic to the given port on " ..
"the internal host"))
toport.optional = true
toport.placeholder = "0-65535"
toport.datatype = "portrange"
toport:depends("proto", "tcp")
toport:depends("proto", "udp")
toport:depends("proto", "tcpudp")
target = s:taboption("advanced", ListValue, "target", translate("Redirection type"))
target:value("DNAT")
target:value("SNAT")
dest = s:taboption("advanced", Value, "dest", translate("Destination zone"))
dest.nocreate = true
dest.default = "lan"
dest.template = "cbi/firewall_zonelist"
src_dip = s:taboption("advanced", Value, "src_dip",
translate("Intended destination address"),
translate(
"For DNAT, match incoming traffic directed at the given destination "..
"ip address. For SNAT rewrite the source address to the given address."
))
src_dip.optional = true
src_dip.datatype = "ip4addr"
src_dip.placeholder = translate("any")
src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address"))
src_mac.optional = true
src_mac.datatype = "macaddr"
src_mac.placeholder = translate("any")
src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address"))
src_ip.optional = true
src_ip.datatype = "ip4addr"
src_ip.placeholder = translate("any")
sport = s:taboption("advanced", Value, "src_port", translate("Source port"),
translate("Match incoming traffic originating from the given " ..
"source port or port range on the client host"))
sport.optional = true
sport.datatype = "portrange"
sport.placeholder = "0-65536"
sport:depends("proto", "tcp")
sport:depends("proto", "udp")
sport:depends("proto", "tcpudp")
reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback"))
reflection.rmempty = true
reflection:depends({ target = "DNAT", src = wan_zone })
reflection.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
return m
|
applications/luci-firewall: some fixes on redirection page
|
applications/luci-firewall: some fixes on redirection page
|
Lua
|
apache-2.0
|
maxrio/luci981213,remakeelectric/luci,bittorf/luci,openwrt/luci,urueedi/luci,urueedi/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,ff94315/luci-1,oyido/luci,bittorf/luci,oyido/luci,LuttyYang/luci,openwrt-es/openwrt-luci,NeoRaider/luci,taiha/luci,harveyhu2012/luci,male-puppies/luci,rogerpueyo/luci,nwf/openwrt-luci,jchuang1977/luci-1,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,bright-things/ionic-luci,MinFu/luci,cshore/luci,forward619/luci,kuoruan/luci,nmav/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,marcel-sch/luci,jlopenwrtluci/luci,oneru/luci,zhaoxx063/luci,deepak78/new-luci,fkooman/luci,oyido/luci,thesabbir/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,nmav/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,rogerpueyo/luci,thesabbir/luci,dwmw2/luci,nwf/openwrt-luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,nmav/luci,cshore-firmware/openwrt-luci,david-xiao/luci,taiha/luci,fkooman/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,obsy/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,oyido/luci,openwrt/luci,Hostle/luci,Wedmer/luci,schidler/ionic-luci,palmettos/cnLuCI,chris5560/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,maxrio/luci981213,harveyhu2012/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,981213/luci-1,david-xiao/luci,keyidadi/luci,taiha/luci,slayerrensky/luci,kuoruan/lede-luci,aa65535/luci,florian-shellfire/luci,dwmw2/luci,zhaoxx063/luci,tcatm/luci,jorgifumi/luci,remakeelectric/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,thess/OpenWrt-luci,palmettos/test,urueedi/luci,sujeet14108/luci,nmav/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,aa65535/luci,ff94315/luci-1,cappiewu/luci,ff94315/luci-1,schidler/ionic-luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,jchuang1977/luci-1,kuoruan/lede-luci,Noltari/luci,hnyman/luci,lcf258/openwrtcn,sujeet14108/luci,maxrio/luci981213,tobiaswaldvogel/luci,thesabbir/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,schidler/ionic-luci,hnyman/luci,dismantl/luci-0.12,jorgifumi/luci,deepak78/new-luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,kuoruan/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,chris5560/openwrt-luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,MinFu/luci,ff94315/luci-1,Hostle/luci,jchuang1977/luci-1,cappiewu/luci,LuttyYang/luci,zhaoxx063/luci,slayerrensky/luci,opentechinstitute/luci,remakeelectric/luci,palmettos/cnLuCI,opentechinstitute/luci,jlopenwrtluci/luci,sujeet14108/luci,keyidadi/luci,marcel-sch/luci,opentechinstitute/luci,fkooman/luci,schidler/ionic-luci,ff94315/luci-1,artynet/luci,dismantl/luci-0.12,lcf258/openwrtcn,tobiaswaldvogel/luci,Noltari/luci,jchuang1977/luci-1,obsy/luci,oneru/luci,openwrt-es/openwrt-luci,forward619/luci,kuoruan/luci,lbthomsen/openwrt-luci,openwrt/luci,NeoRaider/luci,RuiChen1113/luci,ollie27/openwrt_luci,jorgifumi/luci,keyidadi/luci,marcel-sch/luci,981213/luci-1,obsy/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,forward619/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,thess/OpenWrt-luci,sujeet14108/luci,maxrio/luci981213,cshore-firmware/openwrt-luci,nmav/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,taiha/luci,palmettos/cnLuCI,daofeng2015/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,chris5560/openwrt-luci,RuiChen1113/luci,ollie27/openwrt_luci,daofeng2015/luci,zhaoxx063/luci,MinFu/luci,bright-things/ionic-luci,schidler/ionic-luci,remakeelectric/luci,tcatm/luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,teslamint/luci,Noltari/luci,david-xiao/luci,aa65535/luci,joaofvieira/luci,male-puppies/luci,artynet/luci,palmettos/cnLuCI,deepak78/new-luci,rogerpueyo/luci,rogerpueyo/luci,deepak78/new-luci,tcatm/luci,teslamint/luci,urueedi/luci,Noltari/luci,shangjiyu/luci-with-extra,jorgifumi/luci,RedSnake64/openwrt-luci-packages,cshore/luci,sujeet14108/luci,florian-shellfire/luci,thess/OpenWrt-luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,obsy/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,openwrt-es/openwrt-luci,deepak78/new-luci,harveyhu2012/luci,florian-shellfire/luci,wongsyrone/luci-1,daofeng2015/luci,bittorf/luci,joaofvieira/luci,wongsyrone/luci-1,aa65535/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,daofeng2015/luci,florian-shellfire/luci,jchuang1977/luci-1,palmettos/cnLuCI,chris5560/openwrt-luci,palmettos/test,Hostle/openwrt-luci-multi-user,urueedi/luci,remakeelectric/luci,male-puppies/luci,Wedmer/luci,slayerrensky/luci,ollie27/openwrt_luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,dwmw2/luci,jorgifumi/luci,wongsyrone/luci-1,lcf258/openwrtcn,lbthomsen/openwrt-luci,ff94315/luci-1,marcel-sch/luci,nmav/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,hnyman/luci,artynet/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,artynet/luci,jlopenwrtluci/luci,kuoruan/luci,sujeet14108/luci,teslamint/luci,teslamint/luci,981213/luci-1,shangjiyu/luci-with-extra,dismantl/luci-0.12,aa65535/luci,teslamint/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,cappiewu/luci,oneru/luci,981213/luci-1,marcel-sch/luci,oneru/luci,jchuang1977/luci-1,NeoRaider/luci,zhaoxx063/luci,thess/OpenWrt-luci,oneru/luci,david-xiao/luci,marcel-sch/luci,palmettos/test,urueedi/luci,bittorf/luci,bright-things/ionic-luci,artynet/luci,NeoRaider/luci,obsy/luci,nwf/openwrt-luci,oyido/luci,oneru/luci,maxrio/luci981213,joaofvieira/luci,Kyklas/luci-proto-hso,oyido/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,joaofvieira/luci,obsy/luci,dwmw2/luci,hnyman/luci,nmav/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,MinFu/luci,david-xiao/luci,Hostle/luci,david-xiao/luci,cappiewu/luci,nmav/luci,artynet/luci,chris5560/openwrt-luci,opentechinstitute/luci,tobiaswaldvogel/luci,dwmw2/luci,hnyman/luci,deepak78/new-luci,daofeng2015/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,harveyhu2012/luci,obsy/luci,openwrt-es/openwrt-luci,NeoRaider/luci,forward619/luci,bittorf/luci,deepak78/new-luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,wongsyrone/luci-1,dwmw2/luci,urueedi/luci,Wedmer/luci,remakeelectric/luci,male-puppies/luci,remakeelectric/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,chris5560/openwrt-luci,fkooman/luci,shangjiyu/luci-with-extra,taiha/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,cshore/luci,aa65535/luci,ff94315/luci-1,tcatm/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,kuoruan/luci,palmettos/cnLuCI,artynet/luci,keyidadi/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,openwrt-es/openwrt-luci,palmettos/test,schidler/ionic-luci,lcf258/openwrtcn,wongsyrone/luci-1,nwf/openwrt-luci,NeoRaider/luci,joaofvieira/luci,joaofvieira/luci,mumuqz/luci,bright-things/ionic-luci,Hostle/luci,chris5560/openwrt-luci,david-xiao/luci,florian-shellfire/luci,thess/OpenWrt-luci,Noltari/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,lcf258/openwrtcn,Kyklas/luci-proto-hso,slayerrensky/luci,jlopenwrtluci/luci,keyidadi/luci,Noltari/luci,openwrt-es/openwrt-luci,tcatm/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,mumuqz/luci,fkooman/luci,deepak78/new-luci,MinFu/luci,aa65535/luci,Wedmer/luci,keyidadi/luci,981213/luci-1,Kyklas/luci-proto-hso,chris5560/openwrt-luci,NeoRaider/luci,lcf258/openwrtcn,tcatm/luci,Noltari/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,shangjiyu/luci-with-extra,dismantl/luci-0.12,taiha/luci,palmettos/test,openwrt/luci,male-puppies/luci,Hostle/luci,kuoruan/luci,wongsyrone/luci-1,MinFu/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,Noltari/luci,wongsyrone/luci-1,bittorf/luci,daofeng2015/luci,jorgifumi/luci,ollie27/openwrt_luci,florian-shellfire/luci,cshore/luci,zhaoxx063/luci,hnyman/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,kuoruan/lede-luci,urueedi/luci,tcatm/luci,RuiChen1113/luci,thesabbir/luci,bright-things/ionic-luci,kuoruan/lede-luci,schidler/ionic-luci,nwf/openwrt-luci,kuoruan/lede-luci,hnyman/luci,joaofvieira/luci,daofeng2015/luci,shangjiyu/luci-with-extra,NeoRaider/luci,slayerrensky/luci,florian-shellfire/luci,kuoruan/luci,obsy/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,tcatm/luci,cshore/luci,RuiChen1113/luci,artynet/luci,RuiChen1113/luci,LuttyYang/luci,cappiewu/luci,jchuang1977/luci-1,teslamint/luci,mumuqz/luci,remakeelectric/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,kuoruan/lede-luci,openwrt/luci,mumuqz/luci,mumuqz/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,nmav/luci,thesabbir/luci,Wedmer/luci,mumuqz/luci,slayerrensky/luci,dismantl/luci-0.12,keyidadi/luci,cshore/luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,dismantl/luci-0.12,david-xiao/luci,teslamint/luci,forward619/luci,cshore-firmware/openwrt-luci,male-puppies/luci,artynet/luci,jorgifumi/luci,fkooman/luci,marcel-sch/luci,taiha/luci,nwf/openwrt-luci,forward619/luci,harveyhu2012/luci,bright-things/ionic-luci,florian-shellfire/luci,maxrio/luci981213,ollie27/openwrt_luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,cshore/luci,thesabbir/luci,oyido/luci,sujeet14108/luci,LuttyYang/luci,thesabbir/luci,wongsyrone/luci-1,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,mumuqz/luci,maxrio/luci981213,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,lbthomsen/openwrt-luci,jorgifumi/luci,aa65535/luci,RuiChen1113/luci,teslamint/luci,palmettos/test,981213/luci-1,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,openwrt/luci,RuiChen1113/luci,forward619/luci,kuoruan/luci,cshore-firmware/openwrt-luci,male-puppies/luci,cshore/luci,openwrt-es/openwrt-luci,Wedmer/luci,MinFu/luci,taiha/luci,marcel-sch/luci,Hostle/luci,cappiewu/luci,nwf/openwrt-luci
|
c250e19ab2347d84376dfa269202662566e58dae
|
mods/item_drop/init.lua
|
mods/item_drop/init.lua
|
item_drop = {}
local enable_damage = minetest.setting_getbool("enable_damage")
local creative_mode = minetest.setting_getbool("creative_mode")
local TICK_UPDATE = 0.1
local die_timeout = 20
local die_time = {}
local die_respawned = {}
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
die_time[player_name] = 0
die_respawned[player_name] = false
end)
minetest.register_on_leaveplayer(function(player)
local player_name = player:get_player_name()
minetest.after(3, function()
die_time[player_name] = nil
die_respawned[player_name] = nil
end)
end)
minetest.register_on_dieplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = false
die_time[player_name] = die_timeout
end)
minetest.register_on_respawnplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = true
end)
-- Following edits by gravgun
item_drop.drop_callbacks = {}
item_drop.pickup_callbacks = {}
-- on_drop(dropper, drop_entity, itemstack)
function item_drop.add_drop_callback(on_drop)
table.insert(item_drop.drop_callbacks, on_drop)
end
-- on_pickup(picker, itemstack)
function item_drop.add_pickup_callback(on_pickup)
table.insert(item_drop.pickup_callbacks, on_pickup)
end
-- Idea is to have a radius pickup range around the player, whatever the height
-- We need to have a radius that will at least contain 1 node distance at the player's feet
-- Using simple trigonometry, we get that we need a radius of
-- sqrt(pickup_range² + player_half_height²)
local pickup_range = 1.3
local pickup_range_squared = pickup_range*pickup_range
local player_half_height = 0.9
local scan_range = math.sqrt(player_half_height*player_half_height + pickup_range_squared)
-- Node drops are insta-pickup, everything else (player drops) are not
local delay_before_playerdrop_pickup = 1
-- Time in which the node comes to the player
local pickup_duration = 0.1
-- Little treshold so the items aren't already on the player's middle
local pickup_inv_duration = 1/pickup_duration*0.7
local function tick()
local tstamp = minetest.get_us_time()
for _,player in ipairs(minetest.get_connected_players()) do
local player_name = player:get_player_name()
if die_time[player_name] < 1 then
if player:get_hp() > 0 or not enable_damage then
local pos = player:getpos()
pos.y = pos.y + player_half_height
local inv = player:get_inventory()
if inv then
for _,object in ipairs(minetest.get_objects_inside_radius(pos, scan_range)) do
local luaEnt = object:get_luaentity()
if luaEnt and luaEnt.name == "__builtin:item" then
local ticky = luaEnt.item_drop_min_tstamp
if ticky then
if tstamp >= ticky then
luaEnt.item_drop_min_tstamp = nil
end
elseif not luaEnt.item_drop_nopickup then
-- Point-line distance computation, heavily simplified since the wanted line,
-- being the player, is completely upright (no variation on X or Z)
local pos2 = object:getpos()
-- No sqrt, avoid useless computation
-- (just take the radius, compare it to the square of what you want)
-- Pos order doesn't really matter, we're squaring the result
-- (but don't change it, we use the cached values afterwards)
local dX = pos.x-pos2.x
local dZ = pos.z-pos2.z
local playerDistance = dX*dX+dZ*dZ
if playerDistance <= pickup_range_squared then
local itemStack = ItemStack(luaEnt.itemstring)
if inv:room_for_item("main", itemStack) then
local vec = {x=dX, y=pos.y-pos2.y, z=dZ}
vec.x = vec.x*pickup_inv_duration
vec.y = vec.y*pickup_inv_duration
vec.z = vec.z*pickup_inv_duration
object:setvelocity(vec)
luaEnt.physical_state = false
luaEnt.object:set_properties({
physical = false
})
-- Mark the object as already picking up
luaEnt.item_drop_nopickup = true
minetest.after(pickup_duration, function()
local lua = luaEnt
if object == nil or lua == nil or lua.itemstring == nil then
return
end
if inv:room_for_item("main", itemStack) then
inv:add_item("main", itemStack)
if luaEnt.itemstring ~= "" then
minetest.sound_play("item_drop_pickup", {pos = pos, gain = 0.3, max_hear_distance = 8})
end
luaEnt.itemstring = ""
object:remove()
for i, cb in ipairs(item_drop.pickup_callbacks) do
cb(player, itemstack)
end
else
object:setvelocity({x = 0,y = 0,z = 0})
luaEnt.physical_state = true
luaEnt.object:set_properties({
physical = true
})
luaEnt.item_drop_nopickup = nil
end
end)
end
end
end
end
end
end
end
else
if die_respawned[player_name] then
die_time[player_name] = (die_time[player_name] or die_timeout) - TICK_UPDATE
end
end
end
minetest.after(TICK_UPDATE, tick)
end
local mt_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
if digger and digger.is_fake_player then -- Pipeworks' wielders
mt_handle_node_drops(pos, drops, digger)
return
end
local inv
if creative_mode and digger and digger:is_player() then
inv = digger:get_inventory()
end
for _,item in ipairs(drops) do
local count, name
if type(item) == "string" then
count = 1
name = item
else
count = item:get_count()
name = item:get_name()
end
if not inv or not inv:contains_item("main", ItemStack(name)) then
for i=1,count do
local obj
local x = math.random(1, 5)
if math.random(1,2) == 1 then x = -x end
local z = math.random(1, 5)
if math.random(1,2) == 1 then z = -z end
obj = minetest.spawn_item(pos, name)
if obj ~= nil then
obj:setvelocity({x=1/x, y=obj:getvelocity().y, z=1/z})
end
end
end
end
end
local mt_item_drop = minetest.item_drop
function minetest.item_drop(itemstack, dropper, pos)
if dropper.is_player then
local v = dropper:get_look_dir()
local p = {x=pos.x, y=pos.y+1.2, z=pos.z}
local cs = itemstack:get_count()
if dropper:get_player_control().sneak then
cs = 1
end
local item = itemstack:take_item(cs)
local obj = core.add_item(p, item)
if obj then
v.x = v.x*2
v.y = v.y*2 + 2
v.z = v.z*2
obj:setvelocity(v)
obj:get_luaentity().item_drop_min_tstamp = minetest.get_us_time() + delay_before_playerdrop_pickup * 1000000
for i, cb in ipairs(item_drop.drop_callbacks) do
cb(dropper, obj, itemstack)
end
end
else
core.add_item(pos, itemstack)
end
return itemstack
end
if minetest.setting_getbool("log_mods") then
minetest.log("action", "[item_drop] item_drop overriden: " .. tostring(mt_item_drop) .. " " .. tostring(minetest.item_drop))
minetest.log("action", "[item_drop] loaded.")
end
tick()
|
item_drop = {}
local enable_damage = minetest.setting_getbool("enable_damage")
local creative_mode = minetest.setting_getbool("creative_mode")
local TICK_UPDATE = 0.1
local die_timeout = 20
local die_time = {}
local die_respawned = {}
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
die_time[player_name] = 0
die_respawned[player_name] = false
end)
minetest.register_on_leaveplayer(function(player)
local player_name = player:get_player_name()
die_time[player_name] = nil
die_respawned[player_name] = nil
end)
minetest.register_on_dieplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = false
die_time[player_name] = die_timeout
end)
minetest.register_on_respawnplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = true
end)
-- Following edits by gravgun
item_drop.drop_callbacks = {}
item_drop.pickup_callbacks = {}
-- on_drop(dropper, drop_entity, itemstack)
function item_drop.add_drop_callback(on_drop)
table.insert(item_drop.drop_callbacks, on_drop)
end
-- on_pickup(picker, itemstack)
function item_drop.add_pickup_callback(on_pickup)
table.insert(item_drop.pickup_callbacks, on_pickup)
end
-- Idea is to have a radius pickup range around the player, whatever the height
-- We need to have a radius that will at least contain 1 node distance at the player's feet
-- Using simple trigonometry, we get that we need a radius of
-- sqrt(pickup_range² + player_half_height²)
local pickup_range = 1.3
local pickup_range_squared = pickup_range*pickup_range
local player_half_height = 0.9
local scan_range = math.sqrt(player_half_height*player_half_height + pickup_range_squared)
-- Node drops are insta-pickup, everything else (player drops) are not
local delay_before_playerdrop_pickup = 1
-- Time in which the node comes to the player
local pickup_duration = 0.1
-- Little treshold so the items aren't already on the player's middle
local pickup_inv_duration = 1/pickup_duration*0.7
local function tick()
local tstamp = minetest.get_us_time()
for _,player in ipairs(minetest.get_connected_players()) do
local player_name = player:get_player_name()
if die_time[player_name] and die_time[player_name] < 1 then
if player:get_hp() > 0 or not enable_damage then
local pos = player:getpos()
pos.y = pos.y + player_half_height
local inv = player:get_inventory()
if inv then
for _,object in ipairs(minetest.get_objects_inside_radius(pos, scan_range)) do
local luaEnt = object:get_luaentity()
if luaEnt and luaEnt.name == "__builtin:item" then
local ticky = luaEnt.item_drop_min_tstamp
if ticky then
if tstamp >= ticky then
luaEnt.item_drop_min_tstamp = nil
end
elseif not luaEnt.item_drop_nopickup then
-- Point-line distance computation, heavily simplified since the wanted line,
-- being the player, is completely upright (no variation on X or Z)
local pos2 = object:getpos()
-- No sqrt, avoid useless computation
-- (just take the radius, compare it to the square of what you want)
-- Pos order doesn't really matter, we're squaring the result
-- (but don't change it, we use the cached values afterwards)
local dX = pos.x-pos2.x
local dZ = pos.z-pos2.z
local playerDistance = dX*dX+dZ*dZ
if playerDistance <= pickup_range_squared then
local itemStack = ItemStack(luaEnt.itemstring)
if inv:room_for_item("main", itemStack) then
local vec = {x=dX, y=pos.y-pos2.y, z=dZ}
vec.x = vec.x*pickup_inv_duration
vec.y = vec.y*pickup_inv_duration
vec.z = vec.z*pickup_inv_duration
object:setvelocity(vec)
luaEnt.physical_state = false
luaEnt.object:set_properties({
physical = false
})
-- Mark the object as already picking up
luaEnt.item_drop_nopickup = true
minetest.after(pickup_duration, function()
local lua = luaEnt
if object == nil or lua == nil or lua.itemstring == nil then
return
end
if inv:room_for_item("main", itemStack) then
inv:add_item("main", itemStack)
if luaEnt.itemstring ~= "" then
minetest.sound_play("item_drop_pickup", {pos = pos, gain = 0.3, max_hear_distance = 8})
end
luaEnt.itemstring = ""
object:remove()
for i, cb in ipairs(item_drop.pickup_callbacks) do
cb(player, itemstack)
end
else
object:setvelocity({x = 0,y = 0,z = 0})
luaEnt.physical_state = true
luaEnt.object:set_properties({
physical = true
})
luaEnt.item_drop_nopickup = nil
end
end)
end
end
end
end
end
end
end
else
if die_respawned[player_name] then
die_time[player_name] = (die_time[player_name] or die_timeout) - TICK_UPDATE
end
end
end
minetest.after(TICK_UPDATE, tick)
end
local mt_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
if digger and digger.is_fake_player then -- Pipeworks' wielders
mt_handle_node_drops(pos, drops, digger)
return
end
local inv
if creative_mode and digger and digger:is_player() then
inv = digger:get_inventory()
end
for _,item in ipairs(drops) do
local count, name
if type(item) == "string" then
count = 1
name = item
else
count = item:get_count()
name = item:get_name()
end
if not inv or not inv:contains_item("main", ItemStack(name)) then
for i=1,count do
local obj
local x = math.random(1, 5)
if math.random(1,2) == 1 then x = -x end
local z = math.random(1, 5)
if math.random(1,2) == 1 then z = -z end
obj = minetest.spawn_item(pos, name)
if obj ~= nil then
obj:setvelocity({x=1/x, y=obj:getvelocity().y, z=1/z})
end
end
end
end
end
local mt_item_drop = minetest.item_drop
function minetest.item_drop(itemstack, dropper, pos)
if dropper.is_player then
local v = dropper:get_look_dir()
local p = {x=pos.x, y=pos.y+1.2, z=pos.z}
local cs = itemstack:get_count()
if dropper:get_player_control().sneak then
cs = 1
end
local item = itemstack:take_item(cs)
local obj = core.add_item(p, item)
if obj then
v.x = v.x*2
v.y = v.y*2 + 2
v.z = v.z*2
obj:setvelocity(v)
obj:get_luaentity().item_drop_min_tstamp = minetest.get_us_time() + delay_before_playerdrop_pickup * 1000000
for i, cb in ipairs(item_drop.drop_callbacks) do
cb(dropper, obj, itemstack)
end
end
else
core.add_item(pos, itemstack)
end
return itemstack
end
if minetest.setting_getbool("log_mods") then
minetest.log("action", "[item_drop] item_drop overriden: " .. tostring(mt_item_drop) .. " " .. tostring(minetest.item_drop))
minetest.log("action", "[item_drop] loaded.")
end
tick()
|
fix itemdrop crash
|
fix itemdrop crash
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server
|
a69f6dca25a34b0dc287e757c0a1df5fda9fa2f2
|
src/luarocks/fetch/git_http.lua
|
src/luarocks/fetch/git_http.lua
|
--- Fetch back-end for retrieving sources from local Git repositories.
module("luarocks.fetch.git_http", package.seeall)
local git = require("luarocks.fetch.git")
--- Fetch sources for building a rock from a local Git repository.
-- @param rockspec table: The rockspec table
-- @param extract boolean: Unused in this module (required for API purposes.)
-- @param dest_dir string or nil: If set, will extract to the given directory.
-- @return (string, string) or (nil, string): The absolute pathname of
-- the fetched source tarball and the temporary directory created to
-- store it; or nil and an error message.
function get_sources(rockspec, extract, dest_dir)
rockspec.source.url = rockspec.source.url:gsub("^git.", "")
return git.get_sources(rockspec, extract, dest_dir, "--")
end
|
--- Fetch back-end for retrieving sources from Git repositories
-- that use http:// transport. For example, for fetching a repository
-- that requires the following command line:
-- `git clone http://example.com/foo.git`
-- you can use this in the rockspec:
-- source = { url = "git+http://example.com/foo.git" }
-- Prefer using the normal git:// fetch mode as it is more widely
-- available in older versions of LuaRocks.
module("luarocks.fetch.git_http", package.seeall)
local git = require("luarocks.fetch.git")
--- Fetch sources for building a rock from a local Git repository.
-- @param rockspec table: The rockspec table
-- @param extract boolean: Unused in this module (required for API purposes.)
-- @param dest_dir string or nil: If set, will extract to the given directory.
-- @return (string, string) or (nil, string): The absolute pathname of
-- the fetched source tarball and the temporary directory created to
-- store it; or nil and an error message.
function get_sources(rockspec, extract, dest_dir)
rockspec.source.url = rockspec.source.url:gsub("^git.", "")
return git.get_sources(rockspec, extract, dest_dir, "--")
end
|
Fix documentation. Thanks @ignacio!
|
Fix documentation. Thanks @ignacio!
|
Lua
|
mit
|
tst2005/luarocks,usstwxy/luarocks,robooo/luarocks,luarocks/luarocks,tarantool/luarocks,leafo/luarocks,tarantool/luarocks,xiaq/luarocks,coderstudy/luarocks,aryajur/luarocks,tst2005/luarocks,usstwxy/luarocks,lxbgit/luarocks,coderstudy/luarocks,keplerproject/luarocks,robooo/luarocks,keplerproject/luarocks,luarocks/luarocks,lxbgit/luarocks,xpol/luarocks,keplerproject/luarocks,xpol/luavm,rrthomas/luarocks,tst2005/luarocks,xpol/luarocks,ignacio/luarocks,starius/luarocks,starius/luarocks,leafo/luarocks,usstwxy/luarocks,xiaq/luarocks,xpol/luarocks,usstwxy/luarocks,ignacio/luarocks,tarantool/luarocks,xpol/luavm,keplerproject/luarocks,ignacio/luarocks,aryajur/luarocks,rrthomas/luarocks,xiaq/luarocks,aryajur/luarocks,starius/luarocks,coderstudy/luarocks,robooo/luarocks,tst2005/luarocks,rrthomas/luarocks,luarocks/luarocks,xpol/luavm,xpol/luavm,starius/luarocks,xpol/luainstaller,coderstudy/luarocks,leafo/luarocks,xpol/luainstaller,lxbgit/luarocks,xpol/luavm,xpol/luainstaller,robooo/luarocks,rrthomas/luarocks,xpol/luarocks,xiaq/luarocks,ignacio/luarocks,xpol/luainstaller,aryajur/luarocks,lxbgit/luarocks
|
10efe4b84885b2a040c084a0dedade8fc3c9d54d
|
kernel/bs_crate.lua
|
kernel/bs_crate.lua
|
local crate = {}
--local turtle = require("turtle")
local crate_turtle = require("crate_turtle")
function crate.toFloraIri(x)
return string.format("i\b%s", x)
end
function crate.toFloraString(x)
return string.format("s\b%s", x)
end
function crate.encodeString(str)
return string.format("'%s'", crate.toFloraString(str:gsub("'", "''")))
end
crate._validFloraTypes = {["date"] = true,
["dateTime"] = true,
["duration"] = true}
-- get the flora representation for a date/time-type value.
function crate._getFloraRepresentation(str, typename)
if str:find("Z$") then -- Flora doesn't like trailing Zs
str = str:gsub("Z$", "")
end
if not crate._validFloraTypes[typename] then
error("Cannot encode types of " .. typename)
end
local q = string.format("flrdatatype_parse:flora_parse_datatype(datatype('\\%s', \"%s\"), noIndex, ParsedDt, Status).", typename, str)
local r = xsb_query(q, ".")
if not r or #r ~= 1 or r[1]:find(".%[%]") ~= (#r[1] - 2) or #r[1] < 4 then
local msg = "<no message>"
if r and r[1] then
msg = r[1]
end
error(string.format("Cannot encode value: `%s' to %s: %s", str, typename, msg))
end
return r[1]:gsub(".%[%]", "")
end
-- we generate a query like: (a[b->d])
-- flrstoragebase:flora_db_insert_base('_$_$_flora''fdbtrie''main', '_$_$_flora''mod''main''mvd'(a,b,d,_h0)).
function crate.assert(s, p, o)
p = crate.toFloraIri(p)
local storageName = "'_$_$_flora''fdbtrie''main'"
local objectString
if type(o) == "table" and #o > 1 then
objectString = "[]"
elseif type(o) == "string" and o:find("bnode_") ~= 1 then
objectString = "'" .. crate.toFloraIri(o) .. "'"
elseif type(o) == "string" and o:find("bnode_") == 1 then
objectString = o
elseif o.nodeType and o:nodeType() == "TypedString" then
if o.datatype.iri:find("#string") then
objectString = crate.encodeString(o.value)
elseif o.datatype.iri:find("#boolean") then
objectString = string.format("'\\%s'", o.value)
elseif o.datatype.iri:find("#integer") then
objectString = o.value
elseif o.datatype.iri:find("#double") then
if o.value:find(".") then
objectString = o.value .. ".0" -- double-typed integer 1 -> 1.0
end
objectString = o.value
elseif o.datatype.iri:find("#dateTime") then
-- TODO we have to canonicalize the representation BEFORE
-- this point so we can handle the comparison when the value
-- is inserted/deleted. Same for date, etc
objectString = crate._getFloraRepresentation(o.value, "dateTime")
o.floraString = objectString
elseif o.datatype.iri:find("#date") then
objectString = crate._getFloraRepresentation(o.value, "date")
o.floraString = objectString
elseif o.datatype.iri:find("#gYear") then
-- TODO what to do with this? Is there a real, practical
-- possibility of making it a proper Flora type that will be
-- useful?
objectString = o.value -- as integer for now
elseif o.datatype.iri:find("#duration") then
objectString = crate._getFloraRepresentation(o.value, "duration")
o.floraString = objectString
elseif o.datatype.iri:find("#anyURI") then
objectString = "'" .. crate.toFloraIri(o) .. "'"
else
error("Unknown datatype: " .. o.datatype.iri)
end
elseif o.nodeType and o:nodeType() == "IriRef" then
objectString = "'" .. crate.toFloraIri(o) .. "'"
elseif o.nodeType and o:nodeType() == "Collection" then
-- TODO - skipped for now
objectString = "[]"
else
_dump(o)
_dump(getmetatable(o))
error("UNKNOWN OBJECT TYPE")
end
if not objectString then
_dump(o)
error("Failed to encode")
end
--print(objectString)
local term = string.format("'_$_$_flora''mod''main''mvd'('%s','%s',%s,_h0)",
s, p, objectString)
--print(term)
local addQuery = string.format("flrstoragebase:flora_db_insert_base(%s, %s).",
"'_$_$_flora''fdbtrie''main'",
term)
--print(addQuery)
xsb_query(addQuery, "")
end
function crate.load(filename)
local bnodeCount, spoCount = 0, 0
local s = crate_turtle.parseFile("/home/jbalint/sw/banshee-sympatico/tmp/bs_stardog-export-20140711_16222_tbc.ttl")
for name, bnode in pairs(s.bnodes) do
for predIri, pred in pairs(bnode) do
for _idx, obj in ipairs(pred.objects or {}) do
if predIri:find("unionOf") then
_dump(obj)
_dump(bnode)
error("bnode_ERROR")
end
crate.assert(name, predIri, obj)
bnodeCount = bnodeCount + 1
end
end
end
for name, sub in pairs(s.spo) do
for predIri, pred in pairs(sub) do
for _idx, obj in ipairs(pred.objects or {}) do
crate.assert(crate.toFloraIri(name), predIri, obj)
spoCount = spoCount + 1
end
end
end
print(string.format("Loaded %d facts (bnode=%d, spo=%d)",
bnodeCount + spoCount, bnodeCount, spoCount))
end
function crate.insert()
error("NOT IMPLEMENTED")
end
function crate.delete()
error("NOT IMPLEMENTED")
end
return crate
|
local crate = {}
--local turtle = require("turtle")
local crate_turtle = require("crate_turtle")
function crate.toFloraIri(x)
return string.format("i\b%s", x)
end
function crate.toFloraString(x)
return string.format("s\b%s", x)
end
function crate.encodeString(str)
return string.format("'%s'", crate.toFloraString(str:gsub("'", "''")))
end
crate._validFloraTypes = {["date"] = true,
["dateTime"] = true,
["duration"] = true}
-- get the flora representation for a date/time-type value.
function crate._getFloraRepresentation(str, typename)
if str:find("Z$") then -- Flora doesn't like trailing Zs
str = str:gsub("Z$", "")
end
if not crate._validFloraTypes[typename] then
error("Cannot encode types of " .. typename)
end
local q = string.format("flrdatatype_parse:flora_parse_datatype(datatype('\\%s', \"%s\"), noIndex, ParsedDt, Status).", typename, str)
local r = xsb_query(q, ".")
if not r or #r ~= 1 or r[1]:find(".%[%]") ~= (#r[1] - 2) or #r[1] < 4 then
local msg = "<no message>"
if r and r[1] then
msg = r[1]
end
error(string.format("Cannot encode value: `%s' to %s: %s", str, typename, msg))
end
return string.format("'\\datatype'(%s, '\\%s')",
r[1]:gsub(".%[%]", ""), typeName)
end
function crate._objectToString(o)
local objectString
if o.nodeType and o:nodeType() == "Collection" then
objectString = "["
for _idx, obj in ipairs(o) do
if objectString == "[" then
objectString = objectString .. crate._objectToString(obj)
else
objectString = objectString .. "," .. crate._objectToString(obj)
end
end
objectString = objectString .. "]"
elseif type(o) == "string" and o:find("bnode_") ~= 1 then
objectString = "'" .. crate.toFloraIri(o) .. "'"
elseif type(o) == "string" and o:find("bnode_") == 1 then
objectString = o
elseif o.nodeType and o:nodeType() == "TypedString" then
if o.datatype.iri:find("#string") then
objectString = crate.encodeString(o.value)
elseif o.datatype.iri:find("#boolean") then
objectString = string.format("'\\%s'", o.value)
elseif o.datatype.iri:find("#integer") then
objectString = o.value
elseif o.datatype.iri:find("#double") then
if not o.value:find("%.") then
objectString = o.value .. ".0" -- double-typed integer 1 -> 1.0
else
objectString = o.value
end
elseif o.datatype.iri:find("#dateTime") then
-- TODO we have to canonicalize the representation BEFORE
-- this point so we can handle the comparison when the value
-- is inserted/deleted. Same for date, etc
objectString = crate._getFloraRepresentation(o.value, "dateTime")
o.floraString = objectString
elseif o.datatype.iri:find("#date") then
objectString = crate._getFloraRepresentation(o.value, "date")
o.floraString = objectString
elseif o.datatype.iri:find("#gYear") then
-- TODO what to do with this? Is there a real, practical
-- possibility of making it a proper Flora type that will be
-- useful?
objectString = o.value -- as integer for now
elseif o.datatype.iri:find("#duration") then
objectString = crate._getFloraRepresentation(o.value, "duration")
o.floraString = objectString
elseif o.datatype.iri:find("#anyURI") then
objectString = "'" .. crate.toFloraIri(o) .. "'"
else
error("Unknown datatype: " .. o.datatype.iri)
end
elseif o.nodeType and o:nodeType() == "IriRef" then
objectString = "'" .. crate.toFloraIri(o) .. "'"
else
_dump(o)
_dump(getmetatable(o))
error("UNKNOWN OBJECT TYPE")
end
if not objectString then
_dump(o)
error("Failed to encode")
end
return objectString
end
-- we generate a query like: (a[b->d])
-- flrstoragebase:flora_db_insert_base('_$_$_flora''fdbtrie''main', '_$_$_flora''mod''main''mvd'(a,b,d,_h0)).
function crate.assert(s, p, o)
p = crate.toFloraIri(p)
local storageName = "'_$_$_flora''fdbtrie''main'"
local objectString = crate._objectToString(o)
-- the actual term we will insert
local term = string.format("'_$_$_flora''mod''main''mvd'('%s','%s',%s,_h0)",
s, p, objectString)
-- the insert statement
local addQuery = string.format("flrstoragebase:flora_db_insert_base(%s, %s).",
storageName, term)
xsb_query(addQuery, "")
end
function crate.load(filename)
local bnodeCount, spoCount = 0, 0
local s = crate_turtle.parseFile("/home/jbalint/sw/banshee-sympatico/tmp/bs_stardog-export-20140711_16222_tbc.ttl")
for name, bnode in pairs(s.bnodes) do
for predIri, pred in pairs(bnode) do
for _idx, obj in ipairs(pred.objects or {}) do
crate.assert(name, predIri, obj)
bnodeCount = bnodeCount + 1
end
end
end
for name, sub in pairs(s.spo) do
for predIri, pred in pairs(sub) do
for _idx, obj in ipairs(pred.objects or {}) do
crate.assert(crate.toFloraIri(name), predIri, obj)
spoCount = spoCount + 1
end
end
end
print(string.format("Loaded %d facts (bnode=%d, spo=%d)",
bnodeCount + spoCount, bnodeCount, spoCount))
end
function crate.insert()
error("NOT IMPLEMENTED")
end
function crate.delete()
error("NOT IMPLEMENTED")
end
return crate
|
fix datatypes and add collection support in CRATE
|
fix datatypes and add collection support in CRATE
|
Lua
|
mit
|
jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico
|
48c95eb11a5e9c3b66ac524e6ea87cfee2c3821e
|
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
|
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
|
wincent.g.map_callbacks = {}
-- TODO: For completeness, should have unmap() too, and other variants
-- as they arise (nunmap() etc); but for now just going with a "dispose"
-- function as return value.
local map = function (mode, lhs, rhs, opts)
opts = opts or {}
local rhs_type = type(rhs)
if rhs_type == 'function' then
local key = wincent.util.get_key_for_fn(rhs, wincent.g.map_callbacks)
wincent.g.map_callbacks[key] = rhs
if opts.expr then
rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()'
else
rhs = ':lua wincent.g.map_callbacks.' .. key .. '()<CR>'
end
elseif rhs_type ~= 'string' then
error('map(): unsupported rhs type: ' .. rhs_type)
end
local buffer = opts.buffer
opts.buffer = nil
if buffer == true then
vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts)
else
vim.api.nvim_set_keymap(mode, lhs, rhs, opts)
end
return {
dispose = function()
if buffer == true then
vim.api.nvim_buf_del_keymap(0, mode, lhs)
else
vim.api.nvim_del_keymap(mode, lhs)
end
wincent.g.map_callbacks[key] = nil
end,
}
end
return map
|
wincent.g.map_callbacks = {}
-- TODO: For completeness, should have unmap() too, and other variants
-- as they arise (nunmap() etc); but for now just going with a "dispose"
-- function as return value.
local map = function (mode, lhs, rhs, opts)
opts = opts or {}
local rhs_type = type(rhs)
local key
if rhs_type == 'function' then
key = wincent.util.get_key_for_fn(rhs, wincent.g.map_callbacks)
wincent.g.map_callbacks[key] = rhs
if opts.expr then
rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()'
else
rhs = ':lua wincent.g.map_callbacks.' .. key .. '()<CR>'
end
elseif rhs_type ~= 'string' then
error('map(): unsupported rhs type: ' .. rhs_type)
end
local buffer = opts.buffer
opts.buffer = nil
if buffer == true then
vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts)
else
vim.api.nvim_set_keymap(mode, lhs, rhs, opts)
end
return {
dispose = function()
if buffer == true then
vim.api.nvim_buf_del_keymap(0, mode, lhs)
else
vim.api.nvim_del_keymap(mode, lhs)
end
if key ~= nil then
wincent.g.map_callbacks[key] = nil
end
end,
}
end
return map
|
fix(nvim): avoid accessing uninitialized `key` variable
|
fix(nvim): avoid accessing uninitialized `key` variable
Closes: https://github.com/wincent/wincent/issues/119
|
Lua
|
unlicense
|
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
|
8ecfe2f58f9da6663dc80c005db503908efb2e97
|
lib/luvit/utils.lua
|
lib/luvit/utils.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. tostring(string) .. utils.color(reset_name)
end
local escapes = { backslash = "\\\\", null = "\\0", newline = "\\n", carriage = "\\r",
tab = "\\t", quote = '"', quote2 = '"', obracket = '[', cbracket = ']'
}
local colorized_escapes = {}
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
colorized_escapes["backslash"] = utils.colorize("Bgreen", escapes.backslash, "green")
colorized_escapes["null"] = utils.colorize("Bgreen", escapes.null, "green")
colorized_escapes["newline"] = utils.colorize("Bgreen", escapes.newline, "green")
colorized_escapes["carriage"] = utils.colorize("Bgreen", escapes.carriage, "green")
colorized_escapes["tab"] = utils.colorize("Bgreen", escapes.tab, "green")
colorized_escapes["quote"] = utils.colorize("Bgreen", escapes.quote, "green")
colorized_escapes["quote2"] = utils.colorize("Bgreen", escapes.quote2)
for k,v in pairs(escapes) do
if not colorized_escapes[k] then
colorized_escapes[k] = utils.colorize("B", v)
end
end
end
utils.loadColors()
local function colorize_nop(color, obj)
return obj
end
function utils.dump(o, depth, no_colorize, seen_tables)
local colorize_func
local _escapes
if not seen_tables then
seen_tables = {}
end
local function seenTable(tbl)
return seen_tables[tostring(tbl)]
end
local function addTable(tbl)
if tostring(tbl) == nil then
return
end
seen_tables[tostring(tbl)] = true
end
if no_colorize then
_escapes = escapes
colorize_func = colorize_nop
else
_escapes = colorized_escapes
colorize_func = utils.colorize
end
local t = type(o)
if t == 'string' then
return _escapes.quote .. o:gsub("\\", _escapes.backslash):gsub("%z", _escapes.null):gsub("\n", _escapes.newline):gsub("\r", _escapes.carriage):gsub("\t", _escapes.tab) .. _escapes.quote2
end
if t == 'nil' then
return colorize_func("Bblack", "nil")
end
if t == 'boolean' then
return colorize_func("yellow", tostring(o))
end
if t == 'number' then
return colorize_func("blue", tostring(o))
end
if t == 'userdata' then
return colorize_func("magenta", tostring(o))
end
if t == 'thread' then
return colorize_func("Bred", tostring(o))
end
if t == 'function' then
return colorize_func("cyan", tostring(o))
end
if t == 'cdata' then
return colorize_func("Bmagenta", tostring(o))
end
if t == 'table' then
if seenTable(o) then
return ''
end
addTable(o)
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return colorize_func("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1, k, v
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100, no_colorize, seen_tables) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1, no_colorize, seen_tables)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
local s = "{\n " .. indent
for k, v in pairs(lines) do
s = s .. v .. ",\n " .. indent
end
s = s .. "\n" .. indent .. "}"
return s
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local bindArgsLength = select("#", ...)
-- Simple binding, just inserts self (or one arg or any kind)
if bindArgsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- More complex binding inserts arbitrary number of args into call.
local bindArgs = {...}
return function (...)
local argsLength = select("#", ...)
local args = {...}
local arguments = {}
for i = 1, bindArgsLength do
arguments[i] = bindArgs[i]
end
for i = 1, argsLength do
arguments[i + bindArgsLength] = args[i]
end
return fn(self, unpack(arguments, 1, bindArgsLength + argsLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. tostring(string) .. utils.color(reset_name)
end
local escapes = { backslash = "\\\\", null = "\\0", newline = "\\n", carriage = "\\r",
tab = "\\t", quote = '"', quote2 = '"', obracket = '[', cbracket = ']'
}
local colorized_escapes = {}
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
colorized_escapes["backslash"] = utils.colorize("Bgreen", escapes.backslash, "green")
colorized_escapes["null"] = utils.colorize("Bgreen", escapes.null, "green")
colorized_escapes["newline"] = utils.colorize("Bgreen", escapes.newline, "green")
colorized_escapes["carriage"] = utils.colorize("Bgreen", escapes.carriage, "green")
colorized_escapes["tab"] = utils.colorize("Bgreen", escapes.tab, "green")
colorized_escapes["quote"] = utils.colorize("Bgreen", escapes.quote, "green")
colorized_escapes["quote2"] = utils.colorize("Bgreen", escapes.quote2)
for k,v in pairs(escapes) do
if not colorized_escapes[k] then
colorized_escapes[k] = utils.colorize("B", v)
end
end
end
utils.loadColors()
local function colorize_nop(color, obj)
return obj
end
function utils.dump(o, depth, no_colorize, seen_tables)
local colorize_func
local _escapes
if not seen_tables then
seen_tables = {}
end
local function seenTable(tbl)
return seen_tables[tostring(tbl)]
end
local function addTable(tbl)
if tostring(tbl) == nil then
return
end
seen_tables[tostring(tbl)] = true
end
if no_colorize then
_escapes = escapes
colorize_func = colorize_nop
else
_escapes = colorized_escapes
colorize_func = utils.colorize
end
local t = type(o)
if t == 'string' then
return _escapes.quote .. o:gsub("\\", _escapes.backslash):gsub("%z", _escapes.null):gsub("\n", _escapes.newline):gsub("\r", _escapes.carriage):gsub("\t", _escapes.tab) .. _escapes.quote2
end
if t == 'nil' then
return colorize_func("Bblack", "nil")
end
if t == 'boolean' then
return colorize_func("yellow", tostring(o))
end
if t == 'number' then
return colorize_func("blue", tostring(o))
end
if t == 'userdata' then
return colorize_func("magenta", tostring(o))
end
if t == 'thread' then
return colorize_func("Bred", tostring(o))
end
if t == 'function' then
return colorize_func("cyan", tostring(o))
end
if t == 'cdata' then
return colorize_func("Bmagenta", tostring(o))
end
if t == 'table' then
if seenTable(o) then
return ''
end
addTable(o)
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return colorize_func("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1, k, v
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100, no_colorize, seen_tables) .. '] = '
end
end
local tmpStr = utils.dump(v, depth + 1, no_colorize, seen_tables)
if #tmpStr > 0 then
lines[i] = table.concat({s, tmpStr})
estimated = estimated + #lines[i]
i = i + 1
end
end
if estimated > 200 then
local s = "{\n " .. indent
for k, v in pairs(lines) do
s = s .. v .. ",\n " .. indent
end
s = s .. "\n" .. indent .. "}"
return s
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local bindArgsLength = select("#", ...)
-- Simple binding, just inserts self (or one arg or any kind)
if bindArgsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- More complex binding inserts arbitrary number of args into call.
local bindArgs = {...}
return function (...)
local argsLength = select("#", ...)
local args = {...}
local arguments = {}
for i = 1, bindArgsLength do
arguments[i] = bindArgs[i]
end
for i = 1, argsLength do
arguments[i + bindArgsLength] = args[i]
end
return fn(self, unpack(arguments, 1, bindArgsLength + argsLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
fix utils.dump
|
fix utils.dump
|
Lua
|
apache-2.0
|
bsn069/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,luvit/luvit,sousoux/luvit,DBarney/luvit,kaustavha/luvit,zhaozg/luvit,bsn069/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,kaustavha/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,rjeli/luvit,bsn069/luvit,DBarney/luvit,rjeli/luvit,DBarney/luvit,boundary/luvit,kaustavha/luvit,DBarney/luvit,boundary/luvit,zhaozg/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,sousoux/luvit
|
3946f836483537f78736332049fe5262b037cf05
|
AceGUI-3.0/widgets/AceGUIWidget-Label.lua
|
AceGUI-3.0/widgets/AceGUIWidget-Label.lua
|
--[[-----------------------------------------------------------------------------
Label Widget
Displays text and optionally an icon.
-------------------------------------------------------------------------------]]
local Type, Version = "Label", 20
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local max, select = math.max, select
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateImageAnchor(self)
local frame = self.frame
local width = frame.width or frame:GetWidth() or 0
local image = self.image
local label = self.label
local height
label:ClearAllPoints()
image:ClearAllPoints()
if self.imageshown then
local imagewidth = image:GetWidth()
if (width - imagewidth) < 200 or (label:GetText() or "") == "" then
-- image goes on top centered when less than 200 width for the text, or if there is no text
image:SetPoint("TOP")
label:SetPoint("TOP", image, "BOTTOM")
label:SetPoint("LEFT")
label:SetPoint("RIGHT")
height = image:GetHeight() + label:GetHeight()
else
-- image on the left
image:SetPoint("TOPLEFT")
label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0)
label:SetPoint("TOPRIGHT")
height = max(image:GetHeight(), label:GetHeight())
end
else
-- no image shown
label:SetPoint("TOPLEFT")
label:SetPoint("TOPRIGHT")
height = label:GetHeight()
end
self.resizing = true
frame:SetHeight(height)
frame.height = height
self.resizing = nil
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(18)
self:SetWidth(200)
self:SetText("")
self:SetImage(nil)
self:SetImageSize(16, 16)
self:SetColor()
self.label:SetFontObject(nil)
self.label:SetFont(GameFontHighlightSmall:GetFont())
end,
-- ["OnRelease"] = nil,
["SetText"] = function(self, text)
self.label:SetText(text or "")
UpdateImageAnchor(self)
end,
["SetColor"] = function(self, r, g, b)
if not (r and g and b) then
r, g, b = 1, 1, 1
end
self.label:SetVertexColor(r, g, b)
end,
["OnWidthSet"] = function(self, width)
if self.resizing then return end
UpdateImageAnchor(self)
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
self.imageshown = true
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
else
self.imageshown = nil
end
UpdateImageAnchor(self)
end,
["SetFont"] = function(self, font, height, flags)
self.label:SetFont(font, height, flags)
end,
["SetFontObject"] = function(self, font)
self.label:SetFontObject(font or GameFontHighlightSmall)
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
UpdateImageAnchor(self)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
label:SetJustifyH("LEFT")
label:SetJustifyV("TOP")
local image = frame:CreateTexture(nil, "BACKGROUND")
-- create widget
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
--[[-----------------------------------------------------------------------------
Label Widget
Displays text and optionally an icon.
-------------------------------------------------------------------------------]]
local Type, Version = "Label", 20
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local max, select = math.max, select
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateImageAnchor(self)
local frame = self.frame
local width = frame.width or frame:GetWidth() or 0
local image = self.image
local label = self.label
local height
label:ClearAllPoints()
image:ClearAllPoints()
if self.imageshown then
local imagewidth = image:GetWidth()
if (width - imagewidth) < 200 or (label:GetText() or "") == "" then
-- image goes on top centered when less than 200 width for the text, or if there is no text
image:SetPoint("TOP")
label:SetPoint("TOP", image, "BOTTOM")
label:SetPoint("LEFT")
label:SetWidth(width)
height = image:GetHeight() + label:GetHeight()
else
-- image on the left
image:SetPoint("TOPLEFT")
label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0)
label:SetWidth(width - imagewidth - 4)
height = max(image:GetHeight(), label:GetHeight())
end
else
-- no image shown
label:SetPoint("TOPLEFT")
label:SetWidth(width)
height = label:GetHeight()
end
self.resizing = true
frame:SetHeight(height)
frame.height = height
self.resizing = nil
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(18)
self:SetWidth(200)
self:SetText("")
self:SetImage(nil)
self:SetImageSize(16, 16)
self:SetColor()
self.label:SetFontObject(nil)
self.label:SetFont(GameFontHighlightSmall:GetFont())
end,
-- ["OnRelease"] = nil,
["SetText"] = function(self, text)
self.label:SetText(text or "")
UpdateImageAnchor(self)
end,
["SetColor"] = function(self, r, g, b)
if not (r and g and b) then
r, g, b = 1, 1, 1
end
self.label:SetVertexColor(r, g, b)
end,
["OnWidthSet"] = function(self, width)
if self.resizing then return end
UpdateImageAnchor(self)
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
self.imageshown = true
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
else
self.imageshown = nil
end
UpdateImageAnchor(self)
end,
["SetFont"] = function(self, font, height, flags)
self.label:SetFont(font, height, flags)
end,
["SetFontObject"] = function(self, font)
self.label:SetFontObject(font or GameFontHighlightSmall)
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
UpdateImageAnchor(self)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
label:SetJustifyH("LEFT")
label:SetJustifyV("TOP")
local image = frame:CreateTexture(nil, "BACKGROUND")
-- create widget
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
AceGUI-3.0: Fix height-adjustments of the Label widget, apparently the height doesn't adjust itself when you anchor the top two corners, it needs a fixed width value.
|
AceGUI-3.0: Fix height-adjustments of the Label widget, apparently the height doesn't adjust itself when you anchor the top two corners, it needs a fixed width value.
git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@927 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
a7a366e23a334cd9457251076e3ecccb402be377
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.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.fs")
require("luci.ip")
mp = Map("olsrd", "OLSR - Plugins")
p = mp:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
p.anonymous = true
ign = p:option(Flag, "ignore")
ign.enabled = "1"
ign.disabled = "0"
ign.optional = true
lib = p:option(ListValue, "library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
local function Range(x,y)
local t = {}
for i = x, y do t[#t+1] = i end
return t
end
local function Cidr2IpMask(val)
if val then
for i = 1, #val do
local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i])
if cidr then
val[i] = cidr:network():string() .. " " .. cidr:mask():string()
end
end
return val
end
end
local function IpMask2Cidr(val)
if val then
for i = 1, #val do
local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")()
local cidr
if ip and mask and ip:match(":") then
cidr = luci.ip.IPv6(ip, mask)
elseif ip and mask then
cidr = luci.ip.IPv4(ip, mask)
end
if cidr then
val[i] = cidr:string()
end
end
return val
end
end
local knownPlParams = {
["olsrd_bmf.so.1.5.3"] = {
{ Value, "BmfInterface", "bmf0" },
{ Value, "BmfInterfaceIp", "10.10.10.234/24" },
{ Flag, "DoLocalBroadcast", "no" },
{ Flag, "CapturePacketsOnOlsrInterfaces", "yes" },
{ ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } },
{ Value, "BroadcastRetransmitCount", "2" },
{ Value, "FanOutLimit", "4" },
{ DynamicList, "NonOlsrIf", "eth1" }
},
["olsrd_dyn_gw.so.0.4"] = {
{ Value, "Interval", "40" },
{ DynamicList, "Ping", "141.1.1.1" },
{ DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_httpinfo.so.0.1"] = {
{ Value, "port", "80" },
{ DynamicList, "Host", "163.24.87.3" },
{ DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_nameservice.so.0.2"] = {
{ DynamicList, "name", "my-name.mesh" },
{ DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" },
{ Value, "suffix", ".olsr" },
{ Value, "hosts_file", "/path/to/hosts_file" },
{ Value, "add_hosts", "/path/to/file" },
{ Value, "dns_server", "141.1.1.1" },
{ Value, "resolv_file", "/path/to/resolv.conf" },
{ Value, "interval", "120" },
{ Value, "timeout", "240" },
{ Value, "lat", "12.123" },
{ Value, "lon", "12.123" },
{ Value, "latlon_file", "/var/run/latlon.js" },
{ Value, "latlon_infile", "/var/run/gps.txt" },
{ Value, "sighup_pid_file", "/var/run/dnsmasq.pid" },
{ Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" },
{ Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }
},
["olsrd_quagga.so.0.2.2"] = {
{ StaticList, "redistribute", {
"system", "kernel", "connect", "static", "rip", "ripng", "ospf",
"ospf6", "isis", "bgp", "hsls"
} },
{ ListValue, "ExportRoutes", { "only", "both" } },
{ Flag, "LocalPref", "true" },
{ Value, "Distance", Range(0,255) }
},
["olsrd_secure.so.0.5"] = {
{ Value, "Keyfile", "/etc/private-olsr.key" }
},
["olsrd_txtinfo.so.0.1"] = {
{ Value, "accept", "10.247.200.4" }
}
}
-- build plugin options with dependencies
for plugin, options in pairs(knownPlParams) do
for _, option in ipairs(options) do
local otype, name, default, uci2cbi, cbi2uci = unpack(option)
local values
if type(default) == "table" then
values = default
default = default[1]
end
if otype == Flag then
local bool = p:option( Flag, name )
if default == "yes" or default == "no" then
bool.enabled = "yes"
bool.disabled = "no"
elseif default == "on" or default == "off" then
bool.enabled = "on"
bool.disabled = "off"
elseif default == "1" or default == "0" then
bool.enabled = "1"
bool.disabled = "0"
else
bool.enabled = "true"
bool.disabled = "false"
end
bool.default = default
bool:depends({ library = plugin })
else
local field = p:option( otype, name )
if values then
for _, value in ipairs(values) do
field:value( value )
end
end
if type(uci2cbi) == "function" then
function field.cfgvalue(self, section)
return uci2cbi(otype.cfgvalue(self, section))
end
end
if type(cbi2uci) == "function" then
function field.formvalue(self, section)
return cbi2uci(otype.formvalue(self, section))
end
end
if otype == DynamicList then
field:value( default )
end
field.default = default
field:depends({ library = plugin })
end
end
end
return mp
|
--[[
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.fs")
require("luci.ip")
mp = Map("olsrd", "OLSR - Plugins")
p = mp:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
p.anonymous = true
ign = p:option(Flag, "ignore")
ign.enabled = "1"
ign.disabled = "0"
ign.optional = true
lib = p:option(ListValue, "library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
local function Range(x,y)
local t = {}
for i = x, y do t[#t+1] = i end
return t
end
local function Cidr2IpMask(val)
if val then
for i = 1, #val do
local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i])
if cidr then
val[i] = cidr:network():string() .. " " .. cidr:mask():string()
end
end
return val
end
end
local function IpMask2Cidr(val)
if val then
for i = 1, #val do
local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")()
local cidr
if ip and mask and ip:match(":") then
cidr = luci.ip.IPv6(ip, mask)
elseif ip and mask then
cidr = luci.ip.IPv4(ip, mask)
end
if cidr then
val[i] = cidr:string()
end
end
return val
end
end
local knownPlParams = {
["olsrd_bmf.so.1.5.3"] = {
{ Value, "BmfInterface", "bmf0" },
{ Value, "BmfInterfaceIp", "10.10.10.234/24" },
{ Flag, "DoLocalBroadcast", "no" },
{ Flag, "CapturePacketsOnOlsrInterfaces", "yes" },
{ ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } },
{ Value, "BroadcastRetransmitCount", "2" },
{ Value, "FanOutLimit", "4" },
{ DynamicList, "NonOlsrIf", "eth1" }
},
["olsrd_dyn_gw.so.0.4"] = {
{ Value, "Interval", "40" },
{ DynamicList, "Ping", "141.1.1.1" },
{ DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_httpinfo.so.0.1"] = {
{ Value, "port", "80" },
{ DynamicList, "Host", "163.24.87.3" },
{ DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_nameservice.so.0.3"] = {
{ DynamicList, "name", "my-name.mesh" },
{ DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" },
{ Value, "suffix", ".olsr" },
{ Value, "hosts_file", "/path/to/hosts_file" },
{ Value, "add_hosts", "/path/to/file" },
{ Value, "dns_server", "141.1.1.1" },
{ Value, "resolv_file", "/path/to/resolv.conf" },
{ Value, "interval", "120" },
{ Value, "timeout", "240" },
{ Value, "lat", "12.123" },
{ Value, "lon", "12.123" },
{ Value, "latlon_file", "/var/run/latlon.js" },
{ Value, "latlon_infile", "/var/run/gps.txt" },
{ Value, "sighup_pid_file", "/var/run/dnsmasq.pid" },
{ Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" },
{ Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }
},
["olsrd_quagga.so.0.2.2"] = {
{ StaticList, "redistribute", {
"system", "kernel", "connect", "static", "rip", "ripng", "ospf",
"ospf6", "isis", "bgp", "hsls"
} },
{ ListValue, "ExportRoutes", { "only", "both" } },
{ Flag, "LocalPref", "true" },
{ Value, "Distance", Range(0,255) }
},
["olsrd_secure.so.0.5"] = {
{ Value, "Keyfile", "/etc/private-olsr.key" }
},
["olsrd_txtinfo.so.0.1"] = {
{ Value, "accept", "10.247.200.4" }
}
}
-- build plugin options with dependencies
for plugin, options in pairs(knownPlParams) do
for _, option in ipairs(options) do
local otype, name, default, uci2cbi, cbi2uci = unpack(option)
local values
if type(default) == "table" then
values = default
default = default[1]
end
if otype == Flag then
local bool = p:option( Flag, name )
if default == "yes" or default == "no" then
bool.enabled = "yes"
bool.disabled = "no"
elseif default == "on" or default == "off" then
bool.enabled = "on"
bool.disabled = "off"
elseif default == "1" or default == "0" then
bool.enabled = "1"
bool.disabled = "0"
else
bool.enabled = "true"
bool.disabled = "false"
end
bool.optional = true
bool.default = default
bool:depends({ library = plugin })
else
local field = p:option( otype, name )
if values then
for _, value in ipairs(values) do
field:value( value )
end
end
if type(uci2cbi) == "function" then
function field.cfgvalue(self, section)
return uci2cbi(otype.cfgvalue(self, section))
end
end
if type(cbi2uci) == "function" then
function field.formvalue(self, section)
return cbi2uci(otype.formvalue(self, section))
end
end
if otype == DynamicList then
field:value( default )
end
field.optional = true
field.default = default
field:depends({ library = plugin })
end
end
end
return mp
|
* luci/app-olsr: further fixes in olsr plugins config
|
* luci/app-olsr: further fixes in olsr plugins config
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3259 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
alxhh/piratenluci,gwlim/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,ch3n2k/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,stephank/luci,yeewang/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,saraedum/luci-packages-old,jschmidlapp/luci,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,ch3n2k/luci,ch3n2k/luci,gwlim/luci,alxhh/piratenluci,gwlim/luci,phi-psi/luci,vhpham80/luci,alxhh/piratenluci,Flexibity/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,vhpham80/luci,freifunk-gluon/luci,projectbismark/luci-bismark,Flexibity/luci,projectbismark/luci-bismark,jschmidlapp/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,Flexibity/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,alxhh/piratenluci,saraedum/luci-packages-old,saraedum/luci-packages-old,yeewang/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,alxhh/piratenluci,ch3n2k/luci,projectbismark/luci-bismark,freifunk-gluon/luci,alxhh/piratenluci,freifunk-gluon/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,Flexibity/luci,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,eugenesan/openwrt-luci,jschmidlapp/luci,freifunk-gluon/luci,vhpham80/luci,freifunk-gluon/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,8devices/carambola2-luci,alxhh/piratenluci,phi-psi/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,stephank/luci,jschmidlapp/luci,vhpham80/luci,phi-psi/luci,vhpham80/luci,Flexibity/luci,jschmidlapp/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,gwlim/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,stephank/luci,8devices/carambola2-luci,stephank/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci
|
a4e35f81cf098bfdc86eb773deae3aaaf6a11aa4
|
resources/prosody-plugins/mod_polls.lua
|
resources/prosody-plugins/mod_polls.lua
|
-- This module provides persistence for the "polls" feature,
-- by keeping track of the state of polls in each room, and sending
-- that state to new participants when they join.
local json = require("util.json");
local st = require("util.stanza");
local util = module:require("util");
local muc = module:depends("muc");
local is_healthcheck_room = util.is_healthcheck_room;
-- Checks if the given stanza contains a JSON message,
-- and that the message type pertains to the polls feature.
-- If yes, returns the parsed message. Otherwise, returns nil.
local function get_poll_message(stanza)
if stanza.attr.type ~= "groupchat" then
return nil;
end
local json_data = stanza:get_child_text("json-message", "http://jitsi.org/jitmeet");
if json_data == nil then
return nil;
end
local data = json.decode(json_data);
if not data or (data.type ~= "new-poll" and data.type ~= "answer-poll") then
return nil;
end
return data;
end
-- Logs a warning and returns true if a room does not
-- have poll data associated with it.
local function check_polls(room)
if room.polls == nil then
module:log("warn", "no polls data in room");
return true;
end
return false;
end
-- Sets up poll data in new rooms.
module:hook("muc-room-created", function(event)
local room = event.room;
if is_healthcheck_room(room.jid) then return end
module:log("debug", "setting up polls in room %s", room.jid);
room.polls = {
by_id = {};
order = {};
};
end);
-- Keeps track of the current state of the polls in each room,
-- by listening to "new-poll" and "answer-poll" messages,
-- and updating the room poll data accordingly.
-- This mirrors the client-side poll update logic.
module:hook("message/bare", function(event)
local data = get_poll_message(event.stanza);
if data == nil then return end
local room = muc.get_room_from_jid(event.stanza.attr.to);
if data.type == "new-poll" then
if check_polls(room) then return end
local answers = {}
local compactAnswers = {}
for i, name in ipairs(data.answers) do
table.insert(answers, { name = name, voters = {} });
table.insert(compactAnswers, { key = i, name = name});
end
local poll = {
id = data.pollId,
sender_id = data.senderId,
sender_name = data.senderName,
question = data.question,
answers = answers
};
room.polls.by_id[data.pollId] = poll
table.insert(room.polls.order, poll)
local pollData = {
event = event,
room = room,
poll = {
pollId = data.pollId,
senderId = data.senderId,
senderName = data.senderName,
question = data.question,
answers = compactAnswers
}
}
module:fire_event("poll-created", pollData);
elseif data.type == "answer-poll" then
if check_polls(room) then return end
local poll = room.polls.by_id[data.pollId];
if poll == nil then
module:log("warn", "answering inexistent poll");
return;
end
local answers = {};
for i, value in ipairs(data.answers) do
table.insert(answers, {
key = i,
value = value,
name = poll.answers[i].name,
});
poll.answers[i].voters[data.voterId] = value and data.voterName or nil;
end
local answerData = {
event = event,
room = room,
pollId = poll.id,
voterName = data.voterName,
voterId = data.voterId,
answers = answers
}
module:fire_event("answer-poll", answerData);
end
end);
-- Sends the current poll state to new occupants after joining a room.
module:hook("muc-occupant-joined", function(event)
local room = event.room;
if is_healthcheck_room(room.jid) then return end
if room.polls == nil or #room.polls.order == 0 then
return
end
local data = {
type = "old-polls",
polls = {},
};
for i, poll in ipairs(room.polls.order) do
data.polls[i] = {
id = poll.id,
senderId = poll.sender_id,
senderName = poll.sender_name,
question = poll.question,
answers = poll.answers
};
end
local stanza = st.message({
from = room.jid,
to = event.occupant.jid
})
:tag("json-message", { xmlns = "http://jitsi.org/jitmeet" })
:text(json.encode(data))
:up();
room:route_stanza(stanza);
end);
|
-- This module provides persistence for the "polls" feature,
-- by keeping track of the state of polls in each room, and sending
-- that state to new participants when they join.
local json = require("util.json");
local st = require("util.stanza");
local jid = require "util.jid";
local util = module:require("util");
local muc = module:depends("muc");
local NS_NICK = 'http://jabber.org/protocol/nick';
local is_healthcheck_room = util.is_healthcheck_room;
-- Checks if the given stanza contains a JSON message,
-- and that the message type pertains to the polls feature.
-- If yes, returns the parsed message. Otherwise, returns nil.
local function get_poll_message(stanza)
if stanza.attr.type ~= "groupchat" then
return nil;
end
local json_data = stanza:get_child_text("json-message", "http://jitsi.org/jitmeet");
if json_data == nil then
return nil;
end
local data = json.decode(json_data);
if not data or (data.type ~= "new-poll" and data.type ~= "answer-poll") then
return nil;
end
return data;
end
-- Logs a warning and returns true if a room does not
-- have poll data associated with it.
local function check_polls(room)
if room.polls == nil then
module:log("warn", "no polls data in room");
return true;
end
return false;
end
--- Returns a table having occupant id and occupant name.
--- If the id cannot be extracted from nick a nil value is returned
--- if the occupant name cannot be extracted from presence the Fellow Jitster
--- name is used
local function get_occupant_details(occupant)
if not occupant then
return nil
end
local presence = occupant:get_presence();
local occupant_name;
if presence then
occupant_name = presence:get_child("nick", NS_NICK) and presence:get_child("nick", NS_NICK):get_text() or 'Fellow Jitster';
else
occupant_name = 'Fellow Jitster'
end
local _, _, occupant_id = jid.split(occupant.nick)
if not occupant_id then
return nil
end
return { ["occupant_id"] = occupant_id, ["occupant_name"] = occupant_name }
end
-- Sets up poll data in new rooms.
module:hook("muc-room-created", function(event)
local room = event.room;
if is_healthcheck_room(room.jid) then return end
module:log("debug", "setting up polls in room %s", room.jid);
room.polls = {
by_id = {};
order = {};
};
end);
-- Keeps track of the current state of the polls in each room,
-- by listening to "new-poll" and "answer-poll" messages,
-- and updating the room poll data accordingly.
-- This mirrors the client-side poll update logic.
module:hook("message/bare", function(event)
local data = get_poll_message(event.stanza);
if data == nil then return end
local room = muc.get_room_from_jid(event.stanza.attr.to);
if data.type == "new-poll" then
if check_polls(room) then return end
local occupant_jid = event.stanza.attr.from;
local occupant = room:get_occupant_by_real_jid(occupant_jid);
if not occupant then
module:log("error", "Occupant %s was not found in room %s", occupant_jid, room.jid)
return
end
local poll_creator = get_occupant_details(occupant)
if not poll_creator then
module:log("error", "Cannot retrieve poll creator id and name for %s from %s", occupant.jid, room.jid)
return
end
local answers = {}
local compact_answers = {}
for i, name in ipairs(data.answers) do
table.insert(answers, { name = name, voters = {} });
table.insert(compact_answers, { key = i, name = name});
end
local poll = {
id = data.pollId,
sender_id = poll_creator.occupant_id,
sender_name = poll_creator.occupant_name,
question = data.question,
answers = answers
};
room.polls.by_id[data.pollId] = poll
table.insert(room.polls.order, poll)
local pollData = {
event = event,
room = room,
poll = {
pollId = data.pollId,
senderId = poll_creator.occupant_id,
senderName = poll_creator.occupant_name,
question = data.question,
answers = compact_answers
}
}
module:fire_event("poll-created", pollData);
elseif data.type == "answer-poll" then
if check_polls(room) then return end
local occupant_jid = event.stanza.attr.from;
local occupant = room:get_occupant_by_real_jid(occupant_jid);
if not occupant then
module:log("error", "Occupant %s does not exists for room %s", occupant_jid, room.jid)
return
end
local poll = room.polls.by_id[data.pollId];
if poll == nil then
module:log("warn", "answering inexistent poll");
return;
end
local voter = get_occupant_details(occupant)
if not voter then
module:log("error", "Cannot retrieve voter id and name for %s from %s", occupant.jid, room.jid)
return
end
local answers = {};
for vote_option_idx, vote_flag in ipairs(data.answers) do
table.insert(answers, {
key = vote_option_idx,
value = vote_flag,
name = poll.answers[vote_option_idx].name,
});
poll.answers[vote_option_idx].voters[voter.occupant_id] = vote_flag and voter.occupant_name or nil;
end
local answerData = {
event = event,
room = room,
pollId = poll.id,
voterName = voter.occupant_name,
voterId = voter.occupant_id,
answers = answers
}
module:fire_event("answer-poll", answerData);
end
end);
-- Sends the current poll state to new occupants after joining a room.
module:hook("muc-occupant-joined", function(event)
local room = event.room;
if is_healthcheck_room(room.jid) then return end
if room.polls == nil or #room.polls.order == 0 then
return
end
local data = {
type = "old-polls",
polls = {},
};
for i, poll in ipairs(room.polls.order) do
data.polls[i] = {
id = poll.id,
senderId = poll.sender_id,
senderName = poll.sender_name,
question = poll.question,
answers = poll.answers
};
end
local stanza = st.message({
from = room.jid,
to = event.occupant.jid
})
:tag("json-message", { xmlns = "http://jitsi.org/jitmeet" })
:text(json.encode(data))
:up();
room:route_stanza(stanza);
end);
|
fix(polls) refactor message handling
|
fix(polls) refactor message handling
|
Lua
|
apache-2.0
|
jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
|
59c87257ac3eac2072bd98b35bad6e2924756300
|
particle-maker/lua/autorun/client/particlemaker_locale.lua
|
particle-maker/lua/autorun/client/particlemaker_locale.lua
|
/**
* Copyright 2016 Roelof Roos (SirQuack)
* Part of Particle Maker Garry's Mod Tool
*
* 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.
*/
--[[
This file handles locale support. Since Garry's Mod only imports their own
locales and there is no easy way to find out what language the user uses,
we simply test it against a list of data we /know/ is correct.
Afterwards, we manually add the file to the language database.
]]
local function registerLanguage()
// Generated with get-locales.php
local localeLinks = {
{"Нова игра", "bg"},
{"Spustit novou hru", "cs"},
{"Start nyt spil", "da"},
{"Neues Spiel starten", "de"},
{"Έναρξη νέου παιχνιδιού", "el"},
{"Start New Game", "en"},
{"Sail upon a quest", "en-PT"},
{"Comenzar nueva partida", "es-ES"},
{"Alusta Uut Mängu", "et"},
{"Aloita Uusi Peli", "fi"},
{"Commencer une nouvelle partie", "fr"},
{"התחל משחק חדש", "he"},
{"Započni Novu Igru", "hr"},
{"Új játék indítása", "hu"},
{"Avvia Nuova Partita", "it"},
{"新しいゲームを開始", "ja"},
{"새로운 게임 시작", "ko"},
{"Pradėti naują žaidimą", "lt"},
{"Start een nieuw spel", "nl"},
{"Start nytt spill", "no"},
{"Rozpocznij Nową Grę", "pl"},
{"Iniciar novo jogo", "pt-BR"},
{"Começar Novo Jogo", "pt-PT"},
{"Начать новую игру", "ru"},
{"Nová hra", "sk"},
{"Starta nytt spel", "sv-SE"},
{"เริ่มเกมใหม่", "th"},
{"Yeni Bir Oyun Başlat", "tr"},
{"Нова гра", "uk"},
{"Bắt đầu trò chơi mới", "vi"},
{"开始新游戏", "zh-CN"},
{"開始新遊戲", "zh-TW"}
}
local currentText = language.GetPhrase('new_game');
local currentLocal = 'en'
local languageFile = 'resource/localization/%s/particlemaker.properties'
for _, test in pairs(localeLinks) do
if test[1] == currentText then
currentLocal = test[2]
break
end
end
local langPath = string.format(languageFile, currentLocal)
if not file.Exists(langPath, 'GAME') then
print("Falling back")
langPath = string.format(languageFile, 'en')
end
if not file.Exists(langPath, 'GAME') then
Error("Cannot use path at " .. langPath)
return
end
local data = file.Read(langPath, 'GAME')
local dataLines = string.Split(data, "\n")
for _, line in pairs(dataLines) do
line = string.Trim(line)
if string.len(line) == 0 then continue end
if string.sub(line, 0, 1) == '#' then continue end
local _, _, key, value = string.find(
line,
'([%w%p_]+)=(.+)'
)
language.Add(key, value)
end
end
hook.Add(
"Initialise",
"ParticleMaker_Initialise_Locales",
registerLanguage
)
hook.Add(
"InitPostEntity",
"ParticleMaker_InitPostEntity_Locales",
registerLanguage
)
|
/**
* Copyright 2016 Roelof Roos (SirQuack)
* Part of Particle Maker Garry's Mod Tool
*
* 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.
*/
--[[
This file handles locale support. Since Garry's Mod only imports their own
locales and there is no easy way to find out what language the user uses,
we simply test it against a list of data we /know/ is correct.
Afterwards, we manually add the file to the language database.
]]
local function registerLanguage()
// Generated with get-locales.php
local localeLinks = {
{"Нова игра", "bg"},
{"Spustit novou hru", "cs"},
{"Start nyt spil", "da"},
{"Neues Spiel starten", "de"},
{"Έναρξη νέου παιχνιδιού", "el"},
{"Start New Game", "en"},
{"Sail upon a quest", "en-PT"},
{"Comenzar nueva partida", "es-ES"},
{"Alusta Uut Mängu", "et"},
{"Aloita Uusi Peli", "fi"},
{"Commencer une nouvelle partie", "fr"},
{"התחל משחק חדש", "he"},
{"Započni Novu Igru", "hr"},
{"Új játék indítása", "hu"},
{"Avvia Nuova Partita", "it"},
{"新しいゲームを開始", "ja"},
{"새로운 게임 시작", "ko"},
{"Pradėti naują žaidimą", "lt"},
{"Start een nieuw spel", "nl"},
{"Start nytt spill", "no"},
{"Rozpocznij Nową Grę", "pl"},
{"Iniciar novo jogo", "pt-BR"},
{"Começar Novo Jogo", "pt-PT"},
{"Начать новую игру", "ru"},
{"Nová hra", "sk"},
{"Starta nytt spel", "sv-SE"},
{"เริ่มเกมใหม่", "th"},
{"Yeni Bir Oyun Başlat", "tr"},
{"Нова гра", "uk"},
{"Bắt đầu trò chơi mới", "vi"},
{"开始新游戏", "zh-CN"},
{"開始新遊戲", "zh-TW"}
}
local currentText = language.GetPhrase('new_game');
local currentLocal = 'en'
local languageFile = 'resource/localization/%s/particlemaker.properties'
-- Locales unavailable, abort.
if currentText == "new_game" then return end
for _, test in pairs(localeLinks) do
if test[1] == currentText then
currentLocal = test[2]
break
end
end
local langPath = string.format(languageFile, currentLocal)
if not file.Exists(langPath, 'GAME') then
print("Falling back")
langPath = string.format(languageFile, 'en')
end
if not file.Exists(langPath, 'GAME') then
Error("Cannot use path at " .. langPath)
return
end
local data = file.Read(langPath, 'GAME')
local dataLines = string.Split(data, "\n")
for _, line in pairs(dataLines) do
line = string.Trim(line)
if string.len(line) == 0 then continue end
if string.sub(line, 0, 1) == '#' then continue end
local _, _, key, value = string.find(
line,
'([%w%p_]+)=(.+)'
)
language.Add(key, value)
end
end
-- Run registration upon initialisation
hook.Add(
"Initialise",
"ParticleMaker_Initialise_Locales",
registerLanguage
)
-- Run registration upon entity ready
hook.Add(
"InitPostEntity",
"ParticleMaker_InitPostEntity_Locales",
registerLanguage
)
-- Run it now too, to fix issue #4
registerLanguage()
|
Fixed issue #4
|
Fixed issue #4
|
Lua
|
apache-2.0
|
roelofr/GMod-ParticleMaker
|
e55bc9f1035c2cb1ddd32950fa404521bb6d2245
|
scripts/bgfx.lua
|
scripts/bgfx.lua
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
links {
"gdi32",
}
configuration {}
end
includedirs {
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "../bx/include",
}
defines {
_defines,
}
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "mingw* or vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "xcode4 or osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
configuration {}
copyLib()
end
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration {}
end
includedirs {
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "../bx/include",
}
defines {
_defines,
}
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "mingw* or vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "xcode4 or osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
configuration {}
copyLib()
end
|
Fixed issue #257.
|
Fixed issue #257.
|
Lua
|
bsd-2-clause
|
emoon/bgfx,Vertexwahn/bgfx,septag/bgfx,bkaradzic/bgfx,septag/bgfx,jdryg/bgfx,darkimage/bgfx,Extrawurst/bgfx,mendsley/bgfx,fluffyfreak/bgfx,LWJGL-CI/bgfx,bkaradzic/bgfx,0-wiz-0/bgfx,mendsley/bgfx,jdryg/bgfx,Synxis/bgfx,aonorin/bgfx,kondrak/bgfx,ming4883/bgfx,MikePopoloski/bgfx,mcanthony/bgfx,septag/bgfx,v3n/bgfx,janstk/bgfx,MikePopoloski/bgfx,emoon/bgfx,LSBOSS/bgfx,ocornut/bgfx,LSBOSS/bgfx,attilaz/bgfx,elmindreda/bgfx,cyndis/bgfx,Vertexwahn/bgfx,LWJGL-CI/bgfx,aonorin/bgfx,andr3wmac/bgfx,BlueCrystalLabs/bgfx,marco-we/bgfx,v3n/bgfx,mmicko/bgfx,marco-we/bgfx,MikePopoloski/bgfx,mcanthony/bgfx,sergeScherbakov/bgfx,fluffyfreak/bgfx,sergeScherbakov/bgfx,BlueCrystalLabs/bgfx,janstk/bgfx,elmindreda/bgfx,0-wiz-0/bgfx,cuavas/bgfx,ktotheoz/bgfx,janstk/bgfx,mmicko/bgfx,attilaz/bgfx,mcanthony/bgfx,ming4883/bgfx,Synxis/bgfx,v3n/bgfx,cuavas/bgfx,jpcy/bgfx,LWJGL-CI/bgfx,aonorin/bgfx,darkimage/bgfx,jpcy/bgfx,cuavas/bgfx,0-wiz-0/bgfx,kondrak/bgfx,marco-we/bgfx,Vertexwahn/bgfx,sergeScherbakov/bgfx,mmicko/bgfx,LWJGL-CI/bgfx,jdryg/bgfx,ocornut/bgfx,darkimage/bgfx,cyndis/bgfx,fluffyfreak/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx,LSBOSS/bgfx,ktotheoz/bgfx,ktotheoz/bgfx,mendsley/bgfx,emoon/bgfx,jpcy/bgfx,BlueCrystalLabs/bgfx,Synxis/bgfx,Extrawurst/bgfx,ocornut/bgfx,andr3wmac/bgfx,bkaradzic/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,kondrak/bgfx,cyndis/bgfx,attilaz/bgfx,jpcy/bgfx,elmindreda/bgfx,ming4883/bgfx,jdryg/bgfx
|
3df48322655751e0a06d89e788b2924852895ad9
|
platform/android/llapp_main.lua
|
platform/android/llapp_main.lua
|
local A = require("android")
A.dl.library_path = A.dl.library_path .. ":" .. A.dir .. "/libs"
local ffi = require("ffi")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
]]
-- check uri of the intent that starts this application
local file = A.jni:context(A.app.activity.vm, function(JNI)
local uri = JNI:callObjectMethod(
JNI:callObjectMethod(
A.app.activity.clazz,
"getIntent",
"()Landroid/content/Intent;"
),
"getData",
"()Landroid/net/Uri;"
)
if uri ~= nil then
local path = JNI:callObjectMethod(
uri,
"getPath",
"()Ljava/lang/String;"
)
return JNI:to_string(path)
end
end)
A.LOGI("intent file path " .. (file or ""))
-- run koreader patch before koreader startup
pcall(function() dofile("/sdcard/koreader/patch.lua") end)
-- set proper permission for sdcv
A.execute("chmod", "755", "./sdcv")
-- set TESSDATA_PREFIX env var
ffi.C.putenv("TESSDATA_PREFIX=/sdcard/koreader/data")
-- create fake command-line arguments
arg = {"-d", file or "/sdcard"}
dofile(A.dir.."/reader.lua")
|
local A = require("android")
A.dl.library_path = A.dl.library_path .. ":" .. A.dir .. "/libs"
local ffi = require("ffi")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
void *mmap(void *addr, size_t length, int prot, int flags, int fd, size_t offset);
int munmap(void *addr, size_t length);
]]
-- check uri of the intent that starts this application
local file = A.jni:context(A.app.activity.vm, function(JNI)
local uri = JNI:callObjectMethod(
JNI:callObjectMethod(
A.app.activity.clazz,
"getIntent",
"()Landroid/content/Intent;"
),
"getData",
"()Landroid/net/Uri;"
)
if uri ~= nil then
local path = JNI:callObjectMethod(
uri,
"getPath",
"()Ljava/lang/String;"
)
return JNI:to_string(path)
end
end)
A.LOGI("intent file path " .. (file or ""))
-- reservation enough mmap slots for mcode allocation
local reserved_slots = {}
for i = 1, 32 do
local len = 0x80000 + i*0x2000
local p = ffi.C.mmap(nil, len, 0x3, 0x22, -1, 0)
A.LOGI("mmapped " .. tostring(p))
table.insert(reserved_slots, {p = p, len = len})
end
-- free the reservation immediately
for _, slot in ipairs(reserved_slots) do
local res = ffi.C.munmap(slot.p, slot.len)
A.LOGI("munmap " .. tostring(slot.p) .. " " .. res)
end
-- and allocate a large mcode segment, hopefully it will success.
require("jit.opt").start("sizemcode=512","maxmcode=512")
for i=1,100 do end -- Force allocation of one large segment
-- run koreader patch before koreader startup
pcall(function() dofile("/sdcard/koreader/patch.lua") end)
-- set proper permission for sdcv
A.execute("chmod", "755", "./sdcv")
-- set TESSDATA_PREFIX env var
ffi.C.putenv("TESSDATA_PREFIX=/sdcard/koreader/data")
-- create fake command-line arguments
arg = {"-d", file or "/sdcard"}
dofile(A.dir.."/reader.lua")
|
fix mcode allocation failure on Android This workaround makes a reservation of mmap slots that are hopefully near the address of `mcode_alloc_at`. Then it unmaps those slots and lets luajit allocate a large slot for mcode.
|
fix mcode allocation failure on Android
This workaround makes a reservation of mmap slots that are hopefully
near the address of `mcode_alloc_at`. Then it unmaps those slots and
lets luajit allocate a large slot for mcode.
|
Lua
|
agpl-3.0
|
mihailim/koreader,frankyifei/koreader,apletnev/koreader,Markismus/koreader,poire-z/koreader,houqp/koreader,poire-z/koreader,NickSavage/koreader,NiLuJe/koreader,NiLuJe/koreader,chihyang/koreader,pazos/koreader,Frenzie/koreader,Frenzie/koreader,mwoz123/koreader,lgeek/koreader,Hzj-jie/koreader,koreader/koreader,robert00s/koreader,koreader/koreader
|
f9454f71983c09f5de34dba8b281746856e5c485
|
corovel/corona/timer.lua
|
corovel/corona/timer.lua
|
--====================================================================--
-- corovel/corona/timer.lua
--
--
-- by David McCuskey
-- Documentation: http://docs.davidmccuskey.com/display/docs/Lua+Corovel
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
-- Corovel : Corona-esque Timer Object
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
-- Setup, Constants
local tinsert = table.insert
local tremove = table.remove
local Timer = nil -- forward declare
--====================================================================--
-- Support Functions
-- checkEventSchedule(), static function
--
local function checkEventSchedule( )
-- print( "checkEventSchedule" )
Timer:checkEventSchedule()
end
-- performWithDelay(), static function
--
local function performWithDelay( time, handler, iterations )
-- print("timer.performWithDelay", time, handler, iterations )
if iterations == nil then iterations = 1 end
if iterations < -1 then iterations = -1 end
--==--
local eternal = false
if iterations == 0 or iterations == -1 then eternal = true end
Timer:scheduleEvent( Timer:createEvent( time, handler, iterations, eternal ) )
end
--====================================================================--
-- Timer Object Class
--====================================================================--
Timer = {}
Timer.NAME = "Timer Object Class"
Timer.EVENT = 'timer'
Timer.event_schedule = {} -- the scheduled items
function Timer:createEvent( e_time, e_handler, e_iterations, e_eternal )
-- print( "Timer:createEvent", e_time, e_iterations )
local e_start, e_pos = 0, 0
return { e_time, e_handler, e_iterations, e_eternal, e_start, e_pos }
end
function Timer:scheduleEvent( event )
-- print( "Timer:scheduleEvent" )
self:addEventToSchedule( event )
end
function Timer:rescheduleEvent( event )
self:addEventToSchedule( self:removeEventFromSchedule( event ) )
end
function Timer:addEventToSchedule( event )
-- print( "Timer:addEventToSchedule", event[1] )
-- we keep ordered list of timed events
local schedule = self.event_schedule
local i, end_loop = 1, #schedule
event[5] = event[1] + system.getTimer()
local e_start = event[5]
-- print( 'add at', e_start )
if end_loop == 0 then
event[6] = 1
tinsert( schedule, event )
return
end
repeat
if e_start < schedule[i][5] then break end
i = i + 1
until i > end_loop
event[6] = i
tinsert( schedule, i, event )
-- reindex event positions
while i+1 <= #schedule do
schedule[i+1][6] = i+1
i = i + 1
end
end
function Timer:removeEventFromSchedule( event )
-- print( "Timer:removeEventFromSchedule", event[6] )
local schedule = self.event_schedule
local idx = event[6]
local evt = tremove( schedule, idx )
-- reindex event positions
while idx <= #schedule do
schedule[idx][6] = idx
idx = idx + 1
end
return evt
end
-- checkEventSchedule()
-- checks scheduled events, handles any which need attention
--
function Timer:checkEventSchedule()
-- print( "Timer:checkEventSchedule", #self.event_schedule )
if #self.event_schedule == 0 then return end
local event_schedule = self.event_schedule
local i, end_loop = 1, #event_schedule
local is_done = false
repeat
local t = system.getTimer()
-- print( 'time is ', t, i )
local evt = event_schedule[i]
local e_handler, e_iterate, e_eternal, e_start = evt[2], evt[3], evt[4], evt[5]
if e_start > t then
is_done = true
else
local event = { time=t }
if type( e_handler ) == 'function' then
e_handler( event )
elseif type( e_handler ) == 'table' then
local method = e_handler[ self.EVENT ]
method( e_handler, event )
else
print( "WARNING: Timer handler error" )
end
if not e_eternal then
e_iterate = e_iterate - 1
if e_iterate > 0 then
evt[3] = e_iterate
self:rescheduleEvent( evt )
else
self:removeEventFromSchedule( evt )
i=i-1; end_loop=end_loop-1 -- adjust for shortened length after remove
end
end
end
i = i + 1
-- print( 'time end ', i, end_loop, is_done, #event_schedule )
until is_done or i > end_loop or #event_schedule == 0
end
--====================================================================--
-- Timer Facade
--====================================================================--
return {
_checkEventSchedule = checkEventSchedule,
performWithDelay=performWithDelay
}
|
--====================================================================--
-- corovel/corona/timer.lua
--
--
-- by David McCuskey
-- Documentation: http://docs.davidmccuskey.com/display/docs/Lua+Corovel
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
-- Corovel : Corona-esque Timer Object
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
-- Setup, Constants
local tinsert = table.insert
local tremove = table.remove
local Timer = nil -- forward declare
--====================================================================--
-- Support Functions
-- checkEventSchedule(), static function
--
local function checkEventSchedule( )
-- print( "checkEventSchedule" )
Timer:checkEventSchedule()
end
-- performWithDelay(), static function
--
local function performWithDelay( time, handler, iterations )
-- print("timer.performWithDelay", time, handler, iterations )
if iterations == nil then iterations = 1 end
if iterations < -1 then iterations = -1 end
--==--
local eternal = false
if iterations == 0 or iterations == -1 then eternal = true end
Timer:scheduleEvent( Timer:createEvent( time, handler, iterations, eternal ) )
end
--====================================================================--
-- Timer Object Class
--====================================================================--
Timer = {}
Timer.NAME = "Timer Object Class"
Timer.EVENT = 'timer'
Timer.event_schedule = {} -- the scheduled items
function Timer:createEvent( e_time, e_handler, e_iterations, e_eternal )
-- print( "Timer:createEvent", e_time, e_iterations )
local e_start, e_pos = 0, 0
return { e_time, e_handler, e_iterations, e_eternal, e_start, e_pos }
end
function Timer:scheduleEvent( event )
-- print( "Timer:scheduleEvent" )
self:addEventToSchedule( event )
end
function Timer:rescheduleEvent( event )
self:addEventToSchedule( self:removeEventFromSchedule( event ) )
end
function Timer:addEventToSchedule( event )
-- print( "Timer:addEventToSchedule", event[1] )
-- we keep ordered list of timed events
local schedule = self.event_schedule
local i, end_loop = 1, #schedule
event[5] = event[1] + system.getTimer()
local e_start = event[5]
-- print( 'add at', e_start )
if end_loop == 0 then
event[6] = 1
tinsert( schedule, event )
return
end
repeat
if e_start < schedule[i][5] then break end
i = i + 1
until i > end_loop
event[6] = i
tinsert( schedule, i, event )
-- reindex event positions
while i+1 <= #schedule do
schedule[i+1][6] = i+1
i = i + 1
end
end
function Timer:removeEventFromSchedule( event )
-- print( "Timer:removeEventFromSchedule", event[6] )
local schedule = self.event_schedule
local idx = event[6]
local evt = tremove( schedule, idx )
-- reindex event positions
while idx <= #schedule do
schedule[idx][6] = idx
idx = idx + 1
end
return evt
end
-- checkEventSchedule()
-- checks scheduled events, handles any which need attention
--
function Timer:checkEventSchedule()
-- print( "Timer:checkEventSchedule", #self.event_schedule )
if #self.event_schedule == 0 then return end
local event_schedule = self.event_schedule
local i, end_loop = 1, #event_schedule
local is_done = false
repeat
local t = system.getTimer()
-- print( 'time is ', t, i )
local evt = event_schedule[i]
local e_handler, e_iterate, e_eternal, e_start = evt[2], evt[3], evt[4], evt[5]
if e_start > t then
is_done = true
else
local event = { time=t }
if type( e_handler ) == 'function' then
e_handler( event )
elseif type( e_handler ) == 'table' then
local method = e_handler[ self.EVENT ]
method( e_handler, event )
else
print( "WARNING: Timer handler error" )
end
if e_eternal then
self:rescheduleEvent( evt )
else
e_iterate = e_iterate - 1
if e_iterate > 0 then
evt[3] = e_iterate
self:rescheduleEvent( evt )
else
self:removeEventFromSchedule( evt )
i=i-1; end_loop=end_loop-1 -- adjust for shortened length after remove
end
end
end
i = i + 1
-- print( 'time end ', i, end_loop, is_done, #event_schedule )
until is_done or i > end_loop or #event_schedule == 0
end
--====================================================================--
-- Timer Facade
--====================================================================--
return {
_checkEventSchedule = checkEventSchedule,
performWithDelay=performWithDelay
}
|
fix issue #1, misbehaving infinite timer
|
fix issue #1, misbehaving infinite timer
|
Lua
|
mit
|
dmccuskey/lua-corovel
|
8e6fac3c149344f94de046598781e9d85046a068
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.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.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp", translate("dynamic"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
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.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("DHCP"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
modules/admin-full: fix last commit
|
modules/admin-full: fix last commit
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci
|
4e08637384fdee8dd2aa368734ea1fd73ff5a832
|
examples/route_guide/server_reader/RecordRouteReader.lua
|
examples/route_guide/server_reader/RecordRouteReader.lua
|
--- Server reader class for RecordRoute method.
-- @classmod server_reader.RecordRouteReader
local Reader = {}
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New Reader.
-- @tparam Replier replier Replier object
-- @treturn table Reader object
function Reader:new(replier, db)
assert("table" == type(replier))
local reader = {
-- private:
_replier = replier,
_db = db,
_summary = {
point_count = 0,
feature_count = 0,
distance = 0.0,
elapsed_time = 0, -- in seconds
},
_previous = nil, -- Point
_start_time = os.time(),
}
setmetatable(reader, self)
self.__index = self
return reader
end -- new()
local function get_distance(p1, p2)
local kCoordFactor = 10000000.0
local lat_1 = p1.latitude / kCoordFactor
local lat_2 = p2.latitude / kCoordFactor
local lon_1 = p1.longitude / kCoordFactor
local lon_2 = p2.longitude / kCoordFactor
local lat_rad_1 = math.rad(lat_1)
local lat_rad_2 = math.rad(lat_2)
local delta_lat_rad = math.rad(lat_2-lat_1)
local delta_lon_rad = math.rad(lon_2-lon_1)
local a = math.sin(delta_lat_rad/2) ^ 2
+ math.cos(lat_rad_1) * math.cos(lat_rad_2) *
math.sin(delta_lon_rad/2) ^ 2
local c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
local R = 6371000 -- metres
return R * c
end -- get_distance()
function Reader:on_msg(msg)
assert("table" == type(msg))
self._summary.point_count = self._summary.point_count + 1
if self:_get_feature_name(msg) then
self._summary.feature_count = self._summary.feature_count + 1
end
if self._previous then
self._summary.distance = self._summary.distance
+ get_distance(self._previous, msg);
end
self._previous = msg;
end
function Reader:on_error(error_str, status_code)
assert("string" == type(error_str))
assert("number" == type(status_code))
print(string.format("RecordRoute error: (%d)%s", status_code, error_str))
self._replier.reply_error(error_str, status_code)
end
function Reader:on_end()
print("RecordRoute reader end.")
self._summary.elapsed_time = os.time() - self._start_time
self._replier.Reply(self._summary);
end
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
--- Get feature name.
-- @table point
-- @treturn string|nil
function Reader:_get_feature_name(point)
assert("table" == type(point))
for _, f in ipairs(self._db.features) do
local l = f.location
if l.latitude == point.latitude and
l.longitude == point.longitude then
return f.name
end -- if
end -- for
return nil
end
return Reader
|
--- Server reader class for RecordRoute method.
-- @classmod server_reader.RecordRouteReader
local Reader = {}
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New Reader.
-- @tparam Replier replier Replier object
-- @treturn table Reader object
function Reader:new(replier, db)
assert("table" == type(replier))
local reader = {
-- private:
_replier = replier,
_db = db,
_summary = {
point_count = 0,
feature_count = 0,
distance = 0.0,
elapsed_time = 0, -- in seconds
},
_previous = nil, -- Point
_start_time = os.time(),
}
setmetatable(reader, self)
self.__index = self
return reader
end -- new()
local function get_distance(p1, p2)
local kCoordFactor = 10000000.0
local lat_1 = p1.latitude / kCoordFactor
local lat_2 = p2.latitude / kCoordFactor
local lon_1 = p1.longitude / kCoordFactor
local lon_2 = p2.longitude / kCoordFactor
local lat_rad_1 = math.rad(lat_1)
local lat_rad_2 = math.rad(lat_2)
local delta_lat_rad = math.rad(lat_2-lat_1)
local delta_lon_rad = math.rad(lon_2-lon_1)
local a = math.sin(delta_lat_rad/2) ^ 2
+ math.cos(lat_rad_1) * math.cos(lat_rad_2) *
math.sin(delta_lon_rad/2) ^ 2
local c = 2 * math.atan(math.sqrt(a), math.sqrt(1-a))
local R = 6371000 -- metres
return R * c
end -- get_distance()
function Reader:on_msg(msg)
assert("table" == type(msg))
self._summary.point_count = self._summary.point_count + 1
if self:_get_feature_name(msg) then
self._summary.feature_count = self._summary.feature_count + 1
end
if self._previous then
self._summary.distance = self._summary.distance
+ get_distance(self._previous, msg);
end
self._previous = msg;
end
function Reader:on_error(error_str, status_code)
assert("string" == type(error_str))
assert("number" == type(status_code))
print(string.format("RecordRoute error: (%d)%s", status_code, error_str))
self._replier:reply_error(error_str, status_code)
end
function Reader:on_end()
print("RecordRoute reader end.")
self._summary.elapsed_time = os.time() - self._start_time
-- distance must be integer
self._summary.distance = math.ceil(self._summary.distance)
self._replier:reply(self._summary);
end
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
--- Get feature name.
-- @table point
-- @treturn string|nil
function Reader:_get_feature_name(point)
assert("table" == type(point))
for _, f in ipairs(self._db.features) do
local l = f.location
if l.latitude == point.latitude and
l.longitude == point.longitude then
return f.name
end -- if
end -- for
return nil
end
return Reader
|
Fix RouteRecord.
|
Fix RouteRecord.
|
Lua
|
bsd-3-clause
|
jinq0123/grpc-lua,jinq0123/grpc-lua,jinq0123/grpc-lua
|
57a75cc99493c3a8a683d14355ee6491e247f2b8
|
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,
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
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,
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
|
[fixed] Sith enemies in the Captain Sarguillo patrol questline should no longer disappear if they are in combat - mantis 6663
|
[fixed] Sith enemies in the Captain Sarguillo patrol questline should no
longer disappear if they are in combat - mantis 6663
Change-Id: Ic108258f040bfe10ad7d35364e9d4a12a57f2a92
|
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
|
d75806e8150d18830d60fe9fa0a2fdbcf3b43d8d
|
src/cosy/lang/view/observed.lua
|
src/cosy/lang/view/observed.lua
|
-- Observed Objects
-- ================
--
-- Sometimes, there is a need to observe changes on data, and call a handler
-- to perform some actions on updates. The `observed` view is a way to
-- perform such tasks.
--
-- An observer is not bound to a particular data, as it would be very costly
-- in memory. Instead, observers register callbacks in the `observed`
-- object. These callbacks are all called every time an update is performed
-- on a data wrapped by the `observed` view.
--
-- The callbacks are not just plain functions. They are functions that will
-- be used as coroutines and called in two steps:
--
-- * the initial call is performed __before__ the data update; it allows for
-- instance to save the old value;
-- * the function is resumed __after__ the data update; and can then change
-- some other data.
--
-- __Warning:__ the part __before__ is only allowed to read data, not to
-- write to it!
--
-- Usage
-- -----
--
-- A callback is registered as below:
--
-- local observed = require "cosy.lang.view.observed"
-- observed.my_observer = function (data, key)
-- -- pre:
-- ...
-- coroutine.ield ()
-- -- post:
-- ...
-- end
--
-- Note that insertion of the observer can also be done as:
--
-- observed [#observed + 1] = function (data, key)
-- ...
-- end
--
-- Note that the callback should usually check for the tags it observes, as
-- in the code below:
--
-- observed.my_observer = function (data, key)
-- if key == "mykey" then
-- -- pre:
-- ...
-- coroutine.ield ()
-- -- post:
-- ...
-- end
-- end
-- Dependencies
-- ------------
--
-- The module depends on `tags`, `view` and `error`.
--
local tags = require "cosy.lang.tags"
local raw = require "cosy.lang.data" . raw
local view = require "cosy.lang.data" . view
local error = require "cosy.lang.message" . error
-- The `DATA` tag refers to the data above which a view is built.
--
local DATA = tags.DATA
-- The `VIEWS` tag stores in a view the sequence of views that wrap a raw
-- data. This sequence can then be used to rebuild a similar view on any
-- data.
--
local VIEWS = tags.VIEWS
-- Constructor
-- -----------
--
-- The `observed` object acts as a view constructor over data:
--
-- local view = observed (data)
--
local observed = require "cosy.lang.view.make" ()
-- Read a field
-- ------------
--
-- A field is accessed from a view in the standard Lua way, by using the
-- dotted (`data.field`) or square brackets (`data [tag]`) notations.
-- This view just forwards the `__index` to the underlying view, or to the
-- raw data.
--
function observed:__index (key)
return view (self [DATA] [key], self [VIEWS])
end
-- Write a field
-- -------------
--
-- A field is written using a view in the standard Lua way, by using the
-- dotted (`data.field`) or square brackets (`data [tag]`) notations.
--
-- We provide two `__newindex` implementations: one allows writes, the other
-- one does not. Writes are disabled within the read part of the handler
-- coroutines.
--
local function nonwritable_newindex (self, key, _)
error (self,
"Trying to update " .. tostring (key) ..
" within the 'pre' part of an observer."
)
end
local function writable_newindex (self, key, value)
key = raw (key)
value = raw (value)
local data = self [DATA]
local running = {}
observed.__newindex = nonwritable_newindex
for handler, f in pairs (observed) do
if type (handler) ~= "string" or handler:find ("__") ~= 1 then
local c = coroutine.create (function() f (self, key) end)
running [handler] = c
coroutine.resume (c)
end
end
data [key] = value
observed.__newindex = writable_newindex
for handler, c in pairs (running) do
coroutine.resume (c)
running [handler] = nil
end
end
-- Outside a handler, an observed view is writeable.
--
observed.__newindex = writable_newindex
-- Length
-- ------
--
-- The length operator is simply forwarded to the underlying data or view.
--
function observed:__len ()
return # (self [DATA])
end
-- Module
-- ------
--
-- This module simply returns the `observed` object.
--
return observed
|
-- Observed Objects
-- ================
--
-- Sometimes, there is a need to observe changes on data, and call a handler
-- to perform some actions on updates. The `observed` view is a way to
-- perform such tasks.
--
-- An observer is not bound to a particular data, as it would be very costly
-- in memory. Instead, observers register callbacks in the `observed`
-- object. These callbacks are all called every time an update is performed
-- on a data wrapped by the `observed` view.
--
-- The callbacks are not just plain functions. They are functions that will
-- be used as coroutines and called in two steps:
--
-- * the initial call is performed __before__ the data update; it allows for
-- instance to save the old value;
-- * the function is resumed __after__ the data update; and can then change
-- some other data.
--
-- __Warning:__ the part __before__ is only allowed to read data, not to
-- write to it!
--
-- Usage
-- -----
--
-- A callback is registered as below:
--
-- local observed = require "cosy.lang.view.observed"
-- observed.my_observer = function (data, key)
-- -- pre:
-- ...
-- coroutine.ield ()
-- -- post:
-- ...
-- end
--
-- Note that insertion of the observer can also be done as:
--
-- observed [#observed + 1] = function (data, key)
-- ...
-- end
--
-- Note that the callback should usually check for the tags it observes, as
-- in the code below:
--
-- observed.my_observer = function (data, key)
-- if key == "mykey" then
-- -- pre:
-- ...
-- coroutine.ield ()
-- -- post:
-- ...
-- end
-- end
-- Dependencies
-- ------------
--
-- The module depends on `tags`, `view` and `error`.
--
local tags = require "cosy.lang.tags"
local raw = require "cosy.lang.data" . raw
local view = require "cosy.lang.data" . view
local error = require "cosy.lang.message" . error
-- The `DATA` tag refers to the data above which a view is built.
--
local DATA = tags.DATA
-- The `VIEWS` tag stores in a view the sequence of views that wrap a raw
-- data. This sequence can then be used to rebuild a similar view on any
-- data.
--
local VIEWS = tags.VIEWS
-- Constructor
-- -----------
--
-- The `observed` object acts as a view constructor over data:
--
-- local view = observed (data)
--
local observed = require "cosy.lang.view.make" ()
-- Read a field
-- ------------
--
-- A field is accessed from a view in the standard Lua way, by using the
-- dotted (`data.field`) or square brackets (`data [tag]`) notations.
-- This view just forwards the `__index` to the underlying view, or to the
-- raw data.
--
function observed:__index (key)
return view (self [DATA] [raw (key)], self [VIEWS])
end
-- Write a field
-- -------------
--
-- A field is written using a view in the standard Lua way, by using the
-- dotted (`data.field`) or square brackets (`data [tag]`) notations.
--
-- We provide two `__newindex` implementations: one allows writes, the other
-- one does not. Writes are disabled within the read part of the handler
-- coroutines.
--
local function nonwritable_newindex (self, key, _)
error (self,
"Trying to update " .. tostring (key) ..
" within the 'pre' part of an observer."
)
end
local function writable_newindex (self, key, value)
key = raw (key)
value = raw (value)
local data = self [DATA]
local running = {}
observed.__newindex = nonwritable_newindex
for handler, f in pairs (observed) do
if type (handler) ~= "string" or handler:find ("__") ~= 1 then
local c = coroutine.create (function() f (self, key) end)
running [handler] = c
local ok, err = coroutine.resume (c)
if not ok then
-- print (err)
end
end
end
data [key] = value
observed.__newindex = writable_newindex
for handler, c in pairs (running) do
local ok, err = coroutine.resume (c)
if not ok then
-- print (err)
end
running [handler] = nil
end
end
-- Outside a handler, an observed view is writeable.
--
observed.__newindex = writable_newindex
-- Length
-- ------
--
-- The length operator is simply forwarded to the underlying data or view.
--
function observed:__len ()
return # (self [DATA])
end
-- Module
-- ------
--
-- This module simply returns the `observed` object.
--
return observed
|
Fix comparison of keys.
|
Fix comparison of keys.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
7ff9d988d4dbd8356da628d0b7eb2b8c4b50f1a7
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local serial = require("hs._asm.serial")
local lastScreenId = -1
local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == hs.application.watcher.launched then
watchApp(app)
elseif event == hs.application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == hs.application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == hs.uielement.watcher.windowCreated then
watchWindow(element)
elseif event == hs.uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
updateVirtualScreenIndicator(element:screen(), element)
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == hs.uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
if window:isFullScreen() then
frame = window:frame()
left = frame.x
width = frame.w
else
left = screeng.x
width = screeng.w
end
indicator = hs.canvas.new{
x = left,
y = screeng.y,
w = width,
h = height
}:appendElements(
{
action = "fill",
type = "rectangle",
fillColor = indicatorColor
}
)
indicator
:level(hs.canvas.windowLevels.cursor)
:behavior(hs.canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
function updatePhysicalScreenIndicator(screenId)
local devicePath = getSerialOutputDevice()
if devicePath == "" then return end
port = serial.port(devicePath):baud(115200):open()
if port:isOpen() then
port:write("set " .. screenId .. "\n")
port:flushBuffer()
port:close()
end
end
function getSerialOutputDevice()
local command = "ioreg -c IOSerialBSDClient -r -t " ..
"| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
"| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
-- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
return result:match("^%s*(.-)%s*$")
end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = hs.application.runningApplications()
apps = hs.fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
hs.fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher._element.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
watcher:start({ hs.uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
hs.uielement.watcher.elementDestroyed,
hs.uielement.watcher.windowResized,
hs.uielement.watcher.windowMoved
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = hs.screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = hs.spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = hs.application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == hs.application.watcher.launched then
watchApp(app)
elseif event == hs.application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == hs.application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == hs.uielement.watcher.windowCreated then
watchWindow(element)
elseif event == hs.uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
updateVirtualScreenIndicator(element:screen(), element)
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == hs.uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
if window:isFullScreen() then
frame = window:frame()
left = frame.x
width = frame.w
else
left = screeng.x
width = screeng.w
end
indicator = hs.canvas.new{
x = left,
y = screeng.y,
w = width,
h = height
}:appendElements(
{
action = "fill",
type = "rectangle",
fillColor = indicatorColor
}
)
indicator
:level(hs.canvas.windowLevels.cursor)
:behavior(hs.canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = hs.application.runningApplications()
apps = hs.fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
hs.fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
watcher:start({ hs.uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
hs.uielement.watcher.elementDestroyed,
hs.uielement.watcher.windowResized,
hs.uielement.watcher.windowMoved
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = hs.screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = hs.spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = hs.application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(Hammerspoon): disable hardware screen indicator and fix watcher bug
|
fix(Hammerspoon): disable hardware screen indicator and fix watcher bug
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
edb3c3c00dcfe7d857c30b5f37116c1b02316954
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorBottomHeight = 1
local indicatorTopColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.4
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
local frame = window:frame()
local left = frame.x
local width = frame.w
local menubarHeight = screen:frame().y - screeng.y
local indicatorTopHeight = menubarHeight - indicatorBottomHeight
if menubarHeight > 30 then
-- Notched Menubar
indicatorTopHeight = indicatorTopHeight - 1
end
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = menubarHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved,
uielement.watcher.windowMinimized,
uielement.watcher.windowUnminimized
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorBottomHeight = 2
local indicatorTopColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.6
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
local frame = window:frame()
local left = frame.x
local width = frame.w
local menubarHeight = screen:frame().y - screeng.y - 1
local indicatorTopHeight = menubarHeight - indicatorBottomHeight
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = menubarHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved,
uielement.watcher.windowMinimized,
uielement.watcher.windowUnminimized
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(hammerspoon): ok, jk, everyone gets the offset menubar height
|
fix(hammerspoon): ok, jk, everyone gets the offset menubar height
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
7a9c9f03d3d4cd98b80bd724643f50e44dfe2911
|
OS/DiskOS/Programs/pastebin.lua
|
OS/DiskOS/Programs/pastebin.lua
|
--This program is based on ComputerCraft one: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/programs/http/pastebin.lua
local term = require("C://terminal")
local function printUsage()
color(9) print("Usages:") color(7)
print("pastebin put <filename>")
print("pastebin get <code> <filename>")
end
local function printError(str)
color(8) print(str) color(7)
end
local function getName(str)
local path, name, ext = string.match(str, "(.-)([^\\/]-%.?([^%.\\/]*))$")
return name
end
local function request(url, args)
local ticket = WEB.send(url,args)
for event, id, url, data, errnum, errmsg, errline in pullEvent do
if event == "webrequest" then
if id == ticket then
if data then
data.code = tonumber(data.code)
if (data.code < 200 or data.code >= 300) and data.body:sub(1,21) ~= "https://pastebin.com/" then
cprint("Body: "..tostring(data.body))
return false, "HTTP Error: "..data.code
end
if data.body:sub(1,15) == "Bad API request" then
return false, "API Error: "..data.body
end
return data.body
else
return false, errmsg
end
end
end
end
end
local tArgs = { ... }
if #tArgs < 2 then
printUsage()
return
end
if not WEB then
printError( "Pastebin requires WEB peripheral" )
printError( "Edit /bios/bconf.lua and make sure that the WEB peripheral exists" )
return
end
local function get(paste)
color(9) print("Connecting to pastebin.com...") flip() color(7)
local response, err = request("https://pastebin.com/raw/"..WEB.urlEncode(paste))
if response then
color(11) print( "Success." ) color(7) flip() sleep(0.01)
return response
else
printError("Failed: "..tostring(err))
end
end
local sCommand = tArgs[1]
if sCommand == "put" then
-- Upload a file to pastebin.com
-- Determine file to upload
local sFile = tArgs[2]
local sPath = term.resolve(sFile)
if not fs.exists(sPath) or fs.isDirectory(sPath) then
printError("No such file")
return
end
-- Read in the file
local sName = getName(sPath:gsub("///","/"))
local sText = fs.read(sPath)
-- POST the contents to pastebin
color(9) print("Connecting to pastebin.com...") color(7) flip()
local key = "e31065c6df5a451f3df3fdf5f4c2be61"
local response, err = request("https://pastebin.com/api/api_post.php",{
method = "POST",
data = "api_option=paste&"..
"api_dev_key="..key.."&"..
"api_paste_format=lua&"..
"api_paste_name="..WEB.urlEncode(sName).."&"..
"api_paste_code="..WEB.urlEncode(sText)
})
if response then
color(11) print("Success.") flip() sleep(0.01) color(7)
local sCode = string.match(response, "[^/]+$")
color(12) print("Uploaded as "..response) sleep(0.01) color(7)
print('Run "',false) color(6) print('pastebin get '..sCode,false) color(7) print('" to download anywhere') sleep(0.01)
else
printError("Failed: "..tostring(err))
end
elseif sCommand == "get" then
-- Download a file from pastebin.com
if #tArgs < 3 then
printUsage()
return
end
--Determine file to download
local sCode = tArgs[2]
local sFile = tArgs[3]
local sPath = term.resolve(sFile)
if fs.exists( sPath ) then
printError("File already exists")
return
end
-- GET the contents from pastebin
local res = get(sCode)
if res then
fs.write(sPath,res)
color(12) print("Downloaded as "..sFile) sleep(0.01) color(7)
end
else
printUsage()
return
end
|
--This program is based on ComputerCraft one: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/programs/http/pastebin.lua
local term = require("C://terminal")
local function printUsage()
color(9) print("Usages:") color(7)
print("pastebin put <filename>")
print("pastebin get <code> <filename>")
end
local function printError(str)
color(8) print(str) color(7)
end
local function getName(str)
local path, name, ext = string.match(str, "(.-)([^\\/]-%.?([^%.\\/]*))$")
return name
end
local function request(url, args)
local ticket = WEB.send(url,args)
for event, id, url, data, errnum, errmsg, errline in pullEvent do
if event == "webrequest" then
if id == ticket then
if data then
data.code = tonumber(data.code)
if (data.code < 200 or data.code >= 300) and data.body:sub(1,21) ~= "https://pastebin.com/" then
cprint("Body: "..tostring(data.body))
return false, "HTTP Error: "..data.code
end
if data.body:sub(1,15) == "Bad API request" then
return false, "API Error: "..data.body
end
return data.body
else
return false, errmsg
end
end
end
end
end
local tArgs = { ... }
if #tArgs < 2 then
printUsage()
return
end
if not WEB then
printError( "Pastebin requires WEB peripheral" )
printError( "Edit /bios/bconf.lua and make sure that the WEB peripheral exists" )
return
end
local function get(paste)
color(9) print("Connecting to pastebin.com...") flip() color(7)
local response, err = request("https://pastebin.com/raw/"..WEB.urlEncode(paste))
if response then
color(11) print( "Success." ) color(7) flip() sleep(0.01)
return response
else
printError("Failed: "..tostring(err))
end
end
local sCommand = tArgs[1]
if sCommand == "put" then
-- Upload a file to pastebin.com
-- Determine file to upload
local sFile = tArgs[2]
local sPath = term.resolve(sFile)
if not fs.exists(sPath) or fs.isDirectory(sPath) then
printError("No such file")
return
end
-- Read in the file
local sName = getName(sPath:gsub("///","/"))
local sText = fs.read(sPath)
-- POST the contents to pastebin
color(9) print("Connecting to pastebin.com...") color(7) flip()
local key = "e31065c6df5a451f3df3fdf5f4c2be61"
local response, err = request("https://pastebin.com/api/api_post.php",{
method = "POST",
data = "api_option=paste&"..
"api_dev_key="..key.."&"..
"api_paste_format="..(sName:sub(-4,-1) == ".lua" and "lua" or "").."&"..
"api_paste_name="..WEB.urlEncode(sName).."&"..
"api_paste_code="..WEB.urlEncode(sText)
})
if response then
color(11) print("Success.") flip() sleep(0.01) color(7)
local sCode = string.match(response, "[^/]+$")
color(12) print("Uploaded as "..response) sleep(0.01) color(7)
print('Run "',false) color(6) print('pastebin get '..sCode,false) color(7) print('" to download anywhere') sleep(0.01)
else
printError("Failed: "..tostring(err))
end
elseif sCommand == "get" then
-- Download a file from pastebin.com
if #tArgs < 3 then
printUsage()
return
end
--Determine file to download
local sCode = tArgs[2]
local sFile = tArgs[3]
local sPath = term.resolve(sFile)
if fs.exists( sPath ) then
printError("File already exists")
return
end
-- GET the contents from pastebin
local res = get(sCode)
if res then
fs.write(sPath,res)
color(12) print("Downloaded as "..sFile) sleep(0.01) color(7)
end
else
printUsage()
return
end
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
02904ace91e70dc97f1325be2d424b9f1c2c5b1a
|
aspects/nvim/files/.config/nvim/lua/wincent/mappings/leader.lua
|
aspects/nvim/files/.config/nvim/lua/wincent/mappings/leader.lua
|
local leader = {}
local number_flag = 'wincent_number'
local cycle_numbering = function()
local relativenumber = vim.wo.relativenumber
local number = vim.wo.number
-- Cycle through:
-- - relativenumber + number
-- - number (only)
-- - no numbering
if (vim.deep_equal({relativenumber, number}, {true, true})) then
relativenumber, number = false, true
elseif (vim.deep_equal({relativenumber, number}, {false, true})) then
relativenumber, number = false, false
elseif (vim.deep_equal({relativenumber, number}, {false, false})) then
relativenumber, number = true, true
elseif (vim.deep_equal({relativenumber, number}, {true, false})) then
relativenumber, number = false, true
end
vim.wo.relativenumber = relativenumber
vim.wo.number = number
-- Leave a mark so that other functions can check to see if the user has
-- overridden the settings for this window.
vim.w[number_flag] = true
end
-- Based on: http://vim.wikia.com/wiki/Identify_the_syntax_highlighting_group_used_at_the_cursor
local get_highlight_group = function()
local pos = vim.api.nvim_win_get_cursor(0)
local line = pos[1]
local col = pos[2]
local synID = vim.fn.synID
local synIDattr = vim.fn.synIDattr
local synIDtrans = vim.fn.synIDtrans
return (
'hi<' ..
synIDattr(synID(line, col, true), 'name') ..
'> trans<' ..
synIDattr(synID(line, col, false), 'name') ..
'> lo<' ..
synIDattr(synIDtrans(synID(line, col, true)), 'name') ..
'>'
)
end
local jump = function(mapping)
local key = vim.api.nvim_replace_termcodes(mapping, true, false, true)
local previous_file = vim.api.nvim_buf_get_name(0)
local previous_row, previous_column = unpack(vim.api.nvim_win_get_cursor(0))
local limit = 100
local step
step = function ()
vim.api.nvim_feedkeys(key, 'n', true)
-- Need small delay for feedkeys side-effects to finalize.
vim.defer_fn(function()
local next_file = vim.api.nvim_buf_get_name(0)
local next_row, next_column = unpack(vim.api.nvim_win_get_cursor(0))
if next_file ~= previous_file then
-- We successfully moved to the next file; we're done.
return
elseif next_row == previous_row and next_column == previous_column then
-- BUG: if the mark points at an invalid line number (can easily happen
-- in .git/COMMIT_EDITMSG, for example) we may bail here because line
-- number won't change — to be really robust we'd need to parse :jumps
-- output
print('No more jumps!')
return
elseif limit < 0 then
print('Jump limit exceeded! (Aborting)')
return
end
previous_file = next_file
previous_row = next_row
previous_column = next_column
limit = limit - 1
-- Recurse.
step()
end, 0)
end
step()
end
local jump_in_file = function ()
jump('<C-i>')
end
local jump_out_file = function ()
jump('<C-o>')
end
-- TODO: split into files
leader.cycle_numbering = cycle_numbering
leader.get_highlight_group = get_highlight_group
leader.jump_in_file = jump_in_file
leader.jump_out_file = jump_out_file
leader.number_flag = number_flag
return leader
|
local leader = {}
local number_flag = 'wincent_number'
local cycle_numbering = function()
local relativenumber = vim.wo.relativenumber
local number = vim.wo.number
-- Cycle through:
-- - relativenumber + number
-- - number (only)
-- - no numbering
if (vim.deep_equal({relativenumber, number}, {true, true})) then
relativenumber, number = false, true
elseif (vim.deep_equal({relativenumber, number}, {false, true})) then
relativenumber, number = false, false
elseif (vim.deep_equal({relativenumber, number}, {false, false})) then
relativenumber, number = true, true
elseif (vim.deep_equal({relativenumber, number}, {true, false})) then
relativenumber, number = false, true
end
vim.wo.relativenumber = relativenumber
vim.wo.number = number
-- Leave a mark so that other functions can check to see if the user has
-- overridden the settings for this window.
vim.w[number_flag] = true
end
-- Based on: http://vim.wikia.com/wiki/Identify_the_syntax_highlighting_group_used_at_the_cursor
local get_highlight_group = function()
local pos = vim.api.nvim_win_get_cursor(0)
local line = pos[1]
local col = pos[2]
local synID = vim.fn.synID
local synIDattr = vim.fn.synIDattr
local synIDtrans = vim.fn.synIDtrans
return (
'hi<' ..
synIDattr(synID(line, col, true), 'name') ..
'> trans<' ..
synIDattr(synID(line, col, false), 'name') ..
'> lo<' ..
synIDattr(synIDtrans(synID(line, col, true)), 'name') ..
'>'
)
end
local jump = function(mapping, delta)
-- Calculate the number of steps to move up or down through the jump list in
-- order to get to a new bufnr (we use bufnr because not all entries will have a
-- filename).
local count = 0
local jumplist, idx = unpack(vim.fn.getjumplist())
local previous_entry = jumplist[idx]
local next_idx = idx + delta
while next_idx > 0 and next_idx < #jumplist do
count = count + 1
local next_entry = jumplist[next_idx]
if next_entry.bufnr ~= previous_entry.bufnr then
-- We found the next file; we're done.
local key = vim.api.nvim_replace_termcodes(mapping, true, false, true)
vim.api.nvim_feedkeys(count .. key, 'n', true)
vim.cmd('echo') -- Clear any previous "No more jumps!" message.
return
else
previous_entry = next_entry
next_idx = next_idx + delta
end
end
vim.api.nvim_err_writeln('No more jumps!')
end
local jump_in_file = function ()
jump('<C-i>', 1)
end
local jump_out_file = function ()
jump('<C-o>', -1)
end
-- TODO: split into files
leader.cycle_numbering = cycle_numbering
leader.get_highlight_group = get_highlight_group
leader.jump_in_file = jump_in_file
leader.jump_out_file = jump_out_file
leader.number_flag = number_flag
return leader
|
fix(nvim): make file-wise jumping use getjumplist()
|
fix(nvim): make file-wise jumping use getjumplist()
Addresses the problems noted in the previous commit. Namely, the "BUG:"
comment that points out that invalid line numbers can break all the
things. This is nicer anyway, as we're doing all the jumps via a single
mapping, and we should even be able to jump through multiple distinct
unnamed buffers now (not that those come up particularly frequently, but
anyway).
|
Lua
|
unlicense
|
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
|
2b936e13ecec64c0e6be2f793f5fd5654f2093da
|
gfx.lua
|
gfx.lua
|
local ffi = require 'ffi'
local uuid = require 'uuid'
local base64 = require 'base64'
require 'pl.text'.format_operator()
require 'image'
local itorch = require 'itorch._env'
require 'itorch.bokeh'
local util = require 'itorch.util'
-- Example: require 'image';itorch.image(image.scale(image.lena(),16,16))
function itorch.image(img, opts)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
if torch.type(img) == 'string' then -- assume that it is path
img = image.load(img, 3) -- TODO: revamp this to just directly load the blob, infer file prefix, and send.
end
if torch.isTensor(img) or torch.type(img) == 'table' then
opts = opts or {padding=2}
opts.input = img
local imgDisplay = image.toDisplayTensor(opts)
if imgDisplay:dim() == 2 then
imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2))
end
local tmp = os.tmpname() .. '.png'
image.save(tmp, imgDisplay)
-------------------------------------------------------------
-- load the image back as binary blob
local f = assert(torch.DiskFile(tmp,'r',true)):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
os.execute('rm -f ' .. tmp)
------------------------------------------------------------
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/plain'] = 'Console does not support images'
content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size))
content.metadata = { }
content.metadata['image/png'] = {width = imgDisplay:size(3), height = imgDisplay:size(2)}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
else
error('unhandled type in itorch.image:' .. torch.type(img))
end
end
local audio_template = [[
<div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div>
]]
-- Example: itorch.audio('hello.mp3')
function itorch.audio(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac',
'mp3, wav, ogg, aac files supported. But found extension: ' .. ext)
-- load the audio as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64audio = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
audio_template % {
div_id = div_id,
extension = ext,
base64audio = base64audio
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local video_template = [[
<div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div>
]]
-- Example: itorch.video('hello.mp4')
function itorch.video(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
if ext == 'ogv' then ext = 'ogg' end
assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm',
'mp4, ogg, webm files supported. But found extension: ' .. ext)
-- load the video as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64video = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
video_template % {
div_id = div_id,
extension = ext,
base64video = base64video
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
function itorch.lena()
itorch.image(image.lena())
end
local html_template =
[[
<script type="text/javascript">
$(function() {
$("#${window_id}").html('${html_content}'); // clear any previous plot in window_id
});
</script>
<div id="${div_id}"></div>
]]
local function escape_js(s)
-- single quite
s = s:gsub("'","\\'")
-- double quote
s = s:gsub('"','\\"')
-- backslash
s = s:gsub("\\","\\\\")
-- newline
s = s:gsub("\n","\\n")
-- carriage return
s = s:gsub("\r","\\r")
-- tab
s = s:gsub("\t","\\t")
-- backspace
s = s:gsub("\b","\\b")
-- form feed
s = s:gsub("\f","\\f")
return s
end
function itorch.html(html, window_id)
html = escape_js(html)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
local div_id = uuid.new()
window_id = window_id or div_id
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
html_template % {
html_content = html,
window_id = window_id,
div_id = div_id
};
content.metadata = {}
-- send displayData
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local ok,err = pcall(function() require 'xlua' end)
if ok then
local progress_warning = false
local last = os.clock()
xlua.progress = function(i, n)
-- make progress bar really slow in itorch
if os.clock() - last > 15 then -- 15 seconds
print('Progress: ' .. i .. ' / ' .. n)
last = os.clock()
end
-- local m = util.msg('clear_output', itorch._msg)
-- m.content = {}
-- m.content.wait = true
-- m.content.display = true
-- util.ipyEncodeAndSend(itorch._iopub, m)
-- itorch.html(progress_template % {})
end
end
return itorch;
|
local ffi = require 'ffi'
local uuid = require 'uuid'
local base64 = require 'base64'
require 'pl.text'.format_operator()
require 'image'
local itorch = require 'itorch._env'
require 'itorch.bokeh'
local util = require 'itorch.util'
-- Example: require 'image';itorch.image(image.scale(image.lena(),16,16))
function itorch.image(img, opts)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
if torch.type(img) == 'string' then -- assume that it is path
if img:sub(#img-3) == '.svg' then
return itorch.svg(img)
else
img = image.load(img, 3) -- TODO: revamp this to just directly load the blob, infer file prefix, and send.
end
end
if torch.isTensor(img) or torch.type(img) == 'table' then
opts = opts or {padding=2}
opts.input = img
local imgDisplay = image.toDisplayTensor(opts)
if imgDisplay:dim() == 2 then
imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2))
end
local tmp = os.tmpname() .. '.png'
image.save(tmp, imgDisplay)
-------------------------------------------------------------
-- load the image back as binary blob
local f = assert(torch.DiskFile(tmp,'r',true)):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
os.execute('rm -f ' .. tmp)
------------------------------------------------------------
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/plain'] = 'Console does not support images'
content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size))
content.metadata = { }
content.metadata['image/png'] = {width = imgDisplay:size(3), height = imgDisplay:size(2)}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
else
error('unhandled type in itorch.image:' .. torch.type(img))
end
end
local audio_template = [[
<div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div>
]]
-- Example: itorch.audio('hello.mp3')
function itorch.audio(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac',
'mp3, wav, ogg, aac files supported. But found extension: ' .. ext)
-- load the audio as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64audio = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
audio_template % {
div_id = div_id,
extension = ext,
base64audio = base64audio
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local video_template = [[
<div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div>
]]
-- Example: itorch.video('hello.mp4')
function itorch.video(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
if ext == 'ogv' then ext = 'ogg' end
assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm',
'mp4, ogg, webm files supported. But found extension: ' .. ext)
-- load the video as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64video = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
video_template % {
div_id = div_id,
extension = ext,
base64video = base64video
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
function itorch.lena()
itorch.image(image.lena())
end
local html_template =
[[
<script type="text/javascript">
$(function() {
$("#${window_id}").html('${html_content}'); // clear any previous plot in window_id
});
</script>
<div id="${div_id}"></div>
]]
local function escape_js(s)
-- single quite
s = s:gsub("'","\'")
-- double quote
s = s:gsub('"','\"')
-- backslash
s = s:gsub("\\","\\\\")
-- newline
s = s:gsub("\n","\\n")
-- carriage return
s = s:gsub("\r","\\r")
-- tab
s = s:gsub("\t","\\t")
-- backspace
s = s:gsub("\b","\\b")
-- form feed
s = s:gsub("\f","\\f")
return s
end
function itorch.html(html, window_id)
html = escape_js(html)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
local div_id = uuid.new()
window_id = window_id or div_id
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
html_template % {
html_content = html,
window_id = window_id,
div_id = div_id
};
content.metadata = {}
-- send displayData
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
function itorch.svg(filename)
-- first check if file exists.
if paths.filep(filename) then
local f = io.open(filename)
local str = f:read("*all")
f:close()
return itorch.html(str)
else -- try rendering as raw string
return itorch.html(filename)
end
end
local ok,err = pcall(function() require 'xlua' end)
if ok then
local progress_warning = false
local last = os.clock()
xlua.progress = function(i, n)
-- make progress bar really slow in itorch
if os.clock() - last > 15 then -- 15 seconds
print('Progress: ' .. i .. ' / ' .. n)
last = os.clock()
end
-- local m = util.msg('clear_output', itorch._msg)
-- m.content = {}
-- m.content.wait = true
-- m.content.display = true
-- util.ipyEncodeAndSend(itorch._iopub, m)
-- itorch.html(progress_template % {})
end
end
return itorch;
|
added svg rendering via itorch.svg or itorch.image, fixed html bug
|
added svg rendering via itorch.svg or itorch.image, fixed html bug
|
Lua
|
bsd-3-clause
|
facebook/iTorch,facebook/iTorch
|
63e256602edf2269a711175accb8c428405fd7f8
|
src_trunk/resources/gatekeepers-system/c_ped_rightclick.lua
|
src_trunk/resources/gatekeepers-system/c_ped_rightclick.lua
|
wPedRightClick = nil
bTalkToPed, bClosePedMenu = nil
ax, ay = nil
closing = nil
sent=false
function clickPed(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="ped") and (button=="right") and (state=="down") and (sent==false) and (element~=getLocalPlayer()) then
local gatekeeper = getElementData(element, "talk")
if (gatekeeper) then
local x, y, z = getElementPosition(getLocalPlayer())
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wPedRightClick) then
hidePlayerMenu()
end
showCursor(true)
ax = absX
ay = absY
player = element
closing = false
wPedRightClick = guiCreateWindow(ax, ay, 150, 75, getElementData(element, "name"), false)
bTalkToPed = guiCreateButton(0.05, 0.3, 0.87, 0.25, "Talk", true, wPedRightClick)
addEventHandler("onClientGUIClick", bTalkToPed, function (button, state)
if(button == "left" and state == "up") then
hidePedMenu()
local ped = getElementData(element, "name")
if (ped=="Steven Pullman") then
triggerServerEvent( "startStevieConvo", getLocalPlayer())
if (getElementData(element, "activeConvo")~=1) then
triggerEvent ( "stevieIntroEvent", getLocalPlayer()) -- Trigger Client side function to create GUI.
end
elseif (ped=="Hunter") then
triggerServerEvent( "startHunterConvo", getLocalPlayer())
elseif (ped=="Rook") then
triggerServerEvent( "startRookConvo", getLocalPlayer())
else
outputChatBox("Error: Unknown ped.", 255, 0, 0)
end
end
end, false)
bClosePedMenu = guiCreateButton(0.05, 0.6, 0.87, 0.25, "Close Menu", true, wPedRightClick)
addEventHandler("onClientGUIClick", bClosePedMenu, hidePedMenu, false)
sent=true
end
end
end
end
addEventHandler("onClientClick", getRootElement(), clickPed, true)
function hidePedMenu()
if (isElement(bTalkToPed)) then
destroyElement(bTalkToPed)
end
bTalkToPed = nil
if (isElement(bClosePedMenu)) then
destroyElement(bClosePedMenu)
end
bClosePedMenu = nil
if (isElement(wPedRightClick)) then
destroyElement(wPedRightClick)
end
wPedRightClick = nil
ax = nil
ay = nil
sent=false
showCursor(false)
end
|
wPedRightClick = nil
bTalkToPed, bClosePedMenu = nil
ax, ay = nil
closing = nil
sent=false
function pedDamage()
cancelEvent()
end
addEventHandler("onClientPedDamage", getRootElement(), pedDamage)
function clickPed(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="ped") and (button=="right") and (state=="down") and (sent==false) and (element~=getLocalPlayer()) then
local gatekeeper = getElementData(element, "talk")
if (gatekeeper) then
local x, y, z = getElementPosition(getLocalPlayer())
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wPedRightClick) then
hidePlayerMenu()
end
showCursor(true)
ax = absX
ay = absY
player = element
closing = false
wPedRightClick = guiCreateWindow(ax, ay, 150, 75, getElementData(element, "name"), false)
bTalkToPed = guiCreateButton(0.05, 0.3, 0.87, 0.25, "Talk", true, wPedRightClick)
addEventHandler("onClientGUIClick", bTalkToPed, function (button, state)
if(button == "left" and state == "up") then
hidePedMenu()
local ped = getElementData(element, "name")
if (ped=="Steven Pullman") then
triggerServerEvent( "startStevieConvo", getLocalPlayer())
if (getElementData(element, "activeConvo")~=1) then
triggerEvent ( "stevieIntroEvent", getLocalPlayer()) -- Trigger Client side function to create GUI.
end
elseif (ped=="Hunter") then
triggerServerEvent( "startHunterConvo", getLocalPlayer())
elseif (ped=="Rook") then
triggerServerEvent( "startRookConvo", getLocalPlayer())
else
outputChatBox("Error: Unknown ped.", 255, 0, 0)
end
end
end, false)
bClosePedMenu = guiCreateButton(0.05, 0.6, 0.87, 0.25, "Close Menu", true, wPedRightClick)
addEventHandler("onClientGUIClick", bClosePedMenu, hidePedMenu, false)
sent=true
end
end
end
end
addEventHandler("onClientClick", getRootElement(), clickPed, true)
function hidePedMenu()
if (isElement(bTalkToPed)) then
destroyElement(bTalkToPed)
end
bTalkToPed = nil
if (isElement(bClosePedMenu)) then
destroyElement(bClosePedMenu)
end
bClosePedMenu = nil
if (isElement(wPedRightClick)) then
destroyElement(wPedRightClick)
end
wPedRightClick = nil
ax = nil
ay = nil
sent=false
showCursor(false)
end
|
Fixed gatekeepers being killed
|
Fixed gatekeepers being killed
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@746 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
2aa2c197044960ea29f1b8302f398efda6861ece
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s").isnumber = true
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung").isinteger = true
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße").isinteger = true
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
i:option(Value, "Interface", "Netzwerkschnittstellen")
i:option(Value, "HelloInterval", "Hello-Intervall").isnumber = true
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit").isnumber = true
i:option(Value, "TcInterval", "TC-Intervall").isnumber = true
i:option(Value, "TcValidityTime", "TC-Gültigkeit").isnumber = true
i:option(Value, "MidInterval", "MID-Intervall").isnumber = true
i:option(Value, "MidValidityTime", "MID-Gültigkeit").isnumber = true
i:option(Value, "HnaInterval", "HNA-Intervall").isnumber = true
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit").isnumber = true
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s")
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung")
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße")
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", "Netzwerkschnittstellen")
network:value("")
for k, v in pairs(ffluci.model.uci.show("network").network) do
if v[".type"] == "interface" and k ~= "loopback" then
network:value(k)
end
end
i:option(Value, "HelloInterval", "Hello-Intervall")
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit")
i:option(Value, "TcInterval", "TC-Intervall")
i:option(Value, "TcValidityTime", "TC-Gültigkeit")
i:option(Value, "MidInterval", "MID-Intervall")
i:option(Value, "MidValidityTime", "MID-Gültigkeit")
i:option(Value, "HnaInterval", "HNA-Intervall")
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit")
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
|
136836d4503ba8d4eb8804e62cba3f9637202dc5
|
src/FileManager.lua
|
src/FileManager.lua
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local FileManager = {};
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local extensions = {};
local totalFiles = 0;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Splits the extension from a file.
-- @param fileName
--
local function splitExtension(fileName)
local tmp = fileName:reverse();
local pos = tmp:find('%.');
if pos then
return tmp:sub(1, pos):reverse():lower();
else
-- Prevents issues with files sans extension.
return '.?';
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Draws a list of all authors working on the project.
--
function FileManager.draw(x, y)
local count = 0;
love.graphics.print(totalFiles, x + 80, y + 10);
love.graphics.print('Files', x + 10, y + 10);
for ext, tbl in pairs(extensions) do
count = count + 1;
love.graphics.setColor(tbl.color);
love.graphics.print(tbl.amount, x + 80, y + 10 + count * 20);
love.graphics.print(ext, x + 10, y + 10 + count * 20);
love.graphics.setColor(255, 255, 255);
end
end
---
-- Adds a new file extension to the list.
-- @param fileName
--
function FileManager.add(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
extensions[ext] = {};
extensions[ext].amount = 0;
extensions[ext].color = { love.math.random(0, 255), love.math.random(0, 255), love.math.random(0, 255) };
end
extensions[ext].amount = extensions[ext].amount + 1;
totalFiles = totalFiles + 1;
return extensions[ext].color;
end
---
-- Reduce the amount of counted files of the
-- same extension. If there are no more files
-- of that extension, it will remove it from
-- the list.
--
function FileManager.remove(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
error('Tried to remove the non existing file extension "' .. ext .. '".');
end
extensions[ext].amount = extensions[ext].amount - 1;
totalFiles = totalFiles - 1;
if extensions[ext].amount == 0 then
extensions[ext] = nil;
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- @param ext
--
function FileManager.getColor(ext)
return extensions[ext].color;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return FileManager;
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local FileManager = {};
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local extensions = {};
local totalFiles = 0;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Splits the extension from a file.
-- @param fileName
--
local function splitExtension(fileName)
local tmp = fileName:reverse();
local pos = tmp:find('%.');
if pos then
return tmp:sub(1, pos):reverse():lower();
else
-- Prevents issues with files sans extension.
return '.?';
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Draws a counter of all files in the project and
-- a separate counter for each used file extension.
--
function FileManager.draw(x, y)
local count = 0;
love.graphics.print(totalFiles, x + 80, y + 10);
love.graphics.print('Files', x + 10, y + 10);
for ext, tbl in pairs(extensions) do
count = count + 1;
love.graphics.setColor(tbl.color);
love.graphics.print(tbl.amount, x + 80, y + 10 + count * 20);
love.graphics.print(ext, x + 10, y + 10 + count * 20);
love.graphics.setColor(255, 255, 255);
end
end
---
-- Adds a new file extension to the list.
-- @param fileName
--
function FileManager.add(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
extensions[ext] = {};
extensions[ext].amount = 0;
extensions[ext].color = { love.math.random(0, 255), love.math.random(0, 255), love.math.random(0, 255) };
end
extensions[ext].amount = extensions[ext].amount + 1;
totalFiles = totalFiles + 1;
return extensions[ext].color;
end
---
-- Reduce the amount of counted files of the
-- same extension. If there are no more files
-- of that extension, it will remove it from
-- the list.
--
function FileManager.remove(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
error('Tried to remove the non existing file extension "' .. ext .. '".');
end
extensions[ext].amount = extensions[ext].amount - 1;
totalFiles = totalFiles - 1;
if extensions[ext].amount == 0 then
extensions[ext] = nil;
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- @param ext
--
function FileManager.getColor(ext)
return extensions[ext].color;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return FileManager;
|
Fix comment.
|
Fix comment.
|
Lua
|
mit
|
rm-code/logivi
|
2b6ec2def238659e41c120744aa9b531d1896c89
|
base/polygons.lua
|
base/polygons.lua
|
-- basic handling for polygonal areas on the map
require("base.class");
module("base.polygons",package.seeall);
--- representation of a line. All positions have z=0.
-- @param posStruct Start point
-- @param posStruct End point
-- @return LineStruct
Line = base.class.class(
function(obj, startPoint, endPoint)
obj.startPoint = position(startPoint.x, startPoint.y, 0);
obj.endPoint = position(endPoint.x, endPoint.y, 0);
end
);
--- representation of a polygon, requires at least 3 points. All positions have z=0.
-- @field lineList list(LineStruct)
-- @field min posStruct minimum position, i.e. the upper left most corner of the bounding box
-- @field max posStruct maximum position, i.e. the lower right most corner of the bounding box
-- @field zList list(int) list with valid z values for PIP test
-- @param list(posStruct) List of points, neighbours are connected, aswell as first and last point of the list
-- @return PolygonStruct
Polygon = base.class.class(
function(obj, positionList, zList)
if table.getn(positionList) < 3 then
debug("A polygon must have at least 3 points");
return;
end
obj.lineList = {};
local s = positionList[1];
obj.min = position(s.x,s.y,0);
obj.max = position(s.x,s.y,0);
table.insert(positionList, positionList[1]); -- add first point, so there is an edge between first and last point
for i=2,table.getn(positionList) do
table.insert(obj.lineList, Line(s, positionList[i]));
s = positionList[i];
obj.min.x = math.min(obj.min.x, s.x);
obj.min.y = math.min(obj.min.y, s.y);
obj.max.x = math.max(obj.max.x, s.x);
obj.max.y = math.max(obj.max.y, s.y);
end;
if zList==nil then
obj.zList = {0};
else
obj.zList = zList;
end
end
);
--- tests intersection of two lines (actually line segments).
-- @param LineStruct The otherLine for which intersection with current Line is tested
-- @return boolean True if the two lines intersect
-- @return int Number of intersections with the start/end points. [0,1,2]
function Line:intersectsLine(otherLine)
-- solve for p1, p2 i.e. the fraction on the two lines from the start point to the intersection point
local denominator = (otherLine.endPoint.y - otherLine.startPoint.y)*(self.endPoint.x - self.startPoint.x) - (otherLine.endPoint.x - otherLine.startPoint.x)*(self.endPoint.y - self.startPoint.y);
local nominator1 = (otherLine.endPoint.x - otherLine.startPoint.x)*(self.startPoint.y - otherLine.startPoint.y) - (otherLine.endPoint.y - otherLine.startPoint.y)*(self.startPoint.x - otherLine.startPoint.x);
local nominator2 = (self.endPoint.x - self.startPoint.x)*(self.startPoint.y - otherLine.startPoint.y) - (self.endPoint.y - self.startPoint.y)*(self.startPoint.x - otherLine.startPoint.x);
-- debug("d=" .. denominator .. "; n1=" .. nominator1 .. "; n2=" .. nominator2);
if denominator == 0 then
if nominator1==0 and nominator2==0 then
return false,2;
end
return false,0;
end
local p1 = nominator1 / denominator;
local p2 = nominator2 / denominator;
-- count intersections with start (0) or end (1) point
local ret2 = 0;
if p1==0 or p1==1 then
ret2 = 1;
end
if p2==0 or p2==1 then
ret2 = ret2 + 1;
end
-- debug("p1=" .. p1 .. "; p2=" .. p2);
-- intersection point is only on both line segments if 0 < p1,p2 < 1
-- otherwise intersection point is on the line, but not on the segments
if (0<=p1) and (p1<=1) and (0<=p2) and (p2<=1) then
return true, ret2;
end
return false, ret2;
end
--- tests if a point is on a line.
-- @param posStruct The point to be tested.
-- @return boolean True if point is on Line
function Line:pointOnLine(point)
-- check x coordinate
local px = -1;
local py = -2;
local xOkay = false;
local yOkay = false;
if self.startPoint.x == self.endPoint.x then
-- horizontal line
if point.x ~= self.startPoint.x then
return false;
end
xOkay = true;
else
px = (point.x - self.startPoint.x) / (self.endPoint.x - self.startPoint.x);
if not ((0<=px) and (px<=1)) then
return false;
end
end
-- check y coordinate
if self.startPoint.y == self.endPoint.y then
-- vertical line
if point.y ~= self.startPoint.y then
return false;
end
yOkay = true;
else
py = (point.y - self.startPoint.y) / (self.endPoint.y - self.startPoint.y);
if not ((0<=py) and (py<=1)) then
return false;
end
end
-- if the line is horizontal or vertical, then we're alright here.
-- otherwise the fractions px,py have to be equal as the point has to move linearly on the line
return (xOkay or yOkay or (px == py));
end
--- Point-In-Polygon test
-- @param posStruct The point to be tested if inside the Polygon
-- @return boolean True if point is in Polygon
function Polygon:pip(point)
-- valid z level?
local zValid = false;
for _,level in pairs(self.zList) do
if (point.z == level) then
zValid = true;
break;
end
end
if not zValid then
return false;
end
-- coarse test: point in bounding box?
if not ( self.min.x <= point.x and self.min.y <= point.y and point.x <= self.max.x and point.y <= self.max.y) then
return false;
end
-- create a test line from the point to the right most boundary
local testLine = Line(point, position(self.max.x+1, point.y, 0));
local count = 0;
local intWpoints = 0;
for _,curLine in pairs(self.lineList) do
if curLine:pointOnLine(point) then
return true;
end
local b,n = testLine:intersectsLine(curLine);
if b then
count = count + 1;
intWpoints = intWpoints + n;
end
end
-- add (intWpoints + 1) to take multiple intersections with points into account
count = count + intWpoints + 1;
return (count%2 == 1);
end
|
-- basic handling for polygonal areas on the map
require("base.class");
module("base.polygons",package.seeall);
--- representation of a line. All positions have z=0.
-- @param posStruct Start point
-- @param posStruct End point
-- @return LineStruct
Line = base.class.class(
function(obj, startPoint, endPoint)
obj.startPoint = position(startPoint.x, startPoint.y, 0);
obj.endPoint = position(endPoint.x, endPoint.y, 0);
end
);
--- representation of a polygon, requires at least 3 points. All positions have z=0.
-- @field lineList list(LineStruct)
-- @field min posStruct minimum position, i.e. the upper left most corner of the bounding box
-- @field max posStruct maximum position, i.e. the lower right most corner of the bounding box
-- @field zList list(int) list with valid z values for PIP test
-- @param list(posStruct) List of points, neighbours are connected, aswell as first and last point of the list
-- @return PolygonStruct
Polygon = base.class.class(
function(obj, positionList, zList)
if table.getn(positionList) < 3 then
debug("A polygon must have at least 3 points");
return;
end
obj.lineList = {};
local s = positionList[1];
obj.min = position(s.x,s.y,0);
obj.max = position(s.x,s.y,0);
table.insert(positionList, positionList[1]); -- add first point, so there is an edge between first and last point
for i=2,table.getn(positionList) do
table.insert(obj.lineList, Line(s, positionList[i]));
s = positionList[i];
obj.min.x = math.min(obj.min.x, s.x);
obj.min.y = math.min(obj.min.y, s.y);
obj.max.x = math.max(obj.max.x, s.x);
obj.max.y = math.max(obj.max.y, s.y);
end;
if zList==nil then
obj.zList = {0};
else
obj.zList = zList;
end
end
);
--- tests intersection of two lines (actually line segments).
-- @param LineStruct The otherLine for which intersection with current Line is tested
-- @param boolean True if self is a horizontal ray. Thus if the start/end point of otherLine is on self then true is returned if and only if the rest of otherLine is below self.
-- @return boolean True if the two lines intersect, false if no intersection or lines are identical
function Line:intersectsLine(otherLine, selfIsRay)
-- solve for p1, p2 i.e. the fraction on the two lines from the start point to the intersection point
local denominator = (otherLine.endPoint.y - otherLine.startPoint.y)*(self.endPoint.x - self.startPoint.x) - (otherLine.endPoint.x - otherLine.startPoint.x)*(self.endPoint.y - self.startPoint.y);
local nominator1 = (otherLine.endPoint.x - otherLine.startPoint.x)*(self.startPoint.y - otherLine.startPoint.y) - (otherLine.endPoint.y - otherLine.startPoint.y)*(self.startPoint.x - otherLine.startPoint.x);
local nominator2 = (self.endPoint.x - self.startPoint.x)*(self.startPoint.y - otherLine.startPoint.y) - (self.endPoint.y - self.startPoint.y)*(self.startPoint.x - otherLine.startPoint.x);
-- debug("d=" .. denominator .. "; n1=" .. nominator1 .. "; n2=" .. nominator2);
if denominator == 0 then
if nominator1==0 and nominator2==0 then
return false;
end
return false;
end
local p1 = nominator1 / denominator; -- fraction of self
local p2 = nominator2 / denominator; -- fraction of otherLine
if selfIsRay then
-- intersections with start (0) or end (1) point
if p2==0 then
-- start of otherLine is on self, check if end is below
return (otherLine.endPoint.y < otherLine.startPoint.y);
elseif p2==1 then
-- end of otherLine is on self, check if start is below
return (otherLine.startPoint.y < otherLine.endPoint.y);
end
end
-- debug("p1=" .. p1 .. "; p2=" .. p2);
-- intersection point is only on both line segments if 0 < p1,p2 < 1
-- otherwise intersection point is on the line, but not on the segments
if (0<=p1) and (p1<=1) and (0<=p2) and (p2<=1) then
return true;
end
return false;
end
--- tests if a point is on a line.
-- @param posStruct The point to be tested.
-- @return boolean True if point is on Line
function Line:pointOnLine(point)
-- check x coordinate
local px = -1;
local py = -2;
local xOkay = false;
local yOkay = false;
if self.startPoint.x == self.endPoint.x then
-- horizontal line
if point.x ~= self.startPoint.x then
return false;
end
xOkay = true;
else
px = (point.x - self.startPoint.x) / (self.endPoint.x - self.startPoint.x);
if not ((0<=px) and (px<=1)) then
return false;
end
end
-- check y coordinate
if self.startPoint.y == self.endPoint.y then
-- vertical line
if point.y ~= self.startPoint.y then
return false;
end
yOkay = true;
else
py = (point.y - self.startPoint.y) / (self.endPoint.y - self.startPoint.y);
if not ((0<=py) and (py<=1)) then
return false;
end
end
-- if the line is horizontal or vertical, then we're alright here.
-- otherwise the fractions px,py have to be equal as the point has to move linearly on the line
return (xOkay or yOkay or (px == py));
end
--- Point-In-Polygon test
-- @param posStruct The point to be tested if inside the Polygon
-- @return boolean True if point is in Polygon
function Polygon:pip(point)
-- valid z level?
local zValid = false;
for _,level in pairs(self.zList) do
if (point.z == level) then
zValid = true;
break;
end
end
if not zValid then
return false;
end
-- coarse test: point in bounding box?
if not ( self.min.x <= point.x and self.min.y <= point.y and point.x <= self.max.x and point.y <= self.max.y) then
return false;
end
-- create a test line from the point to the right most boundary
local testLine = Line(point, position(self.max.x+1, point.y, 0));
local count = 0;
for _,curLine in pairs(self.lineList) do
if curLine:pointOnLine(point) then
return true;
end
if testLine:intersectsLine(curLine, true) then
count = count + 1;
end
end
return (count%2 == 1);
end
|
fixed pip test
|
fixed pip test
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
|
6d3e995b432ee42943d8505d81418be0e6d3815b
|
src/cosy/loader.lua
|
src/cosy/loader.lua
|
local version = tonumber (_VERSION:match "Lua%s*(%d%.%d)")
if version < 5.1
or (version == 5.1 and type (_G.jit) ~= "table") then
error "Cosy requires Luajit >= 2 or Lua >= 5.2 to run."
end
local Loader = {}
local loader = {}
if _G.js then
_G.loadhttp = function (url)
local co = coroutine.running ()
local request = _G.js.new (_G.js.global.XMLHttpRequest)
request:open ("GET", url, true)
request.onreadystatechange = function (event)
if request.readyState == 4 then
if request.status == 200 then
coroutine.resume (co, request.responseText)
else
coroutine.resume (co, nil, event.target.status)
end
end
end
request:send (nil)
local result, err = coroutine.yield ()
if result then
return result
else
error (err)
end
end
_G.require = function (mod_name)
local loaded = package.loaded [mod_name]
if loaded then
return loaded
end
local preloaded = package.preload [mod_name]
if preloaded then
local result = preloaded (mod_name)
package.loaded [mod_name] = result
return result
end
local url = "/lua/" .. mod_name
local result, err
result, err = _G.loadhttp (url)
if not result then
error (err)
end
result, err = load (result, url)
if not result then
error (err)
end
result = result (mod_name)
package.loaded [mod_name] = result
return result
end
loader.hotswap = require
else
local ev = require "ev"
loader.scheduler = require "copas.ev"
loader.scheduler:make_default ()
loader.hotswap = require "hotswap" .new ()
loader.hotswap.register = function (filename, f)
ev.Stat.new (function ()
f ()
end, filename):start (loader.scheduler._loop)
end
end
do
Loader.__index = function (_, key)
return loader.hotswap ("cosy." .. tostring (key))
end
end
return setmetatable (loader, Loader)
|
local version = tonumber (_VERSION:match "Lua%s*(%d%.%d)")
if version < 5.1
or (version == 5.1 and type (_G.jit) ~= "table") then
error "Cosy requires Luajit >= 2 or Lua >= 5.2 to run."
end
local Loader = {}
local loader = {}
if _G.js then
_G.loadhttp = function (url)
local co = coroutine.running ()
local request = _G.js.new (_G.js.global.XMLHttpRequest)
request:open ("GET", url, true)
request.onreadystatechange = function (event)
if request.readyState == 4 then
if request.status == 200 then
coroutine.resume (co, request.responseText)
else
coroutine.resume (co, nil, event.target.status)
end
end
end
request:send (nil)
local result, err = coroutine.yield ()
if result then
return result
else
error (err)
end
end
_G.require = function (mod_name)
local loaded = package.loaded [mod_name]
if loaded then
return loaded
end
local preloaded = package.preload [mod_name]
if preloaded then
local result = preloaded (mod_name)
package.loaded [mod_name] = result
return result
end
local url = "/lua/" .. mod_name
local result, err
result, err = _G.loadhttp (url)
if not result then
error (err)
end
result, err = load (result, url)
if not result then
error (err)
end
result = result (mod_name)
package.loaded [mod_name] = result
return result
end
loader.hotswap = require
else
local ev = require "ev"
loader.scheduler = require "copas.ev"
loader.scheduler:make_default ()
loader.hotswap = require "hotswap" .new ()
loader.hotswap.register = function (filename, f)
ev.Stat.new (function ()
f ()
end, filename):start (loader.scheduler._loop)
end
end
-- FIXME: remove as soon as lua-webosockets has done a new release:
package.preload ["bit32"] = function ()
local result = require "bit"
_G.bit32 = result
result.lrotate = result.rol
result.rrotate = result.ror
return result
end
do
Loader.__index = function (_, key)
return loader.hotswap ("cosy." .. tostring (key))
end
end
return setmetatable (loader, Loader)
|
Add fix for lua-webosckets.
|
Add fix for lua-webosckets.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
f09913517d92f5c1198d1ef6ab32188f82734d3f
|
applications/luci-uvc_streamer/luasrc/model/cbi/uvc_streamer.lua
|
applications/luci-uvc_streamer/luasrc/model/cbi/uvc_streamer.lua
|
--[[
LuCI UVC Streamer
(c) 2008 Yanira <[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$
]]--
-- find current lan address and port of first uvc_streamer config section
local uci = luci.model.uci.cursor_state()
local addr = uci:get("network", "lan", "ipaddr")
local port
uci:foreach( "uvc_streamer", "uvc_streamer",
function(section) port = port or tonumber(section.port) end )
m = Map("uvc_streamer", translate("uvc_streamer"),
translatef("uvc_streamer_desc", nil, addr, port, addr, port))
s = m:section(TypedSection, "uvc_streamer", translate("settings"))
s.addremove = false
s.anonymous = true
s:option(Flag, "enabled", translate("enabled", "Enable"))
s:option(Value, "device", translate("device")).rmempty = true
nm = s:option(Value, "resolution", translate("resolution"))
nm:value("640x480")
nm:value("320x240")
nm:value("160x120")
s:option(Value, "framespersecond", translate("framespersecond")).rmempty = true
s:option(Value, "port", translate("port", "Port")).rmempty = true
return m
|
--[[
LuCI UVC Streamer
(c) 2008 Yanira <[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$
]]--
-- find current lan address and port of first uvc_streamer config section
local uci = luci.model.uci.cursor_state()
local addr = uci:get("network", "lan", "ipaddr")
local port
uci:foreach( "uvc_streamer", "uvc_streamer",
function(section) port = port or tonumber(section.port) end )
addr = addr or "192.168.1.1"
port = port or 8080
m = Map("uvc_streamer", translate("uvc_streamer"),
translatef("uvc_streamer_desc", nil, addr, port, addr, port))
s = m:section(TypedSection, "uvc_streamer", translate("settings"))
s.addremove = false
s.anonymous = true
s:option(Flag, "enabled", translate("enabled", "Enable"))
s:option(Value, "device", translate("device")).rmempty = true
nm = s:option(Value, "resolution", translate("resolution"))
nm:value("640x480")
nm:value("320x240")
nm:value("160x120")
s:option(Value, "framespersecond", translate("framespersecond")).rmempty = true
s:option(Value, "port", translate("port", "Port")).rmempty = true
return m
|
* luci/applications/uvc-streamer: fix possible crash when no uvc_streamer sections is defined in config
|
* luci/applications/uvc-streamer: fix possible crash when no uvc_streamer sections is defined in config
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3140 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
dtaht/cerowrt-luci-3.3,jschmidlapp/luci,gwlim/luci,vhpham80/luci,Flexibity/luci,alxhh/piratenluci,Canaan-Creative/luci,Canaan-Creative/luci,projectbismark/luci-bismark,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,eugenesan/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,saraedum/luci-packages-old,8devices/carambola2-luci,stephank/luci,yeewang/openwrt-luci,gwlim/luci,gwlim/luci,phi-psi/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,gwlim/luci,8devices/carambola2-luci,jschmidlapp/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,zwhfly/openwrt-luci,stephank/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,stephank/luci,ch3n2k/luci,vhpham80/luci,vhpham80/luci,stephank/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,Flexibity/luci,Canaan-Creative/luci,8devices/carambola2-luci,jschmidlapp/luci,Canaan-Creative/luci,alxhh/piratenluci,jschmidlapp/luci,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,alxhh/piratenluci,jschmidlapp/luci,jschmidlapp/luci,saraedum/luci-packages-old,phi-psi/luci,ThingMesh/openwrt-luci,vhpham80/luci,Flexibity/luci,alxhh/piratenluci,ch3n2k/luci,phi-psi/luci,8devices/carambola2-luci,saraedum/luci-packages-old,Canaan-Creative/luci,zwhfly/openwrt-luci,vhpham80/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,gwlim/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,freifunk-gluon/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,Flexibity/luci,saraedum/luci-packages-old,Flexibity/luci,8devices/carambola2-luci,Flexibity/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,alxhh/piratenluci,yeewang/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,jschmidlapp/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,jschmidlapp/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Flexibity/luci,stephank/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ch3n2k/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark
|
74f3619fb852244a1bfc3334d25f45721506fd81
|
share/media/ted.lua
|
share/media/ted.lua
|
-- libquvi-scripts
-- Copyright (C) 2012,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2011 Bastien Nocera <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- 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/>.
--
local Ted = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Ted.can_parse_url(qargs),
domains = table.concat({'ted.com'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
if not Ted.chk_ext(qargs, p) then
qargs.title = p:match('<title>(.-)%s+|') or ''
end
return qargs
end
--
-- Utility functions
--
function Ted.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('^www.ted%.com$')
and t.path and t.path:lower():match('^/talks/.+$')
then
return true
else
return false
end
end
function Ted.chk_ext(qargs, p)
Ted.iter_streams(qargs, p)
if #qargs.streams >0 then -- Self-hosted media.
return false
else -- External media. Try the first iframe.
qargs.goto_url = p:match('<iframe src="(.-)"') or ''
if #qargs.goto_url >0 then
return true
else
error('no match: media stream URL')
end
end
end
function Ted.iter_streams(qargs, p)
qargs.streams = {}
local d = p:match('talkDetails%s+=%s+(.-)<') or ''
if #d ==0 then return end
local S = require 'quvi/stream'
local J = require 'json'
local j = J.decode(d)
Ted.rtmp_streams(qargs, S, J, j)
Ted.html_streams(qargs, S, j)
qargs.duration_ms = tonumber(j['duration'] or 0) * 1000
qargs.thumb_url = j['posterUrl'] or ''
qargs.id = j['id'] or ''
if #qargs.streams >1 then
Ted.ch_best(qargs, S)
end
end
function Ted.html_streams(qargs, S, j)
local h = j['htmlStreams']
for i=1, #h do
local u = h[i]['file']
local t = S.stream_new(u)
t.video.bitrate_kbit_s = tonumber(u:match('(%d+)k') or 0)
t.container = u:match('%d+k%.(%w+)') or ''
t.id = Ted.html_stream_id(h[i]['id'], t)
table.insert(qargs.streams, t)
end
end
function Ted.rtmp_streams(qargs, S, J, j)
local U = require 'quvi/util'
local l = J.decode(U.unescape(j['flashVars']['playlist']))
for _,v in pairs(l['talks']) do
local s = v['streamer'] or error('no match: streamer')
for _,vv in pairs(v['resource']) do
local u = table.concat({s,vv['file']:match('^%w+:(.-)$')},'/')
local t = S.stream_new(u)
t.video.bitrate_kbit_s = tonumber(vv['bitrate'] or 0)
t.video.height = tonumber(vv['height'] or 0)
t.video.width = tonumber(vv['width'] or 0)
t.container = vv['file']:match('^(%w+):') or ''
t.id = Ted.rtmp_stream_id(t)
table.insert(qargs.streams, t)
end
end
end
function Ted.html_stream_id(id, t)
return string.format('%s_%s_%sk', id, t.container, t.video.bitrate_kbit_s)
end
function Ted.rtmp_stream_id(t)
return string.format('%s_%dk_%dp',
t.container, t.video.bitrate_kbit_s, t.video.height)
end
function Ted.ch_best(qargs, S)
local r = qargs.streams[1] -- Make the first one the 'best' by default.
r.flags.best = true
for _,v in pairs(qargs.streams) do
if v.video.height > r.video.height then
r = S.swap_best(r,v)
end
end
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2011 Bastien Nocera <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- 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/>.
--
local Ted = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Ted.can_parse_url(qargs),
domains = table.concat({'ted.com'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
if not Ted.chk_ext(qargs, p) then
qargs.title = p:match('<title>(.-)%s+|') or ''
end
return qargs
end
--
-- Utility functions
--
function Ted.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('^www.ted%.com$')
and t.path and t.path:lower():match('^/talks/.+$')
then
return true
else
return false
end
end
function Ted.chk_ext(qargs, p)
Ted.iter_streams(qargs, p)
if #qargs.streams >0 then -- Self-hosted media.
return false
else -- External media. Try the first iframe.
qargs.goto_url = p:match('<iframe src="(.-)"') or ''
if #qargs.goto_url >0 then
return true
else
error('no match: media stream URL')
end
end
end
function Ted.iter_streams(qargs, p)
qargs.streams = {}
local d = p:match('talkPage.init",(.-)%)<') or ''
if #d == 0 then return end
local S = require 'quvi/stream'
local J = require 'json'
local j = J.decode(d)
--Ted.rtmp_streams(qargs, S, J, j)
Ted.native_downloads(qargs, S, J, j)
for _,v in pairs(j['talks']) do
qargs.duration_ms = tonumber(v['duration'] or 0) * 1000
qargs.thumb_url = v['thumbs'] or ''
qargs.id = v['id'] or ''
end
if #qargs.streams >1 then
Ted.ch_best(qargs, S)
end
end
-- this correctly identifies the rtmp URLs but leads to
-- "error: protocol `rtmp` is not supported" on quvi get.
--
-- This is unfortunate as the rtmp streams provide better
-- resolution than the native downloads
function Ted.rtmp_streams(qargs, S, J, j)
for _,v in pairs(j['talks']) do
local s = v['streamer'] or error('no match: streamer')
for _,vv in pairs(v['resources']['rtmp']) do
local u = table.concat({s,vv['file']:match('^%w+:(.-)$')},'/')
local t = S.stream_new(u)
t.video.bitrate_kbit_s = tonumber(vv['bitrate'] or 0)
t.video.height = tonumber(vv['height'] or 0)
t.video.width = tonumber(vv['width'] or 0)
t.container = vv['file']:match('^(%w+):') or ''
t.id = Ted.rtmp_stream_id(t)
table.insert(qargs.streams, t)
end
end
end
-- this identifies the highest format native (HTTP)
-- download, which unfortunately is of lower quality than
-- the rtmp streams
function Ted.native_downloads(qargs, S, J, j)
for _,v in pairs(j['talks']) do
local u = v['nativeDownloads']['high']
local t = S.stream_new(u)
t.video.height = tonumber(u:match('-(%d+)p%.') or 0)
table.insert(qargs.streams, t)
end
end
function Ted.rtmp_stream_id(t)
return string.format('%s_%dk_%dp',
t.container, t.video.bitrate_kbit_s, t.video.height)
end
function Ted.ch_best(qargs, S)
local r = qargs.streams[1] -- Make the first one the 'best' by default.
r.flags.best = true
for _,v in pairs(qargs.streams) do
if v.video.height > r.video.height then
r = S.swap_best(r,v)
end
end
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/ted (HTTP download only)
|
FIX: media/ted (HTTP download only)
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,alech/libquvi-scripts
|
46f651cccb15a6a27e044c8afb0eca2e1334e8f0
|
lua_modules/ds18b20/ds18b20.lua
|
lua_modules/ds18b20/ds18b20.lua
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- by @voborsky, @devsaurus
-- encoder module is needed only for debug output; lines can be removed if no
-- debug output is needed and/or encoder module is missing
--
-- by default the module is for integer version, comment integer version and
-- uncomment float version part for float version
--------------------------------------------------------------------------------
return({
pin=3,
sens={},
temp={},
conversion = function(self)
local pin = self.pin
for i,s in ipairs(self.sens) do
if s.status == 0 then
print("starting conversion:", encoder.toHex(s.addr), s.parasite == 1 and "parasite" or " ")
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0x44, 1) -- and start conversion
s.status = 1
if s.parasite == 1 then break end -- parasite sensor blocks bus during conversion
end
end
tmr.alarm(tmr.create(), 750, tmr.ALARM_SINGLE, function() self:readout() end)
end,
readTemp = function(self, cb, lpin)
local pin = self.pin
self.cb = cb
self.temp={}
if lpin then pin = lpin end
ow.setup(pin)
self.sens={}
ow.reset_search(pin)
-- ow.target_search(pin,0x28)
-- search the first device
local addr = ow.search(pin)
-- and loop through all devices
while addr do
-- search next device
local crc=ow.crc8(string.sub(addr,1,7))
if (crc==addr:byte(8)) and ((addr:byte(1)==0x10) or (addr:byte(1)==0x28)) then
ow.reset(pin)
ow.select(pin, addr) -- select the found sensor
ow.write(pin, 0xB4, 1) -- Read Power Supply [B4h]
local parasite = (ow.read(pin)==0 and 1 or 0)
table.insert(self.sens,{addr=addr, parasite=parasite, status=0})
print("contact: ", encoder.toHex(addr), parasite == 1 and "parasite" or " ")
end
addr = ow.search(pin)
tmr.wdclr()
end
-- place powered sensors first
table.sort(self.sens, function(a,b) return a.parasite<b.parasite end)
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
end,
readout=function(self)
local pin = self.pin
local next = false
if not self.sens then return 0 end
for i,s in ipairs(self.sens) do
-- print(encoder.toHex(s.addr), s.status)
if s.status == 1 then
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0xBE, 0) -- READ_SCRATCHPAD
data = ow.read_bytes(pin, 9)
local t=(data:byte(1)+data:byte(2)*256)
if (t > 0x7fff) then t = t - 0x10000 end
if (s.addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
-- integer version
local sgn = t<0 and -1 or 1
local tA = sgn*t
local tH=tA/10000
local tL=(tA%10000)/1000 + ((tA%1000)/100 >= 5 and 1 or 0)
if tH and (tH~=85) then
self.temp[s.addr]=(sgn<0 and "-" or "")..tH.."."..tL
print(encoder.toHex(s.addr),(sgn<0 and "-" or "")..tH.."."..tL)
s.status = 2
end
-- end integer version
-- -- float version
-- if t and (math.floor(t/10000)~=85) then
-- self.temp[s.addr]=t
-- print(encoder.toHex(s.addr), t)
-- s.status = 2
-- end
-- -- end float version
end
next = next or s.status == 0
end
if next then
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
else
self.sens = nil
if self.cb then
node.task.post(node.task.MEDIUM_PRIORITY, function() self.cb(self.temp) end)
end
end
end
})
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- by @voborsky, @devsaurus
-- encoder module is needed only for debug output; lines can be removed if no
-- debug output is needed and/or encoder module is missing
--
-- by default the module is for integer version, comment integer version and
-- uncomment float version part for float version
--------------------------------------------------------------------------------
return({
pin=3,
sens={},
temp={},
conversion = function(self)
local pin = self.pin
for i,s in ipairs(self.sens) do
if s.status == 0 then
print("starting conversion:", encoder.toHex(s.addr), s.parasite == 1 and "parasite" or " ")
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0x44, 1) -- and start conversion
s.status = 1
if s.parasite == 1 then break end -- parasite sensor blocks bus during conversion
end
end
tmr.alarm(tmr.create(), 750, tmr.ALARM_SINGLE, function() self:readout() end)
end,
readTemp = function(self, cb, lpin)
if lpin then self.pin = lpin end
local pin = self.pin
self.cb = cb
self.temp={}
ow.setup(pin)
self.sens={}
ow.reset_search(pin)
-- ow.target_search(pin,0x28)
-- search the first device
local addr = ow.search(pin)
-- and loop through all devices
while addr do
-- search next device
local crc=ow.crc8(string.sub(addr,1,7))
if (crc==addr:byte(8)) and ((addr:byte(1)==0x10) or (addr:byte(1)==0x28)) then
ow.reset(pin)
ow.select(pin, addr) -- select the found sensor
ow.write(pin, 0xB4, 1) -- Read Power Supply [B4h]
local parasite = (ow.read(pin)==0 and 1 or 0)
table.insert(self.sens,{addr=addr, parasite=parasite, status=0})
print("contact: ", encoder.toHex(addr), parasite == 1 and "parasite" or " ")
end
addr = ow.search(pin)
tmr.wdclr()
end
-- place powered sensors first
table.sort(self.sens, function(a,b) return a.parasite<b.parasite end)
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
end,
readout=function(self)
local pin = self.pin
local next = false
if not self.sens then return 0 end
for i,s in ipairs(self.sens) do
-- print(encoder.toHex(s.addr), s.status)
if s.status == 1 then
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0xBE, 0) -- READ_SCRATCHPAD
data = ow.read_bytes(pin, 9)
local t=(data:byte(1)+data:byte(2)*256)
if (t > 0x7fff) then t = t - 0x10000 end
if (s.addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
-- integer version
local sgn = t<0 and -1 or 1
local tA = sgn*t
local tH=tA/10000
local tL=(tA%10000)/1000 + ((tA%1000)/100 >= 5 and 1 or 0)
if tH and (tH~=85) then
self.temp[s.addr]=(sgn<0 and "-" or "")..tH.."."..tL
print(encoder.toHex(s.addr),(sgn<0 and "-" or "")..tH.."."..tL)
s.status = 2
end
-- end integer version
-- -- float version
-- if t and (math.floor(t/10000)~=85) then
-- self.temp[s.addr]=t
-- print(encoder.toHex(s.addr), t)
-- s.status = 2
-- end
-- -- end float version
end
next = next or s.status == 0
end
if next then
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
else
self.sens = nil
if self.cb then
node.task.post(node.task.MEDIUM_PRIORITY, function() self.cb(self.temp) end)
end
end
end
})
|
Fix self.pin when specifying lpin for readTemp() (#1865)
|
Fix self.pin when specifying lpin for readTemp() (#1865)
|
Lua
|
mit
|
FelixPe/nodemcu-firmware,djphoenix/nodemcu-firmware,marcelstoer/nodemcu-firmware,FrankX0/nodemcu-firmware,TerryE/nodemcu-firmware,marcelstoer/nodemcu-firmware,FrankX0/nodemcu-firmware,devsaurus/nodemcu-firmware,HEYAHONG/nodemcu-firmware,marcelstoer/nodemcu-firmware,HEYAHONG/nodemcu-firmware,luizfeliperj/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,luizfeliperj/nodemcu-firmware,nwf/nodemcu-firmware,nodemcu/nodemcu-firmware,TerryE/nodemcu-firmware,FrankX0/nodemcu-firmware,devsaurus/nodemcu-firmware,FelixPe/nodemcu-firmware,nwf/nodemcu-firmware,devsaurus/nodemcu-firmware,luizfeliperj/nodemcu-firmware,vsky279/nodemcu-firmware,nwf/nodemcu-firmware,fetchbot/nodemcu-firmware,nodemcu/nodemcu-firmware,marcelstoer/nodemcu-firmware,devsaurus/nodemcu-firmware,eku/nodemcu-firmware,luizfeliperj/nodemcu-firmware,nwf/nodemcu-firmware,fetchbot/nodemcu-firmware,fetchbot/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,oyooyo/nodemcu-firmware,nodemcu/nodemcu-firmware,devsaurus/nodemcu-firmware,eku/nodemcu-firmware,FelixPe/nodemcu-firmware,vsky279/nodemcu-firmware,TerryE/nodemcu-firmware,djphoenix/nodemcu-firmware,TerryE/nodemcu-firmware,FelixPe/nodemcu-firmware,djphoenix/nodemcu-firmware,djphoenix/nodemcu-firmware,oyooyo/nodemcu-firmware,marcelstoer/nodemcu-firmware,FelixPe/nodemcu-firmware,FrankX0/nodemcu-firmware,nodemcu/nodemcu-firmware,nwf/nodemcu-firmware,HEYAHONG/nodemcu-firmware,oyooyo/nodemcu-firmware,TerryE/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,FrankX0/nodemcu-firmware,fetchbot/nodemcu-firmware,oyooyo/nodemcu-firmware
|
9de176778ff31e89d24242567d355d2fa525e14e
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorTopHeight = 23
local indicatorBottomHeight = 1
local indicatorTopColor = drawing.color.asRGB({
red = 0.26,
green = 0.58,
blue = 0.91,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.26,
green = 0.58,
blue = 0.91,
alpha = 0.4
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
frame = window:frame()
left = frame.x
width = frame.w
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = indicatorTopHeight + indicatorBottomHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorTopHeight = 23
local indicatorBottomHeight = 1
local indicatorTopColor = drawing.color.asRGB({
red = 0.26,
green = 0.58,
blue = 0.91,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.26,
green = 0.58,
blue = 0.91,
alpha = 0.4
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
frame = window:frame()
left = frame.x
width = frame.w
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = indicatorTopHeight + indicatorBottomHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved,
uielement.watcher.windowMinimized,
uielement.watcher.windowUnminimized
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(hammerspoon): handle monitor-monitor window resize done as minimize/unminimize events
|
fix(hammerspoon): handle monitor-monitor window resize done as minimize/unminimize events
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
396cb1ff69b99d1995a2ded4567f99c1110b138c
|
mods/pipeworks/signal_tubes.lua
|
mods/pipeworks/signal_tubes.lua
|
if pipeworks.enable_detector_tube then
local detector_tube_step = 2 * tonumber(minetest.setting_get("dedicated_server_step"))
pipeworks.register_tube("pipeworks:detector_tube_on", {
description = "Detecting Pneumatic Tube Segment on (you hacker you)",
inventory_image = "pipeworks_detector_tube_inv.png",
plain = { "pipeworks_detector_tube_plain.png" },
node_def = {
tube = {can_go = function(pos, node, velocity, stack)
local meta = minetest.get_meta(pos)
local name = minetest.get_node(pos).name
local nitems = meta:get_int("nitems")+1
meta:set_int("nitems", nitems)
local saved_pos = vector.new(pos)
minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos)
return pipeworks.notvel(pipeworks.meseadjlist,velocity)
end},
groups = {mesecon = 2, not_in_creative_inventory = 1},
drop = "pipeworks:detector_tube_off_1",
mesecons = {receptor = {state = "on", rules = pipeworks.mesecons_rules}},
item_exit = function(pos)
local meta = minetest.get_meta(pos)
local nitems = meta:get_int("nitems")-1
local node = minetest.get_node(pos)
local name = node.name
local fdir = node.param2
if nitems == 0 then
minetest.set_node(pos, {name = string.gsub(name, "on", "off"), param2 = fdir})
mesecon.receptor_off(pos, pipeworks.mesecons_rules)
else
meta:set_int("nitems", nitems)
end
end,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_int("nitems", 1)
local name = minetest.get_node(pos).name
local saved_pos = vector.new(pos)
minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos)
end,
},
})
pipeworks.register_tube("pipeworks:detector_tube_off", {
description = "Detecting Pneumatic Tube Segment",
inventory_image = "pipeworks_detector_tube_inv.png",
plain = { "pipeworks_detector_tube_plain.png" },
node_def = {
tube = {can_go = function(pos, node, velocity, stack)
local node = minetest.get_node(pos)
local name = node.name
local fdir = node.param2
minetest.set_node(pos,{name = string.gsub(name, "off", "on"), param2 = fdir})
mesecon.receptor_on(pos, pipeworks.mesecons_rules)
return pipeworks.notvel(pipeworks.meseadjlist, velocity)
end},
groups = {mesecon = 2},
mesecons = {receptor = {state = "off", rules = pipeworks.mesecons_rules }},
},
})
minetest.register_craft( {
output = "pipeworks:conductor_tube_off_1 6",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "mesecons:mesecon", "mesecons:mesecon", "mesecons:mesecon" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
end
if pipeworks.enable_conductor_tube then
pipeworks.register_tube("pipeworks:conductor_tube_off", {
description = "Conducting Pneumatic Tube Segment",
inventory_image = "pipeworks_conductor_tube_inv.png",
short = "pipeworks_conductor_tube_short.png",
plain = { "pipeworks_conductor_tube_plain.png" },
noctr = { "pipeworks_conductor_tube_noctr.png" },
ends = { "pipeworks_conductor_tube_end.png" },
node_def = {
groups = {mesecon = 2},
mesecons = {conductor = {state = "off",
rules = pipeworks.mesecons_rules,
onstate = "pipeworks:conductor_tube_on_#id"}}
},
})
pipeworks.register_tube("pipeworks:conductor_tube_on", {
description = "Conducting Pneumatic Tube Segment on (you hacker you)",
inventory_image = "pipeworks_conductor_tube_inv.png",
short = "pipeworks_conductor_tube_short.png",
plain = { "pipeworks_conductor_tube_on_plain.png" },
noctr = { "pipeworks_conductor_tube_on_noctr.png" },
ends = { "pipeworks_conductor_tube_on_end.png" },
node_def = {
groups = {mesecon = 2, not_in_creative_inventory = 1},
drop = "pipeworks:conductor_tube_off_1",
mesecons = {conductor = {state = "on",
rules = pipeworks.mesecons_rules,
offstate = "pipeworks:conductor_tube_off_#id"}}
},
})
minetest.register_craft( {
output = "pipeworks:detector_tube_off_1 2",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "mesecons:mesecon", "mesecons_materials:silicon", "mesecons:mesecon" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
end
|
if pipeworks.enable_detector_tube then
local detector_tube_step = 1 --MFF crabman(2/1/2016 bug,step too short) 2 * tonumber(minetest.setting_get("dedicated_server_step"))
pipeworks.register_tube("pipeworks:detector_tube_on", {
description = "Detecting Pneumatic Tube Segment on (you hacker you)",
inventory_image = "pipeworks_detector_tube_inv.png",
plain = { "pipeworks_detector_tube_plain.png" },
node_def = {
tube = {can_go = function(pos, node, velocity, stack)
local meta = minetest.get_meta(pos)
local name = minetest.get_node(pos).name
local nitems = meta:get_int("nitems")+1
meta:set_int("nitems", nitems)
local saved_pos = vector.new(pos)
minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos)
return pipeworks.notvel(pipeworks.meseadjlist,velocity)
end},
groups = {mesecon = 2, not_in_creative_inventory = 1},
drop = "pipeworks:detector_tube_off_1",
mesecons = {receptor = {state = "on", rules = pipeworks.mesecons_rules}},
item_exit = function(pos)
local meta = minetest.get_meta(pos)
local nitems = meta:get_int("nitems")-1
local node = minetest.get_node(pos)
local name = node.name
local fdir = node.param2
if nitems == 0 then
minetest.set_node(pos, {name = string.gsub(name, "on", "off"), param2 = fdir})
mesecon.receptor_off(pos, pipeworks.mesecons_rules)
else
meta:set_int("nitems", nitems)
end
end,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_int("nitems", 1)
local name = minetest.get_node(pos).name
local saved_pos = vector.new(pos)
minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos)
end,
},
})
pipeworks.register_tube("pipeworks:detector_tube_off", {
description = "Detecting Pneumatic Tube Segment",
inventory_image = "pipeworks_detector_tube_inv.png",
plain = { "pipeworks_detector_tube_plain.png" },
node_def = {
tube = {can_go = function(pos, node, velocity, stack)
local node = minetest.get_node(pos)
local name = node.name
local fdir = node.param2
minetest.set_node(pos,{name = string.gsub(name, "off", "on"), param2 = fdir})
mesecon.receptor_on(pos, pipeworks.mesecons_rules)
return pipeworks.notvel(pipeworks.meseadjlist, velocity)
end},
groups = {mesecon = 2},
mesecons = {receptor = {state = "off", rules = pipeworks.mesecons_rules }},
},
})
minetest.register_craft( {
output = "pipeworks:conductor_tube_off_1 6",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "mesecons:mesecon", "mesecons:mesecon", "mesecons:mesecon" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
end
if pipeworks.enable_conductor_tube then
pipeworks.register_tube("pipeworks:conductor_tube_off", {
description = "Conducting Pneumatic Tube Segment",
inventory_image = "pipeworks_conductor_tube_inv.png",
short = "pipeworks_conductor_tube_short.png",
plain = { "pipeworks_conductor_tube_plain.png" },
noctr = { "pipeworks_conductor_tube_noctr.png" },
ends = { "pipeworks_conductor_tube_end.png" },
node_def = {
groups = {mesecon = 2},
mesecons = {conductor = {state = "off",
rules = pipeworks.mesecons_rules,
onstate = "pipeworks:conductor_tube_on_#id"}}
},
})
pipeworks.register_tube("pipeworks:conductor_tube_on", {
description = "Conducting Pneumatic Tube Segment on (you hacker you)",
inventory_image = "pipeworks_conductor_tube_inv.png",
short = "pipeworks_conductor_tube_short.png",
plain = { "pipeworks_conductor_tube_on_plain.png" },
noctr = { "pipeworks_conductor_tube_on_noctr.png" },
ends = { "pipeworks_conductor_tube_on_end.png" },
node_def = {
groups = {mesecon = 2, not_in_creative_inventory = 1},
drop = "pipeworks:conductor_tube_off_1",
mesecons = {conductor = {state = "on",
rules = pipeworks.mesecons_rules,
offstate = "pipeworks:conductor_tube_off_#id"}}
},
})
minetest.register_craft( {
output = "pipeworks:detector_tube_off_1 2",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "mesecons:mesecon", "mesecons_materials:silicon", "mesecons:mesecon" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
end
|
fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/355
|
fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/355
|
Lua
|
unlicense
|
crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun
|
aa8d105fa84915cdcb7db9df7a889224693d629f
|
src/program/lwaftr/run_nohw/run_nohw.lua
|
src/program/lwaftr/run_nohw/run_nohw.lua
|
module(..., package.seeall)
local CSVStatsTimer = require("program.lwaftr.csv_stats").CSVStatsTimer
local RawSocket = require("apps.socket.raw").RawSocket
local LwAftr = require("apps.lwaftr.lwaftr").LwAftr
local lib = require("core.lib")
local lwutil = require("apps.lwaftr.lwutil")
local engine = require("core.app")
local file_exists = lwutil.file_exists
local function check(flag, fmt, ...)
if not flag then
io.stderr:write(fmt:format(...), "\n")
main.exit(1)
end
end
local function parse_args(args)
local verbosity = 0
local conf_file, b4_if, inet_if
local bench_file = 'bench.csv'
local handlers = {
v = function ()
verbosity = verbosity + 1
end;
c = function (arg)
check(file_exists(arg), "no such file '%s'", arg)
conf_file = arg
end;
B = function (arg)
b4_if = arg
end;
I = function (arg)
inet_if = arg
end;
b = function (arg)
bench_file = arg
end;
h = function (arg)
print(require("program.lwaftr.run_nohw.README_inc"))
main.exit(0)
end;
}
lib.dogetopt(args, handlers, "b:c:B:I:vh", {
help = "h", conf = "c", verbose = "v",
["b4-if"] = "B", ["inet-if"] = "I",
["bench-file"] = "b",
})
check(conf_file, "no configuration specified (--conf/-c)")
check(b4_if, "no B4-side interface specified (--b4-if/-B)")
check(inet_if, "no Internet-side interface specified (--inet-if/-I)")
return verbosity, conf_file, b4_if, inet_if, bench_file
end
function run(parameters)
local verbosity, conf_file, b4_if, inet_if, bench_file = parse_args(parameters)
local conf = require('apps.lwaftr.conf').load_lwaftr_config(conf_file)
local c = config.new()
-- AFTR
config.app(c, "aftr", LwAftr, conf)
-- B4 side interface
config.app(c, "b4if", RawSocket, b4_if)
-- Internet interface
config.app(c, "inet", RawSocket, inet_if)
-- Connect apps
config.link(c, "inet.tx -> aftr.v4")
config.link(c, "b4if.tx -> aftr.v6")
config.link(c, "aftr.v4 -> inet.rx")
config.link(c, "aftr.v6 -> b4if.rx")
if verbosity >= 1 then
local csv = CSVStatsTimer:new(bench_file)
csv:add_app("inet", {"tx", "rx"}, { tx = "IPv4 TX", rx = "IPv4 RX" })
csv:add_app("tob4", {"tx", "rx"}, { tx = "IPv6 TX", rx = "IPv6 RX" })
csv:activate()
if verbosity >= 2 then
timer.activate(timer.new("report", function ()
app.report_apps()
end, 1e9, "repeating"))
end
end
engine.configure(c)
engine.main {
report = {
showlinks = true;
}
}
end
|
module(..., package.seeall)
local CSVStatsTimer = require("program.lwaftr.csv_stats").CSVStatsTimer
local RawSocket = require("apps.socket.raw").RawSocket
local LwAftr = require("apps.lwaftr.lwaftr").LwAftr
local lib = require("core.lib")
local lwutil = require("apps.lwaftr.lwutil")
local engine = require("core.app")
local file_exists = lwutil.file_exists
local function check(flag, fmt, ...)
if not flag then
io.stderr:write(fmt:format(...), "\n")
main.exit(1)
end
end
local function parse_args(args)
local verbosity = 0
local conf_file, b4_if, inet_if
local bench_file = 'bench.csv'
local handlers = {
v = function ()
verbosity = verbosity + 1
end;
c = function (arg)
check(file_exists(arg), "no such file '%s'", arg)
conf_file = arg
end;
B = function (arg)
b4_if = arg
end;
I = function (arg)
inet_if = arg
end;
b = function (arg)
bench_file = arg
end;
h = function (arg)
print(require("program.lwaftr.run_nohw.README_inc"))
main.exit(0)
end;
}
lib.dogetopt(args, handlers, "b:c:B:I:vh", {
help = "h", conf = "c", verbose = "v",
["b4-if"] = "B", ["inet-if"] = "I",
["bench-file"] = "b",
})
check(conf_file, "no configuration specified (--conf/-c)")
check(b4_if, "no B4-side interface specified (--b4-if/-B)")
check(inet_if, "no Internet-side interface specified (--inet-if/-I)")
return verbosity, conf_file, b4_if, inet_if, bench_file
end
function run(parameters)
local verbosity, conf_file, b4_if, inet_if, bench_file = parse_args(parameters)
local conf = require('apps.lwaftr.conf').load_lwaftr_config(conf_file)
local c = config.new()
-- AFTR
config.app(c, "aftr", LwAftr, conf)
-- B4 side interface
config.app(c, "b4if", RawSocket, b4_if)
-- Internet interface
config.app(c, "inet", RawSocket, inet_if)
-- Connect apps
config.link(c, "inet.tx -> aftr.v4")
config.link(c, "b4if.tx -> aftr.v6")
config.link(c, "aftr.v4 -> inet.rx")
config.link(c, "aftr.v6 -> b4if.rx")
config.link(c, "aftr.hairpin_out -> aftr.hairpin_in")
engine.configure(c)
if verbosity >= 1 then
local csv = CSVStatsTimer:new(bench_file)
csv:add_app("inet", {"tx", "rx"}, { tx = "IPv4 TX", rx = "IPv4 RX" })
csv:add_app("b4if", {"tx", "rx"}, { tx = "IPv6 TX", rx = "IPv6 RX" })
csv:activate()
if verbosity >= 2 then
timer.activate(timer.new("report", function ()
app.report_apps()
end, 1e9, "repeating"))
end
end
engine.main {
report = {
showlinks = true;
}
}
end
|
Fix run_nohw
|
Fix run_nohw
* Add lwAFTR's hairpinning interface.
* Move engine.configure before CSVStats setup.
* Set correct apps names is CSVStats.
|
Lua
|
apache-2.0
|
eugeneia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,Igalia/snabb,eugeneia/snabb,heryii/snabb,alexandergall/snabbswitch,Igalia/snabb,heryii/snabb,eugeneia/snabb,heryii/snabb,alexandergall/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,heryii/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,dpino/snabb,Igalia/snabbswitch,dpino/snabbswitch,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabb,dpino/snabbswitch,snabbco/snabb,dpino/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabb,dpino/snabb,snabbco/snabb,dpino/snabb,snabbco/snabb,snabbco/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabb,snabbco/snabb,eugeneia/snabbswitch,heryii/snabb,heryii/snabb,Igalia/snabb,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch
|
186125607f2271af1387e28ce868fdf6d3dc9f1c
|
resources/prosody-plugins/mod_auth_jitsi-anonymous.lua
|
resources/prosody-plugins/mod_auth_jitsi-anonymous.lua
|
-- Anonymous authentication with extras:
-- * session resumption
-- Copyright (C) 2021-present 8x8, Inc.
local new_sasl = require "util.sasl".new;
local sasl = require "util.sasl";
local sessions = prosody.full_sessions;
-- define auth provider
local provider = {};
function provider.test_password(username, password)
return nil, "Password based auth not supported";
end
function provider.get_password(username)
return nil;
end
function provider.set_password(username, password)
return nil, "Set password not supported";
end
function provider.user_exists(username)
return nil;
end
function provider.create_user(username, password)
return nil;
end
function provider.delete_user(username)
return nil;
end
function provider.get_sasl_handler(session)
-- Custom session matching so we can resume sesssion even with randomly
-- generrated user IDs.
local function get_username(self, message)
if (session.previd ~= nil) then
for _, session1 in pairs(sessions) do
if (session1.resumption_token == session.previd) then
self.username = session1.username;
break;
end
end
else
self.username = message;
end
return true;
end
return new_sasl(module.host, { anonymous = get_username });
end
module:provides("auth", provider);
local function anonymous(self, message)
-- This calls the handler created in 'provider.get_sasl_handler(session)'
local result, err, msg = self.profile.anonymous(self, username, self.realm);
if result == true then
return "success";
else
return "failure", err, msg;
end
end
sasl.registerMechanism("ANONYMOUS", {"anonymous"}, anonymous);
|
-- Anonymous authentication with extras:
-- * session resumption
-- Copyright (C) 2021-present 8x8, Inc.
local generate_random_id = require "util.id".medium;
local new_sasl = require "util.sasl".new;
local sasl = require "util.sasl";
local sessions = prosody.full_sessions;
-- define auth provider
local provider = {};
function provider.test_password(username, password)
return nil, "Password based auth not supported";
end
function provider.get_password(username)
return nil;
end
function provider.set_password(username, password)
return nil, "Set password not supported";
end
function provider.user_exists(username)
return nil;
end
function provider.create_user(username, password)
return nil;
end
function provider.delete_user(username)
return nil;
end
function provider.get_sasl_handler(session)
-- Custom session matching so we can resume sesssion even with randomly
-- generrated user IDs.
local function get_username(self, message)
if (session.previd ~= nil) then
for _, session1 in pairs(sessions) do
if (session1.resumption_token == session.previd) then
self.username = session1.username;
break;
end
end
else
self.username = message;
end
return true;
end
return new_sasl(module.host, { anonymous = get_username });
end
module:provides("auth", provider);
local function anonymous(self, message)
-- Same as the vanilla anonymous auth plugin
local username = generate_random_id():lower();
-- This calls the handler created in 'provider.get_sasl_handler(session)'
local result, err, msg = self.profile.anonymous(self, username, self.realm);
if result == true then
if (self.username == nil) then
-- Session was not resumed
self.username = username;
end
return "success";
else
return "failure", err, msg;
end
end
sasl.registerMechanism("ANONYMOUS", {"anonymous"}, anonymous);
|
fix(prosody) fix username not being set in mod_auth_jitsi-anonymous
|
fix(prosody) fix username not being set in mod_auth_jitsi-anonymous
If the session was not resumed the plugin must generate a random username, just
like the regular anonymous authentication plugin does.
|
Lua
|
apache-2.0
|
jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet
|
4fdb53de6815eb33e03e07da90effb8c7ca98aed
|
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
|
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
|
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE)
healer_bottle_filling = class({
GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end,
})
modifier_healer_bottle_filling = class({
IsPurgable = function() return false end,
IsHidden = function() return true end,
})
if IsServer() then
function modifier_healer_bottle_filling:OnCreated()
self:StartIntervalThink(1)
self:OnIntervalThink()
end
function modifier_healer_bottle_filling:OnIntervalThink()
local caster = self:GetCaster()
local ability = self:GetAbility()
local radius = ability:GetSpecialValueFor("aura_radius")
local delay_duration = ability:GetSpecialValueFor('bottle_refill_cooldown')
for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
if not v:HasModifier("modifier_healer_bottle_filling_delay") then
for i = 0, 11 do
local item = v:GetItemInSlot(i)
if item and item:GetAbilityName() == "item_bottle_arena" then
item:SetCurrentCharges(item:GetCurrentCharges()+1)
v:EmitSound("DOTA_Item.MagicWand.Activate")
if item:GetCurrentCharges() == 3 then
v:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = delay_duration})
end
end
end
end
end
end
end
modifier_healer_bottle_filling_delay = class({
IsDebuff = function() return true end,
IsPurgable = function() return false end,
})
|
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE)
healer_bottle_filling = class({
GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end,
})
modifier_healer_bottle_filling = class({
IsPurgable = function() return false end,
IsHidden = function() return true end,
})
if IsServer() then
function modifier_healer_bottle_filling:OnCreated()
self:StartIntervalThink(1)
self:OnIntervalThink()
end
function modifier_healer_bottle_filling:OnIntervalThink()
local caster = self:GetCaster()
local ability = self:GetAbility()
local radius = ability:GetSpecialValueFor("aura_radius")
local delay_duration = ability:GetSpecialValueFor('bottle_refill_cooldown')
for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
if not v:HasModifier("modifier_healer_bottle_filling_delay") then
for i = 0, 11 do
local item = v:GetItemInSlot(i)
if item and item:GetAbilityName() == "item_bottle_arena" then
item:SetCurrentCharges(3)
v:EmitSound("DOTA_Item.MagicWand.Activate")
v:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = delay_duration})
end
end
end
end
end
end
modifier_healer_bottle_filling_delay = class({
IsDebuff = function() return true end,
IsPurgable = function() return false end,
})
|
fix(abilities): shrine bottle filling: fixed infinity charges bug
|
fix(abilities): shrine bottle filling: fixed infinity charges bug
|
Lua
|
mit
|
ark120202/aabs
|
98566d46931cb7ff3f913c09bbd525e8c65a8cfa
|
lua/entities/gmod_wire_expression2/base/optimizer.lua
|
lua/entities/gmod_wire_expression2/base/optimizer.lua
|
--[[
An optimizer for E2 abstract syntax trees, as produced by the parser and
consumed by the compiler.
Currently it only performs some simple peephole optimizations and constant
propagation. Ideally, we'd do type inference as much as possible before
optimizing, which would give us more useful information throughout.
--]]
E2Lib.Optimizer = {}
local Optimizer = E2Lib.Optimizer
Optimizer.__index = Optimizer
local optimizerDebug = CreateConVar("wire_expression2_optimizer_debug", 0,
"Print an E2's abstract syntax tree after optimization"
)
function Optimizer.Execute(root)
local ok, result = xpcall(Optimizer.Process, E2Lib.errorHandler, root)
if ok and optimizerDebug:GetBool() then
print(E2Lib.Parser.DumpTree(result))
end
return ok, result
end
Optimizer.Passes = {}
function Optimizer.Process(tree)
for i = 3, #tree do
local child = tree[i]
if type(child) == "table" and child.__instruction then
tree[i] = Optimizer.Process(child)
end
end
for _, pass in ipairs(Optimizer.Passes) do
local action = pass[tree[1]]
if action then
tree = assert(action(tree))
end
end
tree.__instruction = true
return tree
end
local constantPropagation = {}
local function evaluateBinary(instruction)
-- this is a little sneaky: we use the operators previously registered with getOperator
-- to do compile-time evaluation, even though it really wasn't designed for it.
local op = wire_expression2_funcs["op:" .. instruction[1] .. "(" .. instruction[3][4] .. instruction[4][4] .. ")"]
local x, y = instruction[3][3], instruction[4][3]
local value = op[3](nil, {nil, {function() return x end}, {function() return y end}})
local type = op[2]
return {"literal", instruction[2], value, type}
end
local function evaluateUnary(instruction)
local op = wire_expression2_funcs["op:" .. instruction[1] .. "(" .. instruction[3][4] .. ")"]
local x = instruction[3][3]
local value = op[3](nil, {nil, {function() return x end}})
local type = op[2]
return {"literal", instruction[2], value, type}
end
for _, operator in pairs({ "add", "sub", "mul", "div", "mod", "exp", "eq", "neq", "geq", "leq",
"gth", "lth", "band", "band", "bor", "bxor", "bshl", "bshr" }) do
constantPropagation[operator] = function(instruction)
if instruction[3][1] ~= "literal" or instruction[4][1] ~= "literal" then return instruction end
return evaluateBinary(instruction)
end
end
function constantPropagation.neg(instruction)
if instruction[3][1] ~= "literal" then return instruction end
return evaluateUnary(instruction)
end
constantPropagation["not"] = function(instruction)
if instruction[3][1] ~= "literal" then return instruction end
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
return evaluateUnary(instruction)
end
for _, operator in pairs({ "and", "or" }) do
constantPropagation[operator] = function(instruction)
if instruction[3][1] ~= "literal" then return instruction end
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
instruction[4] = evaluateUnary({"is", instruction[2], instruction[4]})
return evaluateBinary(instruction)
end
end
table.insert(Optimizer.Passes, constantPropagation)
local peephole = {}
function peephole.add(instruction)
-- (add 0 x) → x
if instruction[3][1] == "literal" and instruction[3][3] == 0 then return instruction[4] end
-- (add x 0) → x
if instruction[4][1] == "literal" and instruction[4][3] == 0 then return instruction[3] end
-- (add (neg x) (neg y)) → (neg (add x y))
if instruction[3][1] == "neg" and instruction[4][1] == "neg" then
return {"neg", instruction[2], {"add", instruction[2], instruction[3][3], instruction[4][3],
__instruction = true}}
end
-- (add x (neg y)) → (sub x y)
if instruction[4][1] == "neg" then
return {"sub", instruction[2], instruction[3], instruction[4][3]}
end
-- (add (neg x) y) → (sub y x)
if instruction[3][1] == "neg" then
return {"sub", instruction[2], instruction[4], instruction[3][3]}
end
return instruction
end
function peephole.sub(instruction)
-- (sub 0 x) → (neg x)
if instruction[3][1] == "literal" and instruction[3][3] == 0 then
return {"neg", instruction[2], instruction[4]}
end
-- (sub x 0) → x
if instruction[4][1] == "literal" and instruction[4][3] == 0 then return instruction[3] end
-- (sub (neg x) (neg y)) → (sub y x)
if instruction[3][1] == "neg" and instruction[4][1] == "neg" then
return {"sub", instruction[2], instruction[4][3], instruction[3][3]}
end
-- (sub x (neg y) → (add x y))
if instruction[4][1] == "neg" then
return {"add", instruction[2], instruction[3], instruction[4][3]}
end
-- (sub (neg x) y) → (neg (add x y))
if instruction[3][1] == "neg" then
return {"neg", instruction[2], {"add", instruction[2], instruction[3][3], instruction[4],
__instruction = true }}
end
return instruction
end
function peephole.mul(instruction)
if instruction[4][1] == "literal" and instruction[3][1] ~= "literal" then
instruction[3], instruction[4] = instruction[4], instruction[3]
end
-- (mul 1 x) → x
if instruction[3][1] == "literal" and instruction[3][3] == 1 then return instruction[4] end
-- (mul 0 x) → 0
if instruction[3][1] == "literal" and instruction[3][3] == 0 then return instruction[3] end
-- (mul -1 x) → (neg x)
if instruction[3][1] == "literal" and instruction[3][3] == -1 then
return {"neg", instruction[2], instruction[4]}
end
return instruction
end
function peephole.neg(instruction)
-- (neg (neg x)) → x
if instruction[3][1] == "neg" then return instruction[3][3] end
return instruction
end
peephole["if"] = function(instruction)
-- (if 1 x y) → x
-- (if 0 x y) → y
if instruction[3][1] == "literal" then
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
if instruction[3][3] == 1 then return instruction[4] end
if instruction[3][3] == 0 then return instruction[5] end
assert(false, "unreachable: `is` evaluation didn't return a boolean")
end
return instruction
end
function peephole.whl(instruction)
-- (while 0 x) → (seq)
if instruction[3][1] == "literal" then
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
if instruction[3][3] == 0 then return {"seq", instruction[2]} end
end
return instruction
end
table.insert(Optimizer.Passes, peephole)
|
--[[
An optimizer for E2 abstract syntax trees, as produced by the parser and
consumed by the compiler.
Currently it only performs some simple peephole optimizations and constant
propagation. Ideally, we'd do type inference as much as possible before
optimizing, which would give us more useful information throughout.
--]]
E2Lib.Optimizer = {}
local Optimizer = E2Lib.Optimizer
Optimizer.__index = Optimizer
local optimizerDebug = CreateConVar("wire_expression2_optimizer_debug", 0,
"Print an E2's abstract syntax tree after optimization"
)
function Optimizer.Execute(root)
local ok, result = xpcall(Optimizer.Process, E2Lib.errorHandler, root)
if ok and optimizerDebug:GetBool() then
print(E2Lib.Parser.DumpTree(result))
end
return ok, result
end
Optimizer.Passes = {}
function Optimizer.Process(tree)
for i = 3, #tree do
local child = tree[i]
if type(child) == "table" and child.__instruction then
tree[i] = Optimizer.Process(child)
end
end
for _, pass in ipairs(Optimizer.Passes) do
local action = pass[tree[1]]
if action then
tree = assert(action(tree))
end
end
tree.__instruction = true
return tree
end
local constantPropagation = {}
local function evaluateBinary(instruction)
-- this is a little sneaky: we use the operators previously registered with getOperator
-- to do compile-time evaluation, even though it really wasn't designed for it.
local op = wire_expression2_funcs["op:" .. instruction[1] .. "(" .. instruction[3][4] .. instruction[4][4] .. ")"]
local x, y = instruction[3][3], instruction[4][3]
local value = op[3](nil, {nil, {function() return x end}, {function() return y end}})
local type = op[2]
return {"literal", instruction[2], value, type}
end
local function evaluateUnary(instruction)
local op = wire_expression2_funcs["op:" .. instruction[1] .. "(" .. instruction[3][4] .. ")"]
local x = instruction[3][3]
local value = op[3](nil, {nil, {function() return x end}})
local type = op[2]
return {"literal", instruction[2], value, type}
end
for _, operator in pairs({ "add", "sub", "mul", "div", "mod", "exp", "eq", "neq", "geq", "leq",
"gth", "lth", "band", "band", "bor", "bxor", "bshl", "bshr" }) do
constantPropagation[operator] = function(instruction)
if instruction[3][1] ~= "literal" or instruction[4][1] ~= "literal" then return instruction end
return evaluateBinary(instruction)
end
end
function constantPropagation.neg(instruction)
if instruction[3][1] ~= "literal" then return instruction end
return evaluateUnary(instruction)
end
constantPropagation["not"] = function(instruction)
if instruction[3][1] ~= "literal" then return instruction end
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
return evaluateUnary(instruction)
end
for _, operator in pairs({ "and", "or" }) do
constantPropagation[operator] = function(instruction)
if instruction[3][1] ~= "literal" or instruction[4][1] ~= "literal" then return instruction end
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
instruction[4] = evaluateUnary({"is", instruction[2], instruction[4]})
return evaluateBinary(instruction)
end
end
table.insert(Optimizer.Passes, constantPropagation)
local peephole = {}
function peephole.add(instruction)
-- (add 0 x) → x
if instruction[3][1] == "literal" and instruction[3][3] == 0 then return instruction[4] end
-- (add x 0) → x
if instruction[4][1] == "literal" and instruction[4][3] == 0 then return instruction[3] end
-- (add (neg x) (neg y)) → (neg (add x y))
if instruction[3][1] == "neg" and instruction[4][1] == "neg" then
return {"neg", instruction[2], {"add", instruction[2], instruction[3][3], instruction[4][3],
__instruction = true}}
end
-- (add x (neg y)) → (sub x y)
if instruction[4][1] == "neg" then
return {"sub", instruction[2], instruction[3], instruction[4][3]}
end
-- (add (neg x) y) → (sub y x)
if instruction[3][1] == "neg" then
return {"sub", instruction[2], instruction[4], instruction[3][3]}
end
return instruction
end
function peephole.sub(instruction)
-- (sub 0 x) → (neg x)
if instruction[3][1] == "literal" and instruction[3][3] == 0 then
return {"neg", instruction[2], instruction[4]}
end
-- (sub x 0) → x
if instruction[4][1] == "literal" and instruction[4][3] == 0 then return instruction[3] end
-- (sub (neg x) (neg y)) → (sub y x)
if instruction[3][1] == "neg" and instruction[4][1] == "neg" then
return {"sub", instruction[2], instruction[4][3], instruction[3][3]}
end
-- (sub x (neg y) → (add x y))
if instruction[4][1] == "neg" then
return {"add", instruction[2], instruction[3], instruction[4][3]}
end
-- (sub (neg x) y) → (neg (add x y))
if instruction[3][1] == "neg" then
return {"neg", instruction[2], {"add", instruction[2], instruction[3][3], instruction[4],
__instruction = true }}
end
return instruction
end
function peephole.mul(instruction)
if instruction[4][1] == "literal" and instruction[3][1] ~= "literal" then
instruction[3], instruction[4] = instruction[4], instruction[3]
end
-- (mul 1 x) → x
if instruction[3][1] == "literal" and instruction[3][3] == 1 then return instruction[4] end
-- (mul 0 x) → 0
if instruction[3][1] == "literal" and instruction[3][3] == 0 then return instruction[3] end
-- (mul -1 x) → (neg x)
if instruction[3][1] == "literal" and instruction[3][3] == -1 then
return {"neg", instruction[2], instruction[4]}
end
return instruction
end
function peephole.neg(instruction)
-- (neg (neg x)) → x
if instruction[3][1] == "neg" then return instruction[3][3] end
return instruction
end
peephole["if"] = function(instruction)
-- (if 1 x y) → x
-- (if 0 x y) → y
if instruction[3][1] == "literal" then
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
if instruction[3][3] == 1 then return instruction[4] end
if instruction[3][3] == 0 then return instruction[5] end
assert(false, "unreachable: `is` evaluation didn't return a boolean")
end
return instruction
end
function peephole.whl(instruction)
-- (while 0 x) → (seq)
if instruction[3][1] == "literal" then
instruction[3] = evaluateUnary({"is", instruction[2], instruction[3]})
if instruction[3][3] == 0 then return {"seq", instruction[2]} end
end
return instruction
end
table.insert(Optimizer.Passes, peephole)
|
Fix "and" and "or" optimizations
|
Fix "and" and "or" optimizations
The second argument wasn't checked for being a literal.
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,Grocel/wire,thegrb93/wire,garrysmodlua/wire,dvdvideo1234/wire,wiremod/wire,sammyt291/wire
|
10288948832bb7735653af4edcf357a7a5b97dff
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
result = os.execute(string.format("tar czvf ../premake-macosx-%s.tar.gz bin/release/premake4 >../release.log", version))
else
result = os.execute(string.format("tar czvf ../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../..")
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
Fixes to release script
|
Fixes to release script
--HG--
extra : convert_revision : svn%3A644ed5ae-bb15-0410-aa60-99f397bbb77a/trunk%40353
|
Lua
|
bsd-3-clause
|
Lusito/premake,annulen/premake-annulen,Lusito/premake,Lusito/premake,annulen/premake-dev-rgeary,annulen/premake,annulen/premake,annulen/premake-annulen,Lusito/premake,warrenseine/premake,annulen/premake,annulen/premake-annulen,warrenseine/premake,warrenseine/premake,annulen/premake-dev-rgeary,annulen/premake-dev-rgeary,annulen/premake-annulen,annulen/premake
|
b41216198b10bc0f5f431c36ba8cdc587845d43e
|
lua/entities/gmod_wire_gate.lua
|
lua/entities/gmod_wire_gate.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gate"
ENT.WireDebugName = "Gate"
if CLIENT then return end -- No more client
local Wire_EnableGateInputValues = CreateConVar("Wire_EnableGateInputValues", 1, FCVAR_ARCHIVE)
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = {}
self.Outputs = {}
end
function ENT:Setup( action, noclip )
local gate = GateActions[action]
if not gate then return end
if GateActions[action].is_banned then return end
self.action = action
self.WireDebugName = gate.name
WireLib.AdjustSpecialInputs(self, gate.inputs, gate.inputtypes )
if (gate.outputs) then
WireLib.AdjustSpecialOutputs(self, gate.outputs, gate.outputtypes)
else
--Wire_AdjustOutputs(self, { "Out" })
WireLib.AdjustSpecialOutputs(self, { "Out" }, gate.outputtypes)
end
if (gate.reset) then
gate.reset(self)
end
local ReadCell = gate.ReadCell
if ReadCell then
function self:ReadCell(Address)
return ReadCell(gate,self,Address)
end
else
self.ReadCell = nil
end
local WriteCell = gate.WriteCell
if WriteCell then
function self:WriteCell(Address,value)
return WriteCell(gate,self,Address,value)
end
else
self.WriteCell = nil
end
if (noclip) then
self:SetCollisionGroup( COLLISION_GROUP_WORLD )
end
self.noclip = noclip
self.Action = gate
self.PrevValue = nil
--self.Action.inputtypes = self.Action.inputtypes or {}
self:CalcOutput()
self:ShowOutput()
end
function ENT:OnInputWireLink(iname, itype, src, oname, otype)
if (self.Action) and (self.Action.OnInputWireLink) then
self.Action.OnInputWireLink(self, iname, itype, src, oname, otype)
end
end
function ENT:OnOutputWireLink(oname, otype, dst, iname, itype)
if (self.Action) and (self.Action.OnOutputWireLink) then
self.Action.OnOutputWireLink(self, oname, otype, dst, iname, itype)
end
end
function ENT:TriggerInput(iname, value, iter)
if (self.Action) and (not self.Action.timed) then
self:CalcOutput(iter)
self:ShowOutput()
end
end
function ENT:Think()
self.BaseClass.Think(self)
if (self.Action) and (self.Action.timed) then
self:CalcOutput()
self:ShowOutput()
self:NextThink(CurTime()+0.02)
return true
end
end
function ENT:CalcOutput(iter)
if (self.Action) and (self.Action.output) then
if (self.Action.outputs) then
local result = { self.Action.output(self, unpack(self:GetActionInputs())) }
for k,v in ipairs(self.Action.outputs) do
Wire_TriggerOutput(self, v, result[k] or WireLib.DT[ self.Outputs[v].Type ].Zero, iter)
end
else
local value = self.Action.output(self, unpack(self:GetActionInputs())) or WireLib.DT[ self.Outputs.Out.Type ].Zero
Wire_TriggerOutput(self, "Out", value, iter)
end
end
end
function ENT:ShowOutput()
local txt = ""
if (self.Action) then
txt = (self.Action.name or "No Name")
if (self.Action.label) then
txt = txt.."\n"..self.Action.label(self:GetActionOutputs(), unpack(self:GetActionInputs(Wire_EnableGateInputValues:GetBool())))
end
else
txt = "Invalid gate!"
end
self:SetOverlayText(txt)
end
function ENT:OnRestore()
self.Action = GateActions[self.action]
self.BaseClass.OnRestore(self)
end
function ENT:GetActionInputs(as_names)
local Args = {}
if (self.Action.compact_inputs) then
-- If a gate has compact inputs (like Arithmetic - Add), nil inputs are truncated so {0, nil, nil, 5, nil, 1} becomes {0, 5, 1}
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if IsValid(input.Src) then
if (as_names) then
table.insert(Args, input.Src.WireName or input.Src.WireDebugName or v)
else
table.insert(Args, input.Value)
end
end
end
while (#Args < self.Action.compact_inputs) do
if (as_names) then
table.insert(Args, self.Action.inputs[#Args+1] or "*Not enough inputs*")
else
--table.insert( Args, WireLib.DT[ (self.Action.inputtypes[#Args+1] or "NORMAL") ].Zero )
table.insert( Args, WireLib.DT[ self.Inputs[ self.Action.inputs[#Args+1] ].Type ].Zero )
end
end
else
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if (as_names) then
Args[k] = IsValid(input.Src) and (input.Src.WireName or input.Src.WireDebugName) or v
else
Args[k] = IsValid(input.Src) and input.Value or WireLib.DT[ self.Inputs[v].Type ].Zero
end
end
end
return Args
end
function ENT:GetActionOutputs()
if (self.Action.outputs) then
local result = {}
for _,v in ipairs(self.Action.outputs) do
result[v] = self.Outputs[v].Value or WireLib.DT[ self.Outputs[v].Type ].Zero
end
return result
end
return self.Outputs.Out.Value or WireLib.DT[ self.Outputs.Out.Type ].Zero
end
function MakeWireGate(pl, Pos, Ang, model, action, noclip, frozen, nocollide)
if not GateActions[action] then return end
if GateActions[action].is_banned then return end
return WireLib.MakeWireEnt(pl, { Class = "gmod_wire_gate", Pos=Pos, Angle=Ang, Model=model }, action, noclip)
end
duplicator.RegisterEntityClass("gmod_wire_gate", MakeWireGate, "Pos", "Ang", "Model", "action", "noclip")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gate"
ENT.WireDebugName = "Gate"
if CLIENT then return end -- No more client
local Wire_EnableGateInputValues = CreateConVar("Wire_EnableGateInputValues", 1, FCVAR_ARCHIVE)
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = {}
self.Outputs = {}
end
function ENT:Setup( action, noclip )
local gate = GateActions[action]
if not gate then return end
if GateActions[action].is_banned then return end
self.Updating = true
self.action = action
self.WireDebugName = gate.name
WireLib.AdjustSpecialInputs(self, gate.inputs, gate.inputtypes )
if (gate.outputs) then
WireLib.AdjustSpecialOutputs(self, gate.outputs, gate.outputtypes)
else
--Wire_AdjustOutputs(self, { "Out" })
WireLib.AdjustSpecialOutputs(self, { "Out" }, gate.outputtypes)
end
if (gate.reset) then
gate.reset(self)
end
local ReadCell = gate.ReadCell
if ReadCell then
function self:ReadCell(Address)
return ReadCell(gate,self,Address)
end
else
self.ReadCell = nil
end
local WriteCell = gate.WriteCell
if WriteCell then
function self:WriteCell(Address,value)
return WriteCell(gate,self,Address,value)
end
else
self.WriteCell = nil
end
if (noclip) then
self:SetCollisionGroup( COLLISION_GROUP_WORLD )
end
self.noclip = noclip
self.Action = gate
self.PrevValue = nil
--self.Action.inputtypes = self.Action.inputtypes or {}
self.Updating = nil
self:CalcOutput()
self:ShowOutput()
end
function ENT:OnInputWireLink(iname, itype, src, oname, otype)
if (self.Action) and (self.Action.OnInputWireLink) then
self.Action.OnInputWireLink(self, iname, itype, src, oname, otype)
end
end
function ENT:OnOutputWireLink(oname, otype, dst, iname, itype)
if (self.Action) and (self.Action.OnOutputWireLink) then
self.Action.OnOutputWireLink(self, oname, otype, dst, iname, itype)
end
end
function ENT:TriggerInput(iname, value, iter)
if self.Updating then return end
if (self.Action) and (not self.Action.timed) then
self:CalcOutput(iter)
self:ShowOutput()
end
end
function ENT:Think()
self.BaseClass.Think(self)
if (self.Action) and (self.Action.timed) then
self:CalcOutput()
self:ShowOutput()
self:NextThink(CurTime()+0.02)
return true
end
end
function ENT:CalcOutput(iter)
if (self.Action) and (self.Action.output) then
if (self.Action.outputs) then
local result = { self.Action.output(self, unpack(self:GetActionInputs())) }
for k,v in ipairs(self.Action.outputs) do
Wire_TriggerOutput(self, v, result[k] or WireLib.DT[ self.Outputs[v].Type ].Zero, iter)
end
else
local value = self.Action.output(self, unpack(self:GetActionInputs())) or WireLib.DT[ self.Outputs.Out.Type ].Zero
Wire_TriggerOutput(self, "Out", value, iter)
end
end
end
function ENT:ShowOutput()
local txt = ""
if (self.Action) then
txt = (self.Action.name or "No Name")
if (self.Action.label) then
txt = txt.."\n"..self.Action.label(self:GetActionOutputs(), unpack(self:GetActionInputs(Wire_EnableGateInputValues:GetBool())))
end
else
txt = "Invalid gate!"
end
self:SetOverlayText(txt)
end
function ENT:OnRestore()
self.Action = GateActions[self.action]
self.BaseClass.OnRestore(self)
end
function ENT:GetActionInputs(as_names)
local Args = {}
if (self.Action.compact_inputs) then
-- If a gate has compact inputs (like Arithmetic - Add), nil inputs are truncated so {0, nil, nil, 5, nil, 1} becomes {0, 5, 1}
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")\n")
return {}
end
if IsValid(input.Src) then
if (as_names) then
table.insert(Args, input.Src.WireName or input.Src.WireDebugName or v)
else
table.insert(Args, input.Value)
end
end
end
while (#Args < self.Action.compact_inputs) do
if (as_names) then
table.insert(Args, self.Action.inputs[#Args+1] or "*Not enough inputs*")
else
--table.insert( Args, WireLib.DT[ (self.Action.inputtypes[#Args+1] or "NORMAL") ].Zero )
table.insert( Args, WireLib.DT[ self.Inputs[ self.Action.inputs[#Args+1] ].Type ].Zero )
end
end
else
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")\n")
return {}
end
if (as_names) then
Args[k] = IsValid(input.Src) and (input.Src.WireName or input.Src.WireDebugName) or v
else
Args[k] = IsValid(input.Src) and input.Value or WireLib.DT[ self.Inputs[v].Type ].Zero
end
end
end
return Args
end
function ENT:GetActionOutputs()
if (self.Action.outputs) then
local result = {}
for _,v in ipairs(self.Action.outputs) do
result[v] = self.Outputs[v].Value or WireLib.DT[ self.Outputs[v].Type ].Zero
end
return result
end
return self.Outputs.Out.Value or WireLib.DT[ self.Outputs.Out.Type ].Zero
end
function MakeWireGate(pl, Pos, Ang, model, action, noclip, frozen, nocollide)
if not GateActions[action] then return end
if GateActions[action].is_banned then return end
return WireLib.MakeWireEnt(pl, { Class = "gmod_wire_gate", Pos=Pos, Angle=Ang, Model=model }, action, noclip)
end
duplicator.RegisterEntityClass("gmod_wire_gate", MakeWireGate, "Pos", "Ang", "Model", "action", "noclip")
|
fixed error when updating gate
|
fixed error when updating gate
|
Lua
|
apache-2.0
|
bigdogmat/wire,sammyt291/wire,NezzKryptic/Wire,dvdvideo1234/wire,wiremod/wire,thegrb93/wire,garrysmodlua/wire,Grocel/wire
|
f6c8467ce686b689fe069f4bb8aa9710c91dfcf8
|
quick3d.lua
|
quick3d.lua
|
-- Copyright (C) 2016 Chris Liebert
local wrapper = nil
function require_shared_library()
wrapper = require "quick3dwrapper"
end
-- Determine whether platform is Windows
function isWindows()
if package.config:sub(1,1) == "\\" then return true end
end
-- Generate the wrapper source and compile the shared libarary
function build_wrapper()
-- Generate quick3d_wrapper.c
local make_program = "make"
if isWindows() then
make_program = "mingw32-make.exe"
os.execute("copy target\\debug\\quick3d.dll .")
end
local make_cmd = make_program.." lualib"
local make_result = os.execute(make_cmd)
if not make_result == 0 then
os.exit(2)
end
end
-- Load the shared library
function quick3d_init()
if pcall(require_shared_library) then
print "Loaded shared library"
else
print "Building shared library"
build_wrapper()
-- try to load the shared library again
if not pcall(require_shared_library) then
print "Unable to load quick3dwrapper shared library"
os.exit(2)
end
end
return wrapper
end
|
-- Copyright (C) 2016 Chris Liebert
local wrapper = nil
function require_shared_library()
wrapper = require "quick3dwrapper"
end
-- Determine whether platform is Windows
function isWindows()
if package.config:sub(1,1) == "\\" then return true end
end
-- Generate the wrapper source and compile the shared libarary
function build_wrapper()
-- Generate quick3d_wrapper.c
local make_program = "make"
if isWindows() then
make_program = "mingw32-make.exe"
end
local make_cmd = make_program.." lualib"
local make_result = os.execute(make_cmd)
if not make_result == 0 then
os.exit(2)
end
if isWindows() then
os.execute("copy target\\debug\\quick3d.dll .")
end
end
-- Load the shared library
function quick3d_init()
if pcall(require_shared_library) then
print "Loaded shared library"
else
print "Building shared library"
build_wrapper()
-- try to load the shared library again
if not pcall(require_shared_library) then
print "Unable to load quick3dwrapper shared library"
os.exit(2)
end
end
return wrapper
end
|
fixed copy-after-build windows problem
|
fixed copy-after-build windows problem
|
Lua
|
mit
|
chrisliebert/quick-3d,chrisliebert/quick-3d,chrisliebert/quick-3d,chrisliebert/quick-3d,chrisliebert/quick-3d
|
f262789b46fac3164256d5122e37bfa110983d34
|
lualib/util.lua
|
lualib/util.lua
|
local skynet = require "skynet"
local util = {}
function util.process(CMD, cmd, ...)
if not cmd then
return
end
local f = CMD[cmd]
if not f then
tlog.error("cmd %s not found", tostring(cmd))
return
end
f(...)
end
function util.nowstr()
local t = os.date("*t")
return string.format("%04d-%02d-%02d %02d:%02d:%02d",
t.year, t.month, t.day, t.hour, t.min, t.sec)
end
function util.newtimer()
local timer = {}
local handles = {} --setmetatable({}, {__mode = "kv"})
function timer.timeout(ti, f)
if ti > TM_TIMEOUT_LIMIT then
tlog.warn("long timeout:%d! %s", ti, debug.traceback())
end
local function tf()
local f = handles[tf]
if f then
f()
end
end
skynet.timeout(ti, tf)
handles[tf] = f
return tf
end
function timer.cancel(tf)
handles[tf] = nil
end
function timer.clear()
for k, _ in pairs(handles) do
handles[k] = nil
end
end
return timer
end
return util
|
local skynet = require "skynet"
local util = {}
function util.process(CMD, cmd, ...)
if not cmd then
return
end
local f = CMD[cmd]
if not f then
tlog.error("cmd %s not found", tostring(cmd))
return
end
f(...)
end
function util.nowstr()
local t = os.date("*t")
return string.format("%04d-%02d-%02d %02d:%02d:%02d",
t.year, t.month, t.day, t.hour, t.min, t.sec)
end
function util.newtimer()
local timer = {}
local handles = {} --setmetatable({}, {__mode = "kv"})
function timer.timeout(ti, f)
if ti > TM_TIMEOUT_LIMIT then
tlog.warn("long timeout:%d! %s", ti, debug.traceback())
end
local function tf()
local f = handles[tf]
if f then
handles[tf] = nil
f()
end
end
skynet.timeout(ti, tf)
handles[tf] = f
return tf
end
function timer.cancel(tf)
handles[tf] = nil
end
function timer.clear()
for k, _ in pairs(handles) do
handles[k] = nil
end
end
return timer
end
return util
|
bug fixed.
|
bug fixed.
|
Lua
|
mit
|
qinhanlei/terminator
|
1fabec9b218825b917e636374474bda6b239a146
|
mod_seclabels/mod_seclabels.lua
|
mod_seclabels/mod_seclabels.lua
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
local function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook_global("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
-- TODO query remote servers
--[[ FIXME later
labels = module:fire_event("sec-label-catalog", {
to = catalog_request.attr.to,
request = request; -- or just origin?
labels = labels;
}) or labels;
--]]
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
mod_seclabels: Fix config reloading
|
mod_seclabels: Fix config reloading
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
cd18cb24ed958c0b4abb38d00b13ff42a70b8473
|
config/webkitten/commands/go-or-search.lua
|
config/webkitten/commands/go-or-search.lua
|
function description()
return "Open a passed URL or searches for it on DuckDuckGo"
end
function run()
local windex = focused_window_index()
local input = table.concat(arguments, " ")
if looks_like_url(input) then
local target = input
else
local encoded = url_encode(input)
local target = table.concat({"https://duckduckgo.com?q=", encoded}, "")
end
load_uri(windex, focused_webview_index(windex), target)
return true
end
function looks_like_url(str)
-- Anything with a space in it is treat it as a search
-- EX: "foo bar"
if str:find(" ") then
return false
end
-- If it doesn't have a dot, treat it as a search
-- EX: "foo"
if str:find("%.") == nil then
return false
end
-- If it starts with a question mark, treat it as a search
-- EX: "?google.com"
if str:find("^?") then
return false
end
return true
end
function url_encode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
|
function description()
return "Open a passed URL or searches for it on DuckDuckGo"
end
function run()
local windex = focused_window_index()
local input = table.concat(arguments, " ")
local target = ""
if looks_like_url(input) then
target = input
else
local encoded = url_encode(input)
target = table.concat({"https://duckduckgo.com?q=", encoded}, "")
end
load_uri(windex, focused_webview_index(windex), target)
return true
end
function looks_like_url(str)
-- Anything with a space in it is treat it as a search
-- EX: "foo bar"
if str:find(" ") then
return false
end
-- If it doesn't have a dot, treat it as a search
-- EX: "foo"
if str:find("%.") == nil then
return false
end
-- If it starts with a question mark, treat it as a search
-- EX: "?google.com"
if str:find("^?") then
return false
end
return true
end
function url_encode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
|
Fix local lua vars
|
Fix local lua vars
|
Lua
|
mit
|
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
|
186cab7ff2d737b2353a896f4803ce8b91e05dea
|
main.lua
|
main.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.
--]]
-- Create a luvit powered main that does the luvit CLI interface
return require('./init')(function (...)
local luvi = require('luvi')
local uv = require('uv')
local utils = require('utils')
local package = require('./package.lua')
local startRepl = nil
local combo = nil
local script = nil
local extra = {}
local function usage()
print("Usage: " .. args[0] .. " [options] script.lua [arguments]"..[[
Options:
-h, --help Print this help screen.
-v, --version Print the version.
-e code_chunk Evaluate code chunk and print result.
-i, --interactive Enter interactive repl after executing script.
-l libname Require library.
-n, --no-color Disable colors.
-c, --16-colors Use simple ANSI colors
-C, --256-colors Use 256-mode ANSI colors
(Note, if no script is provided, a repl is run instead.)
]])
startRepl = false
end
local function version()
print('luvit version: ' .. package.version)
print('luvi version: ' .. require('luvi').version)
for k, v in pairs(require('luvi').options) do
print(k .. ' version: ' .. tostring(v))
end
startRepl = false
end
local shorts = {
h = "help",
v = "version",
e = "eval",
i = "interactive",
l = "require",
n = "no-color",
c = "16-colors",
C = "256-colors",
}
local flags = {
help = usage,
version = version,
eval = function ()
local repl = require('repl')(utils.stdin, utils.stdout)
combo = repl.evaluateLine
startRepl = false
end,
interactive = function ()
startRepl = true
end,
["no-color"] = function ()
utils.loadColors(false)
end,
["16-colors"] = function ()
utils.loadColors(16)
end,
["256-colors"] = function ()
utils.loadColors(256)
end,
}
local i, arg = 1
repeat
arg = args[i]
if script then
extra[#extra + 1] = arg
elseif combo then
combo(arg)
combo = nil
elseif string.sub(arg, 1, 1) == "-" then
local flag
if (string.sub(arg, 2, 2) == "-") then
flag = string.sub(arg, 3)
else
arg = string.sub(arg, 2)
flag = shorts[arg] or arg
end
if flag=='require' then
i=i+1
require(args[i])
else
local fn = flags[flag] or usage
fn()
end
else
script = arg
end
i = i + 1
until i > #args
if combo then error("Missing flag value") end
if startRepl == nil and not script then startRepl = true end
if script then
require(luvi.path.join(uv.cwd(), script))
end
if startRepl then
local env = require('env')
local pathJoin = require('luvi').path.join
local fs = require('fs')
local c = utils.color
local greeting = "Welcome to the " .. c("err") .. "L" .. c("quotes") .. "uv" .. c("table") .. "it" .. c() .. " repl!"
local historyFile
if require('ffi').os == "Windows" then
historyFile = pathJoin(env.get("APPDATA"), "luvit_history")
else
historyFile = pathJoin(env.get("HOME"), ".luvit_history")
end
local lines = fs.readFileSync(historyFile) or ""
local function saveHistory(lines)
fs.writeFileSync(historyFile, lines)
end
require('repl')(utils.stdin, utils.stdout, greeting, ...).start(lines, saveHistory)
end
end, ...)
|
--[[
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.
--]]
-- Create a luvit powered main that does the luvit CLI interface
return require('./init')(function (...)
local luvi = require('luvi')
local uv = require('uv')
local utils = require('utils')
local package = require('./package.lua')
local startRepl = nil
local combo = nil
local script = nil
local extra = {}
local function usage()
print("Usage: " .. args[0] .. " [options] script.lua [arguments]"..[[
Options:
-h, --help Print this help screen.
-v, --version Print the version.
-e code_chunk Evaluate code chunk and print result.
-i, --interactive Enter interactive repl after executing script.
-l libname Require library.
-n, --no-color Disable colors.
-c, --16-colors Use simple ANSI colors
-C, --256-colors Use 256-mode ANSI colors
(Note, if no script is provided, a repl is run instead.)
]])
startRepl = false
end
local function version()
print('luvit version: ' .. package.version)
print('luvi version: ' .. require('luvi').version)
for k, v in pairs(require('luvi').options) do
print(k .. ' version: ' .. tostring(v))
end
startRepl = false
end
local shorts = {
h = "help",
v = "version",
e = "eval",
i = "interactive",
l = "require",
n = "no-color",
c = "16-colors",
C = "256-colors",
}
local flags = {
help = usage,
version = version,
eval = function ()
local repl = require('repl')(utils.stdin, utils.stdout)
combo = repl.evaluateLine
startRepl = false
end,
interactive = function ()
startRepl = true
end,
["no-color"] = function ()
utils.loadColors(false)
end,
["16-colors"] = function ()
utils.loadColors(16)
end,
["256-colors"] = function ()
utils.loadColors(256)
end,
}
local i, arg = 1
arg = args[i]
while arg do
if script then
extra[#extra + 1] = arg
elseif combo then
combo(arg)
combo = nil
elseif string.sub(arg, 1, 1) == "-" then
local flag
if (string.sub(arg, 2, 2) == "-") then
flag = string.sub(arg, 3)
else
arg = string.sub(arg, 2)
flag = shorts[arg] or arg
end
if flag=='require' then
i=i+1
require(args[i])
else
local fn = flags[flag] or usage
fn()
end
else
script = arg
end
i = i + 1
arg = args[i]
end
if combo then error("Missing flag value") end
if startRepl == nil and not script then startRepl = true end
if script then
require(luvi.path.join(uv.cwd(), script))
end
if startRepl then
local env = require('env')
local pathJoin = require('luvi').path.join
local fs = require('fs')
local c = utils.color
local greeting = "Welcome to the " .. c("err") .. "L" .. c("quotes") .. "uv" .. c("table") .. "it" .. c() .. " repl!"
local historyFile
if require('ffi').os == "Windows" then
historyFile = pathJoin(env.get("APPDATA"), "luvit_history")
else
historyFile = pathJoin(env.get("HOME"), ".luvit_history")
end
local lines = fs.readFileSync(historyFile) or ""
local function saveHistory(lines)
fs.writeFileSync(historyFile, lines)
end
require('repl')(utils.stdin, utils.stdout, greeting, ...).start(lines, saveHistory)
end
end, ...)
|
fix luvit handle args
|
fix luvit handle args
introduce in https://github.com/luvit/luvit/commit/9146ae5b3ca5da447a05136ba13d804a9d47ef6c
|
Lua
|
apache-2.0
|
zhaozg/luvit,luvit/luvit,luvit/luvit,zhaozg/luvit
|
0e350d87bfedde187dc6555d79163bf53caa5d00
|
packages/luci-app-batman-adv/files/usr/lib/lua/luci/controller/batman.lua
|
packages/luci-app-batman-adv/files/usr/lib/lua/luci/controller/batman.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2012 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.batman", package.seeall)
function index()
local page
page = node("admin", "network", "batman")
page.target = template("batman")
page.title = _("BATMAN-Adv")
page.order = 1
node("batman")
page = node("batman", "json")
page.target = call("act_json")
page = node("batman", "vis")
page.target = call("act_vis")
page.leaf = true
page = node("batman", "topo")
page.target = call("act_topo")
page.leaf = true
page = node("batman", "graph")
page.target = template("batman_graph")
page.leaf = true
end
function act_vis(mode)
if mode == "server" or mode == "client" or mode == "off" then
luci.sys.call("batctl vm %q >/dev/null" % mode)
luci.http.prepare_content("application/json")
luci.http.write_json(mode)
else
luci.http.status(500, "Bad mode")
end
end
function act_topo(mode)
if not mode or mode == "dot" or mode == "json" then
local fd = io.popen("batctl vd %s" %( mode or "dot" ))
if fd then
if mode == "json" then
luci.http.prepare_content("application/json")
luci.http.write("[")
local ln
repeat
ln = fd:read("*l")
if ln then
luci.http.write(ln)
luci.http.write(", ")
end
until not ln
luci.http.write("{ } ]")
else
luci.http.prepare_content("text/vnd.graphviz")
luci.http.header("Content-Disposition",
"attachment; filename=topo-%s-%s.vd"
%{ luci.sys.hostname(), os.date("%Y%m%d-%H%M%S") })
luci.http.write(fd:read("*a"))
end
fd:close()
else
luci.http.status(500, "No data")
end
else
luci.http.status(500, "Bad mode")
end
end
function act_json()
local v, l, fd
local rv = {
interfaces = { },
originators = { },
gateways = { }
}
--
-- interfaces
--
fd = io.popen("batctl if")
if fd then
repeat
l = fd:read("*l")
v = l and l:match("^(.-):")
if v then
rv.interfaces[#rv.interfaces+1] = v
end
until not l
fd:close()
end
--
-- originators
--
fd = io.popen("batctl o")
if fd then
-- skip header lines
fd:read("*l")
fd:read("*l")
repeat
l = fd:read("*l")
if l then
local m, s, q, n, i = l:match("^ *([^ ]+) +([%d%.]+)s +%( *(%d+)%) +([^ ]+) +%[ *(%S+)%]:")
if m and s and q then
rv.originators[#rv.originators+1] = {
m,
tonumber(s) * 1000,
tonumber(q),
n,
i
}
end
end
until not l
fd:close()
end
--
-- gateways
--
fd = io.popen("batctl gwl")
if fd then
-- skip header line
fd:read("*l")
repeat
l = fd:read("*l")
if l then
local a, m, q, n, i, c, r = l:match("^(%S*) +([^ ]+) +%( *(%d+)%) +([^ ]+) +%[ *(%S+)%]: +(%d+) +- +(%S+)")
if a and m and q and n and i and c and r then
rv.gateways[#rv.gateways+1] = {
#a > 0,
m,
tonumber(q),
n,
i,
tonumber(c),
r
}
end
end
until not l
fd:close()
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2012 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.batman", package.seeall)
local function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
function index()
local page
page = node("admin", "network", "batman")
page.target = template("batman")
page.title = _("BATMAN-Adv")
page.order = 1
node("batman")
page = node("batman", "json")
page.target = call("act_json")
page = node("batman", "vis")
page.target = call("act_vis")
page.leaf = true
page = node("batman", "topo")
page.target = call("act_topo")
page.leaf = true
page = node("batman", "graph")
page.target = template("batman_graph")
page.leaf = true
end
function act_vis(mode)
if mode == "server" or mode == "client" or mode == "off" then
luci.sys.call("batctl vm %q >/dev/null" % mode)
luci.http.prepare_content("application/json")
luci.http.write_json(mode)
else
luci.http.status(500, "Bad mode")
end
end
function act_topo(mode)
if not mode or mode == "dot" or mode == "json" then
local fd = io.popen("batctl vd %s" %( mode or "dot" ))
if fd then
if mode == "json" then
luci.http.prepare_content("application/json")
luci.http.write("[")
local ln
repeat
ln = fd:read("*l")
if ln then
luci.http.write(ln)
luci.http.write(", ")
end
until not ln
luci.http.write("{ } ]")
else
luci.http.prepare_content("text/vnd.graphviz")
luci.http.header("Content-Disposition",
"attachment; filename=topo-%s-%s.vd"
%{ luci.sys.hostname(), os.date("%Y%m%d-%H%M%S") })
luci.http.write(fd:read("*a"))
end
fd:close()
else
luci.http.status(500, "No data")
end
else
luci.http.status(500, "Bad mode")
end
end
function act_json()
local v, l, fd
local rv = {
interfaces = { },
originators = { },
gateways = { }
}
--
-- interfaces
--
fd = io.popen("batctl if")
if fd then
repeat
l = fd:read("*l")
v = l and l:match("^(.-):")
if v then
rv.interfaces[#rv.interfaces+1] = v
end
until not l
fd:close()
end
--
-- originators
--
local originators_command = (
"batctl o -H 2>/dev/null ".. -- gets originators from batctl
"| tr -d '[]()' ".. -- removes brackets and parenthesis
"| sed 's/^ / -/g' ".. -- normalizes output, adding a minus when no asterisk is outputed in each line
"| sed 's/^ //g' ".. -- removes the space from the beginning of the line
"| sed -r 's/\\s+/,/g'".. -- replaces tabs for commas
"| sed -r 's/s,/,/g'" -- removes the 's' from the last_seen field referencing seconds
)
fd = io.popen(originators_command)
if fd then
repeat
l = fd:read()
if l then
local asterisk, originator_name, last_seen, link_quality, next_hop, outgoing_if
asterisk, originator_name, last_seen, link_quality, next_hop, outgoing_if = unpack(split(l, ","))
if originator_name and last_seen and link_quality then
rv.originators[#rv.originators+1] = {
originator_name,
tonumber(last_seen) * 1000,
tonumber(link_quality),
next_hop,
outgoing_if
}
end
end
until not l
fd:close()
end
--
-- gateways
--
fd = io.popen("batctl gwl")
if fd then
-- skip header line
fd:read("*l")
repeat
l = fd:read("*l")
if l then
local a, m, q, n, i, c, r = l:match("^(%S*) +([^ ]+) +%( *(%d+)%) +([^ ]+) +%[ *(%S+)%]: +(%d+) +- +(%S+)")
if a and m and q and n and i and c and r then
rv.gateways[#rv.gateways+1] = {
#a > 0,
m,
tonumber(q),
n,
i,
tonumber(c),
r
}
end
end
until not l
fd:close()
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
|
Fix batman-adv Status WebUI. Closes #110.
|
Fix batman-adv Status WebUI. Closes #110.
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages
|
23fc1676f1140bb75e818e8aae0fb5fd514a5065
|
src/loader/src/LoaderUtils.lua
|
src/loader/src/LoaderUtils.lua
|
---
-- @module LoaderUtils
-- @author Quenty
local loader = script.Parent
local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils)
local GroupInfoUtils = require(script.Parent.GroupInfoUtils)
local PackageInfoUtils = require(script.Parent.PackageInfoUtils)
local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils)
local Utils = require(script.Parent.Utils)
local LoaderUtils = {}
LoaderUtils.Utils = Utils -- TODO: Remove this
LoaderUtils.ContextTypes = Utils.readonly({
CLIENT = "client";
SERVER = "server";
})
LoaderUtils.IncludeBehavior = Utils.readonly({
NO_INCLUDE = "noInclude";
INCLUDE_ONLY = "includeOnly";
INCLUDE_SHARED = "includeShared";
})
function LoaderUtils.toWallyFormat(instance)
assert(typeof(instance) == "Instance", "Bad instance")
local topLevelPackages = {}
LoaderUtils.discoverTopLevelPackages(topLevelPackages, instance)
local packageInfoList = {}
for _, folder in pairs(topLevelPackages) do
local packageInfo = PackageInfoUtils.getOrCreatePackageInfo(folder, {}, "")
table.insert(packageInfoList, packageInfo)
end
PackageInfoUtils.fillDependencySet(packageInfoList)
local clientGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
local serverGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SERVER)
local sharedGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SHARED)
local publishSet = LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local clientFolder = Instance.new("Folder")
clientFolder.Name = "Packages"
local sharedFolder = Instance.new("Folder")
sharedFolder.Name = "SharedPackages"
local serverFolder = Instance.new("Folder")
serverFolder.Name = "Packages"
LoaderUtils.reifyGroupList(clientGroupList, publishSet, clientFolder, ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
LoaderUtils.reifyGroupList(serverGroupList, publishSet, serverFolder, ScriptInfoUtils.ModuleReplicationTypes.SERVER)
LoaderUtils.reifyGroupList(sharedGroupList, publishSet, sharedFolder, ScriptInfoUtils.ModuleReplicationTypes.SHARED)
return clientFolder, serverFolder, sharedFolder
end
function LoaderUtils.isPackage(folder)
assert(typeof(folder) == "Instance", "Bad instance")
for _, item in pairs(folder:GetChildren()) do
if item:IsA("Folder") then
if item.Name == "Server"
or item.Name == "Client"
or item.Name == "Shared"
or item.Name == ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then
return true
end
end
end
return false
end
function LoaderUtils.discoverTopLevelPackages(packages, instance)
assert(type(packages) == "table", "Bad packages")
assert(typeof(instance) == "Instance", "Bad instance")
if LoaderUtils.isPackage(instance) then
table.insert(packages, instance)
else
-- Loop through all folders
for _, item in pairs(instance:GetChildren()) do
if item:IsA("Folder") then
LoaderUtils.discoverTopLevelPackages(packages, item)
end
end
end
end
function LoaderUtils.reifyGroupList(groupInfoList, publishSet, parent, replicationMode)
assert(type(groupInfoList) == "table", "Bad groupInfoList")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = "_Index"
for _, groupInfo in pairs(groupInfoList) do
LoaderUtils.reifyGroup(groupInfo, publishSet, folder, replicationMode)
end
-- Publish
for packageInfo, _ in pairs(publishSet) do
for scriptName, scriptInfo in pairs(packageInfo.scriptInfoLookup[replicationMode]) do
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = parent
end
end
folder.Parent = parent
end
function LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local packageInfoSet = {}
for _, packageInfo in pairs(packageInfoList) do
packageInfoSet[packageInfo] = true
-- First level declared dependencies too (assuming we're importing just one item)
for dependentPackageInfo, _ in pairs(packageInfo.explicitDependencySet) do
packageInfoSet[dependentPackageInfo] = true
end
end
return packageInfoSet
end
function LoaderUtils.reifyGroup(groupInfo, publishSet, parent, replicationMode)
assert(type(groupInfo) == "table", "Bad groupInfo")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = assert(next(groupInfo.packageSet).fullName, "Bad package fullName")
for scriptName, scriptInfo in pairs(groupInfo.packageScriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if scriptInfo.replicationMode == replicationMode then
if scriptInfo.instance == loader and loader.Parent == game:GetService("ReplicatedStorage") then
-- Hack to prevent reparenting of loader in legacy mode
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
else
scriptInfo.instance.Name = scriptName
scriptInfo.instance.Parent = folder
end
else
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
-- Link all of the other dependencies
for scriptName, scriptInfo in pairs(groupInfo.scriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if not groupInfo.packageScriptInfoMap[scriptName] then
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
folder.Parent = parent
end
return LoaderUtils
|
---
-- @module LoaderUtils
-- @author Quenty
local loader = script.Parent
local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils)
local GroupInfoUtils = require(script.Parent.GroupInfoUtils)
local PackageInfoUtils = require(script.Parent.PackageInfoUtils)
local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils)
local Utils = require(script.Parent.Utils)
local LoaderUtils = {}
LoaderUtils.Utils = Utils -- TODO: Remove this
LoaderUtils.ContextTypes = Utils.readonly({
CLIENT = "client";
SERVER = "server";
})
LoaderUtils.IncludeBehavior = Utils.readonly({
NO_INCLUDE = "noInclude";
INCLUDE_ONLY = "includeOnly";
INCLUDE_SHARED = "includeShared";
})
function LoaderUtils.toWallyFormat(instance)
assert(typeof(instance) == "Instance", "Bad instance")
local topLevelPackages = {}
LoaderUtils.discoverTopLevelPackages(topLevelPackages, instance)
local packageInfoList = {}
for _, folder in pairs(topLevelPackages) do
local packageInfo = PackageInfoUtils.getOrCreatePackageInfo(folder, {}, "")
table.insert(packageInfoList, packageInfo)
end
PackageInfoUtils.fillDependencySet(packageInfoList)
local clientGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
local serverGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SERVER)
local sharedGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SHARED)
local publishSet = LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local clientFolder = Instance.new("Folder")
clientFolder.Name = "Packages"
local sharedFolder = Instance.new("Folder")
sharedFolder.Name = "SharedPackages"
local serverFolder = Instance.new("Folder")
serverFolder.Name = "Packages"
LoaderUtils.reifyGroupList(clientGroupList, publishSet, clientFolder, ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
LoaderUtils.reifyGroupList(serverGroupList, publishSet, serverFolder, ScriptInfoUtils.ModuleReplicationTypes.SERVER)
LoaderUtils.reifyGroupList(sharedGroupList, publishSet, sharedFolder, ScriptInfoUtils.ModuleReplicationTypes.SHARED)
return clientFolder, serverFolder, sharedFolder
end
function LoaderUtils.isPackage(folder)
assert(typeof(folder) == "Instance", "Bad instance")
for _, item in pairs(folder:GetChildren()) do
if item:IsA("Folder") then
if item.Name == "Server"
or item.Name == "Client"
or item.Name == "Shared"
or item.Name == ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then
return true
end
end
end
return false
end
function LoaderUtils.discoverTopLevelPackages(packages, instance)
assert(type(packages) == "table", "Bad packages")
assert(typeof(instance) == "Instance", "Bad instance")
if LoaderUtils.isPackage(instance) then
table.insert(packages, instance)
else
-- Loop through all folders
for _, item in pairs(instance:GetChildren()) do
if item:IsA("Folder") then
LoaderUtils.discoverTopLevelPackages(packages, item)
elseif item:IsA("ModuleScript") then
table.insert(packages, item)
end
end
end
end
function LoaderUtils.reifyGroupList(groupInfoList, publishSet, parent, replicationMode)
assert(type(groupInfoList) == "table", "Bad groupInfoList")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = "_Index"
for _, groupInfo in pairs(groupInfoList) do
LoaderUtils.reifyGroup(groupInfo, publishSet, folder, replicationMode)
end
-- Publish
for packageInfo, _ in pairs(publishSet) do
for scriptName, scriptInfo in pairs(packageInfo.scriptInfoLookup[replicationMode]) do
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = parent
end
end
folder.Parent = parent
end
function LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local packageInfoSet = {}
for _, packageInfo in pairs(packageInfoList) do
packageInfoSet[packageInfo] = true
-- First level declared dependencies too (assuming we're importing just one item)
for dependentPackageInfo, _ in pairs(packageInfo.explicitDependencySet) do
packageInfoSet[dependentPackageInfo] = true
end
end
return packageInfoSet
end
function LoaderUtils.reifyGroup(groupInfo, publishSet, parent, replicationMode)
assert(type(groupInfo) == "table", "Bad groupInfo")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = assert(next(groupInfo.packageSet).fullName, "Bad package fullName")
for scriptName, scriptInfo in pairs(groupInfo.packageScriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if scriptInfo.replicationMode == replicationMode then
if scriptInfo.instance == loader and loader.Parent == game:GetService("ReplicatedStorage") then
-- Hack to prevent reparenting of loader in legacy mode
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
else
scriptInfo.instance.Name = scriptName
scriptInfo.instance.Parent = folder
end
else
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
-- Link all of the other dependencies
for scriptName, scriptInfo in pairs(groupInfo.scriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if not groupInfo.packageScriptInfoMap[scriptName] then
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
folder.Parent = parent
end
return LoaderUtils
|
fix: Discover top level module scripts
|
fix: Discover top level module scripts
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
f67e2eb2186e363d6f7249a18daf6501bc9066b2
|
modules/title/sites/komplett.lua
|
modules/title/sites/komplett.lua
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local trim = function(s)
if(not s) then return end
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local handler = function(queue, info)
local query = info.query
local path = info.path
if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then
simplehttp(
info.url,
function(data, url, response)
local ins = function(out, fmt, ...)
for i=1, select('#', ...) do
local val = select(i, ...)
if(type(val) == 'nil' or val == -1) then
return
end
end
table.insert(
out,
string.format(fmt, ...)
)
end
local out = {}
local name = data:match('<h1 class="main%-header" itemprop="name">([^<]+)</h1>')
local desc = data:match('<h3 class="secondary%-header" itemprop="description">([^<]+)</h3>')
local price = data:match('<span itemprop="price"[^>]+>([^<]+)</span>')
local storage = data:match('<span class="stock%-details">(.-)</span>')
local bomb = data:match('<div class="bomb">.-<div class="value">([^<]+)</div>')
ins(out, '\002%s\002: ', html2unicode(name))
if(desc) then
ins(out, '%s ,', html2unicode(desc))
end
if(price) then
ins(out, '\002%s\002 ', trim(price))
end
local extra = {}
if(bomb) then
bomb = trim(bomb)
if(bomb:sub(1, 1) == '-') then
bomb = bomb:sub(2)
end
ins(extra, '%s off', bomb)
end
if(storage) then
storage = html2unicode(storage)
storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', ''))
if(storage:sub(-1) == '.') then
storage = storage:sub(1, -2)
end
ins(extra, '%s', storage)
end
if(#extra > 0) then
ins(out, '(%s)', table.concat(extra, ', '))
end
queue:done(table.concat(out, ''))
end
)
return true
end
end
customHosts['komplett%.no'] = handler
customHosts['komplett%.dk'] = handler
customHosts['komplett%.se'] = handler
customHosts['inwarehouse%.se'] = handler
customHosts['mpx%.no'] = handler
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local trim = function(s)
if(not s) then return end
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local handler = function(queue, info)
local query = info.query
local path = info.path
if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then
simplehttp(
info.url,
function(data, url, response)
local ins = function(out, fmt, ...)
for i=1, select('#', ...) do
local val = select(i, ...)
if(type(val) == 'nil' or val == -1) then
return
end
end
table.insert(
out,
string.format(fmt, ...)
)
end
local out = {}
local name = data:match('<h1 class="product%-main%-info%-webtext1" itemprop="name">([^<]+)</h1>')
local desc = data:match('<h2 class="product%-main%-info%-webtext2" itemprop="description">([^<]+)</h2>')
local price = data:match('<span class="product%-price%-now" itemprop=price content=.->([^<]+)</span>')
local storage = data:match('<span class="stockstatus%-stock%-details">([^<]+)</span>')
local bomb = data:match('<span.-class="prodpage-discount-label".->([^<]+)</span>')
ins(out, '\002%s\002: ', html2unicode(trim(name)))
if(desc) then
ins(out, '%s ,', html2unicode(trim(desc)))
end
if(price) then
ins(out, '\002%s\002 ', trim(price))
end
local extra = {}
if(bomb) then
bomb = trim(bomb)
if(bomb:sub(1, 1) == '-') then
bomb = bomb:sub(2)
end
ins(extra, '%s off', bomb)
end
if(storage) then
storage = html2unicode(storage)
storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', ''))
if(storage:sub(-1) == '.') then
storage = storage:sub(1, -2)
end
ins(extra, '%s', storage)
end
if(#extra > 0) then
ins(out, '(%s)', table.concat(extra, ', '))
end
queue:done(table.concat(out, ''))
end
)
return true
end
end
customHosts['komplett%.no'] = handler
customHosts['komplett%.dk'] = handler
customHosts['komplett%.se'] = handler
customHosts['inwarehouse%.se'] = handler
customHosts['mpx%.no'] = handler
|
title/komplett: fix site plugin
|
title/komplett: fix site plugin
Former-commit-id: 725954cf0e1c12e50b996d1d5bc825da188ff946 [formerly a37ddb1b49896cb6d1ba7865b808a8bb6e977f3c]
Former-commit-id: f29b209a8374ec4e2b4ab98aa28971f29c85eea3
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
aefc9f6767564437db7bdb8b55d43a46e921141d
|
lib/core/src/togo/core/utility/utility.lua
|
lib/core/src/togo/core/utility/utility.lua
|
u8R""__RAW_STRING__(
togo = togo or {}
togo.utility = togo.utility or {}
local M = togo.utility
M.debug = false
function M.ternary(cond, x, y)
return (cond)
and x
or y
end
function M.optional(value, default)
return (value ~= nil) and value or default
end
function M.optional_in(table, name, default)
M.type_assert(table, "table")
M.type_assert(name, "string")
table[name] = M.optional(table[name], default)
return table[name]
end
function M.type_class(x)
local t = type(x)
if t == "table" then
local mt = getmetatable(x)
if mt then
return mt
end
end
return t
end
function M.is_type(x, tc, basic)
return basic and type(x) == tc or M.type_class(x) == tc
end
function M.is_type_any(x, types, opt)
M.type_assert(types, "table")
if opt and x == nil then
return true
end
local xt = M.type_class(x)
for _, t in pairs(types) do
if xt == t then
return true
end
end
return false
end
function M.is_instance(x, of)
if type(x) == "table" then
local mt = getmetatable(x)
if mt then
if of then
return mt == of
else
return mt == rawget(mt, "__index")
end
end
end
return false
end
function M.get_trace(level)
local info = debug.getinfo(level + 2, "Sl")
-- return M.pad_left(info.short_src, 28) .. " @ " .. M.pad_right(tostring(info.currentline), 4)
return info.short_src .. " @ " .. M.pad_right(tostring(info.currentline), 4)
end
function M.assertl(level, e, msg, ...)
if not e then
error(M.get_trace(level + 1) .. ": assertion failed: " .. string.format(msg or "<expression>", ...), 0)
end
end
function M.assert(e, msg, ...)
M.assertl(1, e, msg, ...)
end
function M.type_assert(x, tc, opt, level)
level = M.optional(level, 0)
M.assertl(
level + 1,
(opt and x == nil) or M.is_type(x, tc),
"utility.type_assert: '%s' (a %s) is not of type %s",
tostring(x), tostring(type(x)), tostring(tc)
)
return x
end
function M.type_assert_any(x, types, opt, level)
M.type_assert(types, "table")
level = M.optional(level, 0)
if opt and x == nil then
return x
end
local xt = M.type_class(x)
for _, t in pairs(types) do
if xt == t then
return x
end
end
M.assertl(
level + 1, false,
"utility.type_assert_any: '%s' (a %s) is not of any types specified",
tostring(x), tostring(type(x))
)
return x
end
function M.table_last(table, allow_empty)
M.assert(#table > 0 or allow_empty)
return table[#table]
end
function M.table_add(a, b)
M.type_assert(a, "table")
M.type_assert(b, "table")
for k, v in pairs(b) do
a[k] = v
end
end
function M.table_ijoined(...)
local r = {}
for _, t in ipairs({...}) do
M.type_assert(t, "table")
for _, v in ipairs(t) do
table.insert(r, v)
end
end
return r
end
function M.table_inverse(t, value)
local it = {}
for k, v in pairs(t) do
it[v] = value or k
end
return it
end
function M.table_keys(t)
local kt = {}
for k, _ in pairs(t) do
table.insert(kt, k)
end
return kt
end
function M.pad_left(str, length)
if #str < length then
while #str < length do
str = str .. ' '
end
end
return str
end
function M.pad_right(str, length)
if #str < length then
while #str < length do
str = ' ' .. str
end
end
return str
end
function M.trace()
print(M.get_trace(1) .. ": TRACE")
end
function M.print(msg, ...)
M.type_assert(msg, "string")
print(string.format(msg, ...))
end
function M.log(msg, ...)
M.type_assert(msg, "string")
print(M.get_trace(1) .. ": " .. string.format(msg, ...))
end
function M.log_debug_closure(m)
return function(msg, ...)
M.type_assert(msg, "string")
if m.debug then
print(M.get_trace(1) .. ": debug: " .. string.format(msg, ...))
end
end
end
M.log_debug = M.log_debug_closure(M)
function M.min(x, y)
return x < y and x or y
end
function M.max(x, y)
return x > y and x or y
end
function M.clamp(x, min, max)
return x < min and min or x > max and max or x
end
local BYTE_FSLASH = string.byte('/', 1)
local BYTE_BSLASH = string.byte('\\', 1)
local BYTE_DOT = string.byte('.', 1)
function M.trim_leading_slashes(s)
local b
for i = 1, #s do
b = string.byte(s, i)
if b ~= BYTE_FSLASH and b ~= BYTE_BSLASH then
return string.sub(s, i, -1)
end
end
return s
end
function M.trim_trailing_slashes(s)
local b
for i = #s, 1, -1 do
b = string.byte(s, i)
if b ~= BYTE_FSLASH and b ~= BYTE_BSLASH then
return string.sub(s, 1, i)
end
end
return s
end
function M.trim_slashes(s)
return M.trim_leading_slashes(M.trim_trailing_slashes(s))
end
-- a/b/c -> a
-- a -> nil
function M.rootname(s)
M.type_assert(s, "string")
for i = 1, #s do
if string.byte(s, i) == BYTE_FSLASH then
return string.sub(s, 1, i - 1)
end
end
return nil
end
function M.strip_extension(s)
M.type_assert(s, "string")
local b = nil
for i = #s, 1, -1 do
b = string.byte(s, i)
if b == BYTE_FSLASH then
break
elseif b == BYTE_DOT then
return string.sub(s, 1, i - 1)
end
end
return s
end
function M.file_extension(s)
M.type_assert(s, "string")
local b
for i = #s, 1, -1 do
b = string.byte(s, i)
if b == BYTE_FSLASH then
break
elseif b == BYTE_DOT then
return string.sub(s, i + 1, #s)
end
end
return nil
end
function M.join_paths(...)
local parts = {...}
local path = ""
for i, p in ipairs(parts) do
M.type_assert(p, "string")
path = path .. p
if i ~= #parts then
path = path .. "/"
end
end
return path
end
function M.set_functable(t, func)
if not t.__class_static then
t.__class_static = {}
t.__class_static.__index = t.__class_static
setmetatable(t, t.__class_static)
end
t.__class_static.__call = func
end
function M.is_functable(x)
local mt = getmetatable(x)
return mt and mt.__call ~= nil
end
function M.class(c)
if c == nil then
c = {}
end
c.__index = c
M.set_functable(c, function(c, ...)
local obj = {}
setmetatable(obj, c)
obj:__init(...)
return obj
end)
return c
end
function M.module(name)
M.type_assert(name, "string")
local m = _G
for p in string.gmatch(name, "([^.]+)%.?") do
if not m[p] then
m[p] = {}
end
m = m[p]
end
m._NAME = name
m._M = m
return m
end
return M
)"__RAW_STRING__"
|
u8R""__RAW_STRING__(
togo = togo or {}
togo.utility = togo.utility or {}
local M = togo.utility
M.debug = false
function M.ternary(cond, x, y)
return (cond)
and x
or y
end
function M.optional(value, default)
if (value ~= nil) then
return value
end
return default
end
function M.optional_in(table, name, default)
M.type_assert(table, "table")
M.type_assert(name, "string")
table[name] = M.optional(table[name], default)
return table[name]
end
function M.type_class(x)
local t = type(x)
if t == "table" then
local mt = getmetatable(x)
if mt then
return mt
end
end
return t
end
function M.is_type(x, tc, basic)
return basic and type(x) == tc or M.type_class(x) == tc
end
function M.is_type_any(x, types, opt)
M.type_assert(types, "table")
if opt and x == nil then
return true
end
local xt = M.type_class(x)
for _, t in pairs(types) do
if xt == t then
return true
end
end
return false
end
function M.is_instance(x, of)
if type(x) == "table" then
local mt = getmetatable(x)
if mt then
if of then
return mt == of
else
return mt == rawget(mt, "__index")
end
end
end
return false
end
function M.get_trace(level)
local info = debug.getinfo(level + 2, "Sl")
-- return M.pad_left(info.short_src, 28) .. " @ " .. M.pad_right(tostring(info.currentline), 4)
return info.short_src .. " @ " .. M.pad_right(tostring(info.currentline), 4)
end
function M.assertl(level, e, msg, ...)
if not e then
error(M.get_trace(level + 1) .. ": assertion failed: " .. string.format(msg or "<expression>", ...), 0)
end
end
function M.assert(e, msg, ...)
M.assertl(1, e, msg, ...)
end
function M.type_assert(x, tc, opt, level)
level = M.optional(level, 0)
M.assertl(
level + 1,
(opt and x == nil) or M.is_type(x, tc),
"utility.type_assert: '%s' (a %s) is not of type %s",
tostring(x), tostring(type(x)), tostring(tc)
)
return x
end
function M.type_assert_any(x, types, opt, level)
M.type_assert(types, "table")
level = M.optional(level, 0)
if opt and x == nil then
return x
end
local xt = M.type_class(x)
for _, t in pairs(types) do
if xt == t then
return x
end
end
M.assertl(
level + 1, false,
"utility.type_assert_any: '%s' (a %s) is not of any types specified",
tostring(x), tostring(type(x))
)
return x
end
function M.table_last(table, allow_empty)
M.assert(#table > 0 or allow_empty)
return table[#table]
end
function M.table_add(a, b)
M.type_assert(a, "table")
M.type_assert(b, "table")
for k, v in pairs(b) do
a[k] = v
end
end
function M.table_ijoined(...)
local r = {}
for _, t in ipairs({...}) do
M.type_assert(t, "table")
for _, v in ipairs(t) do
table.insert(r, v)
end
end
return r
end
function M.table_inverse(t, value)
local it = {}
for k, v in pairs(t) do
it[v] = value or k
end
return it
end
function M.table_keys(t)
local kt = {}
for k, _ in pairs(t) do
table.insert(kt, k)
end
return kt
end
function M.pad_left(str, length)
if #str < length then
while #str < length do
str = str .. ' '
end
end
return str
end
function M.pad_right(str, length)
if #str < length then
while #str < length do
str = ' ' .. str
end
end
return str
end
function M.trace()
print(M.get_trace(1) .. ": TRACE")
end
function M.print(msg, ...)
M.type_assert(msg, "string")
print(string.format(msg, ...))
end
function M.log(msg, ...)
M.type_assert(msg, "string")
print(M.get_trace(1) .. ": " .. string.format(msg, ...))
end
function M.log_debug_closure(m)
return function(msg, ...)
M.type_assert(msg, "string")
if m.debug then
print(M.get_trace(1) .. ": debug: " .. string.format(msg, ...))
end
end
end
M.log_debug = M.log_debug_closure(M)
function M.min(x, y)
return x < y and x or y
end
function M.max(x, y)
return x > y and x or y
end
function M.clamp(x, min, max)
return x < min and min or x > max and max or x
end
local BYTE_FSLASH = string.byte('/', 1)
local BYTE_BSLASH = string.byte('\\', 1)
local BYTE_DOT = string.byte('.', 1)
function M.trim_leading_slashes(s)
local b
for i = 1, #s do
b = string.byte(s, i)
if b ~= BYTE_FSLASH and b ~= BYTE_BSLASH then
return string.sub(s, i, -1)
end
end
return s
end
function M.trim_trailing_slashes(s)
local b
for i = #s, 1, -1 do
b = string.byte(s, i)
if b ~= BYTE_FSLASH and b ~= BYTE_BSLASH then
return string.sub(s, 1, i)
end
end
return s
end
function M.trim_slashes(s)
return M.trim_leading_slashes(M.trim_trailing_slashes(s))
end
-- a/b/c -> a
-- a -> nil
function M.rootname(s)
M.type_assert(s, "string")
for i = 1, #s do
if string.byte(s, i) == BYTE_FSLASH then
return string.sub(s, 1, i - 1)
end
end
return nil
end
function M.strip_extension(s)
M.type_assert(s, "string")
local b = nil
for i = #s, 1, -1 do
b = string.byte(s, i)
if b == BYTE_FSLASH then
break
elseif b == BYTE_DOT then
return string.sub(s, 1, i - 1)
end
end
return s
end
function M.file_extension(s)
M.type_assert(s, "string")
local b
for i = #s, 1, -1 do
b = string.byte(s, i)
if b == BYTE_FSLASH then
break
elseif b == BYTE_DOT then
return string.sub(s, i + 1, #s)
end
end
return nil
end
function M.join_paths(...)
local parts = {...}
local path = ""
for i, p in ipairs(parts) do
M.type_assert(p, "string")
path = path .. p
if i ~= #parts then
path = path .. "/"
end
end
return path
end
function M.set_functable(t, func)
if not t.__class_static then
t.__class_static = {}
t.__class_static.__index = t.__class_static
setmetatable(t, t.__class_static)
end
t.__class_static.__call = func
end
function M.is_functable(x)
local mt = getmetatable(x)
return mt and mt.__call ~= nil
end
function M.class(c)
if c == nil then
c = {}
end
c.__index = c
M.set_functable(c, function(c, ...)
local obj = {}
setmetatable(obj, c)
obj:__init(...)
return obj
end)
return c
end
function M.module(name)
M.type_assert(name, "string")
local m = _G
for p in string.gmatch(name, "([^.]+)%.?") do
if not m[p] then
m[p] = {}
end
m = m[p]
end
m._NAME = name
m._M = m
return m
end
return M
)"__RAW_STRING__"
|
lib/core/utility/utility.lua: fixed optional() for boolean types.
|
lib/core/utility/utility.lua: fixed optional() for boolean types.
|
Lua
|
mit
|
komiga/togo,komiga/togo,komiga/togo
|
83afb04b542d13dc542322afb78e9cd0f61f1fd3
|
test/unit/modules/graphics.lua
|
test/unit/modules/graphics.lua
|
function lutro.keyboard.setBackgroundColorTest()
red = 115
green = 27
blue = 135
alpha = 50
color = { red, green, blue, alpha }
lutro.graphics.setBackgroundColor(color)
lutro.graphics.setBackgroundColor(red, green, blue, alpha)
end
function lutro.keyboard.getBackgroundColorTest()
r, g, b, a = lutro.graphics.getBackgroundColor()
unit.assertEquals(r, 115)
unit.assertEquals(g, 27)
unit.assertEquals(b, 135)
unit.assertEquals(a, 50)
end
return {
lutro.keyboard.setBackgroundColorTest,
lutro.keyboard.getBackgroundColorTest
}
|
function lutro.graphics.setBackgroundColorTest()
red = 115
green = 27
blue = 135
alpha = 50
color = { red, green, blue, alpha }
lutro.graphics.setBackgroundColor(color)
lutro.graphics.setBackgroundColor(red, green, blue, alpha)
end
function lutro.graphics.getBackgroundColorTest()
r, g, b, a = lutro.graphics.getBackgroundColor()
unit.assertEquals(r, 115)
unit.assertEquals(g, 27)
unit.assertEquals(b, 135)
unit.assertEquals(a, 50)
end
return {
lutro.graphics.setBackgroundColorTest,
lutro.graphics.getBackgroundColorTest
}
|
Fix lutro.keyboard to be lutro.graphics in the unit tests
|
Fix lutro.keyboard to be lutro.graphics in the unit tests
|
Lua
|
mit
|
libretro/libretro-lutro,libretro/libretro-lutro,libretro/libretro-lutro
|
5c27e60f0bb5edf6bcbce419ad239d6470ac481c
|
orange/utils/headers.lua
|
orange/utils/headers.lua
|
--
-- Created by IntelliJ IDEA.
-- User: soul11201 <[email protected]>
-- Date: 2017/4/26
-- Time: 20:50
-- To change this template use File | Settings | File Templates.
--
local handle_util = require("orange.utils.handle")
local extractor_util = require("orange.utils.extractor")
local _M = {}
local function set_header(k,v,overide)
local override = overide or false
end
function _M:set_headers(rule)
local extractor,headers_config= rule.extractor,rule.headers
local variables = extractor_util.extract_variables(extractor)
local req_headers = ngx.req.get_headers();
for _, v in pairs(headers_config) do
-- 不存在 || 存在且覆蓋
ngx.log(ngx.ERR,v.name,v.value);
if not req_headers[v.name] or v.override == '1' then
if v.type == "normal" then
ngx.req.set_header(v.name,v.value)
ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']')
elseif v.type == "extraction" then
local value = handle_util.build_uri(extractor.type, v.value, variables)
ngx.req.set_header(v.name,value)
ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",value,']')
end
end
end
end
return _M
|
--
-- Created by IntelliJ IDEA.
-- User: soul11201 <[email protected]>
-- Date: 2017/4/26
-- Time: 20:50
-- To change this template use File | Settings | File Templates.
--
local handle_util = require("orange.utils.handle")
local extractor_util = require("orange.utils.extractor")
local _M = {}
local function set_header(k,v,overide)
local override = overide or false
end
function _M:set_headers(rule)
local extractor,headers_config= rule.extractor,rule.headers
if not headers_config or type(headers_config) ~= 'table' then
return
end
local variables = extractor_util.extract_variables(extractor)
local req_headers = ngx.req.get_headers();
for _, v in pairs(headers_config) do
-- 不存在 || 存在且覆蓋
ngx.log(ngx.ERR,v.name,v.value);
if not req_headers[v.name] or v.override == '1' then
if v.type == "normal" then
ngx.req.set_header(v.name,v.value)
ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']')
elseif v.type == "extraction" then
local value = handle_util.build_uri(extractor.type, v.value, variables)
ngx.req.set_header(v.name,value)
ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",value,']')
end
end
end
end
return _M
|
fix: headers.lua check the config type of header
|
fix: headers.lua check the config type of header
|
Lua
|
mit
|
thisverygoodhhhh/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange
|
726062b5a31073c095c4b37b772035714bd3db43
|
core/presencemanager.lua
|
core/presencemanager.lua
|
local log = require "util.logger".init("presencemanager")
local require = require;
local pairs = pairs;
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local hosts = hosts;
local rostermanager = require "core.rostermanager";
local sessionmanager = require "core.sessionmanager";
module "presencemanager"
function send_presence_of_available_resources(user, host, jid, recipient_session)
local h = hosts[host];
local count = 0;
if h and h.type == "local" then
local u = h.sessions[user];
if u then
for k, session in pairs(u.sessions) do
local pres = session.presence;
if pres then
pres.attr.to = jid;
pres.attr.from = session.full_jid;
recipient_session.send(pres);
pres.attr.to = nil;
pres.attr.from = nil;
count = count + 1;
end
end
end
end
return count;
end
function handle_outbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
local node, host = jid_split(from_bare);
local st_from, st_to = stanza.attr.from, stanza.attr.to;
stanza.attr.from, stanza.attr.to = from_bare, to_bare;
log("debug", "outbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
if stanza.attr.type == "subscribe" then
-- 1. route stanza
-- 2. roster push (subscription = none, ask = subscribe)
if rostermanager.set_contact_pending_out(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
end -- else file error
core_route_stanza(origin, stanza);
elseif stanza.attr.type == "unsubscribe" then
-- 1. route stanza
-- 2. roster push (subscription = none or from)
if rostermanager.unsubscribe(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare); -- FIXME do roster push when roster has in fact not changed?
end -- else file error
core_route_stanza(origin, stanza);
elseif stanza.attr.type == "subscribed" then
-- 1. route stanza
-- 2. roster_push ()
-- 3. send_presence_of_available_resources
if rostermanager.subscribed(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
core_route_stanza(origin, stanza);
send_presence_of_available_resources(node, host, to_bare, origin);
end
elseif stanza.attr.type == "unsubscribed" then
-- 1. route stanza
-- 2. roster push (subscription = none or to)
if rostermanager.unsubscribed(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
core_route_stanza(origin, stanza);
end
end
stanza.attr.from, stanza.attr.to = st_from, st_to;
end
function handle_inbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
local node, host = jid_split(to_bare);
local st_from, st_to = stanza.attr.from, stanza.attr.to;
stanza.attr.from, stanza.attr.to = from_bare, to_bare;
log("debug", "inbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
if stanza.attr.type == "probe" then
if rostermanager.is_contact_subscribed(node, host, from_bare) then
if 0 == send_presence_of_available_resources(node, host, from_bare, origin) then
-- TODO send last recieved unavailable presence (or we MAY do nothing, which is fine too)
end
else
core_route_stanza(origin, st.presence({from=to_bare, to=from_bare, type="unsubscribed"}));
end
elseif stanza.attr.type == "subscribe" then
if rostermanager.is_contact_subscribed(node, host, from_bare) then
core_route_stanza(origin, st.presence({from=to_bare, to=from_bare, type="subscribed"})); -- already subscribed
else
if not rostermanager.is_contact_pending_in(node, host, from_bare) then
if rostermanager.set_contact_pending_in(node, host, from_bare) then
sessionmanager.send_to_available_resources(node, host, stanza);
end -- TODO else return error, unable to save
end
end
elseif stanza.attr.type == "unsubscribe" then
if rostermanager.process_inbound_unsubscribe(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
elseif stanza.attr.type == "subscribed" then
if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
elseif stanza.attr.type == "unsubscribed" then
if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
end -- discard any other type
stanza.attr.from, stanza.attr.to = st_from, st_to;
end
return _M;
|
local log = require "util.logger".init("presencemanager")
local require = require;
local pairs = pairs;
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local hosts = hosts;
local rostermanager = require "core.rostermanager";
local sessionmanager = require "core.sessionmanager";
module "presencemanager"
function send_presence_of_available_resources(user, host, jid, recipient_session, core_route_stanza)
local h = hosts[host];
local count = 0;
if h and h.type == "local" then
local u = h.sessions[user];
if u then
for k, session in pairs(u.sessions) do
local pres = session.presence;
if pres then
pres.attr.to = jid;
pres.attr.from = session.full_jid;
core_route_stanza(recipient_session, pres);
pres.attr.to = nil;
pres.attr.from = nil;
count = count + 1;
end
end
end
end
return count;
end
function handle_outbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
local node, host = jid_split(from_bare);
local st_from, st_to = stanza.attr.from, stanza.attr.to;
stanza.attr.from, stanza.attr.to = from_bare, to_bare;
log("debug", "outbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
if stanza.attr.type == "subscribe" then
-- 1. route stanza
-- 2. roster push (subscription = none, ask = subscribe)
if rostermanager.set_contact_pending_out(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
end -- else file error
core_route_stanza(origin, stanza);
elseif stanza.attr.type == "unsubscribe" then
-- 1. route stanza
-- 2. roster push (subscription = none or from)
if rostermanager.unsubscribe(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare); -- FIXME do roster push when roster has in fact not changed?
end -- else file error
core_route_stanza(origin, stanza);
elseif stanza.attr.type == "subscribed" then
-- 1. route stanza
-- 2. roster_push ()
-- 3. send_presence_of_available_resources
if rostermanager.subscribed(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
core_route_stanza(origin, stanza);
send_presence_of_available_resources(node, host, to_bare, origin, core_route_stanza);
end
elseif stanza.attr.type == "unsubscribed" then
-- 1. route stanza
-- 2. roster push (subscription = none or to)
if rostermanager.unsubscribed(node, host, to_bare) then
rostermanager.roster_push(node, host, to_bare);
core_route_stanza(origin, stanza);
end
end
stanza.attr.from, stanza.attr.to = st_from, st_to;
end
function handle_inbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
local node, host = jid_split(to_bare);
local st_from, st_to = stanza.attr.from, stanza.attr.to;
stanza.attr.from, stanza.attr.to = from_bare, to_bare;
log("debug", "inbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
if stanza.attr.type == "probe" then
if rostermanager.is_contact_subscribed(node, host, from_bare) then
if 0 == send_presence_of_available_resources(node, host, from_bare, origin, core_route_stanza) then
-- TODO send last recieved unavailable presence (or we MAY do nothing, which is fine too)
end
else
core_route_stanza(origin, st.presence({from=to_bare, to=from_bare, type="unsubscribed"}));
end
elseif stanza.attr.type == "subscribe" then
if rostermanager.is_contact_subscribed(node, host, from_bare) then
core_route_stanza(origin, st.presence({from=to_bare, to=from_bare, type="subscribed"})); -- already subscribed
else
if not rostermanager.is_contact_pending_in(node, host, from_bare) then
if rostermanager.set_contact_pending_in(node, host, from_bare) then
sessionmanager.send_to_available_resources(node, host, stanza);
end -- TODO else return error, unable to save
end
end
elseif stanza.attr.type == "unsubscribe" then
if rostermanager.process_inbound_unsubscribe(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
elseif stanza.attr.type == "subscribed" then
if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
elseif stanza.attr.type == "unsubscribed" then
if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
rostermanager.roster_push(node, host, from_bare);
end
end -- discard any other type
stanza.attr.from, stanza.attr.to = st_from, st_to;
end
return _M;
|
Fix for broadcasting presence of available resources to newly approved contact
|
Fix for broadcasting presence of available resources to newly approved contact
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
005aed184924685a87c5866fc4b0c353be0483bb
|
packages/unichar.lua
|
packages/unichar.lua
|
local function utf8encode(code)
if code < 0 then
error('Code point must not be negative.')
elseif code <= 0x7f then
return string.char(code)
elseif code <= 0x7ff then
local c1 = code / 64 + 192
local c2 = code % 64 + 128
return string.char(c1, c2)
elseif code <= 0xffff then
local c1 = code / 4096 + 224
local c2 = code % 4096 / 64 + 128
local c3 = code % 64 + 128
return string.char(c1, c2, c3)
elseif code <= 0x10ffff then
local c1 = code / 262144 + 240
local c2 = code % 262144 / 4096 + 128
local c3 = code % 4096 / 64 + 128
local c4 = code % 64 + 128
return string.char(c1, c2, c3, c4)
end
return ''
end
SILE.registerCommand("unichar", function(options, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
hex = (cp:match("[Uu]%+(%x+)") or cp:match("0[xX](%x+)"))
if hex then
cp = tonumber("0x"..hex)
elseif tonumber(cp) then
cp = tonumber(cp)
end
SILE.typesetter:typeset(utf8encode(cp))
end)
return { documentation = [[\begin{document}
\script[src=packages/unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges
of the fonts that SILE is using to typeset.) Some Unicode characters are hard to
locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \code{unichar} package helps with this problem by providing a command to enter
Unicode codepoints. After loading \code{unichar}, the \code{\\unichar} command becomes
available:
\begin{verbatim}
\line
\\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}}
\line
\end{verbatim}
If the argument to \code{\\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X},
then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a
decimal codepoint.
\end{document}]] }
|
SILE.registerCommand("unichar", function(options, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
hex = (cp:match("[Uu]%+(%x+)") or cp:match("0[xX](%x+)"))
if hex then
cp = tonumber("0x"..hex)
elseif tonumber(cp) then
cp = tonumber(cp)
end
SILE.typesetter:typeset(SU.utf8char(cp))
end)
return { documentation = [[\begin{document}
\script[src=packages/unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges
of the fonts that SILE is using to typeset.) Some Unicode characters are hard to
locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \code{unichar} package helps with this problem by providing a command to enter
Unicode codepoints. After loading \code{unichar}, the \code{\\unichar} command becomes
available:
\begin{verbatim}
\line
\\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}}
\line
\end{verbatim}
If the argument to \code{\\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X},
then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a
decimal codepoint.
\end{document}]] }
|
Simplify the code, and fix #112. I love it.
|
Simplify the code, and fix #112. I love it.
|
Lua
|
mit
|
neofob/sile,simoncozens/sile,neofob/sile,anthrotype/sile,WAKAMAZU/sile_fe,anthrotype/sile,simoncozens/sile,alerque/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,alerque/sile,alerque/sile,neofob/sile,neofob/sile,anthrotype/sile,simoncozens/sile,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,anthrotype/sile
|
8d78b6ef684ab463b147d6a0f9a3be31a794e82a
|
tests/config/test_links.lua
|
tests/config/test_links.lua
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
--
-- If fetching directories, the libdirs should be included in the result.
--
function suite.includesLibDirs_onDirectories()
libdirs { "../libs" }
local r = prepare("all", "directory")
test.isequal({ "../libs" }, r)
end
|
Added test for libdirs fix
|
Added test for libdirs fix
|
Lua
|
bsd-3-clause
|
jsfdez/premake-core,premake/premake-core,mandersan/premake-core,CodeAnxiety/premake-core,noresources/premake-core,Yhgenomics/premake-core,lizh06/premake-core,dcourtois/premake-core,Yhgenomics/premake-core,noresources/premake-core,alarouche/premake-core,dcourtois/premake-core,noresources/premake-core,premake/premake-core,resetnow/premake-core,aleksijuvani/premake-core,noresources/premake-core,premake/premake-core,tvandijck/premake-core,akaStiX/premake-core,soundsrc/premake-core,xriss/premake-core,aleksijuvani/premake-core,prapin/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,Tiger66639/premake-core,noresources/premake-core,grbd/premake-core,lizh06/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,noresources/premake-core,resetnow/premake-core,LORgames/premake-core,mandersan/premake-core,PlexChat/premake-core,mandersan/premake-core,lizh06/premake-core,Blizzard/premake-core,kankaristo/premake-core,soundsrc/premake-core,Meoo/premake-core,Meoo/premake-core,akaStiX/premake-core,alarouche/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,premake/premake-core,prapin/premake-core,mandersan/premake-core,Blizzard/premake-core,PlexChat/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,starkos/premake-core,soundsrc/premake-core,resetnow/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,saberhawk/premake-core,TurkeyMan/premake-core,starkos/premake-core,Blizzard/premake-core,LORgames/premake-core,premake/premake-core,resetnow/premake-core,Tiger66639/premake-core,grbd/premake-core,tvandijck/premake-core,dcourtois/premake-core,kankaristo/premake-core,xriss/premake-core,felipeprov/premake-core,soundsrc/premake-core,jsfdez/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,PlexChat/premake-core,noresources/premake-core,jstewart-amd/premake-core,xriss/premake-core,TurkeyMan/premake-core,xriss/premake-core,martin-traverse/premake-core,alarouche/premake-core,mendsley/premake-core,akaStiX/premake-core,dcourtois/premake-core,tritao/premake-core,premake/premake-core,martin-traverse/premake-core,lizh06/premake-core,aleksijuvani/premake-core,Meoo/premake-core,kankaristo/premake-core,jstewart-amd/premake-core,martin-traverse/premake-core,sleepingwit/premake-core,jsfdez/premake-core,TurkeyMan/premake-core,jstewart-amd/premake-core,mendsley/premake-core,bravnsgaard/premake-core,mandersan/premake-core,Tiger66639/premake-core,soundsrc/premake-core,saberhawk/premake-core,LORgames/premake-core,starkos/premake-core,starkos/premake-core,felipeprov/premake-core,CodeAnxiety/premake-core,felipeprov/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,saberhawk/premake-core,felipeprov/premake-core,tvandijck/premake-core,mendsley/premake-core,akaStiX/premake-core,alarouche/premake-core,sleepingwit/premake-core,jsfdez/premake-core,Blizzard/premake-core,Yhgenomics/premake-core,dcourtois/premake-core,tritao/premake-core,xriss/premake-core,saberhawk/premake-core,tvandijck/premake-core,dcourtois/premake-core,starkos/premake-core,prapin/premake-core,starkos/premake-core,tritao/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,kankaristo/premake-core,martin-traverse/premake-core,jstewart-amd/premake-core,grbd/premake-core,TurkeyMan/premake-core,tritao/premake-core,mendsley/premake-core,prapin/premake-core,grbd/premake-core,Zefiros-Software/premake-core,CodeAnxiety/premake-core,Meoo/premake-core,sleepingwit/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,bravnsgaard/premake-core,PlexChat/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,resetnow/premake-core,starkos/premake-core,premake/premake-core,mendsley/premake-core
|
17d9298b10c17e2bda7a9f5f7b139b42b466c9f5
|
game/scripts/vscripts/heroes/hero_saitama/modifier_saitama_limiter.lua
|
game/scripts/vscripts/heroes/hero_saitama/modifier_saitama_limiter.lua
|
modifier_saitama_limiter = class({
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
GetTexture = function() return "arena/modifier_saitama_limiter" end,
})
function modifier_saitama_limiter:DeclareFunctions()
return {MODIFIER_EVENT_ON_DEATH}
end
if IsServer() then
function modifier_saitama_limiter:OnDeath(keys)
local caster = self:GetCaster()
local ability = caster:FindAbilityByName("saitama_limiter")
local level = ability and math.max(ability:GetLevel(), 1) or 1
if keys.attacker == caster and keys.unit:IsTrueHero() then
self:SetStackCount(self:GetStackCount() + GetAbilitySpecial("saitama_limiter", "stacks_for_kill", level))
elseif keys.unit == caster then
self:SetStackCount(math.ceil(self:GetStackCount() * (1 - GetAbilitySpecial("saitama_limiter", "loss_stacks_pct", level) * 0.01)))
end
end
end
|
modifier_saitama_limiter = class({
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
GetTexture = function() return "arena/modifier_saitama_limiter" end,
})
function modifier_saitama_limiter:DeclareFunctions()
return {MODIFIER_EVENT_ON_DEATH}
end
if IsServer() then
function modifier_saitama_limiter:OnDeath(keys)
local caster = self:GetCaster()
local ability = caster:FindAbilityByName("saitama_limiter")
local level = ability and math.max(ability:GetLevel(), 1) or 1
if keys.unit == caster then
self:SetStackCount(math.ceil(self:GetStackCount() * (1 - GetAbilitySpecial("saitama_limiter", "loss_stacks_pct", level) * 0.01)))
elseif (
keys.attacker == caster and
keys.unit:IsTrueHero() and
caster:GetTeamNumber() ~= keys.unit:GetTeamNumber()
) then
self:SetStackCount(self:GetStackCount() + GetAbilitySpecial("saitama_limiter", "stacks_for_kill", level))
end
end
end
|
fix(saitama): limiter gets stacks for deny
|
fix(saitama): limiter gets stacks for deny
|
Lua
|
mit
|
ark120202/aabs
|
37d01e3897937d78a548ea6fc902b7e34eb45f78
|
.config/awesome/widgets/mpd.lua
|
.config/awesome/widgets/mpd.lua
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local wibox = require("wibox")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local MPDWidget = BaseWidget.derive()
local mpdmenu = awful.menu({
items = {
{ "Play/Pause", "mpc toggle" },
{ "Stop", "mpc stop" },
{ "Next", "mpc next" },
{ "Previous", "mpc prev" },
{ "Toggle random", "mpc random" },
{ "Toggle repeat", "mpc repeat" },
{ "Toggle single", "mpc single" },
},
theme = { width = 120 }
})
-- Strips the path part from the filename
local function getFilename(fname)
-- The '/' at the beginning of the filename ensures that the regex will
-- also work for files in the root of the music directory (which don't
-- have any '/' inside their filename).
return ("/" .. fname):match(".*/(.*)")
end
local function prettyTime(seconds)
local sec = (seconds % 60)
return math.floor(seconds / 60) .. ":" .. (sec < 10 and "0" or "") .. sec
end
function MPDWidget:create(args)
args = args or {}
args.settings = function() self:updateText() end
self.lainwidget = lain.widgets.mpd(args)
local widget = wibox.container.constraint(self.lainwidget.widget, "max", 125, nil)
widget.widget:set_align("right")
local box = self:init(widget, args.icon or icons.mpd)
self:attach(box)
end
function MPDWidget:update()
self.lainwidget.update()
end
function MPDWidget:updateText()
self.data = mpd_now
if mpd_now.state == "stop" then
widget:set_markup("")
return
elseif mpd_now.title == "N/A" then
widget:set_markup(getFilename(self.data.file))
else
widget:set_markup(mpd_now.title)
end
end
function MPDWidget:attach(box)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run_term("ncmpcpp -s visualizer") end),
awful.button({}, 3, function() mpdmenu:toggle() end),
awful.button({}, 4, function() awful.spawn("mpc volume +2") end),
awful.button({}, 5, function() awful.spawn("mpc volume -2") end)
))
utils.registerPopupNotify(box, "MPD", function(w)
return "Title:\t\t" .. self.data.title ..
"\nAlbum:\t" .. self.data.album ..
"\nArtist:\t" .. self.data.artist ..
"\nGenre:\t" .. self.data.genre ..
"\nFile:\t\t" .. getFilename(self.data.file) ..
"\nState:\t" .. self.data.state ..
"\nLength:\t" .. prettyTime(tonumber(self.data.time))
end)
end
return MPDWidget
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local wibox = require("wibox")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local MPDWidget = BaseWidget.derive()
local mpdmenu = awful.menu({
items = {
{ "Play/Pause", "mpc toggle" },
{ "Stop", "mpc stop" },
{ "Next", "mpc next" },
{ "Previous", "mpc prev" },
{ "Toggle random", "mpc random" },
{ "Toggle repeat", "mpc repeat" },
{ "Toggle single", "mpc single" },
},
theme = { width = 120 }
})
-- Strips the path part from the filename
local function getFilename(fname)
-- The '/' at the beginning of the filename ensures that the regex will
-- also work for files in the root of the music directory (which don't
-- have any '/' inside their filename).
return ("/" .. fname):match(".*/(.*)")
end
local function prettyTime(seconds)
if not seconds then
return -1
end
local sec = (seconds % 60)
return math.floor(seconds / 60) .. ":" .. (sec < 10 and "0" or "") .. sec
end
function MPDWidget:create(args)
args = args or {}
args.settings = function() self:updateText() end
self.lainwidget = lain.widgets.mpd(args)
local widget = wibox.container.constraint(self.lainwidget.widget, "max", 125, nil)
widget.widget:set_align("right")
local box = self:init(widget, args.icon or icons.mpd)
self:attach(box)
end
function MPDWidget:update()
self.lainwidget.update()
end
function MPDWidget:updateText()
self.data = mpd_now
if mpd_now.state == "stop" then
widget:set_markup("")
return
elseif mpd_now.title == "N/A" then
widget:set_markup(getFilename(self.data.file))
else
widget:set_markup(mpd_now.title)
end
end
function MPDWidget:attach(box)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run_term("ncmpcpp -s visualizer") end),
awful.button({}, 3, function() mpdmenu:toggle() end),
awful.button({}, 4, function() awful.spawn("mpc volume +2") end),
awful.button({}, 5, function() awful.spawn("mpc volume -2") end)
))
utils.registerPopupNotify(box, "MPD", function(w)
return "Title:\t\t" .. self.data.title ..
"\nAlbum:\t" .. self.data.album ..
"\nArtist:\t" .. self.data.artist ..
"\nGenre:\t" .. self.data.genre ..
"\nFile:\t\t" .. getFilename(self.data.file) ..
"\nState:\t" .. self.data.state ..
"\nLength:\t" .. prettyTime(tonumber(self.data.time))
end)
end
return MPDWidget
|
[Awesome] Fix nil access when MPD is stopped
|
[Awesome] Fix nil access when MPD is stopped
|
Lua
|
mit
|
mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mall0c/dotfiles,mphe/dotfiles,mall0c/dotfiles,mphe/dotfiles
|
912b00825221047e5f23f578b32af48c035a5b4e
|
asset/src/framework/texture/manager.lua
|
asset/src/framework/texture/manager.lua
|
--[[
Description: Ref count machanism to manage textures.
Author: M.Wan
Date: 09/1/2015
]]
--[[
* TextureManager is used to manage textures life cycle based on reference count machanism.
* The reference count will increase 1 every time you load a texture, vice versa.
* @func loadTexture: load a texture. (sync)
* @func unloadTexture: unload a texture.
* @func didLoadTexture: whether did load the texture.
* @func loadTextureAsync: load a texture. (async)
* @func forceUnloadTexture: force unload a texture, which will ignore the reference count.
* @func setPvrTexturesSupportPremultipliedAlpha: set if .pvr texture supports premultiplied alpha.
]]
local TextureManager = {}
TextureManager._textureMap = {}
function TextureManager:loadTexture(plist, texture)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if type(texture) ~= "string" then
logError("Invalid param 'texture', should be a string value.")
return
end
if self._textureMap[plist] then
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] + 1
else
cc.SpriteFrameCache:getInstance():addSpriteFrames(plist, texture)
self._textureMap[plist] = {
ref = 1,
tex = texture,
}
end
log("Texture %s loaded, reference count: %d", plist, self._textureMap[plist]["ref"])
end
function TextureManager:unloadTexture(plist)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if not self:didLoadTexture(plist) then
logError("The texture %s hasn't been loaded.", plist)
return
end
log("Texture %s unloaded, reference count: %d", plist, self._textureMap[plist]["ref"])
if self._textureMap[plist]["ref"] <= 0 then
cc.SpriteFrameCache:getInstance():removeSpriteFramesFromFile(plist)
cc.Director:getTextureCache():removeTextureForKey(self._textureMap[plist]["tex"])
self._textureMap[plist] = nil
end
end
function TextureManager:didLoadTexture(plist)
return self._textureMap[plist] ~= nil
end
function TextureManager:loadTextureAsync(plist, texture, callback)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if type(texture) ~= "string" then
logError("Invalid param 'texture', should be a string value.")
return
end
if type(callback) ~= "function" then
logError("Invalid param 'callback', should be a function.")
return
end
if self:didLoadTexture(plist) then
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] + 1
callback()
else
local realCallback = function()
cc.SpriteFrameCache:getInstance():addSpriteFrames(plist, texture)
self._textureMap[plist] = {
ref = 1,
tex = texture,
}
log("Texture %s loaded, reference count: %d", plist, self._textureMap[plist]["ref"])
callback()
end
cc.Director:getTextureCache():addImageAsync(texture, realCallback)
end
end
function TextureManager:forceUnloadTexture(plist)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if not self:didLoadTexture(plist) then
logError("The texture %s hasn't been loaded.", plist)
return
end
cc.SpriteFrameCache:getInstance():removeSpriteFramesFromFile(plist)
cc.Director:getTextureCache():removeTextureForKey(self._textureMap[plist]["tex"])
self._textureMap[plist] = nil
end
function TextureManager:setPvrTexturesSupportPremultipliedAlpha(bSupport)
cc.Image:setPVRImagesHavePremultipliedAlpha(bSupport);
end
return TextureManager
|
--[[
Description: Ref count machanism to manage textures.
Author: M.Wan
Date: 09/1/2015
]]
--[[
* TextureManager is used to manage textures life cycle based on reference count machanism.
* The reference count will increase 1 every time you load a texture, vice versa.
* @func loadTexture: load a texture. (sync)
* @func unloadTexture: unload a texture.
* @func didLoadTexture: whether did load the texture.
* @func loadTextureAsync: load a texture. (async)
* @func unloadTextureWithDelay: it won't unload the texture immediately when the reference count is 0, it will clean the texture with a delay(So you can load the texture during the delay time).
* @func forceUnloadTexture: force unload a texture, which will ignore the reference count.
* @func setPvrTexturesSupportPremultipliedAlpha: set if .pvr texture supports premultiplied alpha.
]]
local TextureManager = {}
TextureManager._textureMap = {}
function TextureManager:loadTexture(plist, texture)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if type(texture) ~= "string" then
logError("Invalid param 'texture', should be a string value.")
return
end
if self._textureMap[plist] then
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] + 1
else
cc.SpriteFrameCache:getInstance():addSpriteFrames(plist, texture)
self._textureMap[plist] = {
ref = 1,
tex = texture,
}
end
log("Texture %s loaded, reference count: %d", plist, self._textureMap[plist]["ref"])
end
function TextureManager:unloadTexture(plist)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if not self:didLoadTexture(plist) then
logError("The texture %s hasn't been loaded.", plist)
return
end
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] - 1
log("Texture %s unloaded, reference count: %d", plist, self._textureMap[plist]["ref"])
if self._textureMap[plist]["ref"] <= 0 then
cc.SpriteFrameCache:getInstance():removeSpriteFramesFromFile(plist)
cc.Director:getTextureCache():removeTextureForKey(self._textureMap[plist]["tex"])
self._textureMap[plist] = nil
end
end
function TextureManager:didLoadTexture(plist)
return self._textureMap[plist] ~= nil
end
function TextureManager:loadTextureAsync(plist, texture, callback)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if type(texture) ~= "string" then
logError("Invalid param 'texture', should be a string value.")
return
end
if type(callback) ~= "function" then
logError("Invalid param 'callback', should be a function.")
return
end
if self:didLoadTexture(plist) then
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] + 1
callback()
else
local realCallback = function()
cc.SpriteFrameCache:getInstance():addSpriteFrames(plist, texture)
self._textureMap[plist] = {
ref = 1,
tex = texture,
}
log("Texture %s loaded, reference count: %d", plist, self._textureMap[plist]["ref"])
callback()
end
cc.Director:getTextureCache():addImageAsync(texture, realCallback)
end
end
function TextureManager:unloadTextureWithDelay(plist, delay)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if not self:didLoadTexture(plist) then
logError("The texture %s hasn't been loaded.", plist)
return
end
if self._textureMap[plist]["ref"] <= 0 then
logError("Delay removed.")
return
end
self._textureMap[plist]["ref"] = self._textureMap[plist]["ref"] - 1
log("Texture %s unloaded with delay, reference count: %d", plist, self._textureMap[plist]["ref"])
if self._textureMap[plist]["ref"] <= 0 then
local callback = function ()
if self._textureMap[plist]["ref"] <= 0 then
cc.SpriteFrameCache:getInstance():removeSpriteFramesFromFile(plist)
cc.Director:getTextureCache():removeTextureForKey(self._textureMap[plist]["tex"])
self._textureMap[plist] = nil
end
end
cc.Director:getInstance():getScheduler():scheduleScriptFunc(callback, 0)
end
end
function TextureManager:forceUnloadTexture(plist)
if type(plist) ~= "string" then
logError("Invalid param 'plist', should be a string value.")
return
end
if not self:didLoadTexture(plist) then
logError("The texture %s hasn't been loaded.", plist)
return
end
cc.SpriteFrameCache:getInstance():removeSpriteFramesFromFile(plist)
cc.Director:getTextureCache():removeTextureForKey(self._textureMap[plist]["tex"])
self._textureMap[plist] = nil
end
function TextureManager:setPvrTexturesSupportPremultipliedAlpha(bSupport)
cc.Image:setPVRImagesHavePremultipliedAlpha(bSupport);
end
return TextureManager
|
bug fixing
|
bug fixing
|
Lua
|
apache-2.0
|
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
|
fbfadeba6eb1eaada42c9d99a53e32d4aa4fed02
|
AceConsole-3.0/AceConsole-3.0.lua
|
AceConsole-3.0/AceConsole-3.0.lua
|
--[[ $Id$ ]]
local MAJOR,MINOR = "AceConsole-3.0", 1
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConsole then return end -- No upgrade needed
AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in.
AceConsole.commands = AceConsole.commands or {} -- table containing commands registered
AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable
-- local upvalues
local _G = _G
local pairs = pairs
local select = select
local type = type
local tostring = tostring
local strfind = string.find
local strsub = string.sub
local max = math.max
-- AceConsole:Print( [chatframe,] ... )
--
-- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member)
function AceConsole:Print(...)
local text = ""
if self ~= AceConsole then
text = tostring( self )..": "
end
local frame = select(1, ...)
if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member?
frame=nil
end
for i=(frame and 2 or 1), select("#", ...) do
text = text .. tostring( select( i, ...) ) .." "
end
(frame or DEFAULT_CHAT_FRAME):AddMessage( text )
end
-- AceConsole:RegisterChatCommand(. command, func, persist )
--
-- command (string) - chat command to be registered WITHOUT leading "/"
-- func (function|membername) - function to call, or self[membername](self, ...) call
-- persist (boolean) - false: the command will be soft disabled/enabled when aceconsole is used as a mixin (default: true)
-- silent (boolean) - don't whine if command already exists, silently fail
--
-- Register a simple chat command
function AceConsole:RegisterChatCommand( command, func, persist, silent )
if type(command)~="string" then error([[Usage: AceConsole:RegisterChatCommand( "command", func[, persist[, silent] ]): 'command' - expected a string]], 2) end
if persist==nil then persist=true end -- I'd rather have my addon's "/addon enable" around if the author screws up. Having some extra slash regged when it shouldnt be isn't as destructive. True is a better default. /Mikk
local name = "ACECONSOLE_"..command:upper()
if SlashCmdList[name] then
if not silent then
geterrorhandler()(tostring(self)..": Chat Command '"..command.."' already exists, will not overwrite.")
end
return
end
if type( func ) == "string" then
SlashCmdList[name] = function(input)
self[func](self, input)
end
else
SlashCmdList[name] = func
end
_G["SLASH_"..name.."1"] = "/"..command:lower()
AceConsole.commands[command] = name
-- non-persisting commands are registered for enabling disabling
if not persist then
AceConsole.weakcommands[self][command] = func
end
return true
end
-- AceConsole:UnregisterChatCommand( command )
--
-- Unregister a chatcommand
function AceConsole:UnregisterChatCommand( command )
local name = AceConsole.commands[command]
if name then
SlashCmdList[name] = nil
_G["SLASH_" .. name .. "1"] = nil
hash_SlashCmdList["/" .. command:upper()] = nil
AceConsole.commands[command] = nil
end
end
function AceConsole:IterateChatCommands() return pairs(AceConsole.commands) end
local function nils(n, ...)
if n>1 then
return nil, nils(n-1, ...)
elseif n==1 then
return nil, ...
else
return ...
end
end
-- AceConsole:GetArgs(string, numargs, startpos)
--
-- Retreive one or more space-separated arguments from a string.
-- Treats quoted strings and itemlinks as non-spaced.
--
-- string - The raw argument string
-- numargs - How many arguments to get (default 1)
-- startpos - Where in the string to start scanning (default 1)
--
-- Returns arg1, arg2, ..., nextposition
-- Missing arguments will be returned as nils. 'nextposition' is returned as 1e9 at the end of the string.
function AceConsole:GetArgs(str, numargs, startpos)
numargs = numargs or 1
startpos = max(startpos or 1, 1)
local pos=startpos
-- find start of new arg
pos = strfind(str, "[^ ]", pos)
if not pos then -- whoops, end of string
return nils(numargs, 1e9)
end
if numargs<1 then
return pos
end
-- quoted or space separated? find out which pattern to use
local delim_or_pipe
local ch = strsub(str, pos, pos)
if ch=='"' then
pos = pos + 1
delim_or_pipe='([|"])'
elseif ch=="'" then
pos = pos + 1
delim_or_pipe="([|'])"
else
delim_or_pipe="([| ])"
end
startpos = pos
while true do
-- find delimiter or hyperlink
local ch,_
pos,_,ch = strfind(str, delim_or_pipe, pos)
if not pos then break end
if ch=="|" then
-- some kind of escape
if strsub(str,pos,pos+1)=="|H" then
-- It's a |H....|hhyper link!|h
pos=strfind(str, "|h", pos+2) -- first |h
if not pos then break end
pos=strfind(str, "|h", pos+2) -- second |h
if not pos then break end
end
pos=pos+2 -- skip past this escape (last |h if it was a hyperlink)
else
-- found delimiter, done with this arg
return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1)
end
end
-- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink)
return strsub(str, startpos), nils(numargs-1, 1e9)
end
--- embedding and embed handling
local mixins = {
"Print",
"RegisterChatCommand",
"UnregisterChatCommand",
"GetArgs",
}
-- AceConsole:Embed( target )
-- target (object) - target object to embed AceBucket in
--
-- Embeds AceConsole into the target object making the functions from the mixins list available on target:..
function AceConsole:Embed( target )
for k, v in pairs( mixins ) do
target[v] = self[v]
end
self.embeds[target] = true
return target
end
function AceConsole:OnEmbedEnable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry
end
end
end
function AceConsole:OnEmbedDisable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care?
end
end
end
for addon in pairs(AceConsole.embeds) do
AceConsole:Embed(addon)
end
|
--[[ $Id$ ]]
local MAJOR,MINOR = "AceConsole-3.0", 1
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConsole then return end -- No upgrade needed
AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in.
AceConsole.commands = AceConsole.commands or {} -- table containing commands registered
AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable
-- local upvalues
local _G = _G
local pairs = pairs
local select = select
local type = type
local tostring = tostring
local strfind = string.find
local strsub = string.sub
local max = math.max
-- AceConsole:Print( [chatframe,] ... )
--
-- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member)
function AceConsole:Print(...)
local text = ""
if self ~= AceConsole then
text = tostring( self )..": "
end
local frame = select(1, ...)
if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member?
frame=nil
end
for i=(frame and 2 or 1), select("#", ...) do
text = text .. tostring( select( i, ...) ) .." "
end
(frame or DEFAULT_CHAT_FRAME):AddMessage( text )
end
-- AceConsole:RegisterChatCommand(. command, func, persist )
--
-- command (string) - chat command to be registered WITHOUT leading "/"
-- func (function|membername) - function to call, or self[membername](self, ...) call
-- persist (boolean) - false: the command will be soft disabled/enabled when aceconsole is used as a mixin (default: true)
-- silent (boolean) - don't whine if command already exists, silently fail
--
-- Register a simple chat command
function AceConsole:RegisterChatCommand( command, func, persist, silent )
if type(command)~="string" then error([[Usage: AceConsole:RegisterChatCommand( "command", func[, persist[, silent] ]): 'command' - expected a string]], 2) end
if persist==nil then persist=true end -- I'd rather have my addon's "/addon enable" around if the author screws up. Having some extra slash regged when it shouldnt be isn't as destructive. True is a better default. /Mikk
local name = "ACECONSOLE_"..command:upper()
if SlashCmdList[name] then
if not silent then
geterrorhandler()(tostring(self)..": Chat Command '"..command.."' already exists, will not overwrite.")
end
return
end
if type( func ) == "string" then
SlashCmdList[name] = function(input)
self[func](self, input)
end
else
SlashCmdList[name] = func
end
_G["SLASH_"..name.."1"] = "/"..command:lower()
AceConsole.commands[command] = name
-- non-persisting commands are registered for enabling disabling
if not persist then
if not AceConsole.weakcommands[self] then AceConsole.weakcommands[self] = {} end
AceConsole.weakcommands[self][command] = func
end
return true
end
-- AceConsole:UnregisterChatCommand( command )
--
-- Unregister a chatcommand
function AceConsole:UnregisterChatCommand( command )
local name = AceConsole.commands[command]
if name then
SlashCmdList[name] = nil
_G["SLASH_" .. name .. "1"] = nil
hash_SlashCmdList["/" .. command:upper()] = nil
AceConsole.commands[command] = nil
end
end
function AceConsole:IterateChatCommands() return pairs(AceConsole.commands) end
local function nils(n, ...)
if n>1 then
return nil, nils(n-1, ...)
elseif n==1 then
return nil, ...
else
return ...
end
end
-- AceConsole:GetArgs(string, numargs, startpos)
--
-- Retreive one or more space-separated arguments from a string.
-- Treats quoted strings and itemlinks as non-spaced.
--
-- string - The raw argument string
-- numargs - How many arguments to get (default 1)
-- startpos - Where in the string to start scanning (default 1)
--
-- Returns arg1, arg2, ..., nextposition
-- Missing arguments will be returned as nils. 'nextposition' is returned as 1e9 at the end of the string.
function AceConsole:GetArgs(str, numargs, startpos)
numargs = numargs or 1
startpos = max(startpos or 1, 1)
local pos=startpos
-- find start of new arg
pos = strfind(str, "[^ ]", pos)
if not pos then -- whoops, end of string
return nils(numargs, 1e9)
end
if numargs<1 then
return pos
end
-- quoted or space separated? find out which pattern to use
local delim_or_pipe
local ch = strsub(str, pos, pos)
if ch=='"' then
pos = pos + 1
delim_or_pipe='([|"])'
elseif ch=="'" then
pos = pos + 1
delim_or_pipe="([|'])"
else
delim_or_pipe="([| ])"
end
startpos = pos
while true do
-- find delimiter or hyperlink
local ch,_
pos,_,ch = strfind(str, delim_or_pipe, pos)
if not pos then break end
if ch=="|" then
-- some kind of escape
if strsub(str,pos,pos+1)=="|H" then
-- It's a |H....|hhyper link!|h
pos=strfind(str, "|h", pos+2) -- first |h
if not pos then break end
pos=strfind(str, "|h", pos+2) -- second |h
if not pos then break end
end
pos=pos+2 -- skip past this escape (last |h if it was a hyperlink)
else
-- found delimiter, done with this arg
return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1)
end
end
-- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink)
return strsub(str, startpos), nils(numargs-1, 1e9)
end
--- embedding and embed handling
local mixins = {
"Print",
"RegisterChatCommand",
"UnregisterChatCommand",
"GetArgs",
}
-- AceConsole:Embed( target )
-- target (object) - target object to embed AceBucket in
--
-- Embeds AceConsole into the target object making the functions from the mixins list available on target:..
function AceConsole:Embed( target )
for k, v in pairs( mixins ) do
target[v] = self[v]
end
self.embeds[target] = true
return target
end
function AceConsole:OnEmbedEnable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry
end
end
end
function AceConsole:OnEmbedDisable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care?
end
end
end
for addon in pairs(AceConsole.embeds) do
AceConsole:Embed(addon)
end
|
Ace3 - AceConsole-3.0: Fix bug where no table for [self] was created when registering weak commands
|
Ace3 - AceConsole-3.0: Fix bug where no table for [self] was created when registering weak commands
git-svn-id: 7647537e40c65c0861dc9b5b7a3f92438fa62736@526 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
08dd69f2fd440f1baaaec2b02387479a9bba175e
|
src/romdisk/system/lib/org/xboot/timer/timer.lua
|
src/romdisk/system/lib/org/xboot/timer/timer.lua
|
local class = require("org.xboot.lang.class")
---
-- The 'timer' class is used to execute a code at specified intervals.
--
-- @module timer
local M = class()
local __timer_list = {}
---
-- Creates a new 'timer' object with the specified delay and iteration.
--
-- @function [parent=#timer] new
-- @param delay (number) The delay in seconds
-- @param iteration (number) The number of times listener is to be invoked. pass 0 if you want it to loop forever.
-- @param listener (function) The listener to invoke after the delay.
-- @param data (optional) An optional data parameter that is passed to the listener function.
-- @return New 'timer' object.
function M:init(delay, iteration, listener, data)
self.__delay = delay or 1
self.__iteration = iteration or 1
self.__listener = listener
self.__data = data or nil
self.__time = 0
self.__count = 0
self.__running = true
table.insert(__timer_list, self)
end
---
-- Returns the current running status of timer.
--
-- @function [parent=#timer] isrunning
-- @param self
-- @return 'true' if the timer is running, 'false' otherwise.
function M:isrunning()
return self.__running
end
---
-- Resumes the timer that was paused.
--
-- @function [parent=#timer] resume
-- @param self
function M:resume()
self.__running = true
end
---
-- Pauses the timer that was resumed.
--
-- @function [parent=#timer] pause
-- @param self
function M:pause()
self.__running = false
end
---
-- Cancels the timer operation initiated with timer:new().
--
-- @function [parent=#timer] cancel
-- @param self
-- @return the number of iterations.
function M:cancel()
for i, v in ipairs(__timer_list) do
if v.__delay == self.__delay and v.__iteration == self.__iteration and v.__listener == self.__listener and v.__data == self.__data then
v.__running = false
table.remove(__timer_list, i)
return v.__count
end
end
end
---
-- Schedule all timers in list.
--
-- @function [parent=#timer] schedule
-- @param self
-- @param delta (number) The time interval in seconds.
function M:schedule(delta)
for i, v in ipairs(__timer_list) do
if v.__running then
v.__time = v.__time + delta
if v.__time > v.__delay then
v.__count = v.__count + 1
v.__listener(v, {time = v.__time, count = v.__count, data = v.__data})
v.__time = 0
if v.__iteration ~= 0 and v.__count >= v.__iteration then
v.__running = false
table.remove(__timer_list, i)
end
end
end
end
end
return M
|
local class = require("org.xboot.lang.class")
---
-- The 'timer' class is used to execute a code at specified intervals.
--
-- @module timer
local M = class()
local __timer_list = {}
---
-- Creates a new 'timer' object with the specified delay and iteration.
--
-- @function [parent=#timer] new
-- @param delay (number) The delay in seconds
-- @param iteration (number) The number of times listener is to be invoked. pass 0 if you want it to loop forever.
-- @param listener (function) The listener to invoke after the delay.
-- @param data (optional) An optional data parameter that is passed to the listener function.
-- @return New 'timer' object.
function M:init(delay, iteration, listener, data)
self.__delay = delay or 1
self.__iteration = iteration or 1
self.__listener = listener
self.__data = data or nil
self.__time = 0
self.__count = 0
self.__running = true
table.insert(__timer_list, self)
end
---
-- Returns the current running status of timer.
--
-- @function [parent=#timer] isrunning
-- @param self
-- @return 'true' if the timer is running, 'false' otherwise.
function M:isrunning()
return self.__running
end
---
-- Resumes the timer that was paused.
--
-- @function [parent=#timer] resume
-- @param self
function M:resume()
self.__running = true
end
---
-- Pauses the timer that was resumed.
--
-- @function [parent=#timer] pause
-- @param self
function M:pause()
self.__running = false
end
---
-- Cancels the timer operation initiated with timer:new().
--
-- @function [parent=#timer] cancel
-- @param self
-- @return the number of iterations.
function M:cancel()
for i, v in ipairs(__timer_list) do
if v.__delay == self.__delay and v.__iteration == self.__iteration and v.__listener == self.__listener and v.__data == self.__data then
v:pause()
table.remove(__timer_list, i)
return v.__count
end
end
end
---
-- Schedule all timers in list.
--
-- @function [parent=#timer] schedule
-- @param self
-- @param delta (number) The time interval in seconds.
function M:schedule(delta)
for i, v in ipairs(__timer_list) do
if v.__running then
v.__time = v.__time + delta
if v.__time > v.__delay then
v.__count = v.__count + 1
v.__listener(v, {time = v.__time, count = v.__count, data = v.__data})
v.__time = 0
if v.__iteration ~= 0 and v.__count >= v.__iteration then
v:cancel()
end
end
end
end
end
return M
|
fix timer.lua
|
fix timer.lua
|
Lua
|
mit
|
xboot/xboot,xboot/xboot
|
fe061cf3ba3059faf238ab63a9859d491956cb1c
|
MMOCoreORB/bin/scripts/mobile/conversations/imperial_officer_2_conv.lua
|
MMOCoreORB/bin/scripts/mobile/conversations/imperial_officer_2_conv.lua
|
imperial_officer_2_convotemplate = ConvoTemplate:new {
initialScreen = "",
screens = {}
}
imperial_officer_2_convoscreen1 = ConvoScreen:new {
id = "convoscreen1",
leftDialog = "@newbie_tutorial/newbie_convo:banker_1_start",
options = {
{"@newbie_tutorial/newbie_convo:banker_1_reply_1", ""},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen1);
addConversationTemplate("imperial_officer_2_convotemplate", imperial_officer_2_convotemplate);
|
imperial_officer_2_convotemplate = ConvoTemplate:new {
initialScreen = "convoscreen1",
screens = {}
}
imperial_officer_2_convoscreen1 = ConvoScreen:new {
id = "convoscreen1",
leftDialog = "@newbie_tutorial/newbie_convo:banker_1_start",
options = {
{"@newbie_tutorial/newbie_convo:banker_1_reply_1", "convoscreen2"},
{"@newbie_tutorial/newbie_convo:banker_1_reply_2", "convoscreen6"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen1);
imperial_officer_2_convoscreen2 = ConvoScreen:new {
id = "convoscreen2",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_start",
options = {
{"@newbie_tutorial/newbie_convo:banker_2_reply_1", "convoscreen3"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen2);
imperial_officer_2_convoscreen3 = ConvoScreen:new {
id = "convoscreen3",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_more",
options = {
{"@newbie_tutorial/newbie_convo:banker_2_reply_2", "convoscreen4"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen3);
imperial_officer_2_convoscreen4 = ConvoScreen:new {
id = "convoscreen4",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_explain",
options = {
{"@newbie_tutorial/newbie_convo:banker_2_reply_3", "convoscreen5"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen4);
imperial_officer_2_convoscreen5 = ConvoScreen:new {
id = "convoscreen5",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_explain_2",
options = {
{"@newbie_tutorial/newbie_convo:banker_1_reply_2", "convoscreen6"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen5);
imperial_officer_2_convoscreen6 = ConvoScreen:new {
id = "convoscreen6",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_explain_terminals",
options = {
{"@newbie_tutorial/newbie_convo:banker_1_reply_3", "convoscreen7"},
{"@newbie_tutorial/newbie_convo:banker_1_reply_4", "convoscreen11"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen6);
imperial_officer_2_convoscreen7 = ConvoScreen:new {
id = "convoscreen7",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_explain_bank",
options = {
{"@newbie_tutorial/newbie_convo:banker_bank_reply_1", "convoscreen8"},
{"@newbie_tutorial/newbie_convo:banker_2_bank_question", "convoscreen9"},
{"@newbie_tutorial/newbie_convo:banker_bank_question_2", "convoscreen10"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen7);
imperial_officer_2_convoscreen8 = ConvoScreen:new {
id = "convoscreen8",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_more_bank",
options = {
{"@newbie_tutorial/newbie_convo:banker_2_bank_question", "convoscreen9"},
{"@newbie_tutorial/newbie_convo:banker_bank_question_2", "convoscreen10"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen8);
imperial_officer_2_convoscreen9 = ConvoScreen:new {
id = "convoscreen9",
leftDialog = "@newbie_tutorial/newbie_convo:banker_2_bank_answer",
options = {
{"@newbie_tutorial/newbie_convo:banker_bank_reply_1", "convoscreen8"},
{"@newbie_tutorial/newbie_convo:banker_bank_question_2", "convoscreen10"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen9);
imperial_officer_2_convoscreen10 = ConvoScreen:new {
id = "convoscreen10",
leftDialog = "@newbie_tutorial/newbie_convo:banker_bank_answer_2",
options = {
{"@newbie_tutorial/newbie_convo:banker_bank_reply_1", "convoscreen8"},
{"@newbie_tutorial/newbie_convo:banker_2_bank_question", "convoscreen9"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen10);
imperial_officer_2_convoscreen11 = ConvoScreen:new {
id = "convoscreen11",
leftDialog = "@newbie_tutorial/newbie_convo:banker_bazaar_1",
options = {
{"@newbie_tutorial/newbie_convo:banker_bazaar_reply_1", "convoscreen12"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen11);
imperial_officer_2_convoscreen12 = ConvoScreen:new {
id = "convoscreen12",
leftDialog = "@newbie_tutorial/newbie_convo:banker_bazaar_2",
options = {
{"@newbie_tutorial/newbie_convo:banker_bazaar_reply_2", "convoscreen13"},
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen12);
imperial_officer_2_convoscreen13 = ConvoScreen:new {
id = "convoscreen13",
leftDialog = "@newbie_tutorial/newbie_convo:banker_bazaar_3",
options = {
}
}
imperial_officer_2_convotemplate:addScreen(imperial_officer_2_convoscreen13);
addConversationTemplate("imperial_officer_2_convotemplate", imperial_officer_2_convotemplate);
|
[fixed] officer 2's conversation in tutorial to use new system.
|
[fixed] officer 2's conversation in tutorial to use new system.
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3206 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/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,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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.