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
|
|---|---|---|---|---|---|---|---|---|---|
6785fea2ceb8af7348ab8167927b688c2901ffbd
|
lua/starfall/libs_sh/vmatrix.lua
|
lua/starfall/libs_sh/vmatrix.lua
|
-- Credits to Radon & Xandaros
SF.VMatrix = {}
local vmatrix_methods, vmatrix_metamethods = SF.Typedef("VMatrix") -- Define our own VMatrix based off of standard VMatrix
local wrap, unwrap = SF.CreateWrapper( vmatrix_metamethods, true, false )
SF.VMatrix.Methods = vmatrix_methods
SF.VMatrix.Metatable = vmatrix_metamethods
SF.VMatrix.Wrap = wrap
SF.VMatrix.Unwrap = unwrap
SF.DefaultEnvironment.Matrix = function()
return wrap(Matrix())
end
function vmatrix_methods:getAngles()
SF.CheckType( self, vmatrix_metamethods )
return unwrap(self):GetAngles()
end
function vmatrix_methods:getScale()
SF.CheckType( self, vmatrix_metamethods )
return unwrap(self):GetScale()
end
function vmatrix_methods:getTranslation()
SF.CheckType( self, vmatrix_metamethods )
return unwrap(self):GetTranslation()
end
function vmatrix_methods:rotate( ang )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( ang, "Angle")
local v = unwrap(self)
v:Rotate( ang )
end
function vmatrix_methods:scale( vec )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:Scale( vec )
end
function vmatrix_methods:scaleTranslation( num )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( num, "Number" )
local v = unwrap(self)
v:ScaleTranslation( num )
end
function vmatrix_methods:setAngles( ang )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( ang, "Angle" )
local v = unwrap(self)
v:SetAngles( ang )
end
function vmatrix_methods:setTranslation( vec )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:SetTranslation( vec )
end
function vmatrix_methods:translate( vec )
SF.CheckType( self, vmatrix_metamethods )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:Translate( vec )
end
function vmatrix_metamethods.__mul( lhs, rhs )
SF.CheckType( lhs, vmatrix_metamethods )
SF.CheckType( rhs, vmatrix_metamethods )
return wrap(unwrap(rhs) * unwrap(rhs))
end
|
-- Credits to Radon & Xandaros
SF.VMatrix = {}
local vmatrix_methods, vmatrix_metamethods = SF.Typedef("VMatrix") -- Define our own VMatrix based off of standard VMatrix
local wrap, unwrap = SF.CreateWrapper( vmatrix_metamethods, true, false )
SF.VMatrix.Methods = vmatrix_methods
SF.VMatrix.Metatable = vmatrix_metamethods
SF.VMatrix.Wrap = wrap
SF.VMatrix.Unwrap = unwrap
SF.DefaultEnvironment.Matrix = function()
return wrap(Matrix())
end
function vmatrix_methods:getAngles()
return unwrap(self):GetAngles()
end
function vmatrix_methods:getScale()
return unwrap(self):GetScale()
end
function vmatrix_methods:getTranslation()
return unwrap(self):GetTranslation()
end
function vmatrix_methods:rotate( ang )
SF.CheckType( ang, "Angle")
local v = unwrap(self)
v:Rotate( ang )
end
function vmatrix_methods:scale( vec )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:Scale( vec )
end
function vmatrix_methods:scaleTranslation( num )
SF.CheckType( num, "Number" )
local v = unwrap(self)
v:ScaleTranslation( num )
end
function vmatrix_methods:setAngles( ang )
SF.CheckType( ang, "Angle" )
local v = unwrap(self)
v:SetAngles( ang )
end
function vmatrix_methods:setTranslation( vec )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:SetTranslation( vec )
end
function vmatrix_methods:translate( vec )
SF.CheckType( vec, "Vector" )
local v = unwrap(self)
v:Translate( vec )
end
function vmatrix_metamethods.__mul( lhs, rhs )
SF.CheckType( rhs, vmatrix_metamethods )
return wrap(unwrap(rhs) * unwrap(rhs))
end
|
Removed VMatrix SF.CheckType for self metamethods.
|
Removed VMatrix SF.CheckType for self metamethods.
Fixes #36
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall
|
85e1eb6af0b0c772352230a25ccf782c33c75ad3
|
mock/common/ProtoSpawner.lua
|
mock/common/ProtoSpawner.lua
|
module 'mock'
local enumSpawnMethod = _ENUM_V {
'root',
'sibling',
'child',
'parent_sibling'
}
CLASS: ProtoSpawner ( Component )
:MODEL{
Field 'proto' :asset('proto');
Field 'spawnName' :string();
'----';
Field 'copyLoc' :boolean();
Field 'copyRot' :boolean();
Field 'copyScl' :boolean();
'----';
Field 'autoSpawn' :boolean();
Field 'destroyOnSpawn' :boolean();
Field 'spawnMethod' :enum( enumSpawnMethod )
-- Field 'spawnAsChild' :boolean();
}
:META{
category = 'spawner'
}
registerComponent( 'ProtoSpawner', ProtoSpawner )
registerEntityWithComponent( 'ProtoSpawner', ProtoSpawner )
function ProtoSpawner:__init()
self.proto = false
self.autoSpawn = true
self.destroyOnSpawn = true
self.spawnAsChild = false
self.copyLoc = true
self.copyScl = false
self.copyRot = false
self.spawnMethod = 'sibling'
self.spawnName = ''
end
function ProtoSpawner:onStart( ent )
if self.autoSpawn then
self:spawn()
end
end
function ProtoSpawner:spawnOne( ox, oy, oz )
local ent = self._entity
local instance
if self.proto then
instance = createProtoInstance( self.proto )
if instance then
instance:setName( self.spawnName )
local spawnMethod = self.spawnMethod
if spawnMethod == 'child' then
if self.copyLoc then instance:setLoc( 0,0,0 ) end
if self.copyRot then instance:setRot( 0,0,0 ) end
if self.copyScl then instance:setScl( 1,1,1 ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addChild( instance )
elseif spawnMethod == 'sibling' then
if self.copyLoc then instance:setLoc( ent:getLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addSibling( instance )
elseif spawnMethod == 'parent_sibling' then
ent:forceUpdate()
if self.copyLoc then instance:setWorldLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
if ent.parent then
ent.parent:addSibling( instance )
else
ent:getScene():addEntity( instance )
end
elseif spawnMethod == 'root' then
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
end
--FIXME:remove this non-generic code
if ent:isInstance( 'EWMapObject' ) then
instance:setFloor( ent:getFloor() )
end
end
return instance
end
function ProtoSpawner:spawn()
local result = { self:onSpawn() }
self:postSpawn()
return unpack( result )
end
function ProtoSpawner:onSpawn()
return self:spawnOne()
end
function ProtoSpawner:postSpawn()
if self.destroyOnSpawn then
self._entity:destroy()
end
end
--------------------------------------------------------------------
--EDITOR Support
function ProtoSpawner:onBuildGizmo()
local giz = mock_edit.IconGizmo( 'spawn.png' )
return giz
end
|
module 'mock'
local enumSpawnMethod = _ENUM_V {
'root',
'sibling',
'child',
'parent_sibling'
}
CLASS: ProtoSpawner ( Component )
:MODEL{
Field 'proto' :asset('proto');
Field 'spawnName' :string();
'----';
Field 'copyLoc' :boolean();
Field 'copyRot' :boolean();
Field 'copyScl' :boolean();
'----';
Field 'autoSpawn' :boolean();
Field 'destroyOnSpawn' :boolean();
Field 'spawnMethod' :enum( enumSpawnMethod )
-- Field 'spawnAsChild' :boolean();
}
:META{
category = 'spawner'
}
registerComponent( 'ProtoSpawner', ProtoSpawner )
registerEntityWithComponent( 'ProtoSpawner', ProtoSpawner )
function ProtoSpawner:__init()
self.proto = false
self.autoSpawn = true
self.destroyOnSpawn = true
self.spawnAsChild = false
self.copyLoc = true
self.copyScl = false
self.copyRot = false
self.spawnMethod = 'sibling'
self.spawnName = ''
end
function ProtoSpawner:onStart( ent )
if self.autoSpawn then
self:spawn()
end
end
function ProtoSpawner:spawnOne( ox, oy, oz )
local ent = self._entity
local instance
if self.proto then
instance = createProtoInstance( self.proto )
if instance then
instance:setName( self.spawnName )
local spawnMethod = self.spawnMethod
if spawnMethod == 'child' then
if self.copyLoc then instance:setLoc( 0,0,0 ) end
if self.copyRot then instance:setRot( 0,0,0 ) end
if self.copyScl then instance:setScl( 1,1,1 ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addChild( instance )
elseif spawnMethod == 'sibling' then
if self.copyLoc then instance:setLoc( ent:getLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addSibling( instance )
elseif spawnMethod == 'parent_sibling' then
ent:forceUpdate()
if ent.parent then
ent.parent:addSibling( instance )
else
ent:getScene():addEntity( instance )
end
if self.copyLoc then instance:setWorldLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
elseif spawnMethod == 'root' then
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
end
--FIXME:remove this non-generic code
if ent:isInstance( 'EWMapObject' ) then
instance:setFloor( ent:getFloor() )
end
end
return instance
end
function ProtoSpawner:spawn()
local result = { self:onSpawn() }
self:postSpawn()
return unpack( result )
end
function ProtoSpawner:onSpawn()
return self:spawnOne()
end
function ProtoSpawner:postSpawn()
if self.destroyOnSpawn then
self._entity:destroy()
end
end
--------------------------------------------------------------------
--EDITOR Support
function ProtoSpawner:onBuildGizmo()
local giz = mock_edit.IconGizmo( 'spawn.png' )
return giz
end
|
fixed protospawner bug: photo will spawn in error location with parent_sibling
|
fixed protospawner bug: photo will spawn in error location with parent_sibling
|
Lua
|
mit
|
tommo/mock
|
3e177a3fc9fa59123dd858a1551d3137a335f0d1
|
mods/mff/mff_quests/init.lua
|
mods/mff/mff_quests/init.lua
|
mff.quests = {}
mff.QPREFIX = "mff_quests:"
mff.QNOPREFIX = function(s) return s:sub(mff.QPREFIX:len()+1) end
quests.set_hud_position(1, 0.31)
quests.set_hud_offset(-200, 0)
mff.quests.quests = {
still_testing_quests = {
title = "Stone digger",
description = "TEST QUEST!\nGet a Super Apple at the end!",
repeating = 60*60*24,
awards = {["maptools:superapple"] = 1},
tasks = {
diggy = {
title = "Dig 100 stone",
description = "Show you can dig through stone",
max = 100,
objective = {
dig = {"default:stone"}
}
}
}
},
still_testing_quests2 = {
title = "Coal digger",
description = "TEST QUEST!\nGet a Diamond at the end!",
repeating = 60*60*24,
awards = {["default:diamond"] = 1},
tasks = {
diggy = {
title = "Dig 20 coal",
description = "Get the fire mineral",
max = 20,
objective = {
dig = {"default:stone_with_coal"}
}
}
}
},
still_testing_quests3 = {
title = "Shiny diamonds",
description = "TEST QUEST!\nGet a mithril ingot at the end!",
repeating = 60*60*24,
awards = {["moreores:mithril_ingot"] = 1},
tasks = {
diggy = {
title = "Dig 5 diamonds",
description = "Yarr harr fiddle dee-dee, being a pirate is alright with me! Do what you want 'cause a pirate is free, you are a pirate! Go get the precious booty... underground. Mine it :/",
max = 5,
objective = {
dig = {"default:stone_with_diamond"}
}
}
}
}
}
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function mff.quests.start_quest(playername, qname, meta)
quests.start_quest(playername, mff.QPREFIX .. qname, meta)
end
function mff.quests.handle_quest_end(playername, questname, metadata)
for item, count in pairs(mff.quests.quests[mff.QNOPREFIX(questname)].awards) do
local p = minetest.get_player_by_name(playername)
if p then
minetest.add_item(p:getpos(), {name=item, count=count, wear=0, metadata=""})
end
end
end
-- Register the quests defined above
for qname, quest in pairs(mff.quests.quests) do
quest.completecallback = mff.quests.handle_quest_end
local ret = quests.register_quest(mff.QPREFIX .. qname, quest)
end
-- The callback function parameters are as follows:
-- questname, questdef,
-- taskname (nil?), taskdef (nil?),
-- objective_container (that is, either questdef or taskdef),
-- objective (=objectives_container.objectives),
-- function_to_update_the_objective_progress(value)
local function iterate_through_objectives(pname, callback)
for qname, quest in pairs(mff.quests.quests) do
if quest.tasks then
for tname, task in pairs(quest.tasks) do
if not quests.is_task_disabled(pname, mff.QPREFIX .. qname, tname) then
callback(qname, quest, tname, task, task, task.objective, function (value)
quests.update_quest_task(pname, mff.QPREFIX .. qname, tname, value)
end)
end
end
else
callback(qname, quest, nil, nil, quest, quest.objective, function (value)
quests.update_quest(pname, mff.QPREFIX .. qname, value)
end)
end
end
end
local function contains_node_or_group(table, element)
for _, value in pairs(table) do
if value == element or -- Simple node match
(value:len() > 6 and value:sub(0,6) == "group:" and
minetest.get_item_group(element, value:sub(7)) > 0) then -- Group
return true
end
end
return false
end
-- Quest objective: node digging
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger or digger.is_fake_player then return end
local pname = digger:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.dig and contains_node_or_group(objective.dig, oldnode.name) then
update(1)
end
end)
end)
-- Quest objective: node punching
minetest.register_on_punchnode(function(pos, node, puncher, pointed_thing)
if not puncher or puncher.is_fake_player then return end
local pname = puncher:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.punch and contains_node_or_group(objective.punch, node.name) then
update(1)
end
end)
end)
-- Quest objective: node placement
minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack, pointed_thing)
if not placer or placer.is_fake_player then return end
local pname = placer:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.place and contains_node_or_group(objective.place, newnode.name) then
update(1)
end
end)
end)
minetest.register_on_joinplayer(function (player)
local playername = player:get_player_name()
for _, qname in ipairs({"still_testing_quests", "still_testing_quests2", "still_testing_quests3"}) do
if not quests.quest_restarting_in(playername, mff.QPREFIX .. qname) then
mff.quests.start_quest(playername, qname)
end
end
end)
|
mff.quests = {}
mff.QPREFIX = "mff_quests:"
mff.QNOPREFIX = function(s) return s:sub(mff.QPREFIX:len()+1) end
quests.set_hud_position(1, 0.31)
quests.set_hud_offset(-200, 0)
mff.quests.quests = {
still_testing_quests = {
title = "Stone digger",
description = "TEST QUEST!\nGet a Super Apple at the end!",
repeating = 60*60*24,
awards = {["maptools:superapple"] = 1},
tasks = {
diggy = {
title = "Dig 100 stone",
description = "Show you can dig through stone",
max = 100,
objective = {
dig = {"default:stone"}
}
}
}
},
still_testing_quests2 = {
title = "Coal digger",
description = "TEST QUEST!\nGet a Diamond at the end!",
repeating = 60*60*24,
awards = {["default:diamond"] = 1},
tasks = {
diggy = {
title = "Dig 20 coal",
description = "Get the fire mineral",
max = 20,
objective = {
dig = {"default:stone_with_coal"}
}
}
}
},
still_testing_quests3 = {
title = "Shiny diamonds",
description = "TEST QUEST!\nGet a mithril ingot at the end!",
repeating = 60*60*24,
awards = {["moreores:mithril_ingot"] = 1},
tasks = {
diggy = {
title = "Dig 5 diamonds",
description = "Yarr harr fiddle dee-dee, being a pirate is alright with me! Do what you want 'cause a pirate is free, you are a pirate! Go get the precious booty... underground. Mine it :/",
max = 5,
objective = {
dig = {"default:stone_with_diamond"}
}
}
}
},
levermaniac = {
title = "Levermaniac",
description = "For some reason you've become obsessed with Mesecons's lever, causing you to insanely switch the levers on and off at an amazing speed.\nDoctors have diagnosed a strange brain damage, but said you'd be rewarded with a Super Apple if you can assist them in their research about the disease.\nThey simply ask you to flip a lever 5 times, but won't come to inspect and study you afterwards, which may suggest they also are brain damaged.",
repeating = 60*60*24,
max = 5,
awards = {["maptools:superapple"] = 1},
objective = {
punch = {"mesecons_walllever:wall_lever"}
}
}
}
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function mff.quests.start_quest(playername, qname, meta)
quests.start_quest(playername, mff.QPREFIX .. qname, meta)
end
function mff.quests.handle_quest_end(playername, questname, metadata)
for item, count in pairs(mff.quests.quests[mff.QNOPREFIX(questname)].awards) do
local p = minetest.get_player_by_name(playername)
if p then
minetest.add_item(p:getpos(), {name=item, count=count, wear=0, metadata=""})
end
end
end
-- Register the quests defined above
for qname, quest in pairs(mff.quests.quests) do
quest.completecallback = mff.quests.handle_quest_end
local ret, err = quests.register_quest(mff.QPREFIX .. qname, quest)
if not ret then
minetest.log("error", "mff_quests: failed registering " .. qname .. ": " .. err)
end
end
-- The callback function parameters are as follows:
-- questname, questdef,
-- taskname (nil?), taskdef (nil?),
-- objective_container (that is, either questdef or taskdef),
-- objective (=objectives_container.objectives),
-- function_to_update_the_objective_progress(value)
local function iterate_through_objectives(pname, callback)
for qname, quest in pairs(mff.quests.quests) do
if quest.tasks then
for tname, task in pairs(quest.tasks) do
if quests.is_task_disabled(pname, mff.QPREFIX .. qname, tname) == false then
callback(qname, quest, tname, task, task, task.objective, function (value)
quests.update_quest_task(pname, mff.QPREFIX .. qname, tname, value)
end)
end
end
else
if quests.get_quest_progress(pname, mff.QPREFIX .. qname) ~= nil then
callback(qname, quest, nil, nil, quest, quest.objective, function (value)
quests.update_quest(pname, mff.QPREFIX .. qname, value)
end)
end
end
end
end
local function contains_node_or_group(table, element)
for _, value in pairs(table) do
if value == element or -- Simple node match
(value:len() > 6 and value:sub(0,6) == "group:" and
minetest.get_item_group(element, value:sub(7)) > 0) then -- Group
return true
end
end
return false
end
-- Quest objective: node digging
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger or digger.is_fake_player then return end
local pname = digger:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.dig and contains_node_or_group(objective.dig, oldnode.name) then
update(1)
end
end)
end)
-- Quest objective: node punching
minetest.register_on_punchnode(function(pos, node, puncher, pointed_thing)
if not puncher or puncher.is_fake_player then return end
local pname = puncher:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.punch and contains_node_or_group(objective.punch, node.name) then
update(1)
end
end)
end)
-- Quest objective: node placement
minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack, pointed_thing)
if not placer or placer.is_fake_player then return end
local pname = placer:get_player_name()
iterate_through_objectives(pname, function (_, _, _, _, _, objective, update)
if objective.place and contains_node_or_group(objective.place, newnode.name) then
update(1)
end
end)
end)
minetest.register_on_joinplayer(function (player)
local playername = player:get_player_name()
for _, qname in ipairs({"still_testing_quests", "still_testing_quests2", "still_testing_quests3", "levermaniac"}) do
if not quests.quest_restarting_in(playername, mff.QPREFIX .. qname) then
mff.quests.start_quest(playername, qname)
end
end
end)
|
[mff_quests] Add levermaniac quest and fix a crash
|
[mff_quests] Add levermaniac quest and fix a crash
|
Lua
|
unlicense
|
Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
8638bdb5dfe979483602c07a52fb9ec5e7a635ba
|
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 <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
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 <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
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
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5466 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
58771cdb5317e645be63929e10c8f2a8d95053b3
|
prototypes/technology.lua
|
prototypes/technology.lua
|
data:extend({
{
type = "technology",
name = "copper-floor",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon.png",
prerequisites =
{
"concrete",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor",
}
},
unit =
{
count = 75,
time = 30,
ingredients =
{
{"science-pack-1",1},
{"science-pack-2",1}
}
},
order = "[c]"
},
{
type = "technology",
name = "hoverboard",
icon = "__MagneticFloor__/graphics/icons/hoverboard-icon.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "hoverboard",
}
},
unit =
{
count = 20,
time = 30,
ingredients =
{
{"science-pack-1",1},
{"science-pack-2",1}
}
},
order = "[c]"
},
{
type = "technology",
name = "copper-floor2",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon_level2.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor2",
}
},
unit =
{
count = 100,
time = 35,
ingredients =
{
{"science-pack-1",2},
{"science-pack-2",2}
}
},
order = "[c]"
},
{
type = "technology",
name = "copper-floor3",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon_level3.png",
prerequisites =
{
"copper-floor2",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor3",
}
},
unit =
{
count = 150,
time = 60,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3}
}
},
order = "[h]"
},
{
type = "technology",
name = "accelerator",
icon = "__MagneticFloor__/graphics/directives/accelerator.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "accelerator",
}
},
unit =
{
count = 150,
time = 60,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3},
{"science-pack-3",3}
}
},
order = "[ca]"
},
{
type = "technology",
name = "directives",
icon = "__MagneticFloor__/graphics/directives/left.png",
prerequisites =
{
"accelerator",
},
effects =
{
{
type = "unlock-recipe",
recipe = "left","right","down","up"
}
},
unit =
{
count = 300,
time = 70,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3},
{"science-pack-3",3}
}
},
order = "[cd]"
}
})
|
data:extend({
{
type = "technology",
name = "copper-floor",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon.png",
prerequisites =
{
"concrete",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor",
}
},
unit =
{
count = 75,
time = 30,
ingredients =
{
{"science-pack-1",1},
{"science-pack-2",1}
}
},
order = "[c]"
},
{
type = "technology",
name = "hoverboard",
icon = "__MagneticFloor__/graphics/icons/hoverboard-icon.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "hoverboard",
}
},
unit =
{
count = 20,
time = 30,
ingredients =
{
{"science-pack-1",1},
{"science-pack-2",1}
}
},
order = "[c]"
},
{
type = "technology",
name = "copper-floor2",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon_level2.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor2",
}
},
unit =
{
count = 100,
time = 35,
ingredients =
{
{"science-pack-1",2},
{"science-pack-2",2}
}
},
order = "[c]"
},
{
type = "technology",
name = "copper-floor3",
icon = "__MagneticFloor__/graphics/icons/copper-floor-icon_level3.png",
prerequisites =
{
"copper-floor2",
},
effects =
{
{
type = "unlock-recipe",
recipe = "copper-floor3",
}
},
unit =
{
count = 150,
time = 60,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3}
}
},
order = "[h]"
},
{
type = "technology",
name = "accelerator",
icon = "__MagneticFloor__/graphics/directives/accelerator.png",
prerequisites =
{
"copper-floor",
},
effects =
{
{
type = "unlock-recipe",
recipe = "accelerator",
}
},
unit =
{
count = 150,
time = 60,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3},
{"science-pack-3",3}
}
},
order = "[ca]"
},
{
type = "technology",
name = "directives",
icon = "__MagneticFloor__/graphics/directives/left.png",
prerequisites =
{
"accelerator",
},
effects =
{
{
type = "unlock-recipe",
recipe = "left"
},
{
type = "unlock-recipe",
recipe = "right"
},
{
type = "unlock-recipe",
recipe = "down"
},
{
type = "unlock-recipe",
recipe = "up"
},
},
unit =
{
count = 300,
time = 70,
ingredients =
{
{"science-pack-1",3},
{"science-pack-2",3},
{"science-pack-3",3}
}
},
order = "[cd]"
}
})
|
fix unlocking of directive tiles
|
fix unlocking of directive tiles
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
5baa7f356c2b2434751f3c1b86c013fb07cf2463
|
roles/dotfiles/files/.hammerspoon/eventtap.lua
|
roles/dotfiles/files/.hammerspoon/eventtap.lua
|
--
-- Trying to limp along without Karabiner in Sierra.
--
local deepEquals = require 'deepEquals'
local log = require 'log'
local keyDown = hs.eventtap.event.types.keyDown
local keyUp = hs.eventtap.event.types.keyUp
local keyCodes = {
control = 59, -- TODO that's leftControl; figure out rightControl
leftShift = 56,
rightShift = 60,
}
local controlDown = {ctrl = true}
local controlUp = {}
local controlPressed = nil
local shiftDown = {shift = true}
local repeatDelay = hs.eventtap.keyRepeatDelay()
local repeatInterval = hs.eventtap.keyRepeatInterval()
local controlTimer = nil
local controlRepeatTimer = nil
local function modifierHandler(evt)
local flags=evt:getFlags()
local keyCode = evt:getKeyCode()
-- Going to fire a fake f7 key-press so that we can handle this in the
-- keyHandler function along with Return.
if keyCode == keyCodes.control then
-- We only start timers when Control is pressed alone, but we clean them up
-- unconditionally when it is released, so as not to leak.
if flags['ctrl'] == nil and controlPressed == true then
controlPressed = false
hs.eventtap.event.newKeyEvent({}, 'f7', false):post()
if controlTimer ~= nil then
controlTimer:stop()
end
if controlRepeatTimer ~= nil then
controlRepeatTimer:stop()
end
elseif deepEquals(flags, controlDown) then
controlPressed = true
hs.eventtap.event.newKeyEvent({}, 'f7', true):post()
-- We don't get repeat events for modifiers. Have to fake them.
controlTimer = hs.timer.doAfter(
repeatDelay,
(function()
if controlPressed then
controlRepeatTimer = hs.timer.doUntil(
(function() return controlPressed == false end),
(function()
hs.eventtap.event.newKeyEvent({}, 'f7', true):post()
end),
repeatInterval
)
end
end)
)
end
elseif keyCode == keyCodes.leftShift or keyCode == keyCodes.rightShift then
if deepEquals(flags, shiftDown) then
if false then
-- TODO: something like the following, which seems unlikely to work
-- given what the internets say (requires custom keyboard driver).
hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', true):post()
hs.timer.doAfter(
.5,
(function()
hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', false):post()
end)
)
end
else
-- TODO: other modifiers pressed, reset state.
end
end
end
local repeatThreshold = .5
local syntheticEvent = 94025 -- magic number chosen "at random"
local eventSourceUserData = hs.eventtap.event.properties['eventSourceUserData']
local keyboardEventKeyboardType = hs.eventtap.event.properties['keyboardEventKeyboardType']
local internalKeyboardType = 43
local externalKeyboardType = 40 -- YubiKey as well...
local stopPropagation = true
-- These are keys that do one thing when tapped but act like modifiers when
-- chorded.
local conditionalKeys = {
f7 = {
tapped = 'delete',
chorded = 'ctrl',
downAt = nil,
isChording = false,
expectedFlags = {fn = true},
},
}
-- "return" is a reserved word, so have to use longhand:
conditionalKeys['return'] = {
tapped = 'return',
chorded = 'ctrl',
downAt = nil,
isChording = false,
expectedFlags = {},
}
local function keyHandler(evt)
local userData = evt:getProperty(eventSourceUserData)
if userData == syntheticEvent then
return
end
local eventType = evt:getType()
local keyboardType = evt:getProperty(keyboardEventKeyboardType)
local keyCode = evt:getKeyCode()
local flags = evt:getFlags()
local when = hs.timer.secondsSinceEpoch()
if eventType == keyDown then
if keyCode == hs.keycodes.map['i'] then
if deepEquals(flags, {ctrl = true}) then
local frontmost = hs.application.frontmostApplication():bundleID()
if frontmost == 'com.googlecode.iterm2' or frontmost == 'org.vim.MacVim' then
hs.eventtap.event.newKeyEvent({}, 'f6', true):setProperty(eventSourceUserData, syntheticEvent):post()
return stopPropagation
end
end
end
-- Check for conditional keys.
-- Along the way, note which conditional key(s) are already down.
local activeConditionals = {}
for keyName, config in pairs(conditionalKeys) do
if keyCode == hs.keycodes.map[keyName] then
if not deepEquals(flags, config.expectedFlags) or
(config.downAt and when - config.downAt > repeatThreshold) then
local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
elseif not config.downAt then
config.downAt = when
end
return stopPropagation
elseif config.downAt then
activeConditionals[keyName] = config
end
end
-- Potentially begin chording against the active conditionals.
for keyName, config in pairs(activeConditionals) do
if config.isChording or when - config.downAt < repeatThreshold then
if deepEquals(flags, config.expectedFlags) then
config.isChording = true
local synthetic = evt:copy()
local syntheticFlags = {}
syntheticFlags[config.chorded] = true
synthetic:setFlags(syntheticFlags)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
return stopPropagation
end
end
end
elseif eventType == keyUp then
for keyName, config in pairs(conditionalKeys) do
if keyCode == hs.keycodes.map[keyName] then
if config.isChording then
config.isChording = false
else
local downAt = config.downAt
config.downAt = nil
if deepEquals(flags, config.expectedFlags) and
when - downAt <= repeatThreshold then
local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
end
end
return stopPropagation
end
end
end
end
return {
init = (function()
local modifierTap = hs.eventtap.new(
{hs.eventtap.event.types.flagsChanged},
modifierHandler
)
modifierTap:start()
local keyTap = hs.eventtap.new({keyDown, keyUp}, keyHandler)
keyTap:start()
end)
}
|
--
-- Trying to limp along without Karabiner in Sierra.
--
local deepEquals = require 'deepEquals'
local log = require 'log'
local keyDown = hs.eventtap.event.types.keyDown
local keyUp = hs.eventtap.event.types.keyUp
local keyCodes = {
control = 59, -- TODO that's leftControl; figure out rightControl
leftShift = 56,
rightShift = 60,
}
local controlDown = {ctrl = true}
local controlUp = {}
local controlPressed = nil
local shiftDown = {shift = true}
local repeatDelay = hs.eventtap.keyRepeatDelay()
local repeatInterval = hs.eventtap.keyRepeatInterval()
local controlTimer = nil
local controlRepeatTimer = nil
local function cancelTimers()
if controlTimer ~= nil then
controlTimer:stop()
controlTimer = nil
end
if controlRepeatTimer ~= nil then
controlRepeatTimer:stop()
controlRepeatTimer = nil
end
end
local function modifierHandler(evt)
local flags=evt:getFlags()
local keyCode = evt:getKeyCode()
-- Going to fire a fake delete key-press so that we can handle this in the
-- keyHandler function along with return.
if keyCode == keyCodes.control then
-- We only start timers when Control is pressed alone, but we clean them up
-- unconditionally when it is released, so as not to leak.
if flags['ctrl'] == nil and controlPressed == true then
controlPressed = false
hs.eventtap.event.newKeyEvent({}, 'delete', false):post()
cancelTimers()
elseif deepEquals(flags, controlDown) then
controlPressed = true
hs.eventtap.event.newKeyEvent({}, 'delete', true):post()
-- We don't get repeat events for modifiers. Have to fake them.
cancelTimers()
controlTimer = hs.timer.doAfter(
repeatDelay,
(function()
if controlPressed then
controlRepeatTimer = hs.timer.doUntil(
(function() return controlPressed == false end),
(function()
hs.eventtap.event.newKeyEvent({}, 'delete', true):post()
end),
repeatInterval
)
end
end)
)
end
elseif keyCode == keyCodes.leftShift or keyCode == keyCodes.rightShift then
if deepEquals(flags, shiftDown) then
if false then
-- TODO: something like the following, which seems unlikely to work
-- given what the internets say (requires custom keyboard driver).
hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', true):post()
hs.timer.doAfter(
.5,
(function()
hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', false):post()
end)
)
end
else
-- TODO: other modifiers pressed, reset state.
end
end
end
local repeatThreshold = .5
local syntheticEvent = 94025 -- magic number chosen "at random"
local eventSourceUserData = hs.eventtap.event.properties['eventSourceUserData']
local keyboardEventKeyboardType = hs.eventtap.event.properties['keyboardEventKeyboardType']
local internalKeyboardType = 43
local externalKeyboardType = 40 -- YubiKey as well...
local stopPropagation = true
-- These are keys that do one thing when tapped but act like modifiers when
-- chorded.
local conditionalKeys = {
delete = {
tapped = 'delete',
chorded = 'ctrl',
downAt = nil,
isChording = false,
-- Caps Lock is mapped to control, so during chording, keyDown events should
-- have these flags.
expectedFlags = {ctrl = true},
},
}
-- "return" is a reserved word, so have to use longhand:
conditionalKeys['return'] = {
tapped = 'return',
chorded = 'ctrl',
downAt = nil,
isChording = false,
expectedFlags = {},
}
local function keyHandler(evt)
local userData = evt:getProperty(eventSourceUserData)
if userData == syntheticEvent then
return
end
local eventType = evt:getType()
local keyboardType = evt:getProperty(keyboardEventKeyboardType)
local keyCode = evt:getKeyCode()
local flags = evt:getFlags()
local when = hs.timer.secondsSinceEpoch()
if eventType == keyDown then
if keyCode == hs.keycodes.map['i'] then
if deepEquals(flags, {ctrl = true}) then
local frontmost = hs.application.frontmostApplication():bundleID()
if frontmost == 'com.googlecode.iterm2' or frontmost == 'org.vim.MacVim' then
hs.eventtap.event.newKeyEvent({}, 'f6', true):setProperty(eventSourceUserData, syntheticEvent):post()
return stopPropagation
end
end
end
-- Check for conditional keys.
-- Along the way, note which conditional key(s) are already down.
local activeConditionals = {}
for keyName, config in pairs(conditionalKeys) do
if keyCode == hs.keycodes.map[keyName] then
if not deepEquals(flags, {}) or
(config.downAt and when - config.downAt > repeatThreshold) then
if not config.isChording then
local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
end
elseif not config.downAt then
config.downAt = when
end
return stopPropagation
elseif config.downAt then
activeConditionals[keyName] = config
end
end
-- Potentially begin chording against the active conditionals.
for keyName, config in pairs(activeConditionals) do
if config.isChording or when - config.downAt < repeatThreshold then
if deepEquals(flags, config.expectedFlags) then
config.isChording = true
local synthetic = evt:copy()
local syntheticFlags = {}
syntheticFlags[config.chorded] = true
synthetic:setFlags(syntheticFlags)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
return stopPropagation
end
end
end
elseif eventType == keyUp then
for keyName, config in pairs(conditionalKeys) do
if keyCode == hs.keycodes.map[keyName] then
if config.isChording then
config.isChording = false
else
local downAt = config.downAt
config.downAt = nil
if deepEquals(flags, {}) and
when - downAt <= repeatThreshold then
local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true)
synthetic:setProperty(eventSourceUserData, syntheticEvent)
synthetic:post()
end
end
return stopPropagation
end
end
end
end
return {
init = (function()
local modifierTap = hs.eventtap.new(
{hs.eventtap.event.types.flagsChanged},
modifierHandler
)
modifierTap:start()
local keyTap = hs.eventtap.new({keyDown, keyUp}, keyHandler)
keyTap:start()
end)
}
|
hammerspoon: fix breakage on Sierra
|
hammerspoon: fix breakage on Sierra
Some things changed on actually upgrading to Sierra, meaning that this
didn't work properly any more.
- We get {ctrl = true} rather than {fn = true} on our Caps Lock chorded
events now.
Additionally:
- Clean up timers a bit more aggressively, in case one sticks around
(I did see one example of one getting stuck).
- Synthesize "delete" rather than "f7" for Caps Lock, seeing as that's
the default Colemak value for that key, and it's more symmetrical with
what we have on the other side of the keyboard with "return".
|
Lua
|
unlicense
|
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
|
3b861e594e7aa7a525a3472c05765675199dcf3f
|
protocols/6x4/luasrc/model/network/proto_6x4.lua
|
protocols/6x4/luasrc/model/network/proto_6x4.lua
|
--[[
LuCI - Network model - 6to4 & 6in4 protocol extension
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
--[[
LuCI - Network model - 6to4 & 6in4 protocol extension
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh") or
nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
protocols/6x4: fix install state detection with netifd
|
protocols/6x4: fix install state detection with netifd
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8656 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
a962679a7bfafed23ba3615d0b305d674a236279
|
cpp/Tupfile.lua
|
cpp/Tupfile.lua
|
-- Projects that include fibre-cpp and also use tup can place a Tuprules.lua file
-- into their root directory with the line `no_libfibre = true` to prevent
-- libfibre from building.
if no_libfibre == true then
return
end
tup.include('package.lua')
CFLAGS = {'-fPIC -std=c++11 -DFIBRE_COMPILE -Wall'}
LDFLAGS = {'-static-libstdc++'}
if tup.getconfig("CC") == "" then
CXX = 'clang++'
LINKER = 'clang++'
else
CXX = tup.getconfig("CC")
LINKER = tup.getconfig("CC")
end
function get_bool_config(name, default)
if tup.getconfig(name) == "" then
return default
elseif tup.getconfig(name) == "true" then
return true
elseif tup.getconfig(name) == "false" then
return false
else
error(name.." ("..tup.getconfig(name)..") must be 'true' or 'false'.")
end
end
CFLAGS += tup.getconfig("CFLAGS")
LDFLAGS += tup.getconfig("LDFLAGS")
DEBUG = get_bool_config("DEBUG", true)
STRICT = get_bool_config("STRICT", false)
machine = fibre_run_now(CXX..' -dumpmachine') -- works with both clang and GCC
BUILD_TYPE='-shared'
if string.find(machine, "x86_64.*%-linux%-.*") then
outname = 'libfibre-linux-amd64.so'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version -Wl,--gc-sections'
STRIP = not DEBUG
elseif string.find(machine, "arm.*%-linux%-.*") then
outname = 'libfibre-linux-armhf.so'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version -Wl,--gc-sections'
STRIP = false
elseif string.find(machine, "x86_64.*-mingw.*") then
outname = 'libfibre-windows-amd64.dll'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version'
STRIP = not DEBUG
elseif string.find(machine, "x86_64.*-apple-.*") then
outname = 'libfibre-macos-x86.dylib'
STRIP = false
elseif string.find(machine, "wasm.*") then
outname = 'libfibre-wasm.js'
STRIP = false
BUILD_TYPE = ''
else
error('unknown machine identifier '..machine)
end
LDFLAGS += BUILD_TYPE
if DEBUG then
CFLAGS += '-O1 -g'
else
CFLAGS += '-O3' -- TODO: add back -lfto
end
if STRICT then
CFLAGS += '-Werror'
end
function compile(src_file)
obj_file = 'build/'..tup.file(src_file)..'.o'
tup.frule{
inputs={src_file},
command='^co^ '..CXX..' -c %f '..tostring(CFLAGS)..' -o %o',
outputs={obj_file}
}
return obj_file
end
pkg = get_fibre_package({
enable_server=false,
enable_client=true,
enable_tcp_server_backend=get_bool_config("ENABLE_TCP_SERVER_BACKEND", true),
enable_tcp_client_backend=get_bool_config("ENABLE_TCP_CLIENT_BACKEND", true),
enable_libusb_backend=get_bool_config("ENABLE_LIBUSB_BACKEND", true),
allow_heap=true,
pkgconf=(tup.getconfig("USE_PKGCONF") != "") and tup.getconfig("USE_PKGCONF") or nil
})
CFLAGS += pkg.cflags
LDFLAGS += pkg.ldflags
for _, inc in pairs(pkg.include_dirs) do
CFLAGS += '-I./'..inc
end
for _, src_file in pairs(pkg.code_files) do
object_files += compile(src_file)
end
object_files += compile('libfibre.cpp')
outname = 'build/'..outname
if not STRIP then
compile_outname=outname
else
compile_outname=outname..'.fat'
end
if tup.ext(outname) == 'js' then
extra_outputs = {tup.base(compile_outname)..'.wasm'}
else
extra_outputs = {}
end
tup.frule{
inputs=object_files,
command='^c^ '..LINKER..' %f '..tostring(CFLAGS)..' '..tostring(LDFLAGS)..' -o %o',
outputs={compile_outname, extra_outputs=extra_outputs}
}
if STRIP then
tup.frule{
inputs={compile_outname},
command='strip --strip-all --discard-all %f -o %o',
outputs={outname}
}
end
if string.find(machine, "x86_64.*-apple-.*") then
tup.frule{
inputs=outname,
command='^c^ chmod 644 %f',
}
end
|
-- Projects that include fibre-cpp and also use tup can place a Tuprules.lua file
-- into their root directory with the line `no_libfibre = true` to prevent
-- libfibre from building.
if no_libfibre == true then
return
end
tup.include('package.lua')
CFLAGS = {'-fPIC -std=c++11 -DFIBRE_COMPILE -Wall'}
LDFLAGS = {'-static-libstdc++'}
if tup.getconfig("CC") == "" then
CXX = 'clang++'
LINKER = 'clang++'
else
CXX = tup.getconfig("CC")
LINKER = tup.getconfig("CC")
end
function get_bool_config(name, default)
if tup.getconfig(name) == "" then
return default
elseif tup.getconfig(name) == "true" then
return true
elseif tup.getconfig(name) == "false" then
return false
else
error(name.." ("..tup.getconfig(name)..") must be 'true' or 'false'.")
end
end
CFLAGS += tup.getconfig("CFLAGS")
LDFLAGS += tup.getconfig("LDFLAGS")
DEBUG = get_bool_config("DEBUG", true)
STRICT = get_bool_config("STRICT", false)
machine = fibre_run_now(CXX..' -dumpmachine') -- works with both clang and GCC
BUILD_TYPE='-shared'
enable_tcp = true
if string.find(machine, "x86_64.*%-linux%-.*") then
outname = 'libfibre-linux-amd64.so'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version -Wl,--gc-sections'
STRIP = not DEBUG
elseif string.find(machine, "arm.*%-linux%-.*") then
outname = 'libfibre-linux-armhf.so'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version -Wl,--gc-sections'
STRIP = false
elseif string.find(machine, "x86_64.*-mingw.*") then
outname = 'libfibre-windows-amd64.dll'
LDFLAGS += '-lpthread -Wl,--version-script=libfibre.version'
STRIP = not DEBUG
elseif string.find(machine, "x86_64.*-apple-.*") then
outname = 'libfibre-macos-x86.dylib'
STRIP = false
enable_tcp = false
elseif string.find(machine, "arm64.*-apple-.*") then
outname = 'libfibre-macos-arm.dylib'
STRIP = false
enable_tcp = false
elseif string.find(machine, "wasm.*") then
outname = 'libfibre-wasm.js'
STRIP = false
BUILD_TYPE = ''
else
error('unknown machine identifier '..machine)
end
LDFLAGS += BUILD_TYPE
if DEBUG then
CFLAGS += '-O1 -g'
else
CFLAGS += '-O3' -- TODO: add back -lfto
end
if STRICT then
CFLAGS += '-Werror'
end
function compile(src_file)
obj_file = 'build/'..tup.file(src_file)..'.o'
tup.frule{
inputs={src_file},
command='^co^ '..CXX..' -c %f '..tostring(CFLAGS)..' -o %o',
outputs={obj_file}
}
return obj_file
end
pkg = get_fibre_package({
enable_server=false,
enable_client=true,
enable_tcp_server_backend=get_bool_config("ENABLE_TCP_SERVER_BACKEND", enable_tcp),
enable_tcp_client_backend=get_bool_config("ENABLE_TCP_CLIENT_BACKEND", enable_tcp),
enable_libusb_backend=get_bool_config("ENABLE_LIBUSB_BACKEND", true),
allow_heap=true,
pkgconf=(tup.getconfig("USE_PKGCONF") != "") and tup.getconfig("USE_PKGCONF") or nil
})
CFLAGS += pkg.cflags
LDFLAGS += pkg.ldflags
for _, inc in pairs(pkg.include_dirs) do
CFLAGS += '-I./'..inc
end
for _, src_file in pairs(pkg.code_files) do
object_files += compile(src_file)
end
object_files += compile('libfibre.cpp')
outname = 'build/'..outname
if not STRIP then
compile_outname=outname
else
compile_outname=outname..'.fat'
end
if tup.ext(outname) == 'js' then
extra_outputs = {tup.base(compile_outname)..'.wasm'}
else
extra_outputs = {}
end
tup.frule{
inputs=object_files,
command='^c^ '..LINKER..' %f '..tostring(CFLAGS)..' '..tostring(LDFLAGS)..' -o %o',
outputs={compile_outname, extra_outputs=extra_outputs}
}
if STRIP then
tup.frule{
inputs={compile_outname},
command='strip --strip-all --discard-all %f -o %o',
outputs={outname}
}
end
if string.find(machine, "x86_64.*-apple-.*") then
tup.frule{
inputs=outname,
command='^c^ chmod 644 %f',
}
end
|
Fix OSX native build
|
Fix OSX native build
|
Lua
|
mit
|
samuelsadok/fibre,samuelsadok/fibre,samuelsadok/fibre,samuelsadok/fibre,samuelsadok/fibre,samuelsadok/fibre
|
4341ceb101ef34deff2801cecbb0854fbc6c3553
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { target = connect_host, port = connect_port };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_hosts = host_session.srv_hosts;
if not (srv_choice and srv_choice.answer and srv_choice.answer.secure) then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { answer = { secure = true }, { target = connect_host, port = connect_port } };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
2ebc34546212f7e05a4a87d4dd82ba764e3b943e
|
scripts/package.lua
|
scripts/package.lua
|
---
-- Create a source or binary release package.
---
---
-- Helper function: run a command while hiding its output.
---
local function execQuiet(cmd, ...)
cmd = string.format(cmd, ...) .. " > _output_.log 2> _error_.log"
local z = os.execute(cmd)
os.remove("_output_.log")
os.remove("_error_.log")
return z
end
---
-- Check the command line arguments, and show some help if needed.
---
local usage = 'usage is: package <branch> <type>\n' ..
' <branch> is the name of the release branch to target\n' ..
' <type> is one of "source" or "binary"\n'
if #_ARGS ~= 2 then
error(usage, 0)
end
local branch = _ARGS[1]
local kind = _ARGS[2]
if kind ~= "source" and kind ~= "binary" then
error(usage, 0)
end
--
-- Make sure I've got what I've need to be happy.
--
local required = { "git", "make", "gcc", "premake5", "zip" }
for _, value in ipairs(required) do
local z = execQuiet("%s --version", value)
if z ~= 0 then
error("required tool '" .. value .. "' not found", 0)
end
end
--
-- Figure out what I'm making.
--
os.chdir("..")
local text = os.outputof(string.format('git show %s:src/host/premake.h', branch))
local _, _, version = text:find('VERSION%s*"([%w%p]+)"')
local pkgName = "premake-" .. version
local pkgExt = ".zip"
if not os.istarget("windows") and kind == "binary" then
pkgExt = ".tar.gz"
end
--
-- Make sure I'm sure.
--
printf("")
printf("I am about to create a %s package", kind:upper())
printf(" ...named release/%s%s", pkgName, pkgExt)
printf(" ...from the %s branch", branch)
printf("")
printf("Does this look right to you? If so, press [Enter] to begin.")
io.read()
--
-- Pull down the release branch.
--
print("Preparing release folder")
os.mkdir("release")
os.chdir("release")
os.rmdir(pkgName)
print("Cloning source code")
z = os.executef("git clone .. %s", pkgName)
if z ~= 0 then
error("clone failed", 0)
end
os.chdir(pkgName)
z = os.executef("git checkout %s", branch)
if z ~= 0 then
error("unable to checkout branch " .. branch, 0)
end
z = os.executef("git submodule update --init")
if z ~= 0 then
error("unable to clone submodules", 0)
end
--
-- Make absolutely sure the embedded scripts have been updated
--
print("Updating embedded scripts...")
if kind == "source" then
z = execQuiet("premake5 embed")
else
z = execQuiet("premake5 --bytecode embed")
end
if z ~= 0 then
error("failed to update the embedded scripts", 0)
end
--
-- Clear out files I don't want included in any packages.
--
print("Cleaning up the source tree...")
os.rmdir("packages")
os.rmdir(".git")
local removelist = { ".DS_Store", ".git", ".gitignore", ".gitmodules", ".travis.yml", ".editorconfig", "appveyor.yml", "Bootstrap.mak" }
for _, removeitem in ipairs(removelist) do
local founditems = os.matchfiles("**" .. removeitem)
for _, item in ipairs(founditems) do
os.remove(item)
end
end
--
-- Generate a source package.
--
if kind == "source" then
print("Generating project files...")
execQuiet("premake5 /to=build/vs2005 vs2005")
execQuiet("premake5 /to=build/vs2008 vs2008")
execQuiet("premake5 /to=build/vs2010 vs2010")
execQuiet("premake5 /to=build/vs2012 vs2012")
execQuiet("premake5 /to=build/vs2013 vs2013")
execQuiet("premake5 /to=build/vs2015 vs2015")
execQuiet("premake5 /to=build/vs2017 vs2017")
execQuiet("premake5 /to=build/gmake.windows /os=windows gmake")
execQuiet("premake5 /to=build/gmake.unix /os=linux gmake")
execQuiet("premake5 /to=build/gmake.macosx /os=macosx gmake")
execQuiet("premake5 /to=build/gmake.bsd /os=bsd gmake")
print("Creating source code package...")
os.chdir("..")
execQuiet("zip -r9 %s-src.zip %s/*", pkgName, pkgName)
end
--
-- Create a binary package for this platform. This step requires a working
-- GNU/Make/GCC environment. I use MinGW on Windows as it produces the
-- smallest binaries.
--
if kind == "binary" then
print("Building binary...")
execQuiet("premake5 gmake")
z = execQuiet("make config=release")
if z ~= 0 then
error("build failed")
end
os.chdir("bin/release")
local name = string.format("%s-%s%s", pkgName, os.host(), pkgExt)
if os.ishost("windows") then
execQuiet("zip -9 %s premake5.exe", name)
else
execQuiet("tar czvf %s premake5", name)
end
os.copyfile(name, path.join("../../../", name))
os.chdir("../../..")
end
--
-- Clean up
--
os.rmdir(pkgName)
|
---
-- Create a source or binary release package.
---
---
-- Helper function: run a command while hiding its output.
---
local function execQuiet(cmd, ...)
cmd = string.format(cmd, ...) .. " > _output_.log 2> _error_.log"
local z = os.execute(cmd)
os.remove("_output_.log")
os.remove("_error_.log")
return z
end
---
-- Check the command line arguments, and show some help if needed.
---
local usage = 'usage is: package <branch> <type>\n' ..
' <branch> is the name of the release branch to target\n' ..
' <type> is one of "source" or "binary"\n'
if #_ARGS ~= 2 then
error(usage, 0)
end
local branch = _ARGS[1]
local kind = _ARGS[2]
if kind ~= "source" and kind ~= "binary" then
error(usage, 0)
end
--
-- Make sure I've got what I've need to be happy.
--
local required = { "git", "make", "gcc", "premake5", "zip" }
for _, value in ipairs(required) do
local z = execQuiet("%s --version", value)
if not z then
error("required tool '" .. value .. "' not found", 0)
end
end
--
-- Figure out what I'm making.
--
os.chdir("..")
local text = os.outputof(string.format('git show %s:src/host/premake.h', branch))
local _, _, version = text:find('VERSION%s*"([%w%p]+)"')
local pkgName = "premake-" .. version
local pkgExt = ".zip"
if not os.istarget("windows") and kind == "binary" then
pkgExt = ".tar.gz"
end
--
-- Make sure I'm sure.
--
printf("")
printf("I am about to create a %s package", kind:upper())
printf(" ...named release/%s%s", pkgName, pkgExt)
printf(" ...from the %s branch", branch)
printf("")
printf("Does this look right to you? If so, press [Enter] to begin.")
io.read()
--
-- Pull down the release branch.
--
print("Preparing release folder")
os.mkdir("release")
os.chdir("release")
os.rmdir(pkgName)
print("Cloning source code")
z = os.executef("git clone .. %s", pkgName)
if not z then
error("clone failed", 0)
end
os.chdir(pkgName)
z = os.executef("git checkout %s", branch)
if not z then
error("unable to checkout branch " .. branch, 0)
end
z = os.executef("git submodule update --init")
if not z then
error("unable to clone submodules", 0)
end
--
-- Make absolutely sure the embedded scripts have been updated
--
print("Updating embedded scripts...")
if kind == "source" then
z = execQuiet("premake5 embed")
else
z = execQuiet("premake5 --bytecode embed")
end
if not z then
error("failed to update the embedded scripts", 0)
end
--
-- Clear out files I don't want included in any packages.
--
print("Cleaning up the source tree...")
os.rmdir("packages")
os.rmdir(".git")
local removelist = { ".DS_Store", ".git", ".gitignore", ".gitmodules", ".travis.yml", ".editorconfig", "appveyor.yml", "Bootstrap.mak" }
for _, removeitem in ipairs(removelist) do
local founditems = os.matchfiles("**" .. removeitem)
for _, item in ipairs(founditems) do
os.remove(item)
end
end
--
-- Generate a source package.
--
if kind == "source" then
print("Generating project files...")
execQuiet("premake5 /to=build/vs2005 vs2005")
execQuiet("premake5 /to=build/vs2008 vs2008")
execQuiet("premake5 /to=build/vs2010 vs2010")
execQuiet("premake5 /to=build/vs2012 vs2012")
execQuiet("premake5 /to=build/vs2013 vs2013")
execQuiet("premake5 /to=build/vs2015 vs2015")
execQuiet("premake5 /to=build/vs2017 vs2017")
execQuiet("premake5 /to=build/gmake.windows /os=windows gmake")
execQuiet("premake5 /to=build/gmake.unix /os=linux gmake")
execQuiet("premake5 /to=build/gmake.macosx /os=macosx gmake")
execQuiet("premake5 /to=build/gmake.bsd /os=bsd gmake")
print("Creating source code package...")
os.chdir("..")
execQuiet("zip -r9 %s-src.zip %s/*", pkgName, pkgName)
end
--
-- Create a binary package for this platform. This step requires a working
-- GNU/Make/GCC environment. I use MinGW on Windows as it produces the
-- smallest binaries.
--
if kind == "binary" then
print("Building binary...")
execQuiet("premake5 gmake")
z = execQuiet("make config=release")
if not z then
error("build failed")
end
os.chdir("bin/release")
local name = string.format("%s-%s%s", pkgName, os.host(), pkgExt)
if os.ishost("windows") then
execQuiet("zip -9 %s premake5.exe", name)
else
execQuiet("tar czvf %s premake5", name)
end
os.copyfile(name, path.join("../../../", name))
os.chdir("../../..")
end
--
-- Clean up
--
os.rmdir(pkgName)
|
Fix package.lua os.execute return value checks for Lua 5.3
|
Fix package.lua os.execute return value checks for Lua 5.3
|
Lua
|
bsd-3-clause
|
dcourtois/premake-core,premake/premake-core,sleepingwit/premake-core,noresources/premake-core,TurkeyMan/premake-core,premake/premake-core,Blizzard/premake-core,soundsrc/premake-core,LORgames/premake-core,starkos/premake-core,premake/premake-core,soundsrc/premake-core,premake/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,aleksijuvani/premake-core,noresources/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,dcourtois/premake-core,noresources/premake-core,dcourtois/premake-core,starkos/premake-core,TurkeyMan/premake-core,starkos/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,mandersan/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,Blizzard/premake-core,sleepingwit/premake-core,premake/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,noresources/premake-core,starkos/premake-core,Blizzard/premake-core,tvandijck/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,tvandijck/premake-core,sleepingwit/premake-core,premake/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,aleksijuvani/premake-core,LORgames/premake-core,Blizzard/premake-core,dcourtois/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,soundsrc/premake-core,mandersan/premake-core,dcourtois/premake-core,noresources/premake-core,starkos/premake-core,soundsrc/premake-core,tvandijck/premake-core,mandersan/premake-core,LORgames/premake-core,sleepingwit/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core
|
4c0563e6a48e824729500d105add3111c19b3f85
|
editor/code.lua
|
editor/code.lua
|
local cedit = {}
local colorize = require("libraries.colorize_lua")
cedit.colors = {
text = _GetColor(8),
keyword = _GetColor(11),--15),
number = _GetColor(13),--13),
comment = _GetColor(14),
str = _GetColor(13),
}
function cedit:_init(editor)
self:resetBuffer()
self.keymap = self.keymap or {}
self.parent = self.buffer
self.buffer.parent = editor
end
function cedit:resetBuffer()
self.buffer = api.TextBuffer(1,2,47,14,0,0,0)
function self.buffer:_redraw() --To add syntax highlighting
api.rect(1,9,192,128-16,6) api.color(7)
local dbuff, gx,gy, sr = self:getLinesBuffer()
local cbuff = colorize(dbuff,cedit.colors)
api.color(8)
for line, text in ipairs(cbuff) do
api.print(text, (gx*8-6)-sr*4,(gy+line-1)*8-6)
end
api.rect(1,128-7,192,8,10)
api.color(5)
api.print("LINE "..self.cursorY.."/"..#self.buffer.." CHAR "..(self.cursorX-1).."/"..self.buffer[self.cursorY]:len(),2,128-5)
end
end
function cedit:export()
if not self.buffer then self:resetBuffer() end
local code, buff = "", self.buffer:getBuffer()
for line,text in ipairs(buff) do
code = code..text.."\n"
end
return code
end
local function magiclines(s)
if s:sub(-1)~="\n" then s=s.."\n" end
return s:gmatch("(.-)\n")
end
function cedit:load(code)
self:resetBuffer()
self.buffer.buffer = {}
if not code then table.insert(self.buffer.buffer,"") return self end
local code = code
for line in magiclines(code) do
table.insert(self.buffer.buffer,line)
end
return self
end
function cedit:_switch()
end
function cedit:_redraw()
self.buffer:_redraw()
end
function cedit:_update(dt)
self.buffer:_update(dt)
end
function cedit:_mmove(x,y,dx,dy,it,iw)
if math.abs(y) > 5 then return end --Dead mouse wheel strike
if math.abs(x) > 5 then return end --Dead mouse wheel strike
if y > 0 then
self.buffer:_kpress("up",0,false)
elseif y < 0 then
self.buffer:_kpress("down",0,false)
end
if x > 0 then
self.buffer:_kpress("right",0,false) --Maybe ? or inverted..
elseif x < 0 then
self.buffer:_kpress("left",0,false)
end
end
function cedit:_tinput(t)
self.buffer:_tinput(t)
end
function cedit:_tpress()
--This means the user is using a touch device
--self.lineLimit = 7
api.showkeyboard(true)
end
return cedit
|
local cedit = {}
local colorize = require("libraries.colorize_lua")
cedit.colors = {
text = _GetColor(8),
keyword = _GetColor(11),--15),
number = _GetColor(13),--13),
comment = _GetColor(14),
str = _GetColor(13),
}
function cedit:_init()
self:resetBuffer()
self.keymap = self.keymap or {}
end
function cedit:resetBuffer()
self.buffer = api.TextBuffer(1,2,47,14,0,0,0)
self.parent = self.buffer
self.buffer.parent = require("editor")
function self.buffer:_redraw() --To add syntax highlighting
api.rect(1,9,192,128-16,6) api.color(7)
local dbuff, gx,gy, sr = self:getLinesBuffer()
local cbuff = colorize(dbuff,cedit.colors)
api.color(8)
for line, text in ipairs(cbuff) do
api.print(text, (gx*8-6)-sr*4,(gy+line-1)*8-6)
end
api.rect(1,128-7,192,8,10)
api.color(5)
api.print("LINE "..self.cursorY.."/"..#self.buffer.." CHAR "..(self.cursorX-1).."/"..self.buffer[self.cursorY]:len(),2,128-5)
end
end
function cedit:export()
if not self.buffer then self:resetBuffer() end
local code, buff = "", self.buffer:getBuffer()
for line,text in ipairs(buff) do
code = code..text.."\n"
end
return code
end
local function magiclines(s)
if s:sub(-1)~="\n" then s=s.."\n" end
return s:gmatch("(.-)\n")
end
function cedit:load(code)
self:resetBuffer()
self.buffer.buffer = {}
if not code then table.insert(self.buffer.buffer,"") return self end
local code = code
for line in magiclines(code) do
table.insert(self.buffer.buffer,line)
end
return self
end
function cedit:_switch()
end
function cedit:_redraw()
self.buffer:_redraw()
end
function cedit:_update(dt)
self.buffer:_update(dt)
end
function cedit:_mmove(x,y,dx,dy,it,iw)
if math.abs(y) > 5 then return end --Dead mouse wheel strike
if math.abs(x) > 5 then return end --Dead mouse wheel strike
if y > 0 then
self.buffer:_kpress("up",0,false)
elseif y < 0 then
self.buffer:_kpress("down",0,false)
end
if x > 0 then
self.buffer:_kpress("right",0,false) --Maybe ? or inverted..
elseif x < 0 then
self.buffer:_kpress("left",0,false)
end
end
function cedit:_tinput(t)
self.buffer:_tinput(t)
end
function cedit:_tpress()
--This means the user is using a touch device
--self.lineLimit = 7
api.showkeyboard(true)
end
return cedit
|
Fix a bug where resetting the buffer didn't update the keymap parent.
|
Fix a bug where resetting the buffer didn't update the keymap parent.
This is a bit confusing because it's easy to think of the text buffer
as a data structure, not an editor mode, but it's kind of acting as
both. If it were just a data structure, it wouldn't handle key
bindings, but if it were just an editor mode, it wouldn't get replaced
when a new cart gets loaded.
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
53cdba820bec3b9c4bf62e8d6d075a67e03e4201
|
xmake/modules/core/tools/rc.lua
|
xmake/modules/core/tools/rc.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file rc.lua
--
-- imports
import("core.base.option")
import("core.project.project")
-- init it
function init(self)
end
-- make the define flag
function nf_define(self, macro)
return "-D" .. macro
end
-- make the undefine flag
function nf_undefine(self, macro)
return "-U" .. macro
end
-- make the includedir flag
function nf_includedir(self, dir)
return "-I" .. os.args(dir)
end
-- make the compile arguments list
function _compargv1(self, sourcefile, objectfile, flags)
return self:program(), table.join(flags, "-Fo" .. objectfile, sourcefile)
end
-- compile the source file
function _compile1(self, sourcefile, objectfile, dependinfo, flags)
-- ensure the object directory
os.mkdir(path.directory(objectfile))
-- compile it
try
{
function ()
local outdata, errdata = vstool.iorunv(_compargv1(self, sourcefile, objectfile, flags))
return (outdata or "") .. (errdata or "")
end,
catch
{
function (errors)
-- use stdout as errors first from vstool.iorunv()
if type(errors) == "table" then
local errs = errors.stdout or ""
if #errs:trim() == 0 then
errs = errors.stderr or ""
end
errors = errs
end
os.raise(tostring(errors))
end
},
finally
{
function (ok, warnings)
-- print some warnings
if warnings and #warnings > 0 and option.get("verbose") then
cprint("${color.warning}%s", table.concat(table.slice(warnings:split('\n'), 1, 8), '\n'))
end
end
}
}
end
-- make the compile arguments list
function compargv(self, sourcefiles, objectfile, flags)
-- only support single source file now
assert(type(sourcefiles) ~= "table", "'object:sources' not support!")
-- for only single source file
return _compargv1(self, sourcefiles, objectfile, flags)
end
-- compile the source file
function compile(self, sourcefiles, objectfile, dependinfo, flags)
-- only support single source file now
assert(type(sourcefiles) ~= "table", "'object:sources' not support!")
-- for only single source file
_compile1(self, sourcefiles, objectfile, dependinfo, flags)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file rc.lua
--
-- imports
import("core.base.option")
import("core.project.project")
import("private.tools.vstool")
-- init it
function init(self)
end
-- make the define flag
function nf_define(self, macro)
return "-D" .. macro
end
-- make the undefine flag
function nf_undefine(self, macro)
return "-U" .. macro
end
-- make the includedir flag
function nf_includedir(self, dir)
return "-I" .. os.args(dir)
end
-- make the compile arguments list
function _compargv1(self, sourcefile, objectfile, flags)
return self:program(), table.join(flags, "-Fo" .. objectfile, sourcefile)
end
-- compile the source file
function _compile1(self, sourcefile, objectfile, dependinfo, flags)
-- ensure the object directory
os.mkdir(path.directory(objectfile))
-- compile it
try
{
function ()
local outdata, errdata = vstool.iorunv(_compargv1(self, sourcefile, objectfile, flags))
return (outdata or "") .. (errdata or "")
end,
catch
{
function (errors)
-- use stdout as errors first from vstool.iorunv()
if type(errors) == "table" then
local errs = errors.stdout or ""
if #errs:trim() == 0 then
errs = errors.stderr or ""
end
errors = errs
end
os.raise(tostring(errors))
end
},
finally
{
function (ok, warnings)
-- print some warnings
if warnings and #warnings > 0 and option.get("verbose") then
cprint("${color.warning}%s", table.concat(table.slice(warnings:split('\n'), 1, 8), '\n'))
end
end
}
}
end
-- make the compile arguments list
function compargv(self, sourcefiles, objectfile, flags)
-- only support single source file now
assert(type(sourcefiles) ~= "table", "'object:sources' not support!")
-- for only single source file
return _compargv1(self, sourcefiles, objectfile, flags)
end
-- compile the source file
function compile(self, sourcefiles, objectfile, dependinfo, flags)
-- only support single source file now
assert(type(sourcefiles) ~= "table", "'object:sources' not support!")
-- for only single source file
_compile1(self, sourcefiles, objectfile, dependinfo, flags)
end
|
fix rc errors again
|
fix rc errors again
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
c33cdd8704246887e11d7c353f773f7b488a47f2
|
src/lib/virtio/virtq.lua
|
src/lib/virtio/virtq.lua
|
-- Implements virtio virtq
module(...,package.seeall)
local freelist = require("core.freelist")
local lib = require("core.lib")
local memory = require("core.memory")
local ffi = require("ffi")
local C = ffi.C
local band = bit.band
local rshift = bit.rshift
require("lib.virtio.virtio.h")
require("lib.virtio.virtio_vring_h")
--[[
--]]
local vring_desc_ptr_t = ffi.typeof("struct vring_desc *")
VirtioVirtq = {}
function VirtioVirtq:new()
local o = {}
return setmetatable(o, {__index = VirtioVirtq})
end
function VirtioVirtq:enable_indirect_descriptors ()
self.get_desc = self.get_desc_indirect
end
function VirtioVirtq:get_desc_indirect (id)
local device = self.device
local ring_desc = self.virtq.desc
if band(ring_desc[id].flags, C.VIRTIO_DESC_F_INDIRECT) == 0 then
return ring_desc, id
else
local addr = device.map_from_guest(device, ring_desc[id].addr)
return ffi.cast(vring_desc_ptr_t, addr), 0
end
end
function VirtioVirtq:get_desc_direct (id)
return self.virtq.desc, id
end
-- Default: don't support indirect descriptors unless
-- enable_indirect_descriptors is called to replace this binding.
VirtioVirtq.get_desc = VirtioVirtq.get_desc_direct
-- Receive all available packets from the virtual machine.
function VirtioVirtq:get_buffers (kind, ops, hdr_len)
local device = self.device
local idx = self.virtq.avail.idx
local avail, vring_mask = self.avail, self.vring_num-1
while idx ~= avail do
-- Header
local v_header_id = self.virtq.avail.ring[band(avail,vring_mask)]
local desc, id = self:get_desc(v_header_id)
local data_desc = desc[id]
local packet =
ops.packet_start(device, data_desc.addr, data_desc.len)
local total_size = hdr_len
if not packet then break end
-- support ANY_LAYOUT
if hdr_len < data_desc.len then
local addr = data_desc.addr + hdr_len
local len = data_desc.len - hdr_len
local added_len = ops.buffer_add(device, packet, addr, len)
total_size = total_size + added_len
end
-- Data buffer
while band(data_desc.flags, C.VIRTIO_DESC_F_NEXT) ~= 0 do
data_desc = desc[data_desc.next]
local added_len = ops.buffer_add(device, packet, data_desc.addr, data_desc.len)
total_size = total_size + added_len
end
ops.packet_end(device, v_header_id, total_size, packet)
avail = band(avail + 1, 65535)
end
self.avail = avail
end
function VirtioVirtq:put_buffer (id, len)
local used = self.virtq.used.ring[band(self.used, self.vring_num-1)]
used.id, used.len = id, len
self.used = band(self.used + 1, 65535)
end
-- Prepared argument for writing a 1 to an eventfd.
local eventfd_one = ffi.new("uint64_t[1]", {1})
function VirtioVirtq:signal_used()
if self.virtq.used.idx ~= self.used then
self.virtq.used.idx = self.used
if band(self.virtq.avail.flags, C.VRING_F_NO_INTERRUPT) == 0 then
C.write(self.callfd, eventfd_one, 8)
end
end
end
|
-- Implements virtio virtq
module(...,package.seeall)
local freelist = require("core.freelist")
local lib = require("core.lib")
local memory = require("core.memory")
local ffi = require("ffi")
local C = ffi.C
local band = bit.band
local rshift = bit.rshift
require("lib.virtio.virtio.h")
require("lib.virtio.virtio_vring_h")
--[[
--]]
local vring_desc_ptr_t = ffi.typeof("struct vring_desc *")
VirtioVirtq = {}
function VirtioVirtq:new()
local o = {}
return setmetatable(o, {__index = VirtioVirtq})
end
function VirtioVirtq:enable_indirect_descriptors ()
self.get_desc = self.get_desc_indirect
end
function VirtioVirtq:get_desc_indirect (id)
local device = self.device
local ring_desc = self.virtq.desc
if band(ring_desc[id].flags, C.VIRTIO_DESC_F_INDIRECT) == 0 then
return ring_desc, id
else
local addr = device.map_from_guest(device, ring_desc[id].addr)
return ffi.cast(vring_desc_ptr_t, addr), 0
end
end
function VirtioVirtq:get_desc_direct (id)
return self.virtq.desc, id
end
-- Default: don't support indirect descriptors unless
-- enable_indirect_descriptors is called to replace this binding.
VirtioVirtq.get_desc = VirtioVirtq.get_desc_direct
-- Receive all available packets from the virtual machine.
function VirtioVirtq:get_buffers (kind, ops, hdr_len)
local device = self.device
local idx = self.virtq.avail.idx
local avail, vring_mask = self.avail, self.vring_num-1
while idx ~= avail do
-- Header
local v_header_id = self.virtq.avail.ring[band(avail,vring_mask)]
local desc, id = self:get_desc(v_header_id)
local data_desc = desc[id]
local packet =
ops.packet_start(device, data_desc.addr, data_desc.len)
local total_size = hdr_len
if not packet then break end
-- support ANY_LAYOUT
if hdr_len < data_desc.len then
local addr = data_desc.addr + hdr_len
local len = data_desc.len - hdr_len
local added_len = ops.buffer_add(device, packet, addr, len)
total_size = total_size + added_len
end
-- Data buffer
while band(data_desc.flags, C.VIRTIO_DESC_F_NEXT) ~= 0 do
data_desc = desc[data_desc.next]
local added_len = ops.buffer_add(device, packet, data_desc.addr, data_desc.len)
total_size = total_size + added_len
end
ops.packet_end(device, v_header_id, total_size, packet)
avail = band(avail + 1, 65535)
end
self.avail = avail
end
function VirtioVirtq:put_buffer (id, len)
local used = self.virtq.used.ring[band(self.used, self.vring_num-1)]
used.id, used.len = id, len
self.used = band(self.used + 1, 65535)
end
-- Prepared argument for writing a 1 to an eventfd.
local eventfd_one = ffi.new("uint64_t[1]", {1})
function VirtioVirtq:signal_used ()
if self.virtq.used.idx ~= self.used then
self.virtq.used.idx = self.used
C.full_memory_barrier()
if band(self.virtq.avail.flags, C.VRING_F_NO_INTERRUPT) == 0 then
C.write(self.callfd, eventfd_one, 8)
end
end
end
|
virtq: Use hardware memory barrier in "call"
|
virtq: Use hardware memory barrier in "call"
This fixes a subtle bug where the guest can become stuck due to
missing an interrupt. This happens with e.g. Linux kernel guests that
use interrupts and not e.g. DPDK guests that are polling.
See details on snabb-devel:
https://groups.google.com/d/msg/snabb-devel/8oGjqlSkiqw/4Yi9CVEdjD0J
|
Lua
|
apache-2.0
|
pirate/snabbswitch,kellabyte/snabbswitch,virtualopensystems/snabbswitch,mixflowtech/logsensor,justincormack/snabbswitch,heryii/snabb,aperezdc/snabbswitch,mixflowtech/logsensor,pirate/snabbswitch,lukego/snabb,eugeneia/snabb,justincormack/snabbswitch,snabbnfv-goodies/snabbswitch,heryii/snabb,kbara/snabb,virtualopensystems/snabbswitch,lukego/snabbswitch,Igalia/snabb,lukego/snabb,SnabbCo/snabbswitch,fhanik/snabbswitch,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,plajjan/snabbswitch,hb9cwp/snabbswitch,justincormack/snabbswitch,wingo/snabb,eugeneia/snabbswitch,xdel/snabbswitch,dpino/snabb,dpino/snabbswitch,alexandergall/snabbswitch,andywingo/snabbswitch,virtualopensystems/snabbswitch,dpino/snabb,dpino/snabb,lukego/snabbswitch,wingo/snabb,aperezdc/snabbswitch,eugeneia/snabbswitch,xdel/snabbswitch,dpino/snabb,dpino/snabbswitch,snabbco/snabb,lukego/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,mixflowtech/logsensor,wingo/snabbswitch,alexandergall/snabbswitch,andywingo/snabbswitch,snabbco/snabb,wingo/snabbswitch,pavel-odintsov/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,andywingo/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,dpino/snabbswitch,kbara/snabb,justincormack/snabbswitch,aperezdc/snabbswitch,snabbco/snabb,dwdm/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabb,lukego/snabb,Igalia/snabbswitch,heryii/snabb,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,lukego/snabbswitch,wingo/snabbswitch,fhanik/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,andywingo/snabbswitch,snabbco/snabb,xdel/snabbswitch,eugeneia/snabb,plajjan/snabbswitch,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,kellabyte/snabbswitch,plajjan/snabbswitch,Igalia/snabb,javierguerragiraldez/snabbswitch,wingo/snabb,SnabbCo/snabbswitch,heryii/snabb,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,heryii/snabb,eugeneia/snabb,dpino/snabb,pirate/snabbswitch,eugeneia/snabb,kellabyte/snabbswitch,fhanik/snabbswitch,wingo/snabb,wingo/snabb,lukego/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabb,Igalia/snabb,eugeneia/snabb,kbara/snabb,aperezdc/snabbswitch,snabbco/snabb,kbara/snabb,pavel-odintsov/snabbswitch,kbara/snabb,wingo/snabb,Igalia/snabbswitch,Igalia/snabb,wingo/snabbswitch,javierguerragiraldez/snabbswitch,heryii/snabb,eugeneia/snabb,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,kbara/snabb,plajjan/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabb,dwdm/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabbswitch,javierguerragiraldez/snabbswitch,alexandergall/snabbswitch
|
461110842e24b181d48540bf58e25e34beaf170e
|
mod_listusers/mod_listusers.lua
|
mod_listusers/mod_listusers.lua
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
local banner = config.get("*", "console_banner");
if (
(not banner) or
(
(type(banner) == "string") and
(banner:match("^| (.+)$"))
)
) then
repeat
local rec_banner = conn:receive()
until
rec_banner == "" or
rec_banner == nil; -- skip banner
end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
mod_listusers: fixed banner skipping cycle
|
mod_listusers: fixed banner skipping cycle
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
8b39a078f114883c75157118e947f56f6b7dcd02
|
game/entity.lua
|
game/entity.lua
|
-- API for interacting with the entity registration/creation system.
-- For the behaviour of individual Entity instances, see game/Entity.lua
-- For built in entity types, see builtins.lua
local Entity = require 'game.Entity'
entity = {}
local entity_types = {}
-- create a new instance of a named entity.
-- entity.create { type = 'Wall'; Render = {...}; Blocker = {...} }
function entity.create(init)
-- "init" is the initializer for this specific entity
-- it consists of a few top-level fields like id and name, and 0 or more
-- component name => component setting mappings.
-- One of the top-level fields, 'type', tells us what EntityType to load.
-- "def" is the definition for this EntityType. It has two fields, "fields"
-- and "components".
local def = assertf(entity_types[init.type], 'no EntityType found: %s', init.type)
-- To turn init+def into an actual Entity, we need to set up two things.
-- For the top level fields, we assign Entity as the metatable for init,
-- and set _DEF to point to the def table, so that Entity:__index can fall
-- back to it.
-- For the components, we create an empty table for each component that
-- isn't already listed in init, and __index it to the corresponding component
-- in type.
-- Then we just need to run the registered component initializers and we're done!
-- Set up __index for top level & metamethods
init._DEF = def
setmetatable(init, Entity)
-- Set up __index for individual components
for k,v in pairs(def.components) do
init[k] = init[k] or {}
setmetatable(init[k], v)
end
-- Run initializers
for _,fn in ipairs(init.__init or {}) do
fn(init)
end
-- Initialize table of children
init.children = init.children or {}
-- At this point, the entity object contains all those top-level fields that
-- differ from the EntityType, and __index provides the missing ones, as
-- well as all methods and metamethods provided by the components.
-- Metamethods are stored in top level arrays; e.g. init.__frob is an array
-- of all the __frob metamethods provided by its components.
-- Individual component fields (e.g. init.Item) are also tables, __indexed
-- to the corresponding component definition in the EntityType.
return init
end
local function loadComponent(name)
local fullname = 'components.'..name
if not package.loaded[fullname] then
local def = require(fullname)
local metamethods,methods,defaults = {},{},{}
for k,v in pairs(def) do
if type(k) == 'string' and k:match('^__') then
metamethods[k] = v
elseif type(v) == 'function' then
methods[k] = v
else
defaults[k] = v
end
end
package.loaded[fullname] = {
defaults = defaults;
name = name;
metamethods = metamethods;
methods = methods;
}
end
return package.loaded[fullname]
end
-- Register a new entity type. It can then be instantiated with entity.create { type = 'name'; ...}
-- Registration is a curried function taking a name and then a table of constructor data.
-- entity.register 'Wall' {
-- name = 'wall';
-- Render = {...};
-- Blocker = {...};
-- ...
-- }
-- There is at present no support for inheriting from other entity types, a la SS2.
function entity.register(name)
return function(init)
local components = {}
for name,cmp in pairs(init) do
if name:match('^[A-Z]') then
-- keys starting with capital letters are component initializers
init[name],components[name] = nil,cmp
local def = loadComponent(name)
table.merge(cmp, def.defaults, "ignore")
cmp.__index = cmp
table.merge(init, def.methods, "error")
for k,v in pairs(def.metamethods) do
init[k] = init[k] or {}
table.insert(init[k], v)
end
end
end
entity_types[name] = { defaults = init, components = components }
end
end
|
-- API for interacting with the entity registration/creation system.
-- For the behaviour of individual Entity instances, see game/Entity.lua
-- For built in entity types, see builtins.lua
local Entity = require 'game.Entity'
entity = {}
local entity_types = {}
-- create a new instance of a named entity.
-- entity.create { type = 'Wall'; Render = {...}; Blocker = {...} }
function entity.create(init)
-- "init" is the initializer for this specific entity
-- it consists of a few top-level fields like id and name, and 0 or more
-- component name => component setting mappings.
-- One of the top-level fields, 'type', tells us what EntityType to load.
-- "def" is the definition for this EntityType. It has two fields, "fields"
-- and "components".
local def = assertf(entity_types[init.type], 'no EntityType found: %s', init.type)
-- To turn init+def into an actual Entity, we need to set up two things.
-- For the top level fields, we assign Entity as the metatable for init,
-- and set _DEF to point to the def table, so that Entity:__index can fall
-- back to it.
-- For the components, we create an empty table for each component that
-- isn't already listed in init, and __index it to the corresponding component
-- in type.
-- Then we just need to run the registered component initializers and we're done!
-- Set up __index for top level & metamethods
init._DEF = def
setmetatable(init, Entity)
-- Set up __index for individual components
for k,v in pairs(def.components) do
init[k] = init[k] or {}
setmetatable(init[k], v)
end
-- Run initializers
for _,fn in ipairs(init.__init or {}) do
fn(init)
end
-- Initialize table of children
init.children = init.children or {}
-- At this point, the entity object contains all those top-level fields that
-- differ from the EntityType, and __index provides the missing ones, as
-- well as all methods provided by the components.
-- Message handlers are stored in top level arrays; e.g. init.__frob is an
-- array of all the __frob handlers provided by its components. FIXME: we
-- need a less ugly way of specifying message handlers.
-- Individual component fields (e.g. init.Item) are also tables, __indexed
-- to the corresponding component definition in the EntityType.
return init
end
-- Register a new entity type. It can then be instantiated with entity.create { type = 'name'; ...}
-- Registration is a curried function taking a name and then a table of constructor data.
-- entity.register 'Wall' {
-- name = 'wall';
-- Render = {...};
-- Blocker = {...};
-- ...
-- }
-- There is at present no support for inheriting from other entity types, a la SS2.
function entity.register(name)
log.debug('Registering entity type %s', name)
return function(init)
local defaults = {} -- default top-level field values, including methods
local components = {} -- component-specific data
for name,component in pairs(init) do
if not name:match('^[A-Z]') then
-- field is not a component initializer
defaults[name] = component
else
-- field is a component initializer. Load the component definition.
components[name] = component
component.__index = component
local def = require('components.'..name)
for k,v in pairs(def) do
if type(k) == 'string' and k:match('^__') then
-- message handlers go into a top level collection with that name; e.g. for
-- the __frob message, individual handlers are in defaults.__frob
defaults[k] = defaults[k] or {}
table.insert(defaults[k], v)
elseif type(v) == 'function' then
-- functions go directly into the top level; name collisions are an error
assert(defaults[k] == nil)
defaults[k] = v
elseif component[k] == nil then
-- everything else goes in component-specific data, but only if it
-- hasn't been overriden.
component[k] = v
end
end
end
end
entity_types[name] = { defaults = defaults, components = components }
end
end
|
Fix table modification during traversal in entity.register
|
Fix table modification during traversal in entity.register
|
Lua
|
mit
|
ToxicFrog/ttymor
|
491f24d3d19a94416257e4ffacaae01aef9d272d
|
frontend/apps/reader/modules/readerdevicestatus.lua
|
frontend/apps/reader/modules/readerdevicestatus.lua
|
local ButtonDialogTitle = require("ui/widget/buttondialogtitle")
local Device = require("device")
local Font = require("ui/font")
local InputContainer = require("ui/widget/container/inputcontainer")
local Screen = Device.screen
local UIManager = require("ui/uimanager")
local powerd = Device:getPowerDevice()
local _ = require("gettext")
local T = require("ffi/util").template
local ReaderDeviceStatus = InputContainer:new{
}
function ReaderDeviceStatus:init()
if powerd:getCapacity() > 0 or powerd:isCharging() then
self.checkLowBattery = function()
local threshold = G_reader_settings:readSetting("low_battery_threshold") or 20
local battery_capacity = powerd:getCapacity()
if powerd:getDissmisBatteryStatus() ~= true and battery_capacity <= threshold then
local low_battery_info
low_battery_info = ButtonDialogTitle:new {
modal = true,
title = T(_("The battery is getting low.\n%1% remaining."), battery_capacity),
title_align = "center",
title_face = Font:getFace("infofont"),
dismissable = false,
buttons = {
{
{
text = _("Dismiss"),
callback = function()
UIManager:close(low_battery_info)
powerd:setDissmisBatteryStatus(true)
UIManager:scheduleIn(300, self.checkLowBattery)
end,
},
},
}
}
UIManager:show(low_battery_info)
return
elseif powerd:getDissmisBatteryStatus() and battery_capacity > threshold then
powerd:setDissmisBatteryStatus(false)
end
UIManager:scheduleIn(300, self.checkLowBattery)
end
self.ui.menu:registerToMainMenu(self)
self:startBatteryChecker()
else
self.checkLowBattery = nil
end
end
function ReaderDeviceStatus:addToMainMenu(menu_items)
menu_items.battery = {
text = _("Low battery alarm"),
sub_item_table = {
{
text = _("Enable"),
checked_func = function()
return G_reader_settings:nilOrTrue("battery_alarm")
end,
callback = function()
G_reader_settings:flipNilOrTrue("battery_alarm")
if G_reader_settings:nilOrTrue("battery_alarm") then
self:startBatteryChecker()
else
self:stopBatteryChecker()
powerd:setDissmisBatteryStatus(false)
end
end,
},
{
text = _("Low battery threshold"),
enabled_func = function() return G_reader_settings:nilOrTrue("battery_alarm") end,
callback = function()
local SpinWidget = require("ui/widget/spinwidget")
local curr_items = G_reader_settings:readSetting("low_battery_threshold") or 20
local battery_spin = SpinWidget:new {
width = Screen:getWidth() * 0.6,
value = curr_items,
value_min = 5,
value_max = 90,
value_hold_step = 10,
ok_text = _("Set threshold"),
title_text = _("Low battery threshold"),
callback = function(battery_spin)
G_reader_settings:saveSetting("low_battery_threshold", battery_spin.value)
powerd:setDissmisBatteryStatus(false)
end
}
UIManager:show(battery_spin)
end,
},
},
}
end
function ReaderDeviceStatus:startBatteryChecker()
if G_reader_settings:nilOrTrue("battery_alarm") and self.checkLowBattery then
self.checkLowBattery()
end
end
function ReaderDeviceStatus:stopBatteryChecker()
if self.checkLowBattery then
UIManager:unschedule(self.checkLowBattery)
end
end
function ReaderDeviceStatus:onResume()
self:startBatteryChecker()
end
function ReaderDeviceStatus:onSuspend()
self:stopBatteryChecker()
end
function ReaderDeviceStatus:onCloseWidget()
self:stopBatteryChecker()
end
return ReaderDeviceStatus
|
local ButtonDialogTitle = require("ui/widget/buttondialogtitle")
local Device = require("device")
local Font = require("ui/font")
local InputContainer = require("ui/widget/container/inputcontainer")
local Screen = Device.screen
local UIManager = require("ui/uimanager")
local powerd = Device:getPowerDevice()
local _ = require("gettext")
local T = require("ffi/util").template
local ReaderDeviceStatus = InputContainer:new{
}
function ReaderDeviceStatus:init()
if powerd:getCapacity() > 0 or powerd:isCharging() then
self.checkLowBattery = function()
local threshold = G_reader_settings:readSetting("low_battery_threshold") or 20
local battery_capacity = powerd:getCapacity()
if powerd:isCharging() then
powerd:setDissmisBatteryStatus(false)
elseif powerd:getDissmisBatteryStatus() ~= true and battery_capacity <= threshold then
local low_battery_info
low_battery_info = ButtonDialogTitle:new {
modal = true,
title = T(_("The battery is getting low.\n%1% remaining."), battery_capacity),
title_align = "center",
title_face = Font:getFace("infofont"),
dismissable = false,
buttons = {
{
{
text = _("Dismiss"),
callback = function()
UIManager:close(low_battery_info)
powerd:setDissmisBatteryStatus(true)
UIManager:scheduleIn(300, self.checkLowBattery)
end,
},
},
}
}
UIManager:show(low_battery_info)
return
elseif powerd:getDissmisBatteryStatus() and battery_capacity > threshold then
powerd:setDissmisBatteryStatus(false)
end
UIManager:scheduleIn(300, self.checkLowBattery)
end
self.ui.menu:registerToMainMenu(self)
self:startBatteryChecker()
else
self.checkLowBattery = nil
end
end
function ReaderDeviceStatus:addToMainMenu(menu_items)
menu_items.battery = {
text = _("Low battery alarm"),
sub_item_table = {
{
text = _("Enable"),
checked_func = function()
return G_reader_settings:nilOrTrue("battery_alarm")
end,
callback = function()
G_reader_settings:flipNilOrTrue("battery_alarm")
if G_reader_settings:nilOrTrue("battery_alarm") then
self:startBatteryChecker()
else
self:stopBatteryChecker()
powerd:setDissmisBatteryStatus(false)
end
end,
},
{
text = _("Low battery threshold"),
enabled_func = function() return G_reader_settings:nilOrTrue("battery_alarm") end,
callback = function()
local SpinWidget = require("ui/widget/spinwidget")
local curr_items = G_reader_settings:readSetting("low_battery_threshold") or 20
local battery_spin = SpinWidget:new {
width = Screen:getWidth() * 0.6,
value = curr_items,
value_min = 5,
value_max = 90,
value_hold_step = 10,
ok_text = _("Set threshold"),
title_text = _("Low battery threshold"),
callback = function(battery_spin)
G_reader_settings:saveSetting("low_battery_threshold", battery_spin.value)
powerd:setDissmisBatteryStatus(false)
end
}
UIManager:show(battery_spin)
end,
},
},
}
end
function ReaderDeviceStatus:startBatteryChecker()
if G_reader_settings:nilOrTrue("battery_alarm") and self.checkLowBattery then
self.checkLowBattery()
end
end
function ReaderDeviceStatus:stopBatteryChecker()
if self.checkLowBattery then
UIManager:unschedule(self.checkLowBattery)
end
end
function ReaderDeviceStatus:onResume()
self:startBatteryChecker()
end
function ReaderDeviceStatus:onSuspend()
self:stopBatteryChecker()
end
function ReaderDeviceStatus:onCloseWidget()
self:stopBatteryChecker()
end
return ReaderDeviceStatus
|
[UX] Don't show low battery warning when charging (#4563)
|
[UX] Don't show low battery warning when charging (#4563)
Fix #4560
|
Lua
|
agpl-3.0
|
mihailim/koreader,pazos/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,Frenzie/koreader,NiLuJe/koreader,mwoz123/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,houqp/koreader,Hzj-jie/koreader,koreader/koreader
|
ffc27d4437da4b9b001523b603882cad5d48c4bf
|
frontend/ui/device/screen.lua
|
frontend/ui/device/screen.lua
|
local Geom = require("ui/geometry")
local DEBUG = require("dbg")
-- Blitbuffer
-- einkfb
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
width = 0,
height = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:init()
-- for unknown strange reason, pitch*2 is 10 px more than screen width in KPW
self.width, self.height = self.fb:getSize()
-- Blitbuffer still uses inverted 4bpp bitmap, so pitch should be
-- (self.width / 2)
self.bb = Blitbuffer.new(self.width, self.height, self.width/2)
if self.width > self.height then
-- For another unknown strange reason, self.fb:getOrientation always
-- return 0 in KPW, even though we are in landscape mode.
-- Seems like the native framework change framebuffer on the fly when
-- starting booklet. Starting KPV from ssh and KPVBooklet will get
-- different framebuffer height and width.
--
--self.native_rotation_mode = self.fb:getOrientation()
self.native_rotation_mode = 1
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type, waveform_mode, x, y, w, h)
if x then x = x < 0 and 0 or math.floor(x) end
if y then y = y < 0 and 0 or math.floor(y) end
if w then w = w + x > self.width and self.width - x or math.ceil(w) end
if h then h = h + y > self.height and self.height - y or math.ceil(h) end
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
if x and y and w and h then
x, y = y, self.width - w - x
w, h = h, w
end
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 3 then
self.fb.bb:blitFromRotate(self.bb, 90)
if x and y and w and h then
x, y = self.height - h - y, x
w, h = h, w
end
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 0 then
self.fb.bb:blitFromRotate(self.bb, 90)
if x and y and w and h then
x, y = self.height - h - y, x
w, h = h, w
end
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 3 then
self.fb.bb:blitFromRotate(self.bb, 180)
if x and y and w and h then
x, y = self.width - w - x, self.height - h - y
end
end
self.fb:refresh(refesh_type, waveform_mode, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getDPI()
if(self.device:getModel() == "KindlePaperWhite") or (self.device:getModel() == "Kobo_kraken") then
return 212
elseif self.device:getModel() == "Kobo_dragon" then
return 265
elseif self.device:getModel() == "Kobo_pixie" then
return 200
else
return 167
end
end
function Screen:scaleByDPI(px)
return math.floor(px * self:getDPI()/167)
end
function Screen:rescaleByDPI(px)
return math.ceil(px * 167/self:getDPI())
end
function Screen:getPitch()
return self.fb:getPitch()
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self.width > self.height then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.bb = Blitbuffer.new(self.width, self.height, self.width/2)
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(1)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self.width/2)
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self.width/2)
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
return Screen
|
local Geom = require("ui/geometry")
local DEBUG = require("dbg")
-- Blitbuffer
-- einkfb
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
width = 0,
height = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:init()
-- for unknown strange reason, pitch*2 is 10 px more than screen width in KPW
self.width, self.height = self.fb:getSize()
-- Blitbuffer still uses inverted 4bpp bitmap, so pitch should be
-- (self.width / 2)
self.bb = Blitbuffer.new(self.width, self.height, self.width/2)
if self.width > self.height then
-- For another unknown strange reason, self.fb:getOrientation always
-- return 0 in KPW, even though we are in landscape mode.
-- Seems like the native framework change framebuffer on the fly when
-- starting booklet. Starting KPV from ssh and KPVBooklet will get
-- different framebuffer height and width.
--
--self.native_rotation_mode = self.fb:getOrientation()
self.native_rotation_mode = 1
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type, waveform_mode, x, y, w, h)
if x then x = x < 0 and 0 or math.floor(x) end
if y then y = y < 0 and 0 or math.floor(y) end
if w then w = w + x > self.width and self.width - x or math.ceil(w) end
if h then h = h + y > self.height and self.height - y or math.ceil(h) end
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
if x and y and w and h then
x, y = y, self.width - w - x
w, h = h, w
end
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 3 then
self.fb.bb:blitFromRotate(self.bb, 90)
if x and y and w and h then
x, y = self.height - h - y, x
w, h = h, w
end
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 0 then
self.fb.bb:blitFromRotate(self.bb, 90)
if x and y and w and h then
x, y = self.height - h - y, x
w, h = h, w
end
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 3 then
self.fb.bb:blitFromRotate(self.bb, 180)
if x and y and w and h then
x, y = self.width - w - x, self.height - h - y
end
end
self.fb:refresh(refesh_type, waveform_mode, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getDPI()
if(self.device:getModel() == "KindlePaperWhite")
or (self.device:getModel() == "Kobo_kraken")
or (self.device:getModel() == "Kobo_phoenix") then
return 212
elseif self.device:getModel() == "Kobo_dragon" then
return 265
elseif self.device:getModel() == "Kobo_pixie" then
return 200
else
return 167
end
end
function Screen:scaleByDPI(px)
return math.floor(px * self:getDPI()/167)
end
function Screen:rescaleByDPI(px)
return math.ceil(px * 167/self:getDPI())
end
function Screen:getPitch()
return self.fb:getPitch()
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self.width > self.height then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.bb = Blitbuffer.new(self.width, self.height, self.width/2)
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(1)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self.width/2)
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self.width/2)
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
return Screen
|
Fix DPI for nex Kobo Aura (phoenix).
|
Fix DPI for nex Kobo Aura (phoenix).
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,koreader/koreader,Frenzie/koreader,poire-z/koreader,chrox/koreader,houqp/koreader,Markismus/koreader,noname007/koreader,pazos/koreader,ashang/koreader,chihyang/koreader,poire-z/koreader,mwoz123/koreader,koreader/koreader,robert00s/koreader,NiLuJe/koreader,ashhher3/koreader,Frenzie/koreader,lgeek/koreader,apletnev/koreader,Hzj-jie/koreader,mihailim/koreader,frankyifei/koreader,NickSavage/koreader
|
0a63a49515ec91fb005c1673eb627ccec596667e
|
plugins/set.lua
|
plugins/set.lua
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
return false
end
local function set_value(msg, name, value)
if (not name or not value) then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, name, value)
return name .. lang_text('saved')
end
end
local function set_media(msg, name)
if not name then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, 'waiting', name)
return lang_text('sendMedia')
end
end
local function callback(extra, success, result)
if success and result then
local file
if extra.media == 'photo' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg'
elseif extra.media == 'audio' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg'
end
file = file:gsub(':', '.')
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
redis:hset(extra.hash, extra.name, file)
redis:hdel(extra.hash, 'waiting')
print(file)
else
send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver)
end
end
local function run(msg, matches)
local hash = get_variables_hash(msg)
if msg.media then
if hash then
local name = redis:hget(hash, 'waiting')
if name then
if is_momod(msg) then
if msg.media.type == 'photo' then
load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
elseif msg.media.type == 'audio' then
load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
end
else
return lang_text('require_mod')
end
end
return
else
return lang_text('nothingToSet')
end
end
if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then
if is_momod(msg) then
redis:hdel(hash, 'waiting')
return lang_text('cancelled')
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
return set_media(msg, name)
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then
if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then
return lang_text('autoexecDenial')
end
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
local value = string.sub(matches[3], 1, 4096)
return set_value(msg, name, value)
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
return msg
end
return {
description = "SET",
patterns =
{
"^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$",
"%[(photo)%]",
"%[(audio)%]",
-- set
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
"^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
-- setmedia
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
-- cancel
"^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
"^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
},
run = run,
min_rank = 1
-- usage
-- MOD
-- (#set|[sasha] setta) <var_name> <text>
-- (#setmedia|[sasha] setta media) <var_name>
-- (#cancel|[sasha] annulla)
}
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
return false
end
local function set_value(msg, name, value)
if (not name or not value) then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, name, value)
return name .. lang_text('saved')
end
end
local function set_media(msg, name)
if not name then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, 'waiting', name)
return lang_text('sendMedia')
end
end
local function callback(extra, success, result)
if success and result then
local file
if extra.media == 'photo' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg'
elseif extra.media == 'audio' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg'
end
file = file:gsub(':', '.')
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
redis:hset(extra.hash, extra.name, file)
redis:hdel(extra.hash, 'waiting')
print(file)
send_large_msg(extra.receiver, lang_text('mediaSaved') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver)
else
send_large_msg(extra.receiver, lang_text('mediaSaved') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver)
end
end
local function run(msg, matches)
local hash = get_variables_hash(msg)
if msg.media then
if hash then
local name = redis:hget(hash, 'waiting')
if name then
if is_momod(msg) then
if msg.media.type == 'photo' then
return load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
elseif msg.media.type == 'audio' then
return load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
end
else
return lang_text('require_mod')
end
end
return
else
return lang_text('nothingToSet')
end
end
if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then
if is_momod(msg) then
redis:hdel(hash, 'waiting')
return lang_text('cancelled')
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
return set_media(msg, name)
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then
if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then
return lang_text('autoexecDenial')
end
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
local value = string.sub(matches[3], 1, 4096)
return set_value(msg, name, value)
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
return msg
end
return {
description = "SET",
patterns =
{
"^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$",
"%[(photo)%]",
"%[(audio)%]",
-- set
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
"^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
-- setmedia
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
-- cancel
"^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
"^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
},
run = run,
min_rank = 1
-- usage
-- MOD
-- (#set|[sasha] setta) <var_name> <text>
-- (#setmedia|[sasha] setta media) <var_name>
-- (#cancel|[sasha] annulla)
}
|
fix setmedia
|
fix setmedia
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
81b47a6a2e33da7ebdbf4daa7243d5ad90d37031
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
-- TODO merge message handlers into one somehow
module:hook("iq/self/"..xmlns_carbons..":enable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s enabled carbons", origin.full_jid);
origin.want_carbons = true;
origin.send(st.reply(stanza));
return true
end
end);
module:hook("iq/self/"..xmlns_carbons..":disable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s disabled carbons", origin.full_jid);
origin.want_carbons = nil;
origin.send(st.reply(stanza));
return true
end
end);
function c2s_message_handler(event)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return
end
local bare_jid, user_sessions;
if origin.type == "s2s" then
bare_jid = jid_bare(stanza.attr.from);
user_sessions = host_sessions[jid_split(orig_to)];
else
bare_jid = (origin.username.."@"..origin.host)
user_sessions = host_sessions[origin.username];
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if session ~= origin and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
function s2c_message_handler(event)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return
end
local full_jid, bare_jid = orig_to, jid_bare(orig_to);
local username, hostname, resource = jid_split(full_jid);
local user_sessions = username and host_sessions[username];
if not user_sessions or hostname ~= module.host then
return
end
local no_carbon_to = {};
if resource then
no_carbon_to[resource] = true;
else
local top_resources = user_sessions.top_resources;
for i=1,top_resources do
no_carbon_to[top_resources[i]] = true;
end
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if not no_carbon_to[resource] and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanszas to local clients
module:hook("message/bare", s2c_message_handler, 1); -- this will suck
module:hook("message/full", s2c_message_handler, 1);
module:add_feature(xmlns_carbons);
|
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
-- TODO merge message handlers into one somehow
module:hook("iq/self/"..xmlns_carbons..":enable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s enabled carbons", origin.full_jid);
origin.want_carbons = true;
origin.send(st.reply(stanza));
return true
end
end);
module:hook("iq/self/"..xmlns_carbons..":disable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s disabled carbons", origin.full_jid);
origin.want_carbons = nil;
origin.send(st.reply(stanza));
return true
end
end);
function c2s_message_handler(event)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return
end
local bare_jid, user_sessions;
if origin.type == "s2s" then
bare_jid = jid_bare(stanza.attr.from);
user_sessions = host_sessions[jid_split(orig_to)];
else
bare_jid = (origin.username.."@"..origin.host)
user_sessions = host_sessions[origin.username];
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if session ~= origin and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("sent", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
function s2c_message_handler(event)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return
end
local full_jid, bare_jid = orig_to, jid_bare(orig_to);
local username, hostname, resource = jid_split(full_jid);
local user_sessions = username and host_sessions[username];
if not user_sessions or hostname ~= module.host then
return
end
local no_carbon_to = {};
if resource then
no_carbon_to[resource] = true;
else
local top_resources = user_sessions.top_resources;
for i, session in ipairs(top_resources) do
no_carbon_to[session.resource] = true;
module:log("debug", "not going to send to /%s", resource);
end
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if not no_carbon_to[resource] and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanszas to local clients
module:hook("message/bare", s2c_message_handler, 1);
module:hook("message/full", s2c_message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
|
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
|
Lua
|
mit
|
asdofindia/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,prosody-modules/import,apung/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,prosody-modules/import,syntafin/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,softer/prosody-modules,either1/prosody-modules,apung/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,apung/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,dhotson/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,softer/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,prosody-modules/import,mardraze/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules
|
feb3f5ffed3bf143b915d17e6bb944bc8be16a0a
|
src/cjdnstools/tunnel.lua
|
src/cjdnstools/tunnel.lua
|
--- @module cjdnstools.tunnel
local tunnel = {}
local config = require("config")
package.path = package.path .. ";cjdns/contrib/lua/?.lua"
local cjdns = require "cjdns.init"
local addrcalc = require "cjdnstools.addrcalc"
require "cjdns.config" -- ConfigFile null in certain cases?
local conf = cjdns.ConfigFile.new(get_path_from_path_relative_to_config(config.cjdns.config))
local ai = conf:makeInterface()
function tunnel.getConnections()
local response, err = ai:auth({
q = "IpTunnel_listConnections",
publicKeyOfNodeToConnectTo = key,
})
if err then
return nil, "Error adding key " .. key .. ": " .. err
else
return true, nil
end
end
function tunnel.connect(key)
print("Connecting to " .. key)
local response, err = ai:auth({
q = "IpTunnel_connectTo",
publicKeyOfNodeToConnectTo = key,
})
if err then
return nil, "Error adding key " .. key .. ": " .. err
else
return true, nil
end
end
function tunnel.addKey(key, ip4, ip6)
ip4 = ip4 or nil
ip6 = ip6 or nil
if ip4 == nil and ip6 == nil then
return nil, "At least IPv4 or IPv6 address is required"
end
print("Adding key " .. key)
local req = {
q = "IpTunnel_allowConnection",
publicKeyOfAuthorizedNode = key,
}
if ip4 ~= nil then
req['ip4Address'] = ip4
end
if ip6 ~= nil then
req['ip6Address'] = ip6
end
local response, err = ai:auth(req)
if err then
return nil, "Error adding key " .. key .. ": " .. err
else
return true, nil
end
end
function tunnel.removeKey(connIndex)
print("Removing connection " .. connIndex)
local response, err = ai:auth({
q = "IpTunnel_removeConnection",
connection = connIndex,
})
if err then
return nil, "Error removing connection " .. connIndex .. ": " .. err
else
return true, nil
end
end
return tunnel
|
--- @module cjdnstools.tunnel
local tunnel = {}
local config = require("config")
package.path = package.path .. ";cjdns/contrib/lua/?.lua"
local cjdns = require "cjdns.init"
local addrcalc = require "cjdnstools.addrcalc"
require "cjdns.config" -- ConfigFile null in certain cases?
local conf = cjdns.ConfigFile.new(get_path_from_path_relative_to_config(config.cjdns.config))
local ai = conf:makeInterface()
function tunnel.getConnections()
local response, err = ai:auth({
q = "IpTunnel_listConnections"
})
if err then
return nil, "Error getting connections: " .. err
else
return true, nil
end
end
function tunnel.connect(key)
print("Connecting to " .. key)
local response, err = ai:auth({
q = "IpTunnel_connectTo",
publicKeyOfNodeToConnectTo = key,
})
if err then
return nil, "Error connecting to " .. key .. ": " .. err
else
return true, nil
end
end
function tunnel.addKey(key, ip4, ip6)
ip4 = ip4 or nil
ip6 = ip6 or nil
if ip4 == nil and ip6 == nil then
return nil, "At least IPv4 or IPv6 address is required"
end
print("Adding key " .. key)
local req = {
q = "IpTunnel_allowConnection",
publicKeyOfAuthorizedNode = key,
}
if ip4 ~= nil then
req['ip4Address'] = ip4
end
if ip6 ~= nil then
req['ip6Address'] = ip6
end
local response, err = ai:auth(req)
if err then
return nil, "Error adding key " .. key .. ": " .. err
else
return true, nil
end
end
function tunnel.removeKey(connIndex)
print("Removing connection " .. connIndex)
local response, err = ai:auth({
q = "IpTunnel_removeConnection",
connection = connIndex,
})
if err then
return nil, "Error removing connection " .. connIndex .. ": " .. err
else
return true, nil
end
end
return tunnel
|
Fixed copy paste errors
|
Fixed copy paste errors
|
Lua
|
mit
|
transitd/transitd,transitd/transitd,pdxmeshnet/mnigs,intermesh-networks/transitd,transitd/transitd,intermesh-networks/transitd,pdxmeshnet/mnigs
|
d6620c7920c0344a494bf006f5d02da92be4ba8f
|
interface/configenv/range.lua
|
interface/configenv/range.lua
|
return function(env)
function env.range(start, limit, step)
step = step or 1
local v = start - 1
if not limit then
return function()
start = start + step
return v
end
end
return function()
v = v + step
if v > limit then
v = start
end
return v
end
end
function env.randomRange(start, limit)
return function()
return math.random(start, limit)
end
end
function env.list(tbl)
local index, len = 1, #tbl
return function()
local v = tbl[index]
index = index + 1
if index > len then
index = 1
end
return v
end
end
function env.randomList(tbl)
local len = #tbl
return function()
return tbl[math.random(len)]
end
end
end
|
return function(env)
function env.range(start, limit, step)
step = step or 1
local v = start - 1
if not limit then
return function()
start = start + step
return v
end
end
return function()
if v == limit then
v = start
else
v = v + step
end
return v
end
end
function env.randomRange(start, limit)
return function()
return math.random(start, limit)
end
end
function env.list(tbl)
local index, len = 1, #tbl
return function()
local v = tbl[index]
index = index + 1
if index > len then
index = 1
end
return v
end
end
function env.randomList(tbl)
local len = #tbl
return function()
return tbl[math.random(len)]
end
end
end
|
Change range check to use equals. (Fixes ip6 ranges)
|
Change range check to use equals. (Fixes ip6 ranges)
|
Lua
|
mit
|
emmericp/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,scholzd/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen
|
9576b4197f3ff021721567231b4bf449a31992cc
|
pud/kit/Rect.lua
|
pud/kit/Rect.lua
|
require 'pud.util'
local Class = require 'lib.hump.class'
-- Rect
-- provides position and size of a rectangle
-- Note: coordinates are not floored or rounded and may be floats
local Rect = Class{name='Rect',
function(self, x, y, w, h)
x = x or 0
y = y or 0
w = w or 0
h = h or 0
self:setPosition(x, y)
self:setSize(w, h)
end
}
-- destructor
function Rect:destroy()
self._x = nil
self._y = nil
self._w = nil
self._h = nil
self._cx = nil
self._cy = nil
end
-- private function to calculate and store the center coords
local function _calcCenter(self)
if self._x and self._y and self._w and self._h then
self._cx = self._x + (self._w/2)
self._cy = self._y + (self._h/2)
end
end
-- get and set position
function Rect:getX() return self._x end
function Rect:setX(x)
verify('number', x)
self._x = x
_calcCenter(self)
end
function Rect:getY() return self._y end
function Rect:setY(x)
verify('number', x)
self._x = x
_calcCenter(self)
end
function Rect:getPosition() return self:getX(), self:getY() end
function Rect:setPosition(x, y)
self:setX(x)
self:setY(y)
end
-- get and set center coords
function Rect:getCenter() return self._cx, self._cy end
function Rect:setCenter(x, y)
verify('number', x, y)
self._cx = x
self._cy = y
self._x = self._cx - (self._w/2)
self._y = self._cy - (self._h/2)
end
-- get (no set) bounding box coordinates
function Rect:getBBox()
local x, y = self:getPosition()
local w, h = self:getSize()
return x, y, x+w, y+h
end
-- get and set size
function Rect:getWidth() return self._w end
function Rect:setWidth(w)
verify('number', w)
self._w = w
_calcCenter(self)
end
function Rect:getHeight() return self._h end
function Rect:setHeight(h)
verify('number', h)
self._h = h
_calcCenter(self)
end
function Rect:getSize() return self:getWidth(), self:getHeight() end
function Rect:setSize(w, h)
self:setWidth(w)
self:setHeight(h)
end
-- the class
return Rect
|
require 'pud.util'
local Class = require 'lib.hump.class'
-- Rect
-- provides position and size of a rectangle
-- Note: coordinates are not floored or rounded and may be floats
local Rect = Class{name='Rect',
function(self, x, y, w, h)
x = x or 0
y = y or 0
w = w or 0
h = h or 0
self:setPosition(x, y)
self:setSize(w, h)
end
}
-- destructor
function Rect:destroy()
self._x = nil
self._y = nil
self._w = nil
self._h = nil
self._cx = nil
self._cy = nil
end
-- private function to calculate and store the center coords
local function _calcCenter(self)
if self._x and self._y and self._w and self._h then
self._cx = self._x + (self._w/2)
self._cy = self._y + (self._h/2)
end
end
-- get and set position
function Rect:getX() return self._x end
function Rect:setX(x)
verify('number', x)
self._x = x
_calcCenter(self)
end
function Rect:getY() return self._y end
_calcCenter(self)
function Rect:setY(y)
verify('number', y)
self._y = y
end
function Rect:getPosition() return self:getX(), self:getY() end
function Rect:setPosition(x, y)
self:setX(x)
self:setY(y)
end
-- get and set center coords
function Rect:getCenter() return self._cx, self._cy end
function Rect:setCenter(x, y)
verify('number', x, y)
self._cx = x
self._cy = y
self._x = self._cx - (self._w/2)
self._y = self._cy - (self._h/2)
end
-- get (no set) bounding box coordinates
function Rect:getBBox()
local x, y = self:getPosition()
local w, h = self:getSize()
return x, y, x+w, y+h
end
-- get and set size
function Rect:getWidth() return self._w end
function Rect:setWidth(w)
verify('number', w)
self._w = w
_calcCenter(self)
end
function Rect:getHeight() return self._h end
function Rect:setHeight(h)
verify('number', h)
self._h = h
_calcCenter(self)
end
function Rect:getSize() return self:getWidth(), self:getHeight() end
function Rect:setSize(w, h)
self:setWidth(w)
self:setHeight(h)
end
-- the class
return Rect
|
fix setY()
|
fix setY()
|
Lua
|
mit
|
scottcs/wyx
|
408e044d0892fb29b5f099d128159d41607ffa08
|
brightness-widget/brightness.lua
|
brightness-widget/brightness.lua
|
-------------------------------------------------
-- Brightness Widget for Awesome Window Manager
-- Shows the brightness level of the laptop display
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/brightness-widget
-- @author Pavel Makhov
-- @copyright 2021 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local watch = require("awful.widget.watch")
local spawn = require("awful.spawn")
local gfs = require("gears.filesystem")
local naughty = require("naughty")
local beautiful = require("beautiful")
local ICON_DIR = gfs.get_configuration_dir() .. "awesome-wm-widgets/brightness-widget/"
local get_brightness_cmd
local set_brightness_cmd
local inc_brightness_cmd
local dec_brightness_cmd
local brightness_widget = {}
local function show_warning(message)
naughty.notify({
preset = naughty.config.presets.critical,
title = "Brightness Widget",
text = message,
})
end
local function worker(user_args)
local args = user_args or {}
local type = args.type or 'arc' -- arc or icon_and_text
local path_to_icon = args.path_to_icon or ICON_DIR .. 'brightness.svg'
local font = args.font or beautiful.font
local timeout = args.timeout or 100
local program = args.program or 'light'
local step = args.step or 5
local base = args.base or 20
local current_level = 0 -- current brightness value
local tooltip = args.tooltip or false
local percentage = args.percentage or false
if program == 'light' then
get_brightness_cmd = 'light -G'
set_brightness_cmd = 'light -S %d' -- <level>
inc_brightness_cmd = 'light -A ' .. step
dec_brightness_cmd = 'light -U ' .. step
elseif program == 'xbacklight' then
get_brightness_cmd = 'xbacklight -get'
set_brightness_cmd = 'xbacklight -set %d' -- <level>
inc_brightness_cmd = 'xbacklight -inc ' .. step
dec_brightness_cmd = 'xbacklight -dec ' .. step
elseif program == 'brightnessctl' then
get_brightness_cmd = "brightnessctl get"
set_brightness_cmd = "brightnessctl set %d%%" -- <level>
inc_brightness_cmd = "brightnessctl set +" .. step .. "%"
dec_brightness_cmd = "brightnessctl set " .. step .. "-%"
else
show_warning(program .. " command is not supported by the widget")
return
end
if type == 'icon_and_text' then
brightness_widget.widget = wibox.widget {
{
{
image = path_to_icon,
resize = false,
widget = wibox.widget.imagebox,
},
valign = 'center',
layout = wibox.container.place
},
{
id = 'txt',
font = font,
widget = wibox.widget.textbox
},
spacing = 4,
layout = wibox.layout.fixed.horizontal,
set_value = function(self, level)
local display_level = level
if percentage then
display_level = display_level .. '%'
end
self:get_children_by_id('txt')[1]:set_text(display_level)
end
}
elseif type == 'arc' then
brightness_widget.widget = wibox.widget {
{
{
image = path_to_icon,
resize = true,
widget = wibox.widget.imagebox,
},
valign = 'center',
layout = wibox.container.place
},
max_value = 100,
thickness = 2,
start_angle = 4.71238898, -- 2pi*3/4
forced_height = 18,
forced_width = 18,
paddings = 2,
widget = wibox.container.arcchart,
set_value = function(self, level)
self:set_value(level)
end
}
else
show_warning(type .. " type is not supported by the widget")
return
end
local update_widget = function(widget, stdout, _, _, _)
local brightness_level = tonumber(string.format("%.0f", stdout))
current_level = brightness_level
widget:set_value(brightness_level)
end
function brightness_widget:set(value)
current_level = value
spawn.easy_async(string.format(set_brightness_cmd, value), function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
local old_level = 0
function brightness_widget:toggle()
if old_level < 0.1 then
-- avoid toggling between '0' and 'almost 0'
old_level = 1
end
if current_level < 0.1 then
-- restore previous level
current_level = old_level
else
-- save current brightness for later
old_level = current_level
current_level = 0
end
brightness_widget:set(current_level)
end
function brightness_widget:inc()
spawn.easy_async(inc_brightness_cmd, function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
function brightness_widget:dec()
spawn.easy_async(dec_brightness_cmd, function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
brightness_widget.widget:buttons(
awful.util.table.join(
awful.button({}, 1, function() brightness_widget:set(base) end),
awful.button({}, 3, function() brightness_widget:toggle() end),
awful.button({}, 4, function() brightness_widget:inc() end),
awful.button({}, 5, function() brightness_widget:dec() end)
)
)
watch(get_brightness_cmd, timeout, update_widget, brightness_widget.widget)
if tooltip then
awful.tooltip {
objects = { brightness_widget.widget },
timer_function = function()
return current_level .. " %"
end,
}
end
return brightness_widget.widget
end
return setmetatable(brightness_widget, {
__call = function(_, ...)
return worker(...)
end,
})
|
-------------------------------------------------
-- Brightness Widget for Awesome Window Manager
-- Shows the brightness level of the laptop display
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/brightness-widget
-- @author Pavel Makhov
-- @copyright 2021 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local watch = require("awful.widget.watch")
local spawn = require("awful.spawn")
local gfs = require("gears.filesystem")
local naughty = require("naughty")
local beautiful = require("beautiful")
local ICON_DIR = gfs.get_configuration_dir() .. "awesome-wm-widgets/brightness-widget/"
local get_brightness_cmd
local set_brightness_cmd
local inc_brightness_cmd
local dec_brightness_cmd
local brightness_widget = {}
local function show_warning(message)
naughty.notify({
preset = naughty.config.presets.critical,
title = "Brightness Widget",
text = message,
})
end
local function worker(user_args)
local args = user_args or {}
local type = args.type or 'arc' -- arc or icon_and_text
local path_to_icon = args.path_to_icon or ICON_DIR .. 'brightness.svg'
local font = args.font or beautiful.font
local timeout = args.timeout or 100
local program = args.program or 'light'
local step = args.step or 5
local base = args.base or 20
local current_level = 0 -- current brightness value
local tooltip = args.tooltip or false
local percentage = args.percentage or false
if program == 'light' then
get_brightness_cmd = 'light -G'
set_brightness_cmd = 'light -S %d' -- <level>
inc_brightness_cmd = 'light -A ' .. step
dec_brightness_cmd = 'light -U ' .. step
elseif program == 'xbacklight' then
get_brightness_cmd = 'xbacklight -get'
set_brightness_cmd = 'xbacklight -set %d' -- <level>
inc_brightness_cmd = 'xbacklight -inc ' .. step
dec_brightness_cmd = 'xbacklight -dec ' .. step
elseif program == 'brightnessctl' then
get_brightness_cmd = "brightnessctl get"
set_brightness_cmd = "brightnessctl set %d%%" -- <level>
inc_brightness_cmd = "brightnessctl set +" .. step .. "%"
dec_brightness_cmd = "brightnessctl set " .. step .. "-%"
else
show_warning(program .. " command is not supported by the widget")
return
end
if type == 'icon_and_text' then
brightness_widget.widget = wibox.widget {
{
{
image = path_to_icon,
resize = false,
widget = wibox.widget.imagebox,
},
valign = 'center',
layout = wibox.container.place
},
{
id = 'txt',
font = font,
widget = wibox.widget.textbox
},
spacing = 4,
layout = wibox.layout.fixed.horizontal,
set_value = function(self, level)
local display_level = level
if percentage then
display_level = display_level .. '%'
end
self:get_children_by_id('txt')[1]:set_text(display_level)
end
}
elseif type == 'arc' then
brightness_widget.widget = wibox.widget {
{
{
image = path_to_icon,
resize = true,
widget = wibox.widget.imagebox,
},
valign = 'center',
layout = wibox.container.place
},
max_value = 100,
thickness = 2,
start_angle = 4.71238898, -- 2pi*3/4
forced_height = 18,
forced_width = 18,
paddings = 2,
widget = wibox.container.arcchart,
set_value = function(self, level)
self:set_value(level)
end
}
else
show_warning(type .. " type is not supported by the widget")
return
end
local update_widget = function(widget, stdout, _, _, _)
local brightness_level = tonumber(string.format("%.0f", stdout))
current_level = brightness_level
widget:set_value(brightness_level)
end
function brightness_widget:set(value)
current_level = value
spawn.easy_async(string.format(set_brightness_cmd, value), function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
local old_level = 0
function brightness_widget:toggle()
if old_level < 0.1 then
-- avoid toggling between '0' and 'almost 0'
old_level = 1
end
if current_level < 0.1 then
-- restore previous level
current_level = old_level
else
-- save current brightness for later
old_level = current_level
current_level = 0
end
brightness_widget:set(current_level)
end
function brightness_widget:inc()
spawn.easy_async(inc_brightness_cmd, function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
function brightness_widget:dec()
spawn.easy_async(dec_brightness_cmd, function()
spawn.easy_async(get_brightness_cmd, function(out)
update_widget(brightness_widget.widget, out)
end)
end)
end
brightness_widget.widget:buttons(
awful.util.table.join(
awful.button({}, 1, function() brightness_widget:set(base) end),
awful.button({}, 3, function() brightness_widget:toggle() end),
awful.button({}, 4, function() brightness_widget:inc() end),
awful.button({}, 5, function() brightness_widget:dec() end)
)
)
watch(get_brightness_cmd, timeout, update_widget, brightness_widget.widget)
if tooltip then
awful.tooltip {
objects = { brightness_widget.widget },
timer_function = function()
return current_level .. " %"
end,
}
end
return brightness_widget.widget
end
return setmetatable(brightness_widget, {
__call = function(_, ...)
return worker(...)
end,
})
|
Fix luacheck warnings
|
Fix luacheck warnings
This patch fixes luacheck warnings in brightness plugin:
brightness-widget/brightness.lua:60:1:
inconsistent indentation (SPACE followed by TAB)
brightness-widget/brightness.lua:63:60:
line contains trailing whitespace
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
2a8b042bb936a37200cfb09e3c56e86463e8e5c7
|
src/luacheck/expand_rockspec.lua
|
src/luacheck/expand_rockspec.lua
|
local fs = require "luacheck.fs"
local utils = require "luacheck.utils"
local blacklist = utils.array_to_set({"spec", ".luarocks", "lua_modules", "test.lua", "tests.lua"})
-- This reimplements relevant parts of `luarocks.build.builtin.autodetect_modules`.
-- Autodetection works relatively to the directory containing the rockspec.
local function autodetect_modules(rockspec_path)
rockspec_path = fs.normalize(rockspec_path)
local base, rest = fs.split_base(rockspec_path)
local project_dir = base .. (rest:match("^(.*)" .. utils.dir_sep .. ".*$") or "")
local module_dir = project_dir
for _, module_subdir in ipairs({"src", "lua", "lib"}) do
local full_module_dir = fs.join(project_dir, module_subdir)
if fs.is_dir(full_module_dir) then
module_dir = full_module_dir
break
end
end
local res = {}
for _, file in ipairs((fs.extract_files(module_dir, "%.lua$"))) do
-- Extract first part of the path from module_dir to the file, or file name itself.
if not blacklist[file:match("^" .. module_dir:gsub("%p", "%%%0") .. "[\\/]*([^\\/]*)")] then
table.insert(res, file)
end
end
local bin_dir
for _, bin_subdir in ipairs({"src/bin", "bin"}) do
local full_bin_dir = fs.join(project_dir, bin_subdir)
if fs.is_dir(full_bin_dir) then
bin_dir = full_bin_dir
end
end
if bin_dir then
local iter, state, var = fs.dir_iter(bin_dir)
if iter then
for basename in iter, state, var do
if basename:sub(-#".lua") == ".lua" then
table.insert(res, fs.join(bin_dir, basename))
end
end
end
end
return res
end
local function extract_lua_files(rockspec_path, rockspec)
local build = rockspec.build
if type(build) ~= "table" then
return autodetect_modules(rockspec_path)
end
if not build.type or build.type == "builtin" or build.type == "module" then
if not build.modules then
return autodetect_modules(rockspec_path)
end
end
local res = {}
local function scan(t)
if type(t) == "table" then
for _, file in pairs(t) do
if type(file) == "string" and file:sub(-#".lua") == ".lua" then
table.insert(res, file)
end
end
end
end
scan(build.modules)
if type(build.install) == "table" then
scan(build.install.lua)
scan(build.install.bin)
end
table.sort(res)
return res
end
-- Receives a name of a rockspec, returns list of related .lua files.
-- On error returns nil and "I/O", "syntax", or "runtime" and error message.
local function expand_rockspec(rockspec_path)
local rockspec, err_type, err_msg = utils.load_config(rockspec_path)
if not rockspec then
return nil, err_type, err_msg
end
return extract_lua_files(rockspec_path, rockspec)
end
return expand_rockspec
|
local fs = require "luacheck.fs"
local utils = require "luacheck.utils"
local blacklist = utils.array_to_set({"spec", ".luarocks", "lua_modules", "test.lua", "tests.lua"})
-- This reimplements relevant parts of `luarocks.build.builtin.autodetect_modules`.
-- Autodetection works relatively to the directory containing the rockspec.
local function autodetect_modules(rockspec_path)
rockspec_path = fs.normalize(rockspec_path)
local base, rest = fs.split_base(rockspec_path)
local project_dir = base .. (rest:match("^(.*)" .. utils.dir_sep .. ".*$") or "")
if project_dir == "" then
project_dir = "."
end
local module_dir = project_dir
for _, module_subdir in ipairs({"src", "lua", "lib"}) do
local full_module_dir = fs.join(project_dir, module_subdir)
if fs.is_dir(full_module_dir) then
module_dir = full_module_dir
break
end
end
local res = {}
for _, file in ipairs((fs.extract_files(module_dir, "%.lua$"))) do
-- Extract first part of the path from module_dir to the file, or file name itself.
if not blacklist[file:match("^" .. module_dir:gsub("%p", "%%%0") .. "[\\/]*([^\\/]*)")] then
table.insert(res, file)
end
end
local bin_dir
for _, bin_subdir in ipairs({"src/bin", "bin"}) do
local full_bin_dir = fs.join(project_dir, bin_subdir)
if fs.is_dir(full_bin_dir) then
bin_dir = full_bin_dir
end
end
if bin_dir then
local iter, state, var = fs.dir_iter(bin_dir)
if iter then
for basename in iter, state, var do
if basename:sub(-#".lua") == ".lua" then
table.insert(res, fs.join(bin_dir, basename))
end
end
end
end
return res
end
local function extract_lua_files(rockspec_path, rockspec)
local build = rockspec.build
if type(build) ~= "table" then
return autodetect_modules(rockspec_path)
end
if not build.type or build.type == "builtin" or build.type == "module" then
if not build.modules then
return autodetect_modules(rockspec_path)
end
end
local res = {}
local function scan(t)
if type(t) == "table" then
for _, file in pairs(t) do
if type(file) == "string" and file:sub(-#".lua") == ".lua" then
table.insert(res, file)
end
end
end
end
scan(build.modules)
if type(build.install) == "table" then
scan(build.install.lua)
scan(build.install.bin)
end
table.sort(res)
return res
end
-- Receives a name of a rockspec, returns list of related .lua files.
-- On error returns nil and "I/O", "syntax", or "runtime" and error message.
local function expand_rockspec(rockspec_path)
local rockspec, err_type, err_msg = utils.load_config(rockspec_path)
if not rockspec then
return nil, err_type, err_msg
end
return extract_lua_files(rockspec_path, rockspec)
end
return expand_rockspec
|
Fix rockspec module autodetection for bare file names
|
Fix rockspec module autodetection for bare file names
|
Lua
|
mit
|
xpol/luacheck,xpol/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,mpeterv/luacheck
|
db24d2420bbbc89416463ea009bb0ea655d91a1b
|
nvim/lua/ryankoval/nvim-tabline.lua
|
nvim/lua/ryankoval/nvim-tabline.lua
|
require('tabline').setup({
no_name = '[No Name]', -- Name for buffers with no name
modified_icon = '', -- Icon for showing modified buffer
close_icon = '', -- Icon for closing tab with mouse
separator = "▌", -- Separator icon on the left side
padding = 3, -- Prefix and suffix space
color_all_icons = false, -- Color devicons in active and inactive tabs
right_separator = false, -- Show right separator on the last tab
show_index = false, -- Shows the index of tab before filename
show_icon = true, -- Shows the devicon
})
|
require('tabline').setup({
no_name = '[No Name]', -- Name for buffers with no name
modified_icon = '', -- Icon for showing modified buffer
close_icon = '', -- Icon for closing tab with mouse
separator = '▌', -- Separator icon on the left side
padding = 3, -- Prefix and suffix space
color_all_icons = false, -- Color devicons in active and inactive tabs
right_separator = false, -- Show right separator on the last tab
show_index = false, -- Shows the index of tab before filename
show_icon = true, -- Shows the devicon
})
vim.cmd('hi TabLine guifg=#eeeeee')
|
fixed tab color
|
fixed tab color
|
Lua
|
mit
|
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
|
f6c1b74a3d4205f5347a7f3c799bdc4b959717ec
|
Tester.lua
|
Tester.lua
|
local Tester = torch.class('torch.Tester')
function Tester:__init()
self.errors = {}
self.tests = {}
self.testnames = {}
self.curtestname = ''
end
function Tester:assert_sub (condition, message)
self.countasserts = self.countasserts + 1
if not condition then
local ss = debug.traceback('tester',2)
--print(ss)
ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n')
self.errors[#self.errors+1] = self.curtestname .. '\n' .. (message or '') .. '\n' .. ss .. '\n'
end
end
function Tester:assert (condition, message)
self:assert_sub(condition,string.format('%s\n%s condition=%s',(message or ''),' BOOL violation ', tostring(condition)))
end
function Tester:assertlt (val, condition, message)
self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LT(<) violation ', tostring(val), tostring(condition)))
end
function Tester:assertgt (val, condition, message)
self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GT(>) violation ', tostring(val), tostring(condition)))
end
function Tester:assertle (val, condition, message)
self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LE(<=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertge (val, condition, message)
self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GE(>=) violation ', tostring(val), tostring(condition)))
end
function Tester:asserteq (val, condition, message)
self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' EQ(==) violation ', tostring(val), tostring(condition)))
end
function Tester:assertalmosteq (a, b, condition, message)
condition = condition or 1e-16
local err = math.abs(a-b)
self:assert_sub(err < condition, string.format('%s\n%s val=%s, condition=%s',(message or ''),' ALMOST_EQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertne (val, condition, message)
self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' NE(~=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertTensorEq(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTensorNe(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorNE(~=) violation ', tostring(err), tostring(condition)))
end
local function areTablesEqual(ta, tb)
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not areTablesEqual(ta[k], v) then return false end
end
return true
end
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
function Tester:assertTableEq(ta, tb, message)
self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation '))
end
function Tester:assertTableNe(ta, tb, message)
self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation '))
end
function Tester:assertError(f, message)
return self:assertErrorObj(f, function(err) return true end, message)
end
function Tester:assertErrorMsg(f, errmsg, message)
return self:assertErrorObj(f, function(err) return err == errmsg end, message)
end
function Tester:assertErrorPattern(f, errPattern, message)
return self:assertErrorObj(f, function(err) return string.find(err, errPattern) ~= nil end, message)
end
function Tester:assertErrorObj(f, errcomp, message)
-- errcomp must be a function that compares the error object to its expected value
local status, err = pcall(f)
self:assert_sub(status == false and errcomp(err), string.format('%s\n%s err=%s', (message or ''),' ERROR violation ', tostring(err)))
end
function Tester:pcall(f)
local nerr = #self.errors
-- local res = f()
local stat, result = xpcall(f, debug.traceback)
if not stat then
self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n'
end
return stat, result, stat and (nerr == #self.errors)
-- return true, res, nerr == #self.errors
end
function Tester:report(tests)
if not tests then
tests = self.tests
end
print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors')
print()
print(string.rep('-',80))
for i,v in ipairs(self.errors) do
print(v)
print(string.rep('-',80))
end
end
function Tester:run(run_tests)
local tests, testnames
self.countasserts = 0
tests = self.tests
testnames = self.testnames
if type(run_tests) == 'string' then
run_tests = {run_tests}
end
if type(run_tests) == 'table' then
tests = {}
testnames = {}
for i,fun in ipairs(self.tests) do
for j,name in ipairs(run_tests) do
if self.testnames[i] == name or i == name then
tests[#tests+1] = self.tests[i]
testnames[#testnames+1] = self.testnames[i]
end
end
end
end
print('Running ' .. #tests .. ' tests')
local statstr = string.rep('_',#tests)
local pstr = ''
io.write(statstr .. '\r')
for i,v in ipairs(tests) do
self.curtestname = testnames[i]
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
--write
pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname
io.write('\r' .. pstr)
io.flush()
local stat, message, pass = self:pcall(v)
if pass then
--io.write(string.format('\b_'))
statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1)
else
statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1)
--io.write(string.format('\b*'))
end
if not stat then
-- print()
-- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i])
-- print(message)
end
collectgarbage()
end
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
-- write finish
pstr = statstr .. ' ==> Done '
io.write('\r' .. pstr)
io.flush()
print()
print()
self:report(tests)
end
function Tester:add(f,name)
name = name or 'unknown'
if type(f) == "table" then
for i,v in pairs(f) do
self:add(v,i)
end
elseif type(f) == "function" then
self.tests[#self.tests+1] = f
self.testnames[#self.tests] = name
else
error('Tester:add(f) expects a function or a table of functions')
end
end
|
local Tester = torch.class('torch.Tester')
function Tester:__init()
self.errors = {}
self.tests = {}
self.testnames = {}
self.curtestname = ''
end
function Tester:assert_sub (condition, message)
self.countasserts = self.countasserts + 1
if not condition then
local ss = debug.traceback('tester',2)
--print(ss)
ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n')
self.errors[#self.errors+1] = self.curtestname .. '\n' .. (message or '') .. '\n' .. ss .. '\n'
end
end
function Tester:assert (condition, message)
self:assert_sub(condition,string.format('%s\n%s condition=%s',(message or ''),' BOOL violation ', tostring(condition)))
end
function Tester:assertlt (val, condition, message)
self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LT(<) violation ', tostring(val), tostring(condition)))
end
function Tester:assertgt (val, condition, message)
self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GT(>) violation ', tostring(val), tostring(condition)))
end
function Tester:assertle (val, condition, message)
self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LE(<=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertge (val, condition, message)
self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GE(>=) violation ', tostring(val), tostring(condition)))
end
function Tester:asserteq (val, condition, message)
self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' EQ(==) violation ', tostring(val), tostring(condition)))
end
function Tester:assertalmosteq (a, b, condition, message)
condition = condition or 1e-16
local err = math.abs(a-b)
self:assert_sub(err < condition, string.format('%s\n%s val=%s, condition=%s',(message or ''),' ALMOST_EQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertne (val, condition, message)
self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' NE(~=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertTensorEq(ta, tb, condition, message)
if ta:dim() == 0 and tb:dim() == 0 then
return
end
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTensorNe(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorNE(~=) violation ', tostring(err), tostring(condition)))
end
local function areTablesEqual(ta, tb)
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not areTablesEqual(ta[k], v) then return false end
end
return true
end
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
function Tester:assertTableEq(ta, tb, message)
self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation '))
end
function Tester:assertTableNe(ta, tb, message)
self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation '))
end
function Tester:assertError(f, message)
return self:assertErrorObj(f, function(err) return true end, message)
end
function Tester:assertErrorMsg(f, errmsg, message)
return self:assertErrorObj(f, function(err) return err == errmsg end, message)
end
function Tester:assertErrorPattern(f, errPattern, message)
return self:assertErrorObj(f, function(err) return string.find(err, errPattern) ~= nil end, message)
end
function Tester:assertErrorObj(f, errcomp, message)
-- errcomp must be a function that compares the error object to its expected value
local status, err = pcall(f)
self:assert_sub(status == false and errcomp(err), string.format('%s\n%s err=%s', (message or ''),' ERROR violation ', tostring(err)))
end
function Tester:pcall(f)
local nerr = #self.errors
-- local res = f()
local stat, result = xpcall(f, debug.traceback)
if not stat then
self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n'
end
return stat, result, stat and (nerr == #self.errors)
-- return true, res, nerr == #self.errors
end
function Tester:report(tests)
if not tests then
tests = self.tests
end
print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors')
print()
print(string.rep('-',80))
for i,v in ipairs(self.errors) do
print(v)
print(string.rep('-',80))
end
end
function Tester:run(run_tests)
local tests, testnames
self.countasserts = 0
tests = self.tests
testnames = self.testnames
if type(run_tests) == 'string' then
run_tests = {run_tests}
end
if type(run_tests) == 'table' then
tests = {}
testnames = {}
for i,fun in ipairs(self.tests) do
for j,name in ipairs(run_tests) do
if self.testnames[i] == name or i == name then
tests[#tests+1] = self.tests[i]
testnames[#testnames+1] = self.testnames[i]
end
end
end
end
print('Running ' .. #tests .. ' tests')
local statstr = string.rep('_',#tests)
local pstr = ''
io.write(statstr .. '\r')
for i,v in ipairs(tests) do
self.curtestname = testnames[i]
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
--write
pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname
io.write('\r' .. pstr)
io.flush()
local stat, message, pass = self:pcall(v)
if pass then
--io.write(string.format('\b_'))
statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1)
else
statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1)
--io.write(string.format('\b*'))
end
if not stat then
-- print()
-- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i])
-- print(message)
end
collectgarbage()
end
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
-- write finish
pstr = statstr .. ' ==> Done '
io.write('\r' .. pstr)
io.flush()
print()
print()
self:report(tests)
end
function Tester:add(f,name)
name = name or 'unknown'
if type(f) == "table" then
for i,v in pairs(f) do
self:add(v,i)
end
elseif type(f) == "function" then
self.tests[#self.tests+1] = f
self.testnames[#self.tests] = name
else
error('Tester:add(f) expects a function or a table of functions')
end
end
|
fix assertTensorEq for case of empty tensors
|
fix assertTensorEq for case of empty tensors
The case of empty tensors was handled wrongly: leading to exception. In the test of torch.maskedSelect and similar the case of an empty tensor can occur, leading to occasional test failures.
|
Lua
|
bsd-3-clause
|
nicholas-leonard/torch7,bartvm/torch7,eulerreich/torch7,massimobernava/torch7,xindaya/torch7,MOUlili/torch7,diz-vara/torch7,PrajitR/torch7,adamlerer/torch7,yozw/torch7,ninjin/torch7,jbeich/torch7,chenfsjz/torch7,wheatwaves/torch7,douwekiela/torch7,ilovecv/torch7,ninjin/torch7,yozw/torch7,0wu/torch7,Moodstocks/torch7,iamtrask/torch7,pushups/torch7,syhw/torch7,stein2013/torch7,yt752/torch7,hmandal/torch7,MOUlili/torch7,Srisai85/torch7,voidException/torch7,bnk-iitb/torch7,akhti/torch7,rickyHong/torchPlusDQN,chenfsjz/torch7,hmandal/torch7,Peilong/torch7,wickedfoo/torch7,jibaro/torch7,hughperkins/torch7,hughperkins/torch7,yaolubrain/torch7,adamlerer/torch7,alexbw/torch7,kidaa/torch7,u20024804/torch7,bartvm/torch7,kirangonella/torch7,wgapl/torch7,waitwaitforget/torch7,mr-justin/torch7,eriche2016/torch7,ominux/torch7,jlegendary/torch7,dhruvparamhans/torch7,jlegendary/torch7,redbill/torch7,LinusU/torch7,jibaro/torch7,mr-justin/torch7,eriche2016/torch7,WangHong-yang/torch7,kaustubhcs/torch7,xindaya/torch7,nkhuyu/torch7,rotmanmi/torch7,kaustubhcs/torch7,douwekiela/torch7,jbeich/torch7,golden1232004/torch7,redbill/torch7,syhw/torch7,colesbury/torch7,u20024804/torch7,ujjwalkarn/torch7,wickedfoo/torch7,kidaa/torch7,dhruvparamhans/torch7,wangg12/torch7,wgapl/torch7,golden1232004/torch7,fmassa/torch7,waitwaitforget/torch7,dariosena/torch7,bnk-iitb/torch7,ilovecv/torch7,kirangonella/torch7,rickyHong/torchPlusDQN,wangg12/torch7,yt752/torch7,pushups/torch7,kod3r/torch7,akhti/torch7,LinusU/torch7,szagoruyko/torch7,Atcold/torch7,Cadene/torch7,hechenfon/torch7,szagoruyko/torch7,breakds/torch7,dariosena/torch7,ominux/torch7,nkhuyu/torch7,wheatwaves/torch7,clementfarabet/torch7,eulerreich/torch7,massimobernava/torch7,jaak-s/torch7,breakds/torch7,kod3r/torch7,Moodstocks/torch7,PierrotLC/torch7,Peilong/torch7,stein2013/torch7,yaolubrain/torch7,Cadene/torch7,diz-vara/torch7,PrajitR/torch7,WangHong-yang/torch7,clementfarabet/torch7,alexbw/torch7,voidException/torch7,rotmanmi/torch7,iamtrask/torch7,0wu/torch7,ujjwalkarn/torch7,PierrotLC/torch7,colesbury/torch7,jaak-s/torch7,fmassa/torch7,hechenfon/torch7,Srisai85/torch7,nicholas-leonard/torch7,Atcold/torch7
|
d8b61a53941ce5f0e5139f7c4d776abefad9b466
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].Iface)
or routes[section].Iface
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Destination, 32):string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Mask, 32):string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Gateway, 32):string()
end
metric = v:option(DummyValue, "Metric", translate("metric"))
end
s = m:section(TypedSection, "route", translate("a_n_routes_static"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].Iface)
or routes[section].Iface
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Destination, 32):string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Mask, 32):string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Gateway, 32):string()
end
metric = v:option(DummyValue, "Metric", translate("metric"))
end
s = m:section(TypedSection, "route", translate("a_n_routes_static"))
s.addremove = true
s.anonymous = true
function s.render(...)
luci.model.uci.load_config("network")
TypedSection.render(...)
end
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
return m
|
modules/admin-fulk: Fixed changes handling of Static Routes configuration page
|
modules/admin-fulk: Fixed changes handling of Static Routes configuration page
|
Lua
|
apache-2.0
|
hnyman/luci,chris5560/openwrt-luci,dwmw2/luci,lcf258/openwrtcn,artynet/luci,male-puppies/luci,MinFu/luci,jchuang1977/luci-1,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,keyidadi/luci,taiha/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,981213/luci-1,kuoruan/luci,obsy/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,rogerpueyo/luci,tcatm/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,jorgifumi/luci,kuoruan/lede-luci,artynet/luci,taiha/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,cappiewu/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,palmettos/cnLuCI,fkooman/luci,bright-things/ionic-luci,jlopenwrtluci/luci,florian-shellfire/luci,harveyhu2012/luci,kuoruan/luci,wongsyrone/luci-1,forward619/luci,teslamint/luci,kuoruan/lede-luci,981213/luci-1,kuoruan/lede-luci,keyidadi/luci,oneru/luci,Sakura-Winkey/LuCI,teslamint/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,Noltari/luci,dwmw2/luci,mumuqz/luci,mumuqz/luci,shangjiyu/luci-with-extra,jorgifumi/luci,joaofvieira/luci,david-xiao/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,obsy/luci,daofeng2015/luci,harveyhu2012/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,taiha/luci,chris5560/openwrt-luci,kuoruan/lede-luci,dwmw2/luci,deepak78/new-luci,jchuang1977/luci-1,tcatm/luci,dwmw2/luci,fkooman/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,male-puppies/luci,jchuang1977/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,NeoRaider/luci,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,dwmw2/luci,Hostle/openwrt-luci-multi-user,nmav/luci,jchuang1977/luci-1,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,teslamint/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,male-puppies/luci,cshore/luci,palmettos/cnLuCI,wongsyrone/luci-1,fkooman/luci,thess/OpenWrt-luci,Wedmer/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,obsy/luci,keyidadi/luci,cshore-firmware/openwrt-luci,deepak78/new-luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,ff94315/luci-1,shangjiyu/luci-with-extra,MinFu/luci,bittorf/luci,jchuang1977/luci-1,daofeng2015/luci,tobiaswaldvogel/luci,Hostle/luci,bittorf/luci,oyido/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,Wedmer/luci,palmettos/test,cappiewu/luci,slayerrensky/luci,shangjiyu/luci-with-extra,david-xiao/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,jlopenwrtluci/luci,hnyman/luci,ollie27/openwrt_luci,joaofvieira/luci,NeoRaider/luci,harveyhu2012/luci,openwrt-es/openwrt-luci,daofeng2015/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,zhaoxx063/luci,chris5560/openwrt-luci,palmettos/test,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,ff94315/luci-1,Sakura-Winkey/LuCI,NeoRaider/luci,maxrio/luci981213,shangjiyu/luci-with-extra,bright-things/ionic-luci,teslamint/luci,openwrt-es/openwrt-luci,artynet/luci,MinFu/luci,openwrt/luci,LuttyYang/luci,nwf/openwrt-luci,nmav/luci,cshore/luci,thesabbir/luci,tobiaswaldvogel/luci,marcel-sch/luci,RuiChen1113/luci,tobiaswaldvogel/luci,openwrt/luci,mumuqz/luci,teslamint/luci,slayerrensky/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,kuoruan/luci,daofeng2015/luci,slayerrensky/luci,dismantl/luci-0.12,kuoruan/luci,Sakura-Winkey/LuCI,MinFu/luci,palmettos/test,NeoRaider/luci,aa65535/luci,opentechinstitute/luci,thesabbir/luci,dismantl/luci-0.12,Hostle/luci,jlopenwrtluci/luci,Hostle/luci,tcatm/luci,marcel-sch/luci,nwf/openwrt-luci,sujeet14108/luci,981213/luci-1,cappiewu/luci,forward619/luci,ff94315/luci-1,wongsyrone/luci-1,dwmw2/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,LuttyYang/luci,zhaoxx063/luci,remakeelectric/luci,maxrio/luci981213,lcf258/openwrtcn,nmav/luci,maxrio/luci981213,florian-shellfire/luci,nmav/luci,urueedi/luci,rogerpueyo/luci,dismantl/luci-0.12,Wedmer/luci,marcel-sch/luci,RuiChen1113/luci,kuoruan/lede-luci,thess/OpenWrt-luci,lcf258/openwrtcn,remakeelectric/luci,NeoRaider/luci,deepak78/new-luci,nmav/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,joaofvieira/luci,male-puppies/luci,Noltari/luci,Hostle/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,palmettos/test,openwrt/luci,ollie27/openwrt_luci,oneru/luci,RedSnake64/openwrt-luci-packages,cshore/luci,Noltari/luci,thesabbir/luci,thesabbir/luci,Kyklas/luci-proto-hso,cappiewu/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,keyidadi/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,fkooman/luci,joaofvieira/luci,bittorf/luci,taiha/luci,openwrt/luci,taiha/luci,bright-things/ionic-luci,dwmw2/luci,jlopenwrtluci/luci,thess/OpenWrt-luci,jorgifumi/luci,sujeet14108/luci,oyido/luci,chris5560/openwrt-luci,florian-shellfire/luci,openwrt/luci,ff94315/luci-1,palmettos/cnLuCI,zhaoxx063/luci,nmav/luci,maxrio/luci981213,Kyklas/luci-proto-hso,LuttyYang/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,oneru/luci,MinFu/luci,remakeelectric/luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,sujeet14108/luci,palmettos/cnLuCI,kuoruan/luci,LuttyYang/luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,lbthomsen/openwrt-luci,david-xiao/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,maxrio/luci981213,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,oyido/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,jlopenwrtluci/luci,sujeet14108/luci,palmettos/test,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,zhaoxx063/luci,cappiewu/luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,aa65535/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,remakeelectric/luci,981213/luci-1,lcf258/openwrtcn,dismantl/luci-0.12,slayerrensky/luci,slayerrensky/luci,nwf/openwrt-luci,obsy/luci,MinFu/luci,bright-things/ionic-luci,urueedi/luci,mumuqz/luci,Hostle/luci,male-puppies/luci,aa65535/luci,florian-shellfire/luci,wongsyrone/luci-1,urueedi/luci,opentechinstitute/luci,schidler/ionic-luci,thesabbir/luci,opentechinstitute/luci,Noltari/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,fkooman/luci,kuoruan/lede-luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,sujeet14108/luci,chris5560/openwrt-luci,harveyhu2012/luci,rogerpueyo/luci,aa65535/luci,schidler/ionic-luci,tcatm/luci,openwrt/luci,fkooman/luci,mumuqz/luci,jlopenwrtluci/luci,nmav/luci,981213/luci-1,artynet/luci,aa65535/luci,bright-things/ionic-luci,palmettos/test,thess/OpenWrt-luci,palmettos/cnLuCI,remakeelectric/luci,nwf/openwrt-luci,joaofvieira/luci,david-xiao/luci,david-xiao/luci,hnyman/luci,nwf/openwrt-luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,LuttyYang/luci,openwrt/luci,joaofvieira/luci,urueedi/luci,RuiChen1113/luci,cshore/luci,florian-shellfire/luci,ff94315/luci-1,artynet/luci,lcf258/openwrtcn,hnyman/luci,Sakura-Winkey/LuCI,artynet/luci,Noltari/luci,Wedmer/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,forward619/luci,shangjiyu/luci-with-extra,NeoRaider/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,sujeet14108/luci,schidler/ionic-luci,maxrio/luci981213,cshore/luci,openwrt-es/openwrt-luci,aa65535/luci,jorgifumi/luci,male-puppies/luci,oneru/luci,cshore-firmware/openwrt-luci,thesabbir/luci,schidler/ionic-luci,tobiaswaldvogel/luci,LuttyYang/luci,florian-shellfire/luci,Noltari/luci,Hostle/luci,urueedi/luci,artynet/luci,sujeet14108/luci,bright-things/ionic-luci,ollie27/openwrt_luci,schidler/ionic-luci,forward619/luci,harveyhu2012/luci,chris5560/openwrt-luci,cshore/luci,tobiaswaldvogel/luci,teslamint/luci,dismantl/luci-0.12,MinFu/luci,kuoruan/luci,urueedi/luci,deepak78/new-luci,deepak78/new-luci,remakeelectric/luci,marcel-sch/luci,fkooman/luci,981213/luci-1,forward619/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,jorgifumi/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,rogerpueyo/luci,Wedmer/luci,harveyhu2012/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,forward619/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,thess/OpenWrt-luci,NeoRaider/luci,cshore/luci,david-xiao/luci,bittorf/luci,deepak78/new-luci,lcf258/openwrtcn,hnyman/luci,jorgifumi/luci,jlopenwrtluci/luci,zhaoxx063/luci,hnyman/luci,deepak78/new-luci,maxrio/luci981213,taiha/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,opentechinstitute/luci,maxrio/luci981213,nwf/openwrt-luci,RuiChen1113/luci,marcel-sch/luci,dwmw2/luci,fkooman/luci,jchuang1977/luci-1,lbthomsen/openwrt-luci,tcatm/luci,artynet/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,daofeng2015/luci,wongsyrone/luci-1,tcatm/luci,forward619/luci,florian-shellfire/luci,thesabbir/luci,rogerpueyo/luci,nmav/luci,david-xiao/luci,rogerpueyo/luci,obsy/luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,tcatm/luci,obsy/luci,tcatm/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,florian-shellfire/luci,keyidadi/luci,rogerpueyo/luci,mumuqz/luci,lcf258/openwrtcn,bright-things/ionic-luci,palmettos/test,bittorf/luci,cshore-firmware/openwrt-luci,bittorf/luci,ff94315/luci-1,bright-things/ionic-luci,RuiChen1113/luci,hnyman/luci,teslamint/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,oyido/luci,RuiChen1113/luci,bittorf/luci,thesabbir/luci,oyido/luci,obsy/luci,slayerrensky/luci,lbthomsen/openwrt-luci,forward619/luci,dismantl/luci-0.12,palmettos/cnLuCI,mumuqz/luci,david-xiao/luci,joaofvieira/luci,male-puppies/luci,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,oyido/luci,MinFu/luci,teslamint/luci,cappiewu/luci,Noltari/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,lcf258/openwrtcn,Noltari/luci,marcel-sch/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,aa65535/luci,openwrt-es/openwrt-luci,hnyman/luci,oneru/luci,obsy/luci,opentechinstitute/luci,aa65535/luci,oneru/luci,opentechinstitute/luci,zhaoxx063/luci,wongsyrone/luci-1,artynet/luci,thess/OpenWrt-luci,Noltari/luci,opentechinstitute/luci
|
4485e389801fcc0686db18bbdf4ecc37916affd0
|
translations/others/scripts/quest/paramtext.lua
|
translations/others/scripts/quest/paramtext.lua
|
function itemShortDescription(itemDescriptor)
return root.itemConfig(itemDescriptor).config.shortdescription or itemDescriptor.name
end
local function getCountEnding(count)
local residue = count % 10
if count > 10 and count < 21 then return ""
elseif resudue == 1 then return "а"
elseif residue > 1 and residue < 5 then return "и"
else return "" end
end
local function newSub(match, subtable)
return {match = type(match) == "string" and {match} or match,
sub = setmetatable(subtable, {__index = function(t,k)
if k == "any" then return end
if t.any then return t.any end
if k == "neutral" and t.male then return t.male end
return "%0"
end})
}
end
local function iterateRules(rules, matcher)
assert(type(rules) == "table")
assert(type(matcher) == "function")
for i = 1, #rules do
for _, match in pairs(rules[i].match) do
local result = matcher(match, rules[i], rules.nonstop)
if result then
return result
end
end
end
end
local function matchTable(object, mtable)
local plain = type(object) == "string"
local name = plain and object or object.name
if not plain then
mtable.remove_guards = {
nonstop = true,
newSub(":guard:(.*)", {any = "%1"}),
}
local gender = object.gender or "neutral"
local rules = mtable[object.species] or {}
local act = function(pat, rule, nonstop)
local result, count = name:gsub(pat.."$", rule.sub[gender])
if count > 0 then
if nonstop then name = result return
else return result end end
end
local additionals = rules.additional or {"any"}
table.insert(additionals, "remove_guards")
name = iterateRules(rules, act) or name
for i, e in pairs(additionals) do
name = iterateRules(mtable[e] or {}, act) or name
end
return name
elseif mtable.item and mtable.item.formdetector then
local rules = mtable.item
local form, subform
local tailname = ""
local matcher = function(pat, rule)
if name:match(pat.."$") then
form = form or rule.form
if not subform then
if rule.subform == "of" then
name, tailname = name:match("^(.-)(%s.+)$")
end
subform = rule.subform
end
end
if form and subform then return form end
end
local newobj = {
gender = iterateRules(rules.formdetector, matcher),
species = "item",
}
newobj.name = name
return matchTable(newobj, mtable)..tailname
end
return name
end
local formdetector = {
{match = {"емена.*"}, form = "plural"},
{match = {"ие%s.+", "ые%s.+"}, form = "plural", subform = "normal"},
{match = {"ое%s.+", "ее%s.+"}, form = "neutral", subform = "normal"},
{match = {"емя.*", "o"}, form = "neutral"},
{match = {"ая%s.+", "яя%s.+"},form = "female", subform = "normal"},
{match = {"й%s.+", "е%s.+"}, subform = "normal"},
{match = {".%s.+"}, subform = "of"},
{match = {"и", "ы"}, form = "plural"},
{match = {"а", "я", "сть"}, form = "female"},
{match = {"."}, form = "male", subform = "normal"},
}
local consonants = {"ц", "к", "н", "ш", "щ", "з", "х", "ф", "в", "п",
"р", "л", "д", "ж", "ч", "с", "м", "т", "б"}
local function convertToObjective(object)
local variants = {
any = {
newSub("й", {male = "ю"}),
newSub("ия", {male = "ие", female = "ии"}),
newSub("ень", {male = "ню"}),
newSub("ь", {male = "ю", female = "и"}),
newSub({"а", "я"}, {any = "е", neutral = "ени", plural = "%0м"}),
newSub(consonants, {male = "%0у"}),
},
glitch = {
newSub({"ый(.+)", "ой(.+)", "ое(.*)"}, {any = "ому%1", female = "%0"}),
newSub({"(к)ий(.+)", "(г)ий(.+)"}, {male = "%1ому%2"}),
newSub("ий(.+)", {male = "ему%1"}),
newSub("ая(.+)", {female = "ой%1"}),
newSub("яя(.+)", {female = "ей%1"}),
newSub({"е", "о"}, {any = "у"}),
newSub({"ок", "ек"}, {any = "ку"}),
nonstop = true,
},
item = {
formdetector = formdetector,
additional = {"glitch", "any"},
nonstop = true,
newSub("ы", {plural = "ам"}),
newSub({"(г)и", "(к)и"}, {plural = "%1ам:guard:"}),
newSub("и", {plural = "ям"}),
newSub("е(%s.+)", {plural = "м%1"}),
}
}
return matchTable(object, variants)
end
local function convertToReflexive(object)
local variants = {
any = {
newSub("а", {any = "у"}),
newSub("я", {any = "ю"}),
newSub("й", {male = "я"}),
newSub("ень", {male = "ня"}),
newSub("ь", {male = "я"}),
newSub(consonants, {male = "%0а"}),
},
glitch = {
newSub({"ый(.+)", "ой(.+)", "oe(.*)"}, {any = "ого%1", female = "%0"}),
newSub({"(к)ий(.+)", "(г)ий(.+)"}, {male = "%1ого%2"}),
newSub("ий(.+)", {male = "его%1"}),
newSub({"ок", "ек"}, {male = "ка:guard:"}),
-- :guard: notation will be removed automatically at the end of processing
-- it is necessary to prevent changing this ending
additional = {"any", "item"},
},
item = {
formdetector = formdetector,
additional = {},
nonstop = true,
newSub("ая(.+)", {female = "ую%1"}),
newSub("яя(.+)", {female = "юю%1"}),
newSub("е(%s.+)", {plural = "х%1"}),
newSub({"(г)и", "(к)и"}, {plural = "%1ов:guard:"}),
newSub("и", {plural = "ей"}),
newSub("ы", {plural = "ов"}),
newSub("а", {female = "у"}),
newSub("я", {female = "ю"}),
},
}
return matchTable(object, variants)
end
function questParameterText(paramValue, caseModifier)
caseModifier = caseModifier or
function(a) return type(a) == "string" and a or a.name end
if paramValue.name then
return caseModifier(paramValue)
end
if paramValue.type == "item" then
return caseModifier(itemShortDescription(paramValue.item))
elseif paramValue.type == "itemList" then
local listString = ""
local count = 0
for _,item in ipairs(paramValue.items) do
if listString ~= "" then
if count > 1 then
listString = "; " .. listString
else
listString = " и " .. listString
end
end
local description = caseModifier(itemShortDescription(item))
if item.count > 1 then
local thingEnd = getCountEnding(item.count)
listString = string.format("%s, %s штук%s", description, item.count,
thingEnd) .. listString
else
listString = description .. listString
end
count = count + 1
end
return listString
end
end
function questParameterTags(parameters)
local result = {}
for k, v in pairs(parameters) do
result[k] = questParameterText(v)
result[k..".reflexive"] = questParameterText(v, convertToReflexive)
result[k..".objective"] = questParameterText(v, convertToObjective)
end
return result
end
|
function itemShortDescription(itemDescriptor)
return root.itemConfig(itemDescriptor).config.shortdescription or itemDescriptor.name
end
local function getCountEnding(count)
local residue = count % 10
if count > 10 and count < 21 then return ""
elseif resudue == 1 then return "а"
elseif residue > 1 and residue < 5 then return "и"
else return "" end
end
local function newSub(match, subtable)
return {match = type(match) == "string" and {match} or match,
sub = setmetatable(subtable, {__index = function(t,k)
if k == "any" then return end
if t.any then return t.any end
if k == "neutral" and t.male then return t.male end
return "%0"
end})
}
end
local function iterateRules(rules, matcher)
assert(type(rules) == "table")
assert(type(matcher) == "function")
for i = 1, #rules do
for _, match in pairs(rules[i].match) do
local result = matcher(match, rules[i], rules.nonstop)
if result then
return result
end
end
end
end
local function matchTable(object, mtable)
local plain = type(object) == "string"
local name = plain and object or object.name
if not plain then
mtable.remove_guards = {
nonstop = true,
newSub(":guard:(.*)", {any = "%1"}),
}
local gender = object.gender or "plural"
local rules = mtable[object.species] or {}
local act = function(pat, rule, nonstop)
local result, count = name:gsub(pat.."$", rule.sub[gender])
if count > 0 then
if nonstop then name = result return
else return result end end
end
local additionals = rules.additional or {"any"}
table.insert(additionals, "remove_guards")
name = iterateRules(rules, act) or name
for i, e in pairs(additionals) do
name = iterateRules(mtable[e] or {}, act) or name
end
return name
elseif mtable.item and mtable.item.formdetector then
local rules = mtable.item
local form, subform
local tailname = ""
local matcher = function(pat, rule)
if name:match(pat.."$") then
form = form or rule.form
if not subform then
if rule.subform == "of" then
name, tailname = name:match("^(.-)(%s.+)$")
end
subform = rule.subform
end
end
if form and subform then return form end
end
local newobj = {
gender = iterateRules(rules.formdetector, matcher),
species = "item",
}
newobj.name = name
return matchTable(newobj, mtable)..tailname
end
return name
end
local formdetector = {
{match = {"емена.*"}, form = "plural"},
{match = {"ие%s.+", "ые%s.+"}, form = "plural", subform = "normal"},
{match = {"ое%s.+", "ее%s.+"}, form = "neutral", subform = "normal"},
{match = {"емя.*", "o"}, form = "neutral"},
{match = {"ая%s.+", "яя%s.+"},form = "female", subform = "normal"},
{match = {"й%s.+", "е%s.+"}, subform = "normal"},
{match = {".%s.+"}, subform = "of"},
{match = {"и", "ы"}, form = "plural"},
{match = {"а", "я", "сть"}, form = "female"},
{match = {"."}, form = "male", subform = "normal"},
}
local consonants = {"ц", "к", "н", "ш", "щ", "з", "х", "ф", "в", "п",
"р", "л", "д", "ж", "ч", "с", "м", "т", "б"}
local function convertToObjective(object)
local variants = {
any = {
newSub("й", {male = "ю"}),
newSub("ия", {male = "ие", female = "ии"}),
newSub("ень", {male = "ню"}),
newSub("ь", {male = "ю", female = "и"}),
newSub({"а", "я"}, {any = "е", neutral = "ени", plural = "%0м"}),
newSub("ы", {plural = "ам"}),
newSub({"(г)и", "(к)и"}, {plural = "%1ам:guard:"}),
newSub("и", {plural = "ям"}),
newSub("е(%s.+)", {plural = "м%1"}),
newSub(consonants, {male = "%0у"}),
nonstop = true,
},
glitch = {
newSub({"ый(.+)", "ой(.+)", "ое(.*)"}, {any = "ому%1", female = "%0"}),
newSub({"(к)ий(.+)", "(г)ий(.+)"}, {male = "%1ому%2"}),
newSub("ий(.+)", {male = "ему%1"}),
newSub("ая(.+)", {female = "ой%1"}),
newSub("яя(.+)", {female = "ей%1"}),
newSub({"е", "о"}, {any = "у"}),
newSub({"ок", "ек"}, {any = "ку"}),
nonstop = true,
},
item = {
formdetector = formdetector,
additional = {"glitch", "any"},
}
}
return matchTable(object, variants)
end
local function convertToReflexive(object)
local variants = {
any = {
newSub("а", {any = "у"}),
newSub("я", {any = "ю"}),
newSub("е(%s.+)", {plural = "х%1"}),
newSub({"(г)и", "(к)и"}, {plural = "%1ов:guard:"}),
newSub("и", {plural = "ей"}),
newSub("ы", {plural = "ов"}),
newSub("й", {male = "я"}),
newSub("ень", {male = "ня"}),
newSub("ь", {male = "я"}),
newSub(consonants, {male = "%0а"}),
nonstop = true,
},
glitch = {
newSub({"ый(.+)", "ой(.+)", "oe(.*)"}, {any = "ого%1", female = "%0"}),
newSub({"(к)ий(.+)", "(г)ий(.+)"}, {male = "%1ого%2"}),
newSub("ий(.+)", {male = "его%1"}),
newSub({"ок", "ек"}, {male = "ка:guard:"}),
-- :guard: notation will be removed automatically at the end of processing
-- it is necessary to prevent changing this ending
additional = {"any", "item"},
},
item = {
formdetector = formdetector,
additional = {},
nonstop = true,
newSub("ая(.+)", {female = "ую%1"}),
newSub("яя(.+)", {female = "юю%1"}),
newSub("а", {female = "у"}),
newSub("я", {female = "ю"}),
},
}
return matchTable(object, variants)
end
function questParameterText(paramValue, caseModifier)
caseModifier = caseModifier or
function(a) return type(a) == "string" and a or a.name end
if paramValue.name then
return caseModifier(paramValue)
end
if paramValue.type == "item" then
return caseModifier(itemShortDescription(paramValue.item))
elseif paramValue.type == "itemList" then
local listString = ""
local count = 0
for _,item in ipairs(paramValue.items) do
if listString ~= "" then
if count > 1 then
listString = "; " .. listString
else
listString = " и " .. listString
end
end
local description = caseModifier(itemShortDescription(item))
if item.count > 1 then
local thingEnd = getCountEnding(item.count)
listString = string.format("%s, %s штук%s", description, item.count,
thingEnd) .. listString
else
listString = description .. listString
end
count = count + 1
end
return listString
end
end
function questParameterTags(parameters)
local result = {}
for k, v in pairs(parameters) do
result[k] = questParameterText(v)
result[k..".reflexive"] = questParameterText(v, convertToReflexive)
result[k..".objective"] = questParameterText(v, convertToObjective)
end
return result
end
|
Fixed plural form handling for non-items
|
Fixed plural form handling for non-items
|
Lua
|
apache-2.0
|
UniverseGuard/Starbound_RU,SBT-community/Starbound_RU,GuardOscar/Starbound_RU,UniverseGuard/Starbound_RU,SBT-community/Starbound_RU,MrHimera/Starbound_RU,MrHimera/Starbound_RU,GuardOscar/Starbound_RU
|
06e676203f8893c9989f5ae7d508227ce0bdde27
|
script/c46772449.lua
|
script/c46772449.lua
|
--励輝士 ヴェルズビュート
function c46772449.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,4),2)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46772449,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c46772449.condition)
e1:SetCost(c46772449.cost)
e1:SetTarget(c46772449.target)
e1:SetOperation(c46772449.operation)
c:RegisterEffect(e1)
end
function c46772449.condition(e,tp,eg,ep,ev,re,r,rp)
local ct1=Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD+LOCATION_HAND,0)
local ct2=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD+LOCATION_HAND)
if ct1>=ct2 then return false end
local ph=Duel.GetCurrentPhase()
if Duel.GetTurnPlayer()==tp then
return ph==PHASE_MAIN1 or ph==PHASE_MAIN2
else
return ph==PHASE_BATTLE
end
end
function c46772449.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetValue(0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c46772449.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not e:GetHandler():IsStatus(STATUS_CHAINING)
and Duel.IsExistingMatchingCard(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c46772449.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
Duel.Destroy(g,REASON_EFFECT)
end
|
--励輝士 ヴェルズビュート
function c46772449.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,4),2)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46772449,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c46772449.condition)
e1:SetCost(c46772449.cost)
e1:SetTarget(c46772449.target)
e1:SetOperation(c46772449.operation)
c:RegisterEffect(e1)
end
function c46772449.condition(e,tp,eg,ep,ev,re,r,rp)
local ct1=Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD+LOCATION_HAND,0)
local ct2=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD+LOCATION_HAND)
if ct1>=ct2 then return false end
local ph=Duel.GetCurrentPhase()
if Duel.GetTurnPlayer()==tp then
return ph==PHASE_MAIN1 or ph==PHASE_MAIN2
else
return ph==PHASE_BATTLE
end
end
function c46772449.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:CheckRemoveOverlayCard(tp,1,REASON_COST) and
c:GetFlagEffect(46772449)==0
end
c:RemoveOverlayCard(tp,1,1,REASON_COST)
c:RegisterFlagEffect(46772449,RESET_CHAIN,0,1)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetValue(0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c46772449.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return
Duel.IsExistingMatchingCard(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c46772449.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
Duel.Destroy(g,REASON_EFFECT)
end
|
fix
|
fix
fixed not being able to chain the effect when XYZ summoned with Star
Drawing or HC Extra Sword
|
Lua
|
mit
|
Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher
|
5ff472b5d849ca55b8c7bb54b542a4d1582f31f0
|
src/cmdrservice/src/Client/CmdrServiceClient.lua
|
src/cmdrservice/src/Client/CmdrServiceClient.lua
|
--[=[
Loads cmdr on the client. See [CmdrService] for the server equivalent.
@client
@class CmdrServiceClient
]=]
local require = require(script.Parent.loader).load(script)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local promiseChild = require("promiseChild")
local PromiseUtils = require("PromiseUtils")
local PermissionServiceClient = require("PermissionServiceClient")
local Maid = require("Maid")
local String = require("String")
local Promise = require("Promise")
local CmdrServiceClient = {}
--[=[
Starts the cmdr service on the client. Should be done via [ServiceBag].
@param serviceBag ServiceBag
]=]
function CmdrServiceClient:Init(serviceBag)
assert(not self._serviceBag, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._maid = Maid.new()
self._permissionService = serviceBag:GetService(PermissionServiceClient)
end
--[=[
Starts the service. Should be done via [ServiceBag].
]=]
function CmdrServiceClient:Start()
assert(self._serviceBag, "Not initialized")
PromiseUtils.all({
self:PromiseCmdr(),
self._permissionService:PromisePermissionProvider()
:Then(function(provider)
return provider:PromiseIsAdmin()
end)
})
:Then(function(cmdr, isAdmin)
if isAdmin then
self:_setBindings(cmdr)
else
cmdr:SetActivationKeys({})
end
end)
end
function CmdrServiceClient:_setBindings(cmdr)
cmdr:SetActivationUnlocksMouse(true)
cmdr:SetActivationKeys({ Enum.KeyCode.F2 })
-- enable activation on mobile
self._maid:GiveTask(Players.LocalPlayer.Chatted:Connect(function(chat)
if String.startsWith(chat, "/cmdr") then
cmdr:Show()
end
end))
-- Default blink for debugging purposes
cmdr.Dispatcher:Run("bind", Enum.KeyCode.G.Name, "blink")
end
--[=[
Retrieves the cmdr for the client.
@return Promise<CmdrClient>
]=]
function CmdrServiceClient:PromiseCmdr()
assert(self._serviceBag, "Not initialized")
if self._cmdrPromise then
return self._cmdrPromise
end
self._cmdrPromise = promiseChild(ReplicatedStorage, "CmdrClient")
:Then(function(cmdClient)
return Promise.spawn(function(resolve, _reject)
-- Requiring cmdr can yield
return resolve(require(cmdClient))
end)
end)
return self._cmdrPromise
end
return CmdrServiceClient
|
--[=[
Loads cmdr on the client. See [CmdrService] for the server equivalent.
@client
@class CmdrServiceClient
]=]
local require = require(script.Parent.loader).load(script)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local promiseChild = require("promiseChild")
local PromiseUtils = require("PromiseUtils")
local PermissionServiceClient = require("PermissionServiceClient")
local Maid = require("Maid")
local String = require("String")
local Promise = require("Promise")
local CmdrServiceClient = {}
--[=[
Starts the cmdr service on the client. Should be done via [ServiceBag].
@param serviceBag ServiceBag
]=]
function CmdrServiceClient:Init(serviceBag)
assert(not self._serviceBag, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._maid = Maid.new()
self._permissionService = serviceBag:GetService(PermissionServiceClient)
end
--[=[
Starts the service. Should be done via [ServiceBag].
]=]
function CmdrServiceClient:Start()
assert(self._serviceBag, "Not initialized")
self._maid:GivePromise(PromiseUtils.all({
self:PromiseCmdr(),
self._maid:GivePromise(self._permissionService:PromisePermissionProvider())
:Then(function(provider)
return provider:PromiseIsAdmin()
end)
}))
:Then(function(cmdr, isAdmin)
if isAdmin then
self:_setBindings(cmdr)
else
cmdr:SetActivationKeys({})
end
end)
end
function CmdrServiceClient:_setBindings(cmdr)
cmdr:SetActivationUnlocksMouse(true)
cmdr:SetActivationKeys({ Enum.KeyCode.F2 })
-- enable activation on mobile
self._maid:GiveTask(Players.LocalPlayer.Chatted:Connect(function(chat)
if String.startsWith(chat, "/cmdr") then
cmdr:Show()
end
end))
-- Default blink for debugging purposes
cmdr.Dispatcher:Run("bind", Enum.KeyCode.G.Name, "blink")
end
--[=[
Retrieves the cmdr for the client.
@return Promise<CmdrClient>
]=]
function CmdrServiceClient:PromiseCmdr()
assert(self._serviceBag, "Not initialized")
if self._cmdrPromise then
return self._cmdrPromise
end
self._cmdrPromise = promiseChild(ReplicatedStorage, "CmdrClient")
:Then(function(cmdClient)
return Promise.spawn(function(resolve, _reject)
-- Requiring cmdr can yield
return resolve(require(cmdClient))
end)
end)
return self._cmdrPromise
end
return CmdrServiceClient
|
fix: Ensure of CmdrServiceClient is disposed of that no more promises are executed.
|
fix: Ensure of CmdrServiceClient is disposed of that no more promises are executed.
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
6ee014dd99323fedebe2e8e511265920f40550ac
|
service/snaxd.lua
|
service/snaxd.lua
|
local skynet = require "skynet"
local c = require "skynet.core"
local snax_interface = require "snax.interface"
local profile = require "profile"
local snax = require "snax"
local snax_name = tostring(...)
local func, pattern = snax_interface(snax_name, _ENV)
local snax_path = pattern:sub(1,pattern:find("?", 1, true)-1) .. snax_name .. "/"
package.path = snax_path .. "?.lua;" .. package.path
SERVICE_NAME = snax_name
SERVICE_PATH = snax_path
local profile_table = {}
local function update_stat(name, ti)
local t = profile_table[name]
if t == nil then
t = { count = 0, time = 0 }
profile_table[name] = t
end
t.count = t.count + 1
t.time = t.time + ti
end
local traceback = debug.traceback
local function do_func(f, msg)
return xpcall(f, traceback, table.unpack(msg))
end
local function dispatch(f, ...)
return skynet.pack(f(...))
end
local function return_f(f, ...)
return skynet.ret(skynet.pack(f(...)))
end
local function timing( method, ... )
local err, msg
profile.start()
if method[2] == "accept" then
-- no return
err,msg = xpcall(method[4], traceback, ...)
else
err,msg = xpcall(return_f, traceback, method[4], ...)
end
local ti = profile.stop()
update_stat(method[3], ti)
assert(err,msg)
end
skynet.start(function()
skynet.dispatch("snax", function ( session , source , id, ...)
local init = false
local method = func[id]
if method[2] == "system" then
local command = method[3]
if command == "hotfix" then
local hotfix = require "snax.hotfix"
skynet.ret(skynet.pack(hotfix(func, ...)))
elseif command == "init" then
assert(not init, "Already init")
local initfunc = method[4] or function() end
initfunc(...)
skynet.ret()
skynet.info_func(function()
return profile_table
end)
init = true
else
assert(init, "Never init")
assert(command == "exit")
local exitfunc = method[4] or function() end
exitfunc(...)
skynet.ret()
init = false
skynet.exit()
end
else
assert(init, "Init first")
timing(method, ...)
end
end)
end)
|
local skynet = require "skynet"
local c = require "skynet.core"
local snax_interface = require "snax.interface"
local profile = require "profile"
local snax = require "snax"
local snax_name = tostring(...)
local func, pattern = snax_interface(snax_name, _ENV)
local snax_path = pattern:sub(1,pattern:find("?", 1, true)-1) .. snax_name .. "/"
package.path = snax_path .. "?.lua;" .. package.path
SERVICE_NAME = snax_name
SERVICE_PATH = snax_path
local profile_table = {}
local function update_stat(name, ti)
local t = profile_table[name]
if t == nil then
t = { count = 0, time = 0 }
profile_table[name] = t
end
t.count = t.count + 1
t.time = t.time + ti
end
local traceback = debug.traceback
local function do_func(f, msg)
return xpcall(f, traceback, table.unpack(msg))
end
local function dispatch(f, ...)
return skynet.pack(f(...))
end
local function return_f(f, ...)
return skynet.ret(skynet.pack(f(...)))
end
local function timing( method, ... )
local err, msg
profile.start()
if method[2] == "accept" then
-- no return
err,msg = xpcall(method[4], traceback, ...)
else
err,msg = xpcall(return_f, traceback, method[4], ...)
end
local ti = profile.stop()
update_stat(method[3], ti)
assert(err,msg)
end
skynet.start(function()
local init = false
skynet.dispatch("snax", function ( session , source , id, ...)
local method = func[id]
if method[2] == "system" then
local command = method[3]
if command == "hotfix" then
local hotfix = require "snax.hotfix"
skynet.ret(skynet.pack(hotfix(func, ...)))
elseif command == "init" then
assert(not init, "Already init")
local initfunc = method[4] or function() end
initfunc(...)
skynet.ret()
skynet.info_func(function()
return profile_table
end)
init = true
else
assert(init, "Never init")
assert(command == "exit")
local exitfunc = method[4] or function() end
exitfunc(...)
skynet.ret()
init = false
skynet.exit()
end
else
assert(init, "Init first")
timing(method, ...)
end
end)
end)
|
bugfix: init should be out
|
bugfix: init should be out
|
Lua
|
mit
|
icetoggle/skynet,kebo/skynet,catinred2/skynet,xcjmine/skynet,firedtoad/skynet,kyle-wang/skynet,ludi1991/skynet,Markal128/skynet,lawnight/skynet,MetSystem/skynet,zhaijialong/skynet,bingo235/skynet,microcai/skynet,czlc/skynet,ludi1991/skynet,felixdae/skynet,iskygame/skynet,matinJ/skynet,kyle-wang/skynet,samael65535/skynet,plsytj/skynet,korialuo/skynet,KittyCookie/skynet,ag6ag/skynet,enulex/skynet,zhoukk/skynet,jiuaiwo1314/skynet,LiangMa/skynet,bttscut/skynet,zhangshiqian1214/skynet,iskygame/skynet,microcai/skynet,helling34/skynet,wangyi0226/skynet,u20024804/skynet,wangyi0226/skynet,pichina/skynet,cuit-zhaxin/skynet,xinjuncoding/skynet,javachengwc/skynet,rainfiel/skynet,helling34/skynet,puXiaoyi/skynet,cpascal/skynet,zhouxiaoxiaoxujian/skynet,lawnight/skynet,KAndQ/skynet,catinred2/skynet,bingo235/skynet,cpascal/skynet,chfg007/skynet,zzh442856860/skynet,great90/skynet,chuenlungwang/skynet,korialuo/skynet,leezhongshan/skynet,sdgdsffdsfff/skynet,korialuo/skynet,asanosoyokaze/skynet,catinred2/skynet,JiessieDawn/skynet,sundream/skynet,puXiaoyi/skynet,vizewang/skynet,yinjun322/skynet,ludi1991/skynet,QuiQiJingFeng/skynet,great90/skynet,asanosoyokaze/skynet,MoZhonghua/skynet,zhouxiaoxiaoxujian/skynet,yinjun322/skynet,wangyi0226/skynet,samael65535/skynet,javachengwc/skynet,zhaijialong/skynet,your-gatsby/skynet,samael65535/skynet,ruleless/skynet,longmian/skynet,chuenlungwang/skynet,sdgdsffdsfff/skynet,javachengwc/skynet,jxlczjp77/skynet,KittyCookie/skynet,pigparadise/skynet,ludi1991/skynet,zhangshiqian1214/skynet,pigparadise/skynet,plsytj/skynet,sundream/skynet,cdd990/skynet,lc412/skynet,helling34/skynet,ruleless/skynet,MRunFoss/skynet,kebo/skynet,zhaijialong/skynet,sdgdsffdsfff/skynet,harryzeng/skynet,zzh442856860/skynet-Note,icetoggle/skynet,sundream/skynet,yinjun322/skynet,boyuegame/skynet,gitfancode/skynet,vizewang/skynet,JiessieDawn/skynet,liuxuezhan/skynet,felixdae/skynet,yunGit/skynet,czlc/skynet,ilylia/skynet,KAndQ/skynet,nightcj/mmo,LuffyPan/skynet,bigrpg/skynet,boyuegame/skynet,xubigshu/skynet,dymx101/skynet,cloudwu/skynet,xcjmine/skynet,sanikoyes/skynet,longmian/skynet,togolwb/skynet,Zirpon/skynet,cloudwu/skynet,bigrpg/skynet,lynx-seu/skynet,jiuaiwo1314/skynet,KAndQ/skynet,bttscut/skynet,ypengju/skynet_comment,cloudwu/skynet,wangjunwei01/skynet,togolwb/skynet,hongling0/skynet,chenjiansnail/skynet,fhaoquan/skynet,letmefly/skynet,chfg007/skynet,lynx-seu/skynet,bttscut/skynet,kebo/skynet,asanosoyokaze/skynet,LiangMa/skynet,winglsh/skynet,Ding8222/skynet,MRunFoss/skynet,codingabc/skynet,fhaoquan/skynet,xjdrew/skynet,zhouxiaoxiaoxujian/skynet,cdd990/skynet,fztcjjl/skynet,yunGit/skynet,xjdrew/skynet,QuiQiJingFeng/skynet,zzh442856860/skynet,iskygame/skynet,LiangMa/skynet,zhangshiqian1214/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,zhoukk/skynet,LuffyPan/skynet,cuit-zhaxin/skynet,leezhongshan/skynet,dymx101/skynet,firedtoad/skynet,zhangshiqian1214/skynet,togolwb/skynet,Markal128/skynet,zhangshiqian1214/skynet,enulex/skynet,Ding8222/skynet,MoZhonghua/skynet,QuiQiJingFeng/skynet,wangjunwei01/skynet,nightcj/mmo,matinJ/skynet,hongling0/skynet,cmingjian/skynet,pichina/skynet,MoZhonghua/skynet,chuenlungwang/skynet,zzh442856860/skynet-Note,zzh442856860/skynet,liuxuezhan/skynet,xcjmine/skynet,lawnight/skynet,fhaoquan/skynet,ypengju/skynet_comment,chfg007/skynet,lynx-seu/skynet,zzh442856860/skynet-Note,winglsh/skynet,liuxuezhan/skynet,plsytj/skynet,JiessieDawn/skynet,MRunFoss/skynet,sanikoyes/skynet,cmingjian/skynet,rainfiel/skynet,Zirpon/skynet,cpascal/skynet,vizewang/skynet,harryzeng/skynet,great90/skynet,microcai/skynet,pichina/skynet,sanikoyes/skynet,xinjuncoding/skynet,chenjiansnail/skynet,jiuaiwo1314/skynet,ypengju/skynet_comment,fztcjjl/skynet,ilylia/skynet,rainfiel/skynet,cmingjian/skynet,codingabc/skynet,felixdae/skynet,cuit-zhaxin/skynet,u20024804/skynet,harryzeng/skynet,letmefly/skynet,lc412/skynet,u20024804/skynet,pigparadise/skynet,bigrpg/skynet,jxlczjp77/skynet,longmian/skynet,lawnight/skynet,puXiaoyi/skynet,your-gatsby/skynet,MetSystem/skynet,xubigshu/skynet,LuffyPan/skynet,fztcjjl/skynet,zzh442856860/skynet-Note,winglsh/skynet,Ding8222/skynet,kyle-wang/skynet,cdd990/skynet,leezhongshan/skynet,Zirpon/skynet,chenjiansnail/skynet,gitfancode/skynet,firedtoad/skynet,Markal128/skynet,ruleless/skynet,letmefly/skynet,yunGit/skynet,bingo235/skynet,ag6ag/skynet,gitfancode/skynet,KittyCookie/skynet,icetoggle/skynet,xinjuncoding/skynet,matinJ/skynet,your-gatsby/skynet,lc412/skynet,ag6ag/skynet,codingabc/skynet,hongling0/skynet,nightcj/mmo,enulex/skynet,letmefly/skynet,wangjunwei01/skynet,boyuegame/skynet,zhoukk/skynet,MetSystem/skynet,liuxuezhan/skynet,ilylia/skynet,czlc/skynet,xjdrew/skynet,dymx101/skynet
|
66c6d425de88d0146aeca3d75219c7a5a5742f40
|
app/modules/utils/init.lua
|
app/modules/utils/init.lua
|
local uv = require('uv')
local prettyPrint, dump, strip, color, colorize, loadColors
local theme = {}
local useColors = false
local stdout, stdin, stderr, width
local quote, quote2, obracket, cbracket, obrace, cbrace, comma, equals, controls
local themes = {
[16] = require('./theme-16.lua'),
[256] = require('./theme-256.lua'),
}
local special = {
[7] = 'a',
[8] = 'b',
[9] = 't',
[10] = 'n',
[11] = 'v',
[12] = 'f',
[13] = 'r'
}
function loadColors(index)
-- Remove the old theme
for key in pairs(theme) do
theme[key] = nil
end
if index then
local new = themes[index]
if not new then error("Invalid theme index: " .. tostring(index)) end
-- Add the new theme
for key in pairs(new) do
theme[key] = new[key]
end
useColors = true
else
useColors = false
end
quote = colorize('quotes', "'", 'string')
quote2 = colorize('quotes', "'")
obrace = colorize('braces', '{ ')
cbrace = colorize('braces', '}')
obracket = colorize('property', '[')
cbracket = colorize('property', ']')
comma = colorize('sep', ', ')
equals = colorize('sep', ' = ')
controls = {}
for i = 0, 31 do
local c = special[i]
if not c then
if i < 10 then
c = "00" .. tostring(i)
else
c = "0" .. tostring(i)
end
end
controls[i] = colorize('escape', '\\' .. c, 'string')
end
end
function color(colorName)
return '\27[' .. (theme[colorName] or '0') .. 'm'
end
function colorize(colorName, string, resetName)
return useColors and
(color(colorName) .. tostring(string) .. color(resetName)) or
tostring(string)
end
local function stringEscape(c)
return controls[string.byte(c, 1)]
end
function dump(value)
local seen = {}
local output = {}
local offset = 0
local stack = {}
local function recalcOffset(index)
for i = index + 1, #output do
local m = string.match(output[i], "\n([^\n]*)$")
if m then
offset = #(strip(m))
else
offset = offset + #(strip(output[i]))
end
end
end
local function write(text, length)
if not length then length = #(strip(text)) end
-- Create room for data by opening parent blocks
-- Start at the root and go down.
local i = 1
while offset + length > width and stack[i] do
local entry = stack[i]
if not entry.opened then
entry.opened = true
table.insert(output, entry.index + 1, "\n" .. string.rep(" ", i))
-- Recalculate the offset
recalcOffset(entry.index)
-- Bump the index of all deeper entries
for j = i + 1, #stack do
stack[j].index = stack[j].index + 1
end
end
i = i + 1
end
output[#output + 1] = text
offset = offset + length
if offset > width then
dump(stack)
end
end
local function indent()
stack[#stack + 1] = {
index = #output,
opened = false,
}
end
local function unindent()
stack[#stack] = nil
end
local function process(value)
local typ = type(value)
if typ == 'string' then
write(quote .. string.gsub(value, '%c', stringEscape) .. quote2)
elseif typ == 'table' and not seen[value] then
seen[value] = true
write(obrace)
local i = 1
-- Count the number of keys so we know when to stop adding commas
local total = 0
for _ in pairs(value) do total = total + 1 end
for k, v in pairs(value) do
indent()
if k == i then
-- if the key matches the index, don't show it.
-- This is how lists print without keys
process(v)
else
if type(k) == "string" and string.find(k,"^[%a_][%a%d_]*$") then
write(colorize("property", k) .. equals)
else
write(obracket)
process(k)
write(cbracket .. equals)
end
if type(v) == "table" then
process(v)
else
indent()
process(v)
unindent()
end
end
if i < total then
write(comma)
else
write(" ")
end
i = i + 1
unindent()
end
write(cbrace)
else
write(colorize(typ, tostring(value)))
end
end
process(value)
return table.concat(output, "")
end
-- Print replacement that goes through libuv. This is useful on windows
-- to use libuv's code to translate ansi escape codes to windows API calls.
function print(...)
uv.write(stdout, table.concat({...}, "\t") .. "\n")
end
function prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = dump(arguments[i])
end
print(table.concat(arguments, "\t"))
end
function strip(str)
return string.gsub(str, '\027%[[^m]*m', '')
end
if uv.guess_handle(0) == 'TTY' then
stdin = assert(uv.new_tty(0, true))
else
stdin = uv.new_pipe(false)
uv.pipe_open(stdin, 0)
end
if uv.guess_handle(1) == 'TTY' then
stdout = assert(uv.new_tty(1, false))
width = uv.tty_get_winsize(stdout)
-- TODO: auto-detect when 16 color mode should be used
loadColors(256)
else
stdout = uv.new_pipe(false)
uv.pipe_open(stdout, 1)
width = 80
end
if uv.guess_handle(2) == 'TTY' then
stderr = assert(uv.new_tty(2, false))
else
stderr = uv.new_pipe(false)
uv.pipe_open(stderr, 2)
end
return {
loadColors = loadColors,
theme = theme,
print = print,
prettyPrint = prettyPrint,
dump = dump,
color = color,
colorize = colorize,
stdin = stdin,
stdout = stdout,
stderr = stderr,
}
|
local uv = require('uv')
local prettyPrint, dump, strip, color, colorize, loadColors
local theme = {}
local useColors = false
local stdout, stdin, stderr, width
local quote, quote2, dquote, dquote2, obracket, cbracket, obrace, cbrace, comma, equals, controls
local themes = {
[16] = require('./theme-16.lua'),
[256] = require('./theme-256.lua'),
}
local special = {
[7] = 'a',
[8] = 'b',
[9] = 't',
[10] = 'n',
[11] = 'v',
[12] = 'f',
[13] = 'r'
}
function loadColors(index)
-- Remove the old theme
for key in pairs(theme) do
theme[key] = nil
end
if index then
local new = themes[index]
if not new then error("Invalid theme index: " .. tostring(index)) end
-- Add the new theme
for key in pairs(new) do
theme[key] = new[key]
end
useColors = true
else
useColors = false
end
quote = colorize('quotes', "'", 'string')
quote2 = colorize('quotes', "'")
dquote = colorize('quotes', '"', 'string')
dquote2 = colorize('quotes', '"')
obrace = colorize('braces', '{ ')
cbrace = colorize('braces', '}')
obracket = colorize('property', '[')
cbracket = colorize('property', ']')
comma = colorize('sep', ', ')
equals = colorize('sep', ' = ')
controls = {}
for i = 0, 31 do
local c = special[i]
if not c then
if i < 10 then
c = "00" .. tostring(i)
else
c = "0" .. tostring(i)
end
end
controls[i] = colorize('escape', '\\' .. c, 'string')
end
controls[92] = colorize('escape', '\\\\', 'string')
controls[34] = colorize('escape', '\\"', 'string')
controls[39] = colorize('escape', "\\'", 'string')
end
function color(colorName)
return '\27[' .. (theme[colorName] or '0') .. 'm'
end
function colorize(colorName, string, resetName)
return useColors and
(color(colorName) .. tostring(string) .. color(resetName)) or
tostring(string)
end
local function stringEscape(c)
return controls[string.byte(c, 1)]
end
function dump(value)
local seen = {}
local output = {}
local offset = 0
local stack = {}
local function recalcOffset(index)
for i = index + 1, #output do
local m = string.match(output[i], "\n([^\n]*)$")
if m then
offset = #(strip(m))
else
offset = offset + #(strip(output[i]))
end
end
end
local function write(text, length)
if not length then length = #(strip(text)) end
-- Create room for data by opening parent blocks
-- Start at the root and go down.
local i = 1
while offset + length > width and stack[i] do
local entry = stack[i]
if not entry.opened then
entry.opened = true
table.insert(output, entry.index + 1, "\n" .. string.rep(" ", i))
-- Recalculate the offset
recalcOffset(entry.index)
-- Bump the index of all deeper entries
for j = i + 1, #stack do
stack[j].index = stack[j].index + 1
end
end
i = i + 1
end
output[#output + 1] = text
offset = offset + length
if offset > width then
dump(stack)
end
end
local function indent()
stack[#stack + 1] = {
index = #output,
opened = false,
}
end
local function unindent()
stack[#stack] = nil
end
local function process(value)
local typ = type(value)
if typ == 'string' then
if string.match(value, "'") and not string.match(value, '"') then
write(dquote .. string.gsub(value, '[%c\\]', stringEscape) .. dquote2)
else
write(quote .. string.gsub(value, "[%c\\']", stringEscape) .. quote2)
end
elseif typ == 'table' and not seen[value] then
seen[value] = true
write(obrace)
local i = 1
-- Count the number of keys so we know when to stop adding commas
local total = 0
for _ in pairs(value) do total = total + 1 end
for k, v in pairs(value) do
indent()
if k == i then
-- if the key matches the index, don't show it.
-- This is how lists print without keys
process(v)
else
if type(k) == "string" and string.find(k,"^[%a_][%a%d_]*$") then
write(colorize("property", k) .. equals)
else
write(obracket)
process(k)
write(cbracket .. equals)
end
if type(v) == "table" then
process(v)
else
indent()
process(v)
unindent()
end
end
if i < total then
write(comma)
else
write(" ")
end
i = i + 1
unindent()
end
write(cbrace)
else
write(colorize(typ, tostring(value)))
end
end
process(value)
return table.concat(output, "")
end
-- Print replacement that goes through libuv. This is useful on windows
-- to use libuv's code to translate ansi escape codes to windows API calls.
function print(...)
uv.write(stdout, table.concat({...}, "\t") .. "\n")
end
function prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = dump(arguments[i])
end
print(table.concat(arguments, "\t"))
end
function strip(str)
return string.gsub(str, '\027%[[^m]*m', '')
end
if uv.guess_handle(0) == 'TTY' then
stdin = assert(uv.new_tty(0, true))
else
stdin = uv.new_pipe(false)
uv.pipe_open(stdin, 0)
end
if uv.guess_handle(1) == 'TTY' then
stdout = assert(uv.new_tty(1, false))
width = uv.tty_get_winsize(stdout)
-- TODO: auto-detect when 16 color mode should be used
loadColors(256)
else
stdout = uv.new_pipe(false)
uv.pipe_open(stdout, 1)
width = 80
end
if uv.guess_handle(2) == 'TTY' then
stderr = assert(uv.new_tty(2, false))
else
stderr = uv.new_pipe(false)
uv.pipe_open(stderr, 2)
end
return {
loadColors = loadColors,
theme = theme,
print = print,
prettyPrint = prettyPrint,
dump = dump,
color = color,
colorize = colorize,
stdin = stdin,
stdout = stdout,
stderr = stderr,
}
|
Fix string escaping to print valid code
|
Fix string escaping to print valid code
|
Lua
|
apache-2.0
|
rjeli/luvit,rjeli/luvit,luvit/luvit,rjeli/luvit,bsn069/luvit,bsn069/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,DBarney/luvit,kaustavha/luvit,bsn069/luvit,luvit/luvit,rjeli/luvit
|
c56efeb1654aa3360e76094064f7d5862094bac3
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, no_gw, no_dns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
no_gw = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
no_gw.default = no_gw.enabled
function no_gw.cfgvalue(...)
return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1"
end
function no_gw.write(self, section, value)
if value == "1" then
m:set(section, "gateway", nil)
else
m:set(section, "gateway", "0.0.0.0")
end
end
no_dns = section:taboption("advanced", Flag, "_no_dns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
no_dns.default = no_dns.enabled
function no_dns.cfgvalue(self, section)
local addr
for addr in luci.util.imatch(m:get(section, "dns")) do
return self.disabled
end
return self.enabled
end
function no_dns.remove(self, section)
return m:del(section, "dns")
end
function no_dns.write() end
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("_no_dns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
no_gw = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
no_gw.default = no_gw.enabled
function no_gw.cfgvalue(...)
return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1"
end
function no_gw.write(self, section, value)
if value == "1" then
m:set(section, "gateway", nil)
else
m:set(section, "gateway", "0.0.0.0")
end
end
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
protocols/core: fix peerdns option for dhcp proto
|
protocols/core: fix peerdns option for dhcp proto
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8695 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
freifunk-gluon/luci,stephank/luci,stephank/luci,yeewang/openwrt-luci,ch3n2k/luci,stephank/luci,yeewang/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,8devices/carambola2-luci,vhpham80/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,ch3n2k/luci,vhpham80/luci,gwlim/luci,ch3n2k/luci,zwhfly/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ThingMesh/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,gwlim/luci,8devices/carambola2-luci,yeewang/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,freifunk-gluon/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,Canaan-Creative/luci,phi-psi/luci,stephank/luci,gwlim/luci,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,gwlim/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,gwlim/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,saraedum/luci-packages-old,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,8devices/carambola2-luci,saraedum/luci-packages-old,phi-psi/luci,zwhfly/openwrt-luci,ch3n2k/luci,stephank/luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,ch3n2k/luci
|
148664269b9964f0124c27e667ffcdefa0f13a9f
|
libremap-agent/luasrc/libremap/plugins/system.lua
|
libremap-agent/luasrc/libremap/plugins/system.lua
|
--[[
Copyright 2013 Patrick Grimm <patrick@lunatiki.de>
Copyright 2013 André Gaul <gaul@web-yard.de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
sys = require 'luci.sys'
return {
insert = function(doc, options)
local name, model, memtotal = sys.sysinfo()
local system = {
name = name:match('[^\n]+'),
model = model:match('[^\n]+'),
memtotal = memtotal
}
doc.attributes = doc.attributes or {}
doc.attributes.system = system
end
}
|
--[[
Copyright 2013 Patrick Grimm <patrick@lunatiki.de>
Copyright 2013 André Gaul <gaul@web-yard.de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
sys = require 'luci.sys'
util = require 'luci.util'
return {
insert = function(doc, options)
local sysinfo = util.ubus("system", "info") or { }
local sysboard = util.ubus("system", "board") or { }
local system = { }
system["name"] = sysinfo["hostname"]
system["model"] = sysboard["system"]
system["memtotal"] = sysinfo["memory"]["total"]
doc.attributes = doc.attributes or {}
doc.attributes.system = system
end
}
|
Fix issue #23: drop deprecated sysyinfo call
|
Fix issue #23: drop deprecated sysyinfo call
|
Lua
|
apache-2.0
|
rogerpueyo/libremap-agent-openwrt,libremap/libremap-agent-openwrt,libre-mesh/libremap-agent
|
d42c7eccbfe688ff8a34472cef042e21537da071
|
plugins/lua/sand_modules/cookie.lua
|
plugins/lua/sand_modules/cookie.lua
|
local serialize = require "serialize.serialize"
local deserialize = require "serialize.deserialize"
local types = require "serialize.types"
local cookies = {}
--
-- Ensure our file exists
--
io.open( "cookies.dat", "a" ):close()
local function Load()
local fs = io.open( "cookies.dat", "rb" )
local success, data = pcall( deserialize, fs:read( "a" ) )
if success then
cookies = data
else
cookies = {}
end
fs:close()
end
local function Save()
os.remove( "cookies.dat" )
local fs = io.open( "cookies.dat", "wb" )
fs:write( serialize( cookies ) )
fs:close()
end
local function Size()
local fs = io.open( "cookies.dat", "rb" )
local size = fs:seek( "end" )
fs:close()
return size
end
Load()
local meta = {}
meta.__metatable = false
meta.__len = Size
function meta:__index( k )
if k == "Save" then
return Save
end
return rawget( cookies, k )
end
function meta:__newindex( k, v )
if k == self or v == self then
error( "attempt to store cookie table within itself", 2 )
end
if k == "Save" then
error( "attempt to modify protected member 'Save'", 2 )
end
if not types[ type( k ) ] and type( k ) ~= "table" then
error( "attempt to create cookie with invalid key type (" .. type( k ) .. ")", 2 )
end
if not types[ type( v ) ] and type( v ) ~= "table" and v ~= nil then
error( "attempt to create cookie with invalid value type (" .. type( v ) .. ")", 2 )
end
if type( k ) == "function" and not pcall( string.dump, k ) then
error( "attempt to store invalid function as key", 2 )
end
if type( v ) == "function" and not pcall( string.dump, v ) then
error( "attempt to store invalid function as value", 2 )
end
cookies[ k ] = v
end
function meta:__pairs()
local t = {}
for k, v in pairs( cookies ) do
t[ k ] = v
end
return pairs( t )
end
return setmetatable( {}, meta )
|
local serialize = require "serialize.serialize"
local deserialize = require "serialize.deserialize"
local types = require "serialize.types"
local cookies = {}
--
-- Ensure our file exists
--
io.open( "cookies.dat", "a" ):close()
local function Load()
local fs = io.open( "cookies.dat", "rb" )
local success, data = pcall( deserialize, fs:read( "a" ) )
if success then
cookies = data
else
cookies = {}
end
fs:close()
end
local function Save()
local data = serialize( cookies )
os.remove( "cookies.dat" )
local fs = io.open( "cookies.dat", "wb" )
fs:write( data )
fs:close()
end
local function Size()
local fs = io.open( "cookies.dat", "rb" )
local size = fs:seek( "end" )
fs:close()
return size
end
Load()
local meta = {}
meta.__metatable = false
meta.__len = Size
function meta:__index( k )
if k == "Save" then
return Save
end
return rawget( cookies, k )
end
function meta:__newindex( k, v )
if k == self or v == self then
error( "attempt to store cookie table within itself", 2 )
end
if k == "Save" then
error( "attempt to modify protected member 'Save'", 2 )
end
if not types[ type( k ) ] and type( k ) ~= "table" then
error( "attempt to create cookie with invalid key type (" .. type( k ) .. ")", 2 )
end
if not types[ type( v ) ] and type( v ) ~= "table" and v ~= nil then
error( "attempt to create cookie with invalid value type (" .. type( v ) .. ")", 2 )
end
if type( k ) == "function" and not pcall( string.dump, k ) then
error( "attempt to store invalid function as key", 2 )
end
if type( v ) == "function" and not pcall( string.dump, v ) then
error( "attempt to store invalid function as value", 2 )
end
cookies[ k ] = v
end
function meta:__pairs()
local t = {}
for k, v in pairs( cookies ) do
t[ k ] = v
end
return pairs( t )
end
return setmetatable( {}, meta )
|
hacky fix
|
hacky fix
|
Lua
|
cc0-1.0
|
ModMountain/hash.js,meepdarknessmeep/hash.js,SwadicalRag/hash.js,mcd1992/hash.js
|
972331827b2358421db99b74af1d124bbd0dfcb1
|
src/store/redis/scripts/publish.lua
|
src/store/redis/scripts/publish.lua
|
--input: keys: [], values: [channel_id, time, message, content_type, eventsource_event, msg_ttl, max_msg_buf_size]
--output: message_tag, channel_hash {ttl, time_last_seen, subscribers, messages}
local id=ARGV[1]
local time=tonumber(ARGV[2])
local msg={
id=nil,
data= ARGV[3],
content_type=ARGV[4],
eventsource_event=ARGV[5],
ttl= tonumber(ARGV[6]),
time= time,
tag= 0
}
if msg.ttl == 0 then
msg.ttl = 126144000 --4 years
end
local store_at_most_n_messages = ARGV[7]
if store_at_most_n_messages == nil or store_at_most_n_messages == "" then
return {err="Argument 7, max_msg_buf_size, can't be empty"}
end
local enable_debug=true
local dbg = (function(on)
if on then return function(...)
local arg, cur = {...}, nil
for i = 1, #arg do
arg[i]=tostring(arg[i])
end
redis.call('echo', table.concat(arg))
end; else
return function(...) return; end
end
end)(enable_debug)
if type(msg.content_type)=='string' and msg.content_type:find(':') then
return {err='Message content-type cannot contain ":" character.'}
end
dbg(' ####### PUBLISH ######## ')
-- sets all fields for a hash from a dictionary
local hmset = function (key, dict)
if next(dict) == nil then return nil end
local bulk = {}
for k, v in pairs(dict) do
table.insert(bulk, k)
table.insert(bulk, v)
end
return redis.call('HMSET', key, unpack(bulk))
end
local tohash=function(arr)
if type(arr)~="table" then
return nil
end
local h = {}
local k=nil
for i, v in ipairs(arr) do
if k == nil then
k=v
else
h[k]=v; k=nil
end
end
return h
end
local key={
time_offset= 'nchan:message_time_offset',
last_message= nil,
message= 'channel:msg:%s:'..id, --not finished yet
channel= 'channel:'..id,
messages= 'channel:messages:'..id,
subscribers= 'channel:subscribers:'..id,
subscriber_id='channel:next_subscriber_id:'..id, --integer
}
local channel_pubsub = 'channel:pubsub:'..id
local new_channel
local channel
if redis.call('EXISTS', key.channel) ~= 0 then
channel=tohash(redis.call('HGETALL', key.channel))
end
if channel~=nil then
dbg("channel present")
if channel.current_message ~= nil then
dbg("channel current_message present")
key.last_message=('channel:msg:%s:%s'):format(channel.current_message, id)
else
dbg("channel current_message absent")
key.last_message=nil
end
new_channel=false
else
dbg("channel missing")
channel={}
new_channel=true
key.last_message=nil
end
--set new message id
if key.last_message then
local lastmsg = redis.call('HMGET', key.last_message, 'time', 'tag')
local lasttime, lasttag = tonumber(lastmsg[1]), tonumber(lastmsg[2])
dbg("New message id: last_time ", lasttime, " last_tag ", lasttag, " msg_time ", msg.time)
if lasttime==msg.time then
msg.tag=lasttag+1
end
msg.prev_time = lasttime
msg.prev_tag = lasttag
else
msg.prev_time = 0
msg.prev_tag = 0
end
msg.id=('%i:%i'):format(msg.time, msg.tag)
key.message=key.message:format(msg.id)
if redis.call('EXISTS', key.message) ~= 0 then
return {err=("Message for channel %s id %s already exists"):format(id, msg.id)}
end
msg.prev=channel.current_message
if key.last_message then
redis.call('HSET', key.last_message, 'next', msg.id)
end
--update channel
redis.call('HSET', key.channel, 'current_message', msg.id)
if msg.prev then
redis.call('HSET', key.channel, 'prev_message', msg.prev)
end
if msg.time then
redis.call('HSET', key.channel, 'time', msg.time)
end
if not channel.ttl then
channel.ttl=msg.ttl
redis.call('HSET', key.channel, 'ttl', channel.ttl)
end
if not channel.max_stored_messages then
channel.max_stored_messages = store_at_most_n_messages
redis.call('HSET', key.channel, 'max_stored_messages', store_at_most_n_messages)
dbg("channel.max_stored_messages was not set, but is now ", store_at_most_n_messages)
else
channel.max_stored_messages =tonumber(channel.max_stored_messages)
dbg("channel.mas_stored_messages == " , channel.max_stored_messages)
end
--write message
hmset(key.message, msg)
--check old entries
local oldestmsg=function(list_key, old_fmt)
local old, oldkey
local n, del=0,0
while true do
n=n+1
old=redis.call('lindex', list_key, -1)
if old then
oldkey=old_fmt:format(old)
local ex=redis.call('exists', oldkey)
if ex==1 then
return oldkey
else
redis.call('rpop', list_key)
del=del+1
end
else
break
end
end
end
local max_stored_msgs = tonumber(redis.call('HGET', key.channel, 'max_stored_messages')) or -1
if max_stored_msgs < 0 then --no limit
oldestmsg(key.messages, 'channel:msg:%s:'..id)
redis.call('LPUSH', key.messages, msg.id)
elseif max_stored_msgs > 0 then
local stored_messages = tonumber(redis.call('LLEN', key.messages))
redis.call('LPUSH', key.messages, msg.id)
if stored_messages > max_stored_msgs then
local oldmsgid = redis.call('RPOP', key.messages)
redis.call('DEL', 'channel:msg:'..id..':'..oldmsgid)
end
oldestmsg(key.messages, 'channel:msg:%s:'..id)
end
--set expiration times for all the things
redis.call('EXPIRE', key.message, msg.ttl)
redis.call('EXPIRE', key.time_offset, channel.ttl)
redis.call('EXPIRE', key.channel, channel.ttl)
redis.call('EXPIRE', key.messages, channel.ttl)
redis.call('EXPIRE', key.subscribers, channel.ttl)
redis.call('EXPIRE', key.subscriber_id, channel.ttl)
--publish message
local unpacked
if #msg.data < 5*1024 then
unpacked= {
"msg",
msg.ttl or 0,
msg.time,
tonumber(msg.tag) or 0,
msg.prev_time or 0,
msg.prev_tag or 0,
msg.data or "",
msg.content_type or "",
msg.eventsource_event or ""
}
else
unpacked= {
"msgkey",
msg.time,
tonumber(msg.tag) or 0,
key.message
}
end
local msgpacked
dbg(("Stored message with id %i:%i => %s"):format(msg.time, msg.tag, msg.data))
--now publish to the efficient channel
local numsub = redis.call('PUBSUB','NUMSUB', channel_pubsub)[2]
if tonumber(numsub) > 0 then
msgpacked = cmsgpack.pack(unpacked)
redis.call('PUBLISH', channel_pubsub, msgpacked)
end
local num_messages = redis.call('llen', key.messages)
dbg("channel ", id, " ttl: ",channel.ttl, ", subscribers: ", channel.subscribers, "(fake: ", channel.fake_subscribers or "nil", "), messages: ", num_messages)
return { msg.tag, {tonumber(channel.ttl or msg.ttl), tonumber(channel.time or msg.time), tonumber(channel.fake_subscribers or channel.subscribers or 0), tonumber(num_messages)}, new_channel}
|
--input: keys: [], values: [channel_id, time, message, content_type, eventsource_event, msg_ttl, max_msg_buf_size]
--output: message_tag, channel_hash {ttl, time_last_seen, subscribers, messages}
local id=ARGV[1]
local time=tonumber(ARGV[2])
local msg={
id=nil,
data= ARGV[3],
content_type=ARGV[4],
eventsource_event=ARGV[5],
ttl= tonumber(ARGV[6]),
time= time,
tag= 0
}
if msg.ttl == 0 then
msg.ttl = 126144000 --4 years
end
local store_at_most_n_messages = ARGV[7]
if store_at_most_n_messages == nil or store_at_most_n_messages == "" then
return {err="Argument 7, max_msg_buf_size, can't be empty"}
end
local enable_debug=true
local dbg = (function(on)
if on then return function(...)
local arg, cur = {...}, nil
for i = 1, #arg do
arg[i]=tostring(arg[i])
end
redis.call('echo', table.concat(arg))
end; else
return function(...) return; end
end
end)(enable_debug)
if type(msg.content_type)=='string' and msg.content_type:find(':') then
return {err='Message content-type cannot contain ":" character.'}
end
dbg(' ####### PUBLISH ######## ')
-- sets all fields for a hash from a dictionary
local hmset = function (key, dict)
if next(dict) == nil then return nil end
local bulk = {}
for k, v in pairs(dict) do
table.insert(bulk, k)
table.insert(bulk, v)
end
return redis.call('HMSET', key, unpack(bulk))
end
local tohash=function(arr)
if type(arr)~="table" then
return nil
end
local h = {}
local k=nil
for i, v in ipairs(arr) do
if k == nil then
k=v
else
h[k]=v; k=nil
end
end
return h
end
local key={
time_offset= 'nchan:message_time_offset',
last_message= nil,
message= 'channel:msg:%s:'..id, --not finished yet
channel= 'channel:'..id,
messages= 'channel:messages:'..id,
subscribers= 'channel:subscribers:'..id,
subscriber_id='channel:next_subscriber_id:'..id, --integer
}
local channel_pubsub = 'channel:pubsub:'..id
local new_channel
local channel
if redis.call('EXISTS', key.channel) ~= 0 then
channel=tohash(redis.call('HGETALL', key.channel))
end
if channel~=nil then
dbg("channel present")
if channel.current_message ~= nil then
dbg("channel current_message present")
key.last_message=('channel:msg:%s:%s'):format(channel.current_message, id)
else
dbg("channel current_message absent")
key.last_message=nil
end
new_channel=false
else
dbg("channel missing")
channel={}
new_channel=true
key.last_message=nil
end
--set new message id
if key.last_message then
local lastmsg = redis.call('HMGET', key.last_message, 'time', 'tag')
local lasttime, lasttag = tonumber(lastmsg[1]), tonumber(lastmsg[2])
dbg("New message id: last_time ", lasttime, " last_tag ", lasttag, " msg_time ", msg.time)
if lasttime==msg.time then
msg.tag=lasttag+1
end
msg.prev_time = lasttime
msg.prev_tag = lasttag
else
msg.prev_time = 0
msg.prev_tag = 0
end
msg.id=('%i:%i'):format(msg.time, msg.tag)
key.message=key.message:format(msg.id)
if redis.call('EXISTS', key.message) ~= 0 then
return {err=("Message for channel %s id %s already exists"):format(id, msg.id)}
end
msg.prev=channel.current_message
if key.last_message and redis.call('exists', key.last_message) == 1 then
redis.call('HSET', key.last_message, 'next', msg.id)
end
--update channel
redis.call('HSET', key.channel, 'current_message', msg.id)
if msg.prev then
redis.call('HSET', key.channel, 'prev_message', msg.prev)
end
if msg.time then
redis.call('HSET', key.channel, 'time', msg.time)
end
if not channel.ttl then
channel.ttl=msg.ttl
redis.call('HSET', key.channel, 'ttl', channel.ttl)
end
if not channel.max_stored_messages then
channel.max_stored_messages = store_at_most_n_messages
redis.call('HSET', key.channel, 'max_stored_messages', store_at_most_n_messages)
dbg("channel.max_stored_messages was not set, but is now ", store_at_most_n_messages)
else
channel.max_stored_messages =tonumber(channel.max_stored_messages)
dbg("channel.mas_stored_messages == " , channel.max_stored_messages)
end
--write message
hmset(key.message, msg)
--check old entries
local oldestmsg=function(list_key, old_fmt)
local old, oldkey
local n, del=0,0
while true do
n=n+1
old=redis.call('lindex', list_key, -1)
if old then
oldkey=old_fmt:format(old)
local ex=redis.call('exists', oldkey)
if ex==1 then
return oldkey
else
redis.call('rpop', list_key)
del=del+1
end
else
break
end
end
end
local max_stored_msgs = tonumber(redis.call('HGET', key.channel, 'max_stored_messages')) or -1
if max_stored_msgs < 0 then --no limit
oldestmsg(key.messages, 'channel:msg:%s:'..id)
redis.call('LPUSH', key.messages, msg.id)
elseif max_stored_msgs > 0 then
local stored_messages = tonumber(redis.call('LLEN', key.messages))
redis.call('LPUSH', key.messages, msg.id)
if stored_messages > max_stored_msgs then
local oldmsgid = redis.call('RPOP', key.messages)
redis.call('DEL', 'channel:msg:'..id..':'..oldmsgid)
end
oldestmsg(key.messages, 'channel:msg:%s:'..id)
end
--set expiration times for all the things
redis.call('EXPIRE', key.message, msg.ttl)
redis.call('EXPIRE', key.time_offset, channel.ttl)
redis.call('EXPIRE', key.channel, channel.ttl)
redis.call('EXPIRE', key.messages, channel.ttl)
redis.call('EXPIRE', key.subscribers, channel.ttl)
redis.call('EXPIRE', key.subscriber_id, channel.ttl)
--publish message
local unpacked
if #msg.data < 5*1024 then
unpacked= {
"msg",
msg.ttl or 0,
msg.time,
tonumber(msg.tag) or 0,
msg.prev_time or 0,
msg.prev_tag or 0,
msg.data or "",
msg.content_type or "",
msg.eventsource_event or ""
}
else
unpacked= {
"msgkey",
msg.time,
tonumber(msg.tag) or 0,
key.message
}
end
local msgpacked
dbg(("Stored message with id %i:%i => %s"):format(msg.time, msg.tag, msg.data))
--now publish to the efficient channel
local numsub = redis.call('PUBSUB','NUMSUB', channel_pubsub)[2]
if tonumber(numsub) > 0 then
msgpacked = cmsgpack.pack(unpacked)
redis.call('PUBLISH', channel_pubsub, msgpacked)
end
local num_messages = redis.call('llen', key.messages)
dbg("channel ", id, " ttl: ",channel.ttl, ", subscribers: ", channel.subscribers, "(fake: ", channel.fake_subscribers or "nil", "), messages: ", num_messages)
return { msg.tag, {tonumber(channel.ttl or msg.ttl), tonumber(channel.time or msg.time), tonumber(channel.fake_subscribers or channel.subscribers or 0), tonumber(num_messages)}, new_channel}
|
fix: redis-store: create invalid prev_msg when publishing after prev_message disappers
|
fix: redis-store: create invalid prev_msg when publishing after prev_message disappers
|
Lua
|
mit
|
slact/nginx_http_push_module,slact/nginx_http_push_module,slact/nginx_http_push_module,slact/nginx_http_push_module
|
e106e36d4de71f68dd1df1370e461a3ab8b2f40f
|
MMOCoreORB/bin/scripts/object/tangible/base/tangible_base.lua
|
MMOCoreORB/bin/scripts/object/tangible/base/tangible_base.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_base_tangible_base = object_tangible_base_shared_tangible_base:new {
playerUseMask = ALL,
level = 10,
maxCondition = 1000,
useCount = 1,
optionsBitmask = 256, --Default all objects to not display ham bars.
pvpStatusBitmask = 0,
objectMenuComponent = "TangibleObjectMenuComponent",
sliceable = 0
}
ObjectTemplates:addTemplate(object_tangible_base_tangible_base, "object/tangible/base/tangible_base.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_base_tangible_base = object_tangible_base_shared_tangible_base:new {
playerUseMask = ALL,
level = 10,
maxCondition = 1000,
useCount = 1,
optionsBitmask = 256, --Default all objects to not display ham bars.
pvpStatusBitmask = 0,
objectMenuComponent = "TangibleObjectMenuComponent",
attributeListComponent = "AttributeListComponent",
sliceable = 0
}
ObjectTemplates:addTemplate(object_tangible_base_tangible_base, "object/tangible/base/tangible_base.iff")
|
[fixed] stability fixes
|
[fixed] stability fixes
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3870 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
849c7c45e7074996ee7b7edd8846b627947d3af3
|
src/cosy/configuration/init.lua
|
src/cosy/configuration/init.lua
|
local Loader = require "cosy.loader"
local I18n = require "cosy.i18n"
local Logger = require "cosy.logger"
local Layer = require "layeredata"
local layers = require "cosy.configuration.layers"
local Lfs = require "lfs"
local i18n = I18n.load "cosy.configuration"
layers.default.locale = "en"
layers.default.__label__ = "configuration"
local Configuration = {}
function Configuration.load (t)
if type (t) ~= "table" then
t = { t }
end
for _, name in ipairs (t) do
require (name .. ".conf")
end
end
local Metatable = {}
function Metatable.__index (_, key)
return layers.whole [key]
end
function Metatable.__newindex (_, key, value)
layers.whole [key] = value
end
setmetatable (Configuration, Metatable)
-- Compute prefix:
local main = package.searchpath ("cosy.configuration", package.path)
if main:sub (1, 1) == "." then
main = Lfs.currentdir () .. "/" .. main
end
local prefix = main:gsub ("/share/lua/5.1/cosy/configuration/.*", "/etc")
local files = {
etc = prefix .. "/cosy.conf",
home = os.getenv "HOME" .. "/.cosy/cosy.conf",
pwd = os.getenv "PWD" .. "/cosy.conf",
}
if not _G.js then
package.searchers [#package.searchers+1] = function (name)
local result, err = io.open (name, "r")
if not result then
return nil, err
end
result, err = loadfile (name)
if not result then
return nil, err
end
return result, name
end
for key, name in pairs (files) do
local result = Loader.hotswap.try_require (name)
if result then
Logger.debug {
_ = i18n ["use"],
path = name,
locale = Configuration.locale or "en",
}
Layer.replacewith (layers [key], result)
else
Logger.warning {
_ = i18n ["skip"],
path = name,
locale = Configuration.locale or "en",
}
end
end
end
return Configuration
|
local Loader = require "cosy.loader"
local I18n = require "cosy.i18n"
local Logger = require "cosy.logger"
local Layer = require "layeredata"
local layers = require "cosy.configuration.layers"
local Lfs = require "lfs"
local i18n = I18n.load "cosy.configuration"
layers.default.locale = "en"
layers.default.__label__ = "configuration"
local Configuration = {}
function Configuration.load (t)
if type (t) ~= "table" then
t = { t }
end
for _, name in ipairs (t) do
require (name .. ".conf")
end
end
local Metatable = {}
function Metatable.__index (_, key)
return layers.whole [key]
end
function Metatable.__newindex (_, key, value)
layers.whole [key] = value
end
setmetatable (Configuration, Metatable)
local files = {
etc = os.getenv "COSY_PREFIX" .. "/etc/cosy.conf",
home = os.getenv "HOME" .. "/.cosy/cosy.conf",
pwd = os.getenv "PWD" .. "/cosy.conf",
}
if not _G.js then
package.searchers [#package.searchers+1] = function (name)
local result, err = io.open (name, "r")
if not result then
return nil, err
end
result, err = loadfile (name)
if not result then
return nil, err
end
return result, name
end
for key, name in pairs (files) do
local result = Loader.hotswap.try_require (name)
if result then
Logger.debug {
_ = i18n ["use"],
path = name,
locale = Configuration.locale or "en",
}
Layer.replacewith (layers [key], result)
else
Logger.warning {
_ = i18n ["skip"],
path = name,
locale = Configuration.locale or "en",
}
end
end
end
return Configuration
|
Configuration uses COSY_PREFIX to load /etc/cosy.conf.
|
Configuration uses COSY_PREFIX to load /etc/cosy.conf.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
cc1b29be06b015e83206eb9dcd11801f8a00b128
|
config/nvim/lua/gb/lsp.lua
|
config/nvim/lua/gb/lsp.lua
|
local utils = require("gb.utils")
local nvim_lsp = require("lspconfig")
keymap = utils.map
opt = utils.opt
local function custom_on_init()
print("Language Server Protocol started!")
end
local function custom_root_dir()
if (string.find(vim.fn.expand("%f"), "node_modules/") == nil) then
return nvim_lsp.util.root_pattern(".git")
end
return nil
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
nvim_lsp.vimls.setup {}
--must have run: npm install -g typescript
nvim_lsp.tsserver.setup {
-- This makes sure tsserver is not used for formatting
-- on_attach = nvim_lsp.tsserver_on_attach,
on_attach = function(client)
if client.config.flags then
client.config.flags.allow_incremental_sync = true
end
client.resolved_capabilities.document_formatting = false
require "lsp_signature".on_attach()
end,
root_dir = nvim_lsp.util.root_pattern("tsconfig.json", ".git"),
cmd = {
"typescript-language-server",
"--tsserver-log-file",
vim.env.HOME .. "/src/tsserver.log",
"--tsserver-log-verbosity",
"verbose",
"--stdio"
},
settings = {documentFormatting = false},
on_init = custom_on_init
}
nvim_lsp.rust_analyzer.setup {}
--must run: npm install -g pyright
nvim_lsp.pyright.setup {
on_init = custom_on_init,
on_attach = function(client)
require "lsp_signature".on_attach()
end
}
vim.lsp.handlers["textDocument/publishDiagnostics"] =
vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics,
{
virtual_text = true,
signs = true,
update_in_insert = true
}
)
-- npm i -g vscode-css-languageserver-bin
nvim_lsp.cssls.setup {
on_init = custom_on_init
}
-- npm i -g vscode-html-languageserver-bin
nvim_lsp.html.setup {
on_init = custom_on_init,
capabilities = capabilities
}
local eslint_d = {
lintCommand = "eslint_d --stdin --fix-to-stdout --stdin-filename ${INPUT}",
lintIgnoreExitCode = true,
lintStdin = true,
lintFormats = {"%f:%l:%c: %m"},
formatCommand = "eslint_d --fix-to-stdout --stdin --stdin-filename ${INPUT}",
formatStdin = true
}
local rustExe = "rustfmt"
local rustArgs = "--emit=stdout"
local rustStdin = true
local rustfmt = {
formatCommand = rustExe .. rustArgs .. "${INPUT}",
formatStdin = rustStdin
}
local prettierArgs = {"--stdin", "--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}
local prettier = {
formatCommand = "./node_modules/.bin/prettier" .. table.concat(prettierArgs, " "),
formatStdin = true
}
local languages = {
typescript = {prettier, eslint_d},
javascript = {prettier, eslint_d},
typescriptreact = {prettier, eslint_d},
["typescript.tsx"] = {prettier, eslint_d},
javascriptreact = {prettier, eslint_d},
["javascript.jsx"] = {prettier, eslint_d},
yaml = {prettier},
json = {prettier},
html = {prettier},
scss = {prettier},
css = {prettier},
markdown = {prettier},
rust = {rustfmt},
python = {
{
formatCommand = "black",
formatStdin = true
},
{
formatCommand = "isort",
formatStdin = true
}
}
}
nvim_lsp.efm.setup {
init_options = {documentFormatting = true},
filetypes = vim.tbl_keys(languages),
root_dir = custom_root_dir(),
settings = {
languages = languages
}
}
require "compe".setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = "enable",
throttle_time = 80,
source_timeout = 200,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = true,
source = {
path = true,
buffer = true,
nvim_lsp = true,
nvim_lua = true,
spell = true
}
}
require("lspsaga").init_lsp_saga(
{
error_sign = "▊",
warn_sign = "▊",
hint_sign = "▊",
infor_sign = "▊",
dianostic_header_icon = " ",
code_action_icon = "",
finder_definition_icon = " ",
finder_reference_icon = " ",
definition_preview_icon = " ",
rename_prompt_prefix = "❱❱",
rename_action_keys = {
quit = {"<C-c>", "<esc>"},
exec = "<CR>" -- quit can be a table
}
}
)
require("lspkind").init(
{
with_text = true,
symbol_map = {
Text = " ",
Method = " ",
Function = " ",
Constructor = " ",
Variable = "[]",
Class = " ",
Interface = " 蘒",
Module = " ",
Property = " ",
Unit = " 塞 ",
Value = " ",
Enum = " 練",
Keyword = " ",
Snippet = " ",
Color = "",
File = "",
Folder = " ﱮ ",
EnumMember = " ",
Constant = " ",
Struct = " "
}
}
)
vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"}
opt("o", "completeopt", "menu,menuone,noselect")
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col(".") - 1
if col == 0 or vim.fn.getline("."):sub(col, col):match("%s") then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-n>"
elseif check_back_space() then
return t "<Tab>"
else
return vim.fn["compe#complete"]()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-p>"
else
return t "<S-Tab>"
end
end
keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true})
keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true})
keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
keymap("n", "gd", ":lua vim.lsp.buf.definition()<CR>", {silent = true})
keymap("n", "gR", ":Lspsaga rename<CR>")
keymap("n", "gr", "LspTrouble lsp_references", {cmd_cr = true})
keymap("n", "gs", ":Lspsaga signature_help<CR>")
keymap("n", "<leader>e", ":Lspsaga diagnostic_jump_next<CR>", {silent = true})
keymap("n", "<leader>cd", ":Lspsaga show_line_diagnostics<CR>", {silent = true})
keymap("n", "K", ":Lspsaga hover_doc<CR>", {silent = true})
keymap("i", "<C-Space>", "compe#complete()", {silent = true, expr = true})
keymap("i", "<CR>", 'compe#confirm("<CR>")', {silent = true, expr = true})
|
local utils = require("gb.utils")
local nvim_lsp = require("lspconfig")
keymap = utils.map
opt = utils.opt
local function custom_on_init()
print("Language Server Protocol started!")
end
local function custom_root_dir()
if (string.find(vim.fn.expand("%f"), "node_modules/") == nil) then
return nvim_lsp.util.root_pattern(".git")
end
return nil
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
nvim_lsp.vimls.setup {}
--must have run: npm install -g typescript
nvim_lsp.tsserver.setup {
-- This makes sure tsserver is not used for formatting
-- on_attach = nvim_lsp.tsserver_on_attach,
on_attach = function(client)
if client.config.flags then
client.config.flags.allow_incremental_sync = true
end
client.resolved_capabilities.document_formatting = false
require "lsp_signature".on_attach()
end,
root_dir = nvim_lsp.util.root_pattern("tsconfig.json", ".git"),
-- cmd = {
-- "typescript-language-server",
-- "--tsserver-log-file",
-- vim.env.HOME .. "/src/tsserver.log",
-- "--tsserver-log-verbosity",
-- "verbose",
-- "--stdio"
-- },
settings = {documentFormatting = false},
on_init = custom_on_init
}
nvim_lsp.rust_analyzer.setup {}
--must run: npm install -g pyright
nvim_lsp.pyright.setup {
on_init = custom_on_init,
on_attach = function(client)
require "lsp_signature".on_attach()
end
}
vim.lsp.handlers["textDocument/publishDiagnostics"] =
vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics,
{
virtual_text = true,
signs = true,
update_in_insert = true
}
)
-- npm i -g vscode-css-languageserver-bin
nvim_lsp.cssls.setup {
on_init = custom_on_init
}
-- npm i -g vscode-html-languageserver-bin
nvim_lsp.html.setup {
on_init = custom_on_init,
capabilities = capabilities
}
local eslint_d = {
lintCommand = "eslint_d --stdin --fix-to-stdout --stdin-filename ${INPUT}",
lintIgnoreExitCode = true,
lintStdin = true,
lintFormats = {"%f:%l:%c: %m"},
formatCommand = "eslint_d --fix-to-stdout --stdin --stdin-filename ${INPUT}",
formatStdin = true
}
local rustExe = "rustfmt"
local rustArgs = "--emit=stdout"
local rustStdin = true
local rustfmt = {
formatCommand = rustExe .. rustArgs .. "${INPUT}",
formatStdin = rustStdin
}
local prettierArgs = {"--stdin", "--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}
local prettier = {
formatCommand = "./node_modules/.bin/prettier" .. table.concat(prettierArgs, " "),
formatStdin = true
}
local languages = {
typescript = {prettier, eslint_d},
javascript = {prettier, eslint_d},
typescriptreact = {prettier, eslint_d},
["typescript.tsx"] = {prettier, eslint_d},
javascriptreact = {prettier, eslint_d},
["javascript.jsx"] = {prettier, eslint_d},
yaml = {prettier},
json = {prettier},
html = {prettier},
scss = {prettier},
css = {prettier},
markdown = {prettier},
rust = {rustfmt},
python = {
{
formatCommand = "black",
formatStdin = true
},
{
formatCommand = "isort",
formatStdin = true
}
}
}
nvim_lsp.efm.setup {
init_options = {documentFormatting = true},
filetypes = vim.tbl_keys(languages),
root_dir = custom_root_dir(),
settings = {
languages = languages
}
}
require "compe".setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = "enable",
throttle_time = 80,
source_timeout = 200,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = true,
source = {
path = true,
buffer = true,
treesitter = true,
nvim_lsp = true,
nvim_lua = true,
spell = true
}
}
require("lspsaga").init_lsp_saga(
{
error_sign = "▊",
warn_sign = "▊",
hint_sign = "▊",
infor_sign = "▊",
dianostic_header_icon = " ",
code_action_icon = "",
finder_definition_icon = " ",
finder_reference_icon = " ",
definition_preview_icon = " ",
rename_prompt_prefix = "❱❱",
rename_action_keys = {
quit = {"<C-c>", "<esc>"},
exec = "<CR>" -- quit can be a table
}
}
)
require("lspkind").init(
{
with_text = true,
symbol_map = {
Text = " ",
Method = " ",
Function = " ",
Constructor = " ",
Variable = "[]",
Class = " ",
Interface = " 蘒",
Module = " ",
Property = " ",
Unit = " 塞 ",
Value = " ",
Enum = " 練",
Keyword = " ",
Snippet = " ",
Color = "",
File = "",
Folder = " ﱮ ",
EnumMember = " ",
Constant = " ",
Struct = " "
}
}
)
vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"}
opt("o", "completeopt", "menu,menuone,noselect")
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col(".") - 1
if col == 0 or vim.fn.getline("."):sub(col, col):match("%s") then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-n>"
elseif check_back_space() then
return t "<Tab>"
else
return vim.fn["compe#complete"]()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-p>"
else
return t "<S-Tab>"
end
end
keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true})
keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true})
keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
keymap("n", "gd", ":lua vim.lsp.buf.definition()<CR>", {silent = true})
keymap("n", "gR", ":Lspsaga rename<CR>")
keymap("n", "gr", "LspTrouble lsp_references", {cmd_cr = true})
keymap("n", "gs", ":Lspsaga signature_help<CR>")
keymap("n", "<leader>e", ":Lspsaga diagnostic_jump_next<CR>", {silent = true})
keymap("n", "<leader>cd", ":Lspsaga show_line_diagnostics<CR>", {silent = true})
keymap("n", "K", ":Lspsaga hover_doc<CR>", {silent = true})
keymap("i", "<C-Space>", "compe#complete()", {silent = true, expr = true})
keymap("i", "<CR>", 'compe#confirm("<CR>")', {silent = true, expr = true})
|
Lsp fixups
|
Lsp fixups
|
Lua
|
mit
|
gblock0/dotfiles
|
08b2bfed5606b1601ee11b35a59904f265baf56f
|
libs/git-fs.lua
|
libs/git-fs.lua
|
exports.name = "creationix/git-fs"
exports.version = "0.1.0"
exports.dependencies = {
"creationix/git@0.1.0",
"creationix/hex-bin@1.0.0",
}
--[[
Git Object Database
===================
Consumes a storage interface and return a git database interface
db.has(hash) -> bool - check if db has an object
db.load(hash) -> raw - load raw data, nil if not found
db.loadAny(hash) -> kind, value - pre-decode data, error if not found
db.loadAs(kind, hash) -> value - pre-decode and check type or error
db.save(raw) -> hash - save pre-encoded and framed data
db.saveAs(kind, value) -> hash - encode, frame and save to objects/$ha/$sh
db.hashes() -> iter - Iterate over all hashes
db.getHead() -> hash - Read the hash via HEAD
db.getRef(ref) -> hash - Read hash of a ref
db.resolve(ref) -> hash - Given a hash, tag, branch, or HEAD, return the hash
]]
local git = require('git')
local miniz = require('miniz')
local openssl = require('openssl')
local hexBin = require('hex-bin')
return function (storage)
local encoders = git.encoders
local decoders = git.decoders
local frame = git.frame
local deframe = git.deframe
local deflate = miniz.deflate
local inflate = miniz.inflate
local digest = openssl.digest.digest
local binToHex = hexBin.binToHex
local db = { storage = storage }
local fs = storage.fs
-- Initialize the git file storage tree if it does't exist yet
if not fs.access("HEAD") then
assert(fs.mkdirp("objects"))
assert(fs.mkdirp("refs/tags"))
assert(fs.writeFile("HEAD", "ref: refs/heads/master\n"))
assert(fs.writeFile("config", [[
[core]
repositoryformatversion = 0
filemode = true
bare = true
[gc]
auto = 0
]]))
end
local function assertHash(hash)
assert(hash and #hash == 40 and hash:match("^%x+$"), "Invalid hash")
end
local function hashPath(hash)
return string.format("objects/%s/%s", hash:sub(1, 2), hash:sub(3))
end
function db.has(hash)
assertHash(hash)
return storage.read(hashPath(hash)) and true or false
end
local function readUint32(buffer, offset)
return bit.bor(
bit.lshift(buffer:byte(offset + 1), 24),
bit.lshift(buffer:byte(offset + 2), 16),
bit.lshift(buffer:byte(offset + 3), 8),
buffer:byte(offset + 4)
)
end
local function readUint64(buffer, offset)
return bit.bor(
bit.lshift(buffer:byte(offset + 1), 56),
bit.lshift(buffer:byte(offset + 2), 48),
bit.lshift(buffer:byte(offset + 3), 40),
bit.lshift(buffer:byte(offset + 4), 32),
bit.lshift(buffer:byte(offset + 5), 24),
bit.lshift(buffer:byte(offset + 6), 16),
bit.lshift(buffer:byte(offset + 7), 8),
buffer:byte(offset + 8)
)
end
local indexes = {}
local function parseIndex(hash)
local parsed = indexes[hash]
if parsed then return parsed end
local data = storage.read("objects/pack/pack-" .. hash .. ".idx")
assert(data:sub(1, 8) == '\255tOc\0\0\0\2', "Only pack index v2 supported")
-- Get the number of hashes in index
-- This is the value of the last fan-out entry
local length = readUint32(data, 8 + 255 * 4)
local items = {}
indexes[hash] = items
local hashOffset = 8 + 255 * 4 + 4
local crcOffset = hashOffset + 20 * length
local lengthOffset = crcOffset + 4 * length
local largeOffset = lengthOffset + 4 * length
local checkOffset = largeOffset
for i = 1, length do
local start = hashOffset + i * 20
local hash = binToHex(data:sub(start + 1, start + 20))
local offset = readUint32(data, lengthOffset + i * 4);
if bit.band(offset, 0x80000000) > 0 then
offset = largeOffset + bit.band(offset, 0x7fffffff) * 8;
checkOffset = (checkOffset > offset + 8) and checkOffset or offset + 8
offset = readUint64(data, offset);
end
items[hash] = offset
end
return items
end
function db.load(hash)
hash = db.resolve(hash)
assertHash(hash)
local compressed, err = storage.read(hashPath(hash))
if not compressed then
for file in storage.leaves("objects/pack") do
local packHash = file:match("^pack%-(%x+)%.idx$")
if packHash then
local index = parseIndex(packHash)
local offset = index[hash]
if not offset then return end
p(hash, offset)
end
end
return nil, err
end
return inflate(compressed, 1)
end
function db.loadAny(hash)
local raw = assert(db.load(hash), "no such hash")
local kind, value = deframe(raw)
return kind, decoders[kind](value)
end
function db.loadAs(kind, hash)
local actualKind, value = db.loadAny(hash)
assert(kind == actualKind, "Kind mismatch")
return value
end
function db.save(raw)
local hash = digest("sha1", raw)
-- 0x1000 = TDEFL_WRITE_ZLIB_HEADER
-- 4095 = Huffman+LZ (slowest/best compression)
storage.put(hashPath(hash), deflate(raw, 0x1000 + 4095))
return hash
end
function db.saveAs(kind, value)
if type(value) ~= "string" then
value = encoders[kind](value)
end
return db.save(frame(kind, value))
end
function db.hashes()
local groups = storage.nodes("objects")
local prefix, iter
return function ()
while true do
if prefix then
local rest = iter()
if rest then return prefix .. rest end
prefix = nil
iter = nil
end
prefix = groups()
if not prefix then return end
iter = storage.leaves("objects/" .. prefix)
end
end
end
function db.getHead()
local head = storage.read("HEAD")
if not head then return end
local ref = head:match("^ref: *([^\n]+)")
if not ref then return end
return db.getRef(ref)
end
function db.getRef(ref)
local hash = storage.read(ref)
if hash then return hash:match("%x+") end
local refs = storage.read("packed-refs")
return refs:match("(%x+) " .. ref)
end
function db.resolve(ref)
if ref == "HEAD" then return db.getHead() end
local hash = ref:match("^%x+$")
if hash and #hash == 40 then return hash end
return db.getRef(ref)
or db.getRef("refs/heads/" .. ref)
or db.getRef("refs/tags/" .. ref)
end
return db
end
|
exports.name = "creationix/git-fs"
exports.version = "0.1.0"
exports.dependencies = {
"creationix/git@0.1.0",
"creationix/hex-bin@1.0.0",
}
--[[
Git Object Database
===================
Consumes a storage interface and return a git database interface
db.has(hash) -> bool - check if db has an object
db.load(hash) -> raw - load raw data, nil if not found
db.loadAny(hash) -> kind, value - pre-decode data, error if not found
db.loadAs(kind, hash) -> value - pre-decode and check type or error
db.save(raw) -> hash - save pre-encoded and framed data
db.saveAs(kind, value) -> hash - encode, frame and save to objects/$ha/$sh
db.hashes() -> iter - Iterate over all hashes
db.getHead() -> hash - Read the hash via HEAD
db.getRef(ref) -> hash - Read hash of a ref
db.resolve(ref) -> hash - Given a hash, tag, branch, or HEAD, return the hash
]]
local git = require('git')
local miniz = require('miniz')
local openssl = require('openssl')
local hexBin = require('hex-bin')
return function (storage)
local encoders = git.encoders
local decoders = git.decoders
local frame = git.frame
local deframe = git.deframe
local deflate = miniz.deflate
local inflate = miniz.inflate
local digest = openssl.digest.digest
local binToHex = hexBin.binToHex
local db = { storage = storage }
local fs = storage.fs
-- Initialize the git file storage tree if it does't exist yet
if not fs.access("HEAD") then
assert(fs.mkdirp("objects"))
assert(fs.mkdirp("refs/tags"))
assert(fs.writeFile("HEAD", "ref: refs/heads/master\n"))
assert(fs.writeFile("config", [[
[core]
repositoryformatversion = 0
filemode = true
bare = true
[gc]
auto = 0
]]))
end
local function assertHash(hash)
assert(hash and #hash == 40 and hash:match("^%x+$"), "Invalid hash")
end
local function hashPath(hash)
return string.format("objects/%s/%s", hash:sub(1, 2), hash:sub(3))
end
function db.has(hash)
assertHash(hash)
return storage.read(hashPath(hash)) and true or false
end
local function readUint32(buffer, offset)
return bit.bor(
bit.lshift(buffer:byte(offset + 1), 24),
bit.lshift(buffer:byte(offset + 2), 16),
bit.lshift(buffer:byte(offset + 3), 8),
buffer:byte(offset + 4)
)
end
local function readUint64(buffer, offset)
local hi, lo =
bit.bor(
bit.lshift(buffer:byte(offset + 1), 24),
bit.lshift(buffer:byte(offset + 2), 16),
bit.lshift(buffer:byte(offset + 3), 8),
buffer:byte(offset + 4)
),
bit.bor(
bit.lshift(buffer:byte(offset + 5), 24),
bit.lshift(buffer:byte(offset + 6), 16),
bit.lshift(buffer:byte(offset + 7), 8),
buffer:byte(offset + 8)
)
return hi * 0x100000000 + lo;
end
local indexes = {}
local function parseIndex(hash)
local parsed = indexes[hash]
if parsed then return parsed end
local data = storage.read("objects/pack/pack-" .. hash .. ".idx")
assert(data:sub(1, 8) == '\255tOc\0\0\0\2', "Only pack index v2 supported")
-- Get the number of hashes in index
-- This is the value of the last fan-out entry
local length = readUint32(data, 8 + 255 * 4)
local items = {}
indexes[hash] = items
local hashOffset = 8 + 255 * 4 + 4
local crcOffset = hashOffset + 20 * length
local lengthOffset = crcOffset + 4 * length
local largeOffset = lengthOffset + 4 * length
local checkOffset = largeOffset
for i = 1, length do
local start = hashOffset + i * 20
local hash = binToHex(data:sub(start + 1, start + 20))
local offset = readUint32(data, lengthOffset + i * 4);
if bit.band(offset, 0x80000000) > 0 then
offset = largeOffset + bit.band(offset, 0x7fffffff) * 8;
checkOffset = (checkOffset > offset + 8) and checkOffset or offset + 8
offset = readUint64(data, offset);
end
items[hash] = offset
end
return items
end
function db.load(hash)
hash = db.resolve(hash)
assertHash(hash)
local compressed, err = storage.read(hashPath(hash))
if not compressed then
for file in storage.leaves("objects/pack") do
local packHash = file:match("^pack%-(%x+)%.idx$")
if packHash then
local index = parseIndex(packHash)
local offset = index[hash]
if not offset then return end
p(hash, offset)
end
end
return nil, err
end
return inflate(compressed, 1)
end
function db.loadAny(hash)
local raw = assert(db.load(hash), "no such hash")
local kind, value = deframe(raw)
return kind, decoders[kind](value)
end
function db.loadAs(kind, hash)
local actualKind, value = db.loadAny(hash)
assert(kind == actualKind, "Kind mismatch")
return value
end
function db.save(raw)
local hash = digest("sha1", raw)
-- 0x1000 = TDEFL_WRITE_ZLIB_HEADER
-- 4095 = Huffman+LZ (slowest/best compression)
storage.put(hashPath(hash), deflate(raw, 0x1000 + 4095))
return hash
end
function db.saveAs(kind, value)
if type(value) ~= "string" then
value = encoders[kind](value)
end
return db.save(frame(kind, value))
end
function db.hashes()
local groups = storage.nodes("objects")
local prefix, iter
return function ()
while true do
if prefix then
local rest = iter()
if rest then return prefix .. rest end
prefix = nil
iter = nil
end
prefix = groups()
if not prefix then return end
iter = storage.leaves("objects/" .. prefix)
end
end
end
function db.getHead()
local head = storage.read("HEAD")
if not head then return end
local ref = head:match("^ref: *([^\n]+)")
if not ref then return end
return db.getRef(ref)
end
function db.getRef(ref)
local hash = storage.read(ref)
if hash then return hash:match("%x+") end
local refs = storage.read("packed-refs")
return refs:match("(%x+) " .. ref)
end
function db.resolve(ref)
if ref == "HEAD" then return db.getHead() end
local hash = ref:match("^%x+$")
if hash and #hash == 40 then return hash end
return db.getRef(ref)
or db.getRef("refs/heads/" .. ref)
or db.getRef("refs/tags/" .. ref)
end
return db
end
|
Fix 64 bit decoder
|
Fix 64 bit decoder
|
Lua
|
isc
|
creationix/rye,creationix/rye
|
f641fa38cab4273fb0c980c89dc7ad2ac7bdc777
|
lua/path/fs.lua
|
lua/path/fs.lua
|
local DIR_SEP = package.config:sub(1,1)
local IS_WINDOWS = DIR_SEP == '\\'
local function prequire(m)
local ok, err = pcall(require, m)
if not ok then return nil, err end
return err
end
local fs
if not fs and IS_WINDOWS then
local fsload = require"path.win32.fs".load
local ok, mod = pcall(fsload, "ffi", "A")
if not ok then ok, mod = pcall(fsload, "alien", "A") end
fs = ok and mod
end
if not fs and not IS_WINDOWS then
local lfs = prequire"syscall.lfs"
if lfs then
pcall(function() fs = require"path.lfs.impl.fs"(lfs) end)
end
end
if not fs then
fs = prequire"path.lfs.fs"
end
assert(fs, "you need installed LuaFileSystem or FFI/Alien (Windows only)")
return fs
|
local DIR_SEP = package.config:sub(1,1)
local IS_WINDOWS = DIR_SEP == '\\'
local function prequire(m)
local ok, err = pcall(require, m)
if not ok then return nil, err end
return err
end
local fs
if not fs and IS_WINDOWS then
local fsload = require"path.win32.fs".load
local ok, mod = pcall(fsload, "ffi", "A")
if not ok then ok, mod = pcall(fsload, "alien", "A") end
fs = ok and mod
end
if not fs and not IS_WINDOWS then
fs = prequire"path.syscall.fs"
end
if not fs then
fs = prequire"path.lfs.fs"
end
assert(fs, "you need installed LuaFileSystem or FFI/Alien (Windows only)")
return fs
|
Fix. Use `path.syscall.fs` module in `path.fs` module.
|
Fix. Use `path.syscall.fs` module in `path.fs` module.
|
Lua
|
mit
|
mpeterv/lua-path,kidaa/lua-path
|
fb604a838bde9b7559f88fb2872c565c0757f50b
|
plugins/luamacro/luafar/makefarkeys.lua
|
plugins/luamacro/luafar/makefarkeys.lua
|
-- started: 2008-12-15 by Shmuel Zeigerman
local function extract_enums (src)
local collector = {}
for enum in src:gmatch("%senum%s*[%w_]*%s*(%b{})") do
for line in enum:gmatch("[^\n]+") do
if line:match("^%s*#") then table.insert(collector, line)
else
local var = line:match("^%s*([%a_][%w_]*)")
if var then table.insert(collector, var) end
end
end
end
return collector
end
local sTmpFile = [[
#include <windows.h>
#include <stdio.h>
#include <farcolor.hpp>
int main() {
]]
local sOutFile = [[
// This is a generated file.
#include <lua.h>
#include <lauxlib.h>
static const char colors[] = "return { $colors }";
// output table is on stack top
void SetFarColors (lua_State *L)
{
luaL_loadstring(L, colors);
lua_call(L, 0, 1);
lua_setfield(L, -2, "Colors");
}
]]
local function get_insert (in_dir, src)
local tb = { sTmpFile, }
for _,v in ipairs(extract_enums(src)) do
if v:match("^%s*#") then table.insert(tb, v)
else table.insert(tb, (' printf("%s=%%u,", (unsigned int)%s);'):format(v,v))
end
end
table.insert(tb, " return 0;\n}\n")
local fp = assert(io.open("tmp.c", "w"))
fp:write(table.concat(tb, "\n"))
fp:close()
-- Note 1: "-m32" makes possible to cross-compile LuaFAR for 64-bit target on 32-bit OS.
-- Note 2: "-DWINVER=0x601" corresponds to Windows 7.
-- assert(0 == os.execute("gcc -o tmp.exe -m32 -DWINVER=0x601 -I"..in_dir.." tmp.c"))
assert((0 == os.execute("cl.exe /nologo /I"..in_dir.." tmp.c > nul 2>&1")) or (0 == os.execute("gcc -o tmp.exe -m32 -DWINVER=0x601 -I"..in_dir.." tmp.c > nul 2>&1")))
fp = assert(io.popen("tmp.exe"))
local str = fp:read("*all")
fp:close()
os.remove "tmp.exe"
os.remove "tmp.c"
os.remove "tmp.obj"
return str
end
local function makefarcolors (in_dir, out_file)
local fp = assert(io.open(in_dir.."\\farcolor.hpp"))
local src = fp:read("*all")
fp:close()
local out = sOutFile:gsub("$colors", get_insert(in_dir, src))
fp = io.open(out_file, "w")
fp:write(out)
fp:close()
end
local in_dir, out_file = ...
assert(in_dir, "input directory not specified")
assert(out_file, "output file not specified")
makefarcolors(in_dir, out_file)
|
-- started: 2008-12-15 by Shmuel Zeigerman
local function extract_enums (src)
local collector = {}
for enum in src:gmatch("%senum%s*[%w_]*%s*(%b{})") do
for line in enum:gmatch("[^\n]+") do
if line:match("^%s*#") then table.insert(collector, line)
else
local var = line:match("^%s*([%a_][%w_]*)")
if var then table.insert(collector, var) end
end
end
end
return collector
end
local sTmpFile = [[
]]
local sOutFile = [[
// This is a generated file.
#include <lua.h>
#include <lauxlib.h>
static const char colors[] = "return { $colors }";
// output table is on stack top
void SetFarColors (lua_State *L)
{
luaL_loadstring(L, colors);
lua_call(L, 0, 1);
lua_setfield(L, -2, "Colors");
}
]]
local function get_insert (in_dir, src)
local tb = {}
local i = 0
for _,v in ipairs(extract_enums(src)) do
table.insert(tb, ('%s=%d,'):format(v,i))
i = i + 1
end
return table.concat(tb, " ")
end
local function makefarcolors (in_dir, out_file)
local fp = assert(io.open(in_dir.."\\farcolor.hpp"))
local src = fp:read("*all")
fp:close()
local out = sOutFile:gsub("$colors", get_insert(in_dir, src))
fp = io.open(out_file, "w")
fp:write(out)
fp:close()
end
local in_dir, out_file = ...
assert(in_dir, "input directory not specified")
assert(out_file, "output file not specified")
makefarcolors(in_dir, out_file)
|
fix build
|
fix build
|
Lua
|
bsd-3-clause
|
FarGroup/FarManager,johnd0e/FarManager,johnd0e/FarManager,FarGroup/FarManager,FarGroup/FarManager,johnd0e/FarManager,johnd0e/FarManager,johnd0e/FarManager,FarGroup/FarManager,FarGroup/FarManager,johnd0e/FarManager,johnd0e/FarManager,FarGroup/FarManager,johnd0e/FarManager,FarGroup/FarManager,FarGroup/FarManager
|
e5ad312ec1b1696a653fbcb506dc1741cb7e6599
|
options.lua
|
options.lua
|
local mod = EPGP:NewModule("EPGP_Options")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
function mod:OnEnable()
local options = {
name = "EPGP",
type = "group",
get = function(i) return EPGP.db.profile[i[#i]] end,
set = function(i, v) EPGP.db.profile[i[#i]] = v end,
args = {
help = {
order = 0,
type = "description",
name = L["EPGP is an in game, relational loot distribution system"],
},
hint = {
order = 1,
type = "description",
name = L["Hint: You can open these options by typing /epgp config"],
},
gp_on_tooltips = {
order = 11,
type = "toggle",
name = L["Enable GP on tooltips"],
desc = L["Enable a proposed GP value of armor on tooltips. Quest items or tokens that can be traded with armor will also have a proposed GP value."],
width = "double",
},
auto_loot = {
order = 12,
type = "toggle",
name = L["Enable automatic loot tracking"],
desc = L["Enable automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."],
width = "double",
},
auto_loot_threshold = {
order = 13,
type = "select",
name = L["Automatic loot tracking threshold"],
desc = L["Sets automatic loot tracking threshold, to disable the popup on loot below this threshold quality."],
values = {
[2] = ITEM_QUALITY2_DESC,
[3] = ITEM_QUALITY3_DESC,
[4] = ITEM_QUALITY4_DESC,
[5] = ITEM_QUALITY5_DESC,
},
},
announce = {
order = 14,
type = "toggle",
name = L["Enable announce of actions"],
desc = L["Enable announcement of all EPGP actions to the specified medium."],
width = "double",
},
announce_medium = {
order = 15,
type = "select",
name = L["Set the announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = GUILD,
["RAID"] = RAID,
["PARTY"] = PARTY,
["CHANNEL"] = CHANNEL,
},
},
announce_channel = {
order = 16,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
},
reset = {
order = 100,
type = "execute",
name = L["Reset EPGP"],
desc = L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"],
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
},
},
}
local config = LibStub("AceConfig-3.0")
local dialog = LibStub("AceConfigDialog-3.0")
config:RegisterOptionsTable("EPGP-Bliz", options)
dialog:AddToBlizOptions("EPGP-Bliz", "EPGP")
SLASH_EPGP1 = "/epgp"
SlashCmdList["EPGP"] = function(msg)
if msg == "config" then
InterfaceOptionsFrame_OpenToCategory("EPGP")
else
if EPGPFrame then
if EPGPFrame:IsShown() then
HideUIPanel(EPGPFrame)
else
ShowUIPanel(EPGPFrame)
end
end
end
end
end
|
local mod = EPGP:NewModule("EPGP_Options")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
function mod:OnEnable()
local options = {
name = "EPGP",
type = "group",
get = function(i) return EPGP.db.profile[i[#i]] end,
set = function(i, v) EPGP.db.profile[i[#i]] = v end,
args = {
help = {
order = 0,
type = "description",
name = L["EPGP is an in game, relational loot distribution system"],
},
hint = {
order = 1,
type = "description",
name = L["Hint: You can open these options by typing /epgp config"],
},
gp_on_tooltips = {
order = 11,
type = "toggle",
name = L["Enable GP on tooltips"],
desc = L["Enable a proposed GP value of armor on tooltips. Quest items or tokens that can be traded with armor will also have a proposed GP value."],
width = "double",
},
auto_loot = {
order = 12,
type = "toggle",
name = L["Enable automatic loot tracking"],
desc = L["Enable automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."],
width = "double",
},
auto_loot_threshold = {
order = 13,
type = "select",
name = L["Automatic loot tracking threshold"],
desc = L["Sets automatic loot tracking threshold, to disable the popup on loot below this threshold quality."],
values = {
[2] = ITEM_QUALITY2_DESC,
[3] = ITEM_QUALITY3_DESC,
[4] = ITEM_QUALITY4_DESC,
[5] = ITEM_QUALITY5_DESC,
},
},
announce = {
order = 14,
type = "toggle",
name = L["Enable announce of actions"],
desc = L["Enable announcement of all EPGP actions to the specified medium."],
width = "double",
},
announce_medium = {
order = 15,
type = "select",
name = L["Set the announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["OFFICER"] = CHAT_MSG_OFFICER,
["RAID"] = CHAT_MSG_RAID,
["PARTY"] = CHAT_MSG_PARTY,
["CHANNEL"] = CUSTOM,
},
},
announce_channel = {
order = 16,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
},
reset = {
order = 100,
type = "execute",
name = L["Reset EPGP"],
desc = L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"],
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
},
},
}
local config = LibStub("AceConfig-3.0")
local dialog = LibStub("AceConfigDialog-3.0")
config:RegisterOptionsTable("EPGP-Bliz", options)
dialog:AddToBlizOptions("EPGP-Bliz", "EPGP")
SLASH_EPGP1 = "/epgp"
SlashCmdList["EPGP"] = function(msg)
if msg == "config" then
InterfaceOptionsFrame_OpenToCategory("EPGP")
else
if EPGPFrame then
if EPGPFrame:IsShown() then
HideUIPanel(EPGPFrame)
else
ShowUIPanel(EPGPFrame)
end
end
end
end
end
|
Add officer chat to the options of announces. This fixes issue 236.
|
Add officer chat to the options of announces. This fixes issue 236.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,hayword/tfatf_epgp
|
578211e93c1f49f1b97772425a9724d3e3d5680e
|
xmake/modules/privilege/sudo.lua
|
xmake/modules/privilege/sudo.lua
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file sudo.lua
--
-- imports
import("core.base.option")
import("detect.tool.find_sudo")
-- sudo run shell with administrator permission
--
-- .e.g
-- _sudo(os.run, "echo", "hello xmake!")
--
function _sudo(runner, cmd, ...)
-- find sudo
local program = find_sudo()
assert(program, "sudo not found!")
-- run it with administrator permission and preserve parent environment
runner(program .. " PATH=" .. os.getenv("PATH") .. " " .. cmd, ...)
end
-- sudo run shell with administrator permission and arguments list
--
-- .e.g
-- _sudov(os.runv, {"echo", "hello xmake!"})
--
function _sudov(runner, shellname, argv)
-- find sudo
local program = find_sudo()
assert(program, "sudo not found!")
-- run it with administrator permission and preserve parent environment
runner(program, table.join("PATH=" .. os.getenv("PATH"), shellname, argv))
end
-- sudo run lua script with administrator permission and arguments list
--
-- .e.g
-- _lua(os.runv, "xxx.lua", {"arg1", "arg2"})
--
function _lua(runner, luafile, luaargv)
-- init argv
local argv = {"lua", "--root"}
for _, name in ipairs({"file", "project", "backtrace", "verbose", "quiet"}) do
local value = option.get(name)
if type(value) == "string" then
table.insert(argv, "--" .. name .. "=" .. value)
elseif value then
table.insert(argv, "--" .. name)
end
end
-- run it with administrator permission
_sudov(runner, "xmake", table.join(argv, luafile, luaargv))
end
-- has sudo?
function has()
return find_sudo() ~= nil
end
-- sudo run shell
function run(cmd, ...)
return _sudo(os.run, cmd, ...)
end
-- sudo run shell with arguments list
function runv(shellname, argv)
return _sudo(os.run, shellname, argv)
end
-- sudo quietly run shell and echo verbose info if [-v|--verbose] option is enabled
function vrun(cmd, ...)
return _sudo(os.vrun, cmd, ...)
end
-- sudo quietly run shell with arguments list and echo verbose info if [-v|--verbose] option is enabled
function vrunv(shellname, argv)
return _sudo(os.vrunv, shellname, argv)
end
-- sudo run shell and return output and error data
function iorun(cmd, ...)
return _sudo(os.iorun, cmd, ...)
end
-- sudo run shell and return output and error data
function iorunv(shellname, argv)
return _sudo(os.iorunv, shellname, argv)
end
-- sudo execute shell
function exec(cmd, ...)
return _sudo(os.exec, cmd, ...)
end
-- sudo execute shell with arguments list
function execv(shellname, argv)
return _sudo(os.execv, shellname, argv)
end
-- sudo run lua script
function runl(luafile, luaargv)
return _lua(os.runv, luafile, luaargv)
end
-- sudo quietly run lua script and echo verbose info if [-v|--verbose] option is enabled
function vrunl(luafile, luaargv)
return _lua(os.vrunv, luafile, luaargv)
end
-- sudo run lua script and return output and error data
function iorunl(luafile, luaargv)
return _lua(os.iorunv, luafile, luaargv)
end
-- sudo execute lua script
function execl(luafile, luaargv)
return _lua(os.execv, luafile, luaargv)
end
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file sudo.lua
--
-- imports
import("core.base.option")
import("detect.tool.find_sudo")
-- sudo run shell with administrator permission
--
-- .e.g
-- _sudo(os.run, "echo", "hello xmake!")
--
function _sudo(runner, cmd, ...)
-- find sudo
local program = find_sudo()
assert(program, "sudo not found!")
-- FIXME: deal with spaces in `os.getenv("PATH")`
-- run it with administrator permission and preserve parent environment
runner(program .. " env PATH=" .. os.getenv("PATH") .. " " .. cmd, ...)
end
-- sudo run shell with administrator permission and arguments list
--
-- .e.g
-- _sudov(os.runv, {"echo", "hello xmake!"})
--
function _sudov(runner, shellname, argv)
-- find sudo
local program = find_sudo()
assert(program, "sudo not found!")
-- run it with administrator permission and preserve parent environment
runner(program, table.join("env", "PATH=" .. os.getenv("PATH"), shellname, argv))
end
-- sudo run lua script with administrator permission and arguments list
--
-- .e.g
-- _lua(os.runv, "xxx.lua", {"arg1", "arg2"})
--
function _lua(runner, luafile, luaargv)
-- init argv
local argv = {"lua", "--root"}
for _, name in ipairs({"file", "project", "backtrace", "verbose", "quiet"}) do
local value = option.get(name)
if type(value) == "string" then
table.insert(argv, "--" .. name .. "=" .. value)
elseif value then
table.insert(argv, "--" .. name)
end
end
-- run it with administrator permission
_sudov(runner, "xmake", table.join(argv, luafile, luaargv))
end
-- has sudo?
function has()
return find_sudo() ~= nil
end
-- sudo run shell
function run(cmd, ...)
return _sudo(os.run, cmd, ...)
end
-- sudo run shell with arguments list
function runv(shellname, argv)
return _sudo(os.run, shellname, argv)
end
-- sudo quietly run shell and echo verbose info if [-v|--verbose] option is enabled
function vrun(cmd, ...)
return _sudo(os.vrun, cmd, ...)
end
-- sudo quietly run shell with arguments list and echo verbose info if [-v|--verbose] option is enabled
function vrunv(shellname, argv)
return _sudo(os.vrunv, shellname, argv)
end
-- sudo run shell and return output and error data
function iorun(cmd, ...)
return _sudo(os.iorun, cmd, ...)
end
-- sudo run shell and return output and error data
function iorunv(shellname, argv)
return _sudo(os.iorunv, shellname, argv)
end
-- sudo execute shell
function exec(cmd, ...)
return _sudo(os.exec, cmd, ...)
end
-- sudo execute shell with arguments list
function execv(shellname, argv)
return _sudo(os.execv, shellname, argv)
end
-- sudo run lua script
function runl(luafile, luaargv)
return _lua(os.runv, luafile, luaargv)
end
-- sudo quietly run lua script and echo verbose info if [-v|--verbose] option is enabled
function vrunl(luafile, luaargv)
return _lua(os.vrunv, luafile, luaargv)
end
-- sudo run lua script and return output and error data
function iorunl(luafile, luaargv)
return _lua(os.iorunv, luafile, luaargv)
end
-- sudo execute lua script
function execl(luafile, luaargv)
return _lua(os.execv, luafile, luaargv)
end
|
fix sudo PATH passing
|
fix sudo PATH passing
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
54b3f56933b3cd493aa7c3e9a8850faffc4cc794
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) and (isPedInVehicle(source)==false) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function playerEntersVehicle(player)
if (weapons[player]) then
local object = weapons[player][1]
destroyElement(object)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), playerEntersVehicle)
function playerExitsVehicle(player)
if (weapons[player]) then
local weapon = weapons[player][2]
weapons[player][1] = createModel(player, weapon)
weapons[player][3] = isPedDucked(player)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), playerExitsVehicle)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
Bug fix for weapons on back when entering a vehicle
|
Bug fix for weapons on back when entering a vehicle
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1913 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
6fac148f1eb0555d4588de6da1129d4dc159337a
|
openLuup/xml.lua
|
openLuup/xml.lua
|
local version = "XML 2016.04.14 @akbooer"
--
-- Routines to read Device / Service / Implementation XML files
--
-- general xml reader: this is just good enough to read device and implementation .xml files
-- doesn't cope with XML attributes or empty elements: <tag />
--
-- DOES cope with comments (thanks @vosmont)
-- TODO: proper XML parser rather than nasty hack?
--
-- 2016.02.22 skip XML attributes but still parse element
-- 2016.02.23 remove reader and caching, rename encode/decode
-- 2016.02.24 escape special characters in encode and decode
-- 2016.04.14 @explorer expanded tags to alpha-numerics and underscores
--
-- XML:extract ("name", "subname", "subsubname", ...)
-- return named part or empty list
local function extract (self, name, name2, ...)
local x = (self or {}) [name]
if x then
if name2 then
return extract (x, name2, ...)
else
if type(x) == "table" and #x == 0 then x = {x} end -- make it a one element list
return x
end
end
return {} -- always return something
end
local function decode (info)
local msg
local xml = {}
-- remove such like: <!-- This is a comment -->, thanks @vosmont
-- see: http://forum.micasaverde.com/index.php/topic,34572.0.html
if info then info = info: gsub ("<!%-%-.-%-%->", '') end
--
local result = info
for a,b in (info or ''): gmatch "<([%w_]+)>(.-)</%1>" do -- find matching opening and closing tags
local x,y = decode (b) -- get the value of the contents
xml[a] = xml[a] or {} -- if this tag doesn't exist, start a list of values
xml[a][#xml[a]+1] = x or y -- add new value to the list (might be table x, or just text y)
result = xml
end
if type (result) == "table" then
for a,b in pairs (result) do -- go through the contents
if #b == 1 then result[a] = b[1] end -- collapse one-element lists to simple items
end
else
if result then -- in case of failure, simply return whole string as 'error message'
msg = result: gsub ("&(%w+);", {lt = '<', gt = '>', quot = '"', apos = "'", amp = '&'})
end
result = nil -- ...and nil for xml result
end
return result, msg
end
local function encode (Lua, wrapper)
local xml = {} -- or perhaps {'<?xml version="1.0"?>\n'}
local function p(x)
if type (x) ~= "table" then x = {x} end
for _, y in ipairs (x) do xml[#xml+1] = y end
end
local function value (x, name, depth)
local gsub = {['<'] = "<", ['>'] = ">", ['"'] = """, ["'"] = "'", ['&'] = "&"}
local function spc () p ((' '):rep (2*depth)) end
local function atag () spc() ; p {'<', name,'>'} end
local function ztag () p {'</',name:match "^[^%s]+",'>\n'} end
local function str (x) atag() ; p(tostring(x): gsub("%s+", ' '): gsub ([=[[<>"'&]]=], gsub)) ; ztag() end
local function err (x) error ("xml: unsupported data type "..type (x)) end
local function tbl (x)
local y
if #x == 0 then y = {x} else y = x end
for i, z in ipairs (y) do
i = {}
for a in pairs (z) do i[#i+1] = a end
table.sort (i, function (a,b) return tostring(a) < tostring (b) end)
if name then atag() ; p '\n' end
for _,a in ipairs (i) do value(z[a], a, depth+1) end
if name then spc() ; ztag() end
end
end
depth = depth or 0
local dispatch = {table = tbl, string = str, number = str}
return (dispatch [type(x)] or err) (x)
end
-- wrapper parameter allows outer level of tags (with attributes)
local ok, msg = pcall (value, Lua, wrapper)
if ok then ok = table.concat (xml) end
return ok, msg
end
return {
-- constants
version = version,
-- methods
extract = extract,
decode = decode,
encode = encode,
}
|
local version = "XML 2016.04.15 @akbooer"
--
-- Routines to read Device / Service / Implementation XML files
--
-- general xml reader: this is just good enough to read device and implementation .xml files
-- doesn't cope with XML attributes or empty elements: <tag />
--
-- DOES cope with comments (thanks @vosmont)
-- TODO: proper XML parser rather than nasty hack?
--
-- 2016.02.22 skip XML attributes but still parse element
-- 2016.02.23 remove reader and caching, rename encode/decode
-- 2016.02.24 escape special characters in encode and decode
-- 2016.04.14 @explorer expanded tags to alpha-numerics and underscores
-- 2016.04.15 fix attribute skipping (got lost in previous edit)
-- XML:extract ("name", "subname", "subsubname", ...)
-- return named part or empty list
local function extract (self, name, name2, ...)
local x = (self or {}) [name]
if x then
if name2 then
return extract (x, name2, ...)
else
if type(x) == "table" and #x == 0 then x = {x} end -- make it a one element list
return x
end
end
return {} -- always return something
end
local function decode (info)
local msg
local xml = {}
-- remove such like: <!-- This is a comment -->, thanks @vosmont
-- see: http://forum.micasaverde.com/index.php/topic,34572.0.html
if info then info = info: gsub ("<!%-%-.-%-%->", '') end
--
local result = info
for a,b in (info or ''): gmatch "<([%w_]+).->(.-)</%1>" do -- find matching opening and closing tags
local x,y = decode (b) -- get the value of the contents
xml[a] = xml[a] or {} -- if this tag doesn't exist, start a list of values
xml[a][#xml[a]+1] = x or y -- add new value to the list (might be table x, or just text y)
result = xml
end
if type (result) == "table" then
for a,b in pairs (result) do -- go through the contents
if #b == 1 then result[a] = b[1] end -- collapse one-element lists to simple items
end
else
if result then -- in case of failure, simply return whole string as 'error message'
msg = result: gsub ("&(%w+);", {lt = '<', gt = '>', quot = '"', apos = "'", amp = '&'})
end
result = nil -- ...and nil for xml result
end
return result, msg
end
local function encode (Lua, wrapper)
local xml = {} -- or perhaps {'<?xml version="1.0"?>\n'}
local function p(x)
if type (x) ~= "table" then x = {x} end
for _, y in ipairs (x) do xml[#xml+1] = y end
end
local function value (x, name, depth)
local gsub = {['<'] = "<", ['>'] = ">", ['"'] = """, ["'"] = "'", ['&'] = "&"}
local function spc () p ((' '):rep (2*depth)) end
local function atag () spc() ; p {'<', name,'>'} end
local function ztag () p {'</',name:match "^[^%s]+",'>\n'} end
local function str (x) atag() ; p(tostring(x): gsub("%s+", ' '): gsub ([=[[<>"'&]]=], gsub)) ; ztag() end
local function err (x) error ("xml: unsupported data type "..type (x)) end
local function tbl (x)
local y
if #x == 0 then y = {x} else y = x end
for i, z in ipairs (y) do
i = {}
for a in pairs (z) do i[#i+1] = a end
table.sort (i, function (a,b) return tostring(a) < tostring (b) end)
if name then atag() ; p '\n' end
for _,a in ipairs (i) do value(z[a], a, depth+1) end
if name then spc() ; ztag() end
end
end
depth = depth or 0
local dispatch = {table = tbl, string = str, number = str}
return (dispatch [type(x)] or err) (x)
end
-- wrapper parameter allows outer level of tags (with attributes)
local ok, msg = pcall (value, Lua, wrapper)
if ok then ok = table.concat (xml) end
return ok, msg
end
return {
-- constants
version = version,
-- methods
extract = extract,
decode = decode,
encode = encode,
}
|
hot-fix-xml-attributes
|
hot-fix-xml-attributes
- reinstate attribute skipping pattern
- …lost in the previous edit of 2016.02.22
|
Lua
|
apache-2.0
|
akbooer/openLuup
|
67847096db0e70b60bed944cab32e98dd47ab69a
|
premake/bgfx.lua
|
premake/bgfx.lua
|
--
-- Copyright 2010-2014 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
project "bgfx"
uuid "2dc7fd80-ed76-11e0-be50-0800200c9a66"
kind "StaticLib"
includedirs {
BGFX_DIR .. "../bx/include",
}
defines {
-- "BGFX_CONFIG_RENDERER_OPENGL=1",
}
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "windows" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "vs* or linux or mingw or osx or ios*" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
copyLib()
project "bgfx-shared-lib"
uuid "09986168-e9d9-11e3-9c8e-f2aef940a72a"
kind "SharedLib"
includedirs {
BGFX_DIR .. "../bx/include",
}
defines {
"BGFX_SHARED_LIB_BUILD=1",
-- "BGFX_CONFIG_RENDERER_OPENGL=1",
}
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "windows" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "vs* or linux or mingw or osx or ios*" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
copyLib()
|
--
-- Copyright 2010-2014 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
project "bgfx"
uuid "2dc7fd80-ed76-11e0-be50-0800200c9a66"
kind "StaticLib"
includedirs {
BGFX_DIR .. "../bx/include",
}
defines {
-- "BGFX_CONFIG_RENDERER_OPENGL=1",
}
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "windows" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "vs* or linux or mingw or osx or ios*" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
copyLib()
project "bgfx-shared-lib"
uuid "09986168-e9d9-11e3-9c8e-f2aef940a72a"
kind "SharedLib"
includedirs {
BGFX_DIR .. "../bx/include",
}
defines {
"BGFX_SHARED_LIB_BUILD=1",
-- "BGFX_CONFIG_RENDERER_OPENGL=1",
}
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "windows" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "osx or ios*" }
files {
BGFX_DIR .. "src/**.mm",
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs* or linux or mingw or osx or ios*" }
includedirs {
--nacl has GLES2 headers modified...
BGFX_DIR .. "3rdparty/khronos",
}
configuration {}
includedirs {
BGFX_DIR .. "include",
}
files {
BGFX_DIR .. "include/**.h",
BGFX_DIR .. "src/**.cpp",
BGFX_DIR .. "src/**.h",
}
excludes {
BGFX_DIR .. "src/**.bin.h",
}
copyLib()
|
Fixed OSX build.
|
Fixed OSX build.
|
Lua
|
bsd-2-clause
|
mmicko/bgfx,andr3wmac/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,darkimage/bgfx,marco-we/bgfx,v3n/bgfx,LWJGL-CI/bgfx,v3n/bgfx,LSBOSS/bgfx,Extrawurst/bgfx,LSBOSS/bgfx,BlueCrystalLabs/bgfx,aonorin/bgfx,ocornut/bgfx,septag/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,marco-we/bgfx,BlueCrystalLabs/bgfx,mcanthony/bgfx,bkaradzic/bgfx,0-wiz-0/bgfx,mmicko/bgfx,jpcy/bgfx,janstk/bgfx,v3n/bgfx,jdryg/bgfx,MikePopoloski/bgfx,jdryg/bgfx,fluffyfreak/bgfx,cyndis/bgfx,mendsley/bgfx,emoon/bgfx,Vertexwahn/bgfx,sergeScherbakov/bgfx,Synxis/bgfx,fluffyfreak/bgfx,cyndis/bgfx,cuavas/bgfx,ktotheoz/bgfx,Synxis/bgfx,Vertexwahn/bgfx,Extrawurst/bgfx,elmindreda/bgfx,janstk/bgfx,ktotheoz/bgfx,elmindreda/bgfx,kondrak/bgfx,0-wiz-0/bgfx,sergeScherbakov/bgfx,emoon/bgfx,jdryg/bgfx,attilaz/bgfx,sergeScherbakov/bgfx,LSBOSS/bgfx,Extrawurst/bgfx,mcanthony/bgfx,fluffyfreak/bgfx,darkimage/bgfx,ming4883/bgfx,bkaradzic/bgfx,ming4883/bgfx,Vertexwahn/bgfx,darkimage/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx,jdryg/bgfx,andr3wmac/bgfx,cuavas/bgfx,elmindreda/bgfx,cyndis/bgfx,mmicko/bgfx,mcanthony/bgfx,andr3wmac/bgfx,marco-we/bgfx,kondrak/bgfx,LWJGL-CI/bgfx,attilaz/bgfx,mendsley/bgfx,ocornut/bgfx,kondrak/bgfx,mendsley/bgfx,ktotheoz/bgfx,ocornut/bgfx,jpcy/bgfx,BlueCrystalLabs/bgfx,emoon/bgfx,aonorin/bgfx,0-wiz-0/bgfx,bkaradzic/bgfx,Synxis/bgfx,janstk/bgfx,ming4883/bgfx,septag/bgfx,jpcy/bgfx,cuavas/bgfx,jpcy/bgfx,septag/bgfx,aonorin/bgfx,attilaz/bgfx
|
841f3a0344931bf1fc5191593e26039a5235a70d
|
util/events.lua
|
util/events.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local pairs = pairs;
local t_insert = table.insert;
local t_sort = table.sort;
local setmetatable = setmetatable;
local next = next;
module "events"
function new()
local handlers = {};
local global_wrappers;
local wrappers = {};
local event_map = {};
local function _rebuild_index(handlers, event)
local _handlers = event_map[event];
if not _handlers or next(_handlers) == nil then return; end
local index = {};
for handler in pairs(_handlers) do
t_insert(index, handler);
end
t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end);
handlers[event] = index;
return index;
end;
setmetatable(handlers, { __index = _rebuild_index });
local function add_handler(event, handler, priority)
local map = event_map[event];
if map then
map[handler] = priority or 0;
else
map = {[handler] = priority or 0};
event_map[event] = map;
end
handlers[event] = nil;
end;
local function remove_handler(event, handler)
local map = event_map[event];
if map then
map[handler] = nil;
handlers[event] = nil;
if next(map) == nil then
event_map[event] = nil;
end
end
end;
local function add_handlers(handlers)
for event, handler in pairs(handlers) do
add_handler(event, handler);
end
end;
local function remove_handlers(handlers)
for event, handler in pairs(handlers) do
remove_handler(event, handler);
end
end;
local function _fire_event(event_name, event_data)
local h = handlers[event_name];
if h then
for i=1,#h do
local ret = h[i](event_data);
if ret ~= nil then return ret; end
end
end
end;
local function fire_event(event_name, event_data)
local w = wrappers[event_name] or global_wrappers;
if w then
local curr_wrapper = #w;
local function c(event_name, event_data)
curr_wrapper = curr_wrapper - 1;
if curr_wrapper == 0 then
if global_wrappers == nil or w == global_wrappers then
return _fire_event(event_name, event_data);
end
w, curr_wrapper = global_wrappers, #global_wrappers;
return w[curr_wrapper](c, event_name, event_data);
else
return w[curr_wrapper](c, event_name, event_data);
end
end
return w[curr_wrapper](c, event_name, event_data);
end
return _fire_event(event_name, event_data);
end
local function add_wrapper(event_name, wrapper)
local w;
if event_name == false then
w = global_wrappers;
if not w then
w = {};
global_wrappers = w;
end
else
w = wrappers[event_name];
if not w then
w = {};
wrappers[event_name] = w;
end
end
w[#w+1] = wrapper;
end
local function remove_wrapper(event_name, wrapper)
local w;
if event_name == false then
w = global_wrappers;
else
w = wrappers[event_name];
end
if not w then return; end
for i = #w, 1 do
if w[i] == wrapper then
table.remove(w, i);
end
end
if #w == 0 then
if event_name == nil then
global_wrappers = nil;
else
wrappers[event_name] = nil;
end
end
end
return {
add_handler = add_handler;
remove_handler = remove_handler;
add_handlers = add_handlers;
remove_handlers = remove_handlers;
wrappers = {
add_handler = add_wrapper;
remove_handler = remove_wrapper;
};
add_wrapper = add_wrapper;
remove_wrapper = remove_wrapper;
fire_event = fire_event;
_handlers = handlers;
_event_map = event_map;
};
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local pairs = pairs;
local t_insert = table.insert;
local t_remove = table.remove;
local t_sort = table.sort;
local setmetatable = setmetatable;
local next = next;
module "events"
function new()
local handlers = {};
local global_wrappers;
local wrappers = {};
local event_map = {};
local function _rebuild_index(handlers, event)
local _handlers = event_map[event];
if not _handlers or next(_handlers) == nil then return; end
local index = {};
for handler in pairs(_handlers) do
t_insert(index, handler);
end
t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end);
handlers[event] = index;
return index;
end;
setmetatable(handlers, { __index = _rebuild_index });
local function add_handler(event, handler, priority)
local map = event_map[event];
if map then
map[handler] = priority or 0;
else
map = {[handler] = priority or 0};
event_map[event] = map;
end
handlers[event] = nil;
end;
local function remove_handler(event, handler)
local map = event_map[event];
if map then
map[handler] = nil;
handlers[event] = nil;
if next(map) == nil then
event_map[event] = nil;
end
end
end;
local function add_handlers(handlers)
for event, handler in pairs(handlers) do
add_handler(event, handler);
end
end;
local function remove_handlers(handlers)
for event, handler in pairs(handlers) do
remove_handler(event, handler);
end
end;
local function _fire_event(event_name, event_data)
local h = handlers[event_name];
if h then
for i=1,#h do
local ret = h[i](event_data);
if ret ~= nil then return ret; end
end
end
end;
local function fire_event(event_name, event_data)
local w = wrappers[event_name] or global_wrappers;
if w then
local curr_wrapper = #w;
local function c(event_name, event_data)
curr_wrapper = curr_wrapper - 1;
if curr_wrapper == 0 then
if global_wrappers == nil or w == global_wrappers then
return _fire_event(event_name, event_data);
end
w, curr_wrapper = global_wrappers, #global_wrappers;
return w[curr_wrapper](c, event_name, event_data);
else
return w[curr_wrapper](c, event_name, event_data);
end
end
return w[curr_wrapper](c, event_name, event_data);
end
return _fire_event(event_name, event_data);
end
local function add_wrapper(event_name, wrapper)
local w;
if event_name == false then
w = global_wrappers;
if not w then
w = {};
global_wrappers = w;
end
else
w = wrappers[event_name];
if not w then
w = {};
wrappers[event_name] = w;
end
end
w[#w+1] = wrapper;
end
local function remove_wrapper(event_name, wrapper)
local w;
if event_name == false then
w = global_wrappers;
else
w = wrappers[event_name];
end
if not w then return; end
for i = #w, 1 do
if w[i] == wrapper then
t_remove(w, i);
end
end
if #w == 0 then
if event_name == nil then
global_wrappers = nil;
else
wrappers[event_name] = nil;
end
end
end
return {
add_handler = add_handler;
remove_handler = remove_handler;
add_handlers = add_handlers;
remove_handlers = remove_handlers;
wrappers = {
add_handler = add_wrapper;
remove_handler = remove_wrapper;
};
add_wrapper = add_wrapper;
remove_wrapper = remove_wrapper;
fire_event = fire_event;
_handlers = handlers;
_event_map = event_map;
};
end
return _M;
|
util.events: Add local reference to table.remove (fixes traceback)
|
util.events: Add local reference to table.remove (fixes traceback)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
e2456e39d0c121faf5338a67138d7ae6c7c058d0
|
examples/route_guide/server_reader/RouteChatReader.lua
|
examples/route_guide/server_reader/RouteChatReader.lua
|
--- Server reader class for RouteChat method.
-- @classmod server_reader.RouteChatReader
local Reader = {}
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New Reader.
-- @tparam Writer writer `Writer` object
-- @treturn table Reader object
function Reader:new(writer, db)
assert("table" == type(writer))
local reader = {
-- private:
_writer = writer,
_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()
function Reader:on_msg(msg)
assert("table" == type(msg))
local l0 = msg.location
for _, n in ipairs(self._received_notes) do
local l = n.location
if l.latitude == l0.latitude and
l.longitude == l0.longitude then
self._writer:write(n)
end -- if
end -- for
table.insert(self._received_notes, msg)
end
function Reader:on_error(error_str, status_code)
assert("string" == type(error_str))
assert("number" == type(status_code))
print(string.format("RouteChat error: (%d)%s", status_code, error_str)
self._writer:close()
end
function Reader:on_end()
print("RouteChat reader end.")
self._writer:write({});
end
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
return Reader
|
--- Server reader class for RouteChat method.
-- @classmod server_reader.RouteChatReader
local Reader = {}
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New Reader.
-- @tparam Writer writer `Writer` object
-- @treturn table Reader object
function Reader:new(writer, db)
assert("table" == type(writer))
local reader = {
-- private:
_writer = writer,
_db = db,
_summary = {
point_count = 0,
feature_count = 0,
distance = 0.0,
elapsed_time = 0, -- in seconds
},
_previous = nil, -- Point
_start_time = os.time(),
_received_notes = {},
}
setmetatable(reader, self)
self.__index = self
return reader
end -- new()
function Reader:on_msg(msg)
assert("table" == type(msg))
local l0 = msg.location
for _, n in ipairs(self._received_notes) do
local l = n.location
if l.latitude == l0.latitude and
l.longitude == l0.longitude then
self._writer:write(n)
end -- if
end -- for
table.insert(self._received_notes, msg)
end
function Reader:on_error(error_str, status_code)
assert("string" == type(error_str))
assert("number" == type(status_code))
print(string.format("RouteChat error: (%d)%s", status_code, error_str))
self._writer:close()
end
function Reader:on_end()
print("RouteChat reader end.")
self._writer:write({});
end
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
return Reader
|
Fix RouteChat.
|
Fix RouteChat.
|
Lua
|
bsd-3-clause
|
jinq0123/grpc-lua,jinq0123/grpc-lua,jinq0123/grpc-lua
|
23c7c022412d54142b45e4309f407e51c983abcd
|
Engine/coreg.lua
|
Engine/coreg.lua
|
--Corouting Registry: this file is responsible for providing LIKO12 it's api--
local coreg = {reg={}}
local coreg = {reg={}}
local sandbox = require("Engine.sandbox")
--Returns the current active coroutine if exists
function coreg:getCoroutine()
return self.co, self.coglob
end
--Sets the current active coroutine
function coreg:setCoroutine(co,glob)
self.co = co or self.co
self.coglob = glob or self.coglob
return self
end
--Call a function with the coroutine system plugged (A sub-coroutine)
function coreg:subCoroutine(func)
self:pushCoroutine()
self.co = coroutine.create(func)
end
--Resumes the current active coroutine if exists.
function coreg:resumeCoroutine(...)
local lastargs = {...}
while true do
if not self.co or coroutine.status(self.co) == "dead" then
return error(self.co and "The coroutine is dead" or "No coroutine to execute !")
end
local args = {coroutine.resume(self.co,unpack(lastargs))}
if not args[1] then error(args[2]) end --Should have a better error handelling
if coroutine.status(self.co) == "dead" then --The coroutine finished, we hope that a new one has been set.
--Do nothing
elseif args[2] then --There's a command to process
args = {self:trigger(select(2,unpack(args)))}
if not args[1] then --That's a failure
lastargs = args --Let's pass it to the coroutine.
elseif not(type(args[1]) == "number" and args[1] == 2) then --Continue with the loop
lastargs = args --Let's pass it to the coroutine.
else --The registered function will call resumeCoroutine() later some how, exit the loop now.
return
end
end
end
end
--Sandbox a function with the current coroutine environment.
function coreg:sandbox(f)
if self.co and self.coglob then setfenv(f,self.coglob) return end
local GLOB = sandbox(self) --Create a new sandbox.
setfenv(f,GLOB)
return GLOB
end
--Register a value to a specific key.
--If the value is a table, then the values in the table will be registered at key:tableValueKey
--If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully.
--Else, the value will be returned to the liko12 code.
function coreg:register(value,key)
local key = key or "none"
if type(value) == "table" then
for k,v in pairs(value) do
self.reg[key..":"..k] = v
end
end
self.reg[key] = value
end
--Trigger a value in a key.
--If the value is a function, then it will call it instant.
--Else, it will return the value.
--Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message.
--Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1)
--Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called).
function coreg:trigger(key,...)
local key = key or "none"
if type(self.reg[key]) == "nil" then return false, "error, key not found !" end
if type(self.reg[key]) == "function" then
return self.reg[key](...)
else
return true, self.reg[key]
end
end
--Returns the value registered in a specific key.
--Returns: value then the given key.
function coreg:get(key)
local key = key or "none"
return self.reg[key], key
end
--Returns a table containing the list of the registered keys.
--list[key] = type
function coreg:index()
local list = {}
for k,v in pairs(self.reg) do
list[k] = type(v)
end
return list
end
--Returns a clone of the registry table.
function coreg:registry()
local reg = {}
for k,v in pairs(self.reg) do
reg[k] = v
end
return reg
end
return coreg
|
--Corouting Registry: this file is responsible for providing LIKO12 it's api--
local coreg = {reg={}}
local coreg = {reg={}}
local sandbox = require("Engine.sandbox")
--Returns the current active coroutine if exists
function coreg:getCoroutine()
return self.co, self.coglob
end
--Sets the current active coroutine
function coreg:setCoroutine(co,glob)
self.co = co or self.co
self.coglob = glob or self.coglob
return self
end
--Call a function with the coroutine system plugged (A sub-coroutine)
function coreg:subCoroutine(func)
self:pushCoroutine()
self.co = coroutine.create(func)
end
--Resumes the current active coroutine if exists.
function coreg:resumeCoroutine(...)
local lastargs = {...}
while true do
if not self.co or coroutine.status(self.co) == "dead" then
return error(self.co and "The coroutine is dead" or "No coroutine to execute !")
end
local args = {coroutine.resume(self.co,unpack(lastargs))}
if not args[1] then error(args[2]) end --Should have a better error handelling
if coroutine.status(self.co) == "dead" then
--The coroutine finished, we hope that a new one has been set.
elseif tostring(args[2]) == "echo" then
lastargs = {select(3,unpack(args))}
elseif args[2] then --There's a command to process
args = {self:trigger(select(2,unpack(args)))}
if not args[1] then --That's a failure
lastargs = args --Let's pass it to the coroutine.
elseif not(type(args[1]) == "number" and args[1] == 2) then --Continue with the loop
lastargs = args --Let's pass it to the coroutine.
else --The registered function will call resumeCoroutine() later some how, exit the loop now.
return
end
end
end
end
--Sandbox a function with the current coroutine environment.
function coreg:sandbox(f)
if self.co and self.coglob then setfenv(f,self.coglob) return end
local GLOB = sandbox(self) --Create a new sandbox.
setfenv(f,GLOB)
return GLOB
end
--Register a value to a specific key.
--If the value is a table, then the values in the table will be registered at key:tableValueKey
--If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully.
--Else, the value will be returned to the liko12 code.
function coreg:register(value,key)
local key = key or "none"
if type(value) == "table" then
for k,v in pairs(value) do
self.reg[key..":"..k] = v
end
end
self.reg[key] = value
end
--Trigger a value in a key.
--If the value is a function, then it will call it instant.
--Else, it will return the value.
--Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message.
--Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1)
--Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called).
function coreg:trigger(key,...)
local key = key or "none"
if type(self.reg[key]) == "nil" then return false, "error, key not found !" end
if type(self.reg[key]) == "function" then
return self.reg[key](...)
else
return true, self.reg[key]
end
end
--Returns the value registered in a specific key.
--Returns: value then the given key.
function coreg:get(key)
local key = key or "none"
return self.reg[key], key
end
--Returns a table containing the list of the registered keys.
--list[key] = type
function coreg:index()
local list = {}
for k,v in pairs(self.reg) do
list[k] = type(v)
end
return list
end
--Returns a clone of the registry table.
function coreg:registry()
local reg = {}
for k,v in pairs(self.reg) do
reg[k] = v
end
return reg
end
return coreg
|
Bugfixes
|
Bugfixes
Former-commit-id: 08901166411ecc60f5a9cfb2adc32b809753d1eb
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
60b51dcf8580b05d3b250f245514f3a33b5d1032
|
scripts/bgfx.lua
|
scripts/bgfx.lua
|
--
-- Copyright 2010-2020 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
function filesexist(_srcPath, _dstPath, _files)
for _, file in ipairs(_files) do
file = path.getrelative(_srcPath, file)
local filePath = path.join(_dstPath, file)
if not os.isfile(filePath) then return false end
end
return true
end
function overridefiles(_srcPath, _dstPath, _files)
local remove = {}
local add = {}
for _, file in ipairs(_files) do
file = path.getrelative(_srcPath, file)
local filePath = path.join(_dstPath, file)
if not os.isfile(filePath) then return end
table.insert(remove, path.join(_srcPath, file))
table.insert(add, filePath)
end
removefiles {
remove,
}
files {
add,
}
end
function bgfxProjectBase(_kind, _defines)
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
links {
"bimg",
"bx",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BX_DIR, "include"),
path.join(BIMG_DIR, "include"),
}
defines {
_defines,
}
links {
"bx",
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "vs* or mingw*", "not durango" }
includedirs {
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "winstore*" }
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 { "*clang*" }
buildoptions {
"-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int'
"-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension
}
configuration { "osx" }
buildoptions { "-x objective-c++" } -- additional build option for osx
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
"-weak_framework MetalKit",
}
configuration { "not NX32", "not NX64" }
includedirs {
-- NX has EGL headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
path.join(BGFX_DIR, "scripts/**.natvis"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-gnm"), {
path.join(BGFX_DIR, "src/renderer_gnm.cpp"),
path.join(BGFX_DIR, "src/renderer_gnm.h"),
})
overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-nvn"), {
path.join(BGFX_DIR, "src/renderer_nvn.cpp"),
path.join(BGFX_DIR, "src/renderer_nvn.h"),
})
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/debug_**.cpp"),
path.join(BGFX_DIR, "src/dxgi.cpp"),
path.join(BGFX_DIR, "src/glcontext_**.cpp"),
path.join(BGFX_DIR, "src/hmd**.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/nvapi.cpp"),
path.join(BGFX_DIR, "src/renderer_**.cpp"),
path.join(BGFX_DIR, "src/shader**.cpp"),
path.join(BGFX_DIR, "src/topology.cpp"),
path.join(BGFX_DIR, "src/vertexlayout.cpp"),
}
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/amalgamated.mm"),
}
excludes {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration { "not (xcode* or osx or ios*)" }
excludes {
path.join(BGFX_DIR, "src/**.mm"),
}
configuration {}
else
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-gnm"), {
path.join(BGFX_DIR, "scripts/bgfx.lua"), }) then
dofile(path.join(BGFX_DIR, "../bgfx-gnm/scripts/bgfx.lua") )
end
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-nvn"), {
path.join(BGFX_DIR, "scripts/bgfx.lua"), }) then
dofile(path.join(BGFX_DIR, "../bgfx-nvn/scripts/bgfx.lua") )
end
configuration {}
end
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
bgfxProjectBase(_kind, _defines)
copyLib()
end
|
--
-- Copyright 2010-2020 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
function filesexist(_srcPath, _dstPath, _files)
for _, file in ipairs(_files) do
file = path.getrelative(_srcPath, file)
local filePath = path.join(_dstPath, file)
if not os.isfile(filePath) then return false end
end
return true
end
function overridefiles(_srcPath, _dstPath, _files)
local remove = {}
local add = {}
for _, file in ipairs(_files) do
file = path.getrelative(_srcPath, file)
local filePath = path.join(_dstPath, file)
if not os.isfile(filePath) then return end
table.insert(remove, path.join(_srcPath, file))
table.insert(add, filePath)
end
removefiles {
remove,
}
files {
add,
}
end
function bgfxProjectBase(_kind, _defines)
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
links {
"bimg",
"bx",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
links {
"X11",
"GL",
"pthread",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BX_DIR, "include"),
path.join(BIMG_DIR, "include"),
}
defines {
_defines,
}
links {
"bx",
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "vs* or mingw*", "not durango" }
includedirs {
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "winstore*" }
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 { "*clang*" }
buildoptions {
"-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int'
"-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension
}
configuration { "osx" }
buildoptions { "-x objective-c++" } -- additional build option for osx
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
"-weak_framework MetalKit",
}
configuration { "not NX32", "not NX64" }
includedirs {
-- NX has EGL headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
path.join(BGFX_DIR, "scripts/**.natvis"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-gnm"), {
path.join(BGFX_DIR, "src/renderer_gnm.cpp"),
path.join(BGFX_DIR, "src/renderer_gnm.h"),
})
overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-nvn"), {
path.join(BGFX_DIR, "src/renderer_nvn.cpp"),
path.join(BGFX_DIR, "src/renderer_nvn.h"),
})
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/debug_**.cpp"),
path.join(BGFX_DIR, "src/dxgi.cpp"),
path.join(BGFX_DIR, "src/glcontext_**.cpp"),
path.join(BGFX_DIR, "src/hmd**.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/nvapi.cpp"),
path.join(BGFX_DIR, "src/renderer_**.cpp"),
path.join(BGFX_DIR, "src/shader**.cpp"),
path.join(BGFX_DIR, "src/topology.cpp"),
path.join(BGFX_DIR, "src/vertexlayout.cpp"),
}
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/amalgamated.mm"),
}
excludes {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration { "not (xcode* or osx or ios*)" }
excludes {
path.join(BGFX_DIR, "src/**.mm"),
}
configuration {}
else
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-gnm"), {
path.join(BGFX_DIR, "scripts/bgfx.lua"), }) then
dofile(path.join(BGFX_DIR, "../bgfx-gnm/scripts/bgfx.lua") )
end
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-nvn"), {
path.join(BGFX_DIR, "scripts/bgfx.lua"), }) then
dofile(path.join(BGFX_DIR, "../bgfx-nvn/scripts/bgfx.lua") )
end
configuration {}
end
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
bgfxProjectBase(_kind, _defines)
copyLib()
end
|
Fixed #2128.
|
Fixed #2128.
|
Lua
|
bsd-2-clause
|
mendsley/bgfx,LWJGL-CI/bgfx,bkaradzic/bgfx,bkaradzic/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,jdryg/bgfx,jpcy/bgfx,jpcy/bgfx,LWJGL-CI/bgfx,mendsley/bgfx,bkaradzic/bgfx,mendsley/bgfx,jdryg/bgfx,jdryg/bgfx,LWJGL-CI/bgfx,jpcy/bgfx,jpcy/bgfx,emoon/bgfx,jdryg/bgfx,emoon/bgfx,emoon/bgfx
|
4d1ba1ecc6326a294bf92188e8895aad0873d5dd
|
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 <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
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.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
svc:value("", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "")
url.rmempty = true
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
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("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", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
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", translate("min"))
unit:value("hours", translate("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", translate("min"))
unit:value("hours", translate("h"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
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.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = false
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
function svc.cfgvalue(...)
local v = Value.cfgvalue(...)
if not v or #v == 0 then
return "-"
else
return v
end
end
function svc.write(self, section, value)
if value == "-" then
m.uci:delete("ddns", section, self.option)
else
Value.write(self, section, value)
end
end
svc:value("-", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "-")
url.rmempty = true
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
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("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", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
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", translate("min"))
unit:value("hours", translate("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", translate("min"))
unit:value("hours", translate("h"))
return m
|
applications/luci-ddns: fix selection of custom update_url
|
applications/luci-ddns: fix selection of custom update_url
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6588 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
168d9f3de5c1c082efc3a9d013873f79cba66919
|
test/runner.lua
|
test/runner.lua
|
#!/usr/bin/lua
assert(arg[1], "No test files specified")
local gumbo = require "gumbo"
local serialize = require "gumbo.serialize.html5lib"
local util = require "gumbo.serialize.util"
local Buffer = util.Buffer
local verbose = os.getenv "VERBOSE"
local results = {pass = 0, fail = 0, skip = 0, n = 0}
local start = os.clock()
local function printf(...)
io.stdout:write(string.format(...))
end
local function parse_testdata(filename)
local tests = {[0] = {}, n = 0}
local buffer = Buffer()
local field = false
local linenumber = 0
for line in io.lines(filename) do
linenumber = linenumber + 1
local section = line:match("^#(.*)$")
if section then
tests[tests.n][field] = buffer:concat("\n")
buffer = Buffer()
field = section
if section == "data" then
tests.n = tests.n + 1
tests[tests.n] = {line = linenumber}
end
else
buffer:append(line)
end
end
tests[tests.n][field] = buffer:concat("\n") .. "\n"
if tests.n > 0 then
return tests
else
return nil, "No test data found in " .. filename
end
end
for i = 1, #arg do
local filename = arg[i]
local tests = assert(parse_testdata(filename))
local result = {
filename = filename,
basename = filename:gsub("(.*/)(.*)", "%2"),
pass = 0,
fail = 0
}
for i = 1, tests.n do
local test = tests[i]
if test["document-fragment"] then
-- TODO: handle fragment tests
results.skip = results.skip + 1
else
local document = assert(gumbo.parse(test.data))
local serialized = serialize(document)
if serialized == test.document then
result.pass = result.pass + 1
else
result.fail = result.fail + 1
if verbose then
printf("%s\n", string.rep("=", 76))
printf("%s:%d: Test %d failed\n", filename, test.line, i)
printf("%s\n\n", string.rep("=", 76))
printf("Input:\n%s\n\n", test.data)
printf("Expected:\n%s\n", test.document)
printf("Received:\n%s\n", serialized)
end
end
end
end
results.n = results.n + 1
results[results.n] = result
results.pass = results.pass + result.pass
results.fail = results.fail + result.fail
end
for i = 1, results.n do
local r = results[i]
printf("%s: %d passed, %d failed\n", r.basename, r.pass, r.fail)
end
local total = results.pass + results.fail + results.skip
printf("\nRan %d tests in %.2fs\n\n", total, os.clock() - start)
printf("Passed: %d\nFailed: %d\n", results.pass, results.fail)
printf("Skipped: %d\n\n", results.skip)
os.exit(results.fail == 0)
|
#!/usr/bin/lua
assert(arg[1], "No test files specified")
local gumbo = require "gumbo"
local serialize = require "gumbo.serialize.html5lib"
local util = require "gumbo.serialize.util"
local Buffer = util.Buffer
local verbose = os.getenv "VERBOSE"
local results = {pass = 0, fail = 0, skip = 0, n = 0}
local start = os.clock()
local function printf(...)
io.stdout:write(string.format(...))
end
local function parse_testdata(filename)
local file = assert(io.open(filename))
local text = assert(file:read("*a"))
file:close()
local tests = {[0] = {}, n = 0}
local buffer = Buffer()
local field = false
local linenumber = 0
for line in text:gmatch "([^\n]*)\n" do
linenumber = linenumber + 1
local section = line:match("^#(.*)$")
if section then
tests[tests.n][field] = buffer:concat("\n")
buffer = Buffer()
field = section
if section == "data" then
tests.n = tests.n + 1
tests[tests.n] = {line = linenumber}
end
else
buffer:append(line)
end
end
tests[tests.n][field] = buffer:concat("\n") .. "\n"
if tests.n > 0 then
return tests
else
return nil, "No test data found in " .. filename
end
end
for i = 1, #arg do
local filename = arg[i]
local tests = assert(parse_testdata(filename))
local result = {
filename = filename,
basename = filename:gsub("(.*/)(.*)", "%2"),
pass = 0,
fail = 0
}
for i = 1, tests.n do
local test = tests[i]
if test["document-fragment"] then
-- TODO: handle fragment tests
results.skip = results.skip + 1
else
local document = assert(gumbo.parse(test.data))
local serialized = serialize(document)
if serialized == test.document then
result.pass = result.pass + 1
else
result.fail = result.fail + 1
if verbose then
printf("%s\n", string.rep("=", 76))
printf("%s:%d: Test %d failed\n", filename, test.line, i)
printf("%s\n\n", string.rep("=", 76))
printf("Input:\n%s\n\n", test.data)
printf("Expected:\n%s\n", test.document)
printf("Received:\n%s\n", serialized)
end
end
end
end
results.n = results.n + 1
results[results.n] = result
results.pass = results.pass + result.pass
results.fail = results.fail + result.fail
end
for i = 1, results.n do
local r = results[i]
printf("%s: %d passed, %d failed\n", r.basename, r.pass, r.fail)
end
local total = results.pass + results.fail + results.skip
printf("\nRan %d tests in %.2fs\n\n", total, os.clock() - start)
printf("Passed: %d\nFailed: %d\n", results.pass, results.fail)
printf("Skipped: %d\n\n", results.skip)
os.exit(results.fail)
|
Fix test runner...
|
Fix test runner...
The io.lines() iterator truncates any line that contains embedded zeros
and was causing a few html5lib tests to fail. As a replacement, we read
the file into memory and iterate over lines with a gmatch pattern.
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
5ec0c7800fc351e7ff762e9a487174933a7ce26f
|
util/timer.lua
|
util/timer.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local event = require "net.server".event;
local event_base = require "net.server".event_base;
local math_min = math.min
local math_huge = math.huge
local get_time = require "socket".gettime;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local _add_task;
if not event then
function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else
func();
end
end
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in pairs(new_data) do
t_insert(data, d);
end
new_data = {};
end
local next_time = math_huge;
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
data[i] = nil;
local r = func(current_time);
if type(r) == "number" then
_add_task(r, func);
next_time = math_min(next_time, r);
end
else
next_time = math_min(next_time, t - current_time);
end
end
return next_time;
end);
else
local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
function _add_task(delay, func)
local event_handle;
event_handle = event_base:addevent(nil, 0, function ()
local ret = func();
if ret then
return 0, ret;
elseif event_handle then
return EVENT_LEAVE;
end
end
, delay);
end
end
add_task = _add_task;
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local event = require "net.server".event;
local event_base = require "net.server".event_base;
local math_min = math.min
local math_huge = math.huge
local get_time = require "socket".gettime;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local _add_task;
if not event then
function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else
local r = func();
if r and type(r) == "number" then
return _add_task(r, func);
end
end
end
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in pairs(new_data) do
t_insert(data, d);
end
new_data = {};
end
local next_time = math_huge;
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
data[i] = nil;
local r = func(current_time);
if type(r) == "number" then
_add_task(r, func);
next_time = math_min(next_time, r);
end
else
next_time = math_min(next_time, t - current_time);
end
end
return next_time;
end);
else
local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
function _add_task(delay, func)
local event_handle;
event_handle = event_base:addevent(nil, 0, function ()
local ret = func();
if ret then
return 0, ret;
elseif event_handle then
return EVENT_LEAVE;
end
end
, delay);
end
end
add_task = _add_task;
return _M;
|
util.timer: Fix corner case of timer not repeating if it returns <= 0
|
util.timer: Fix corner case of timer not repeating if it returns <= 0
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
ae6ed497194b81d4bdd18fbea6fdee7de946341e
|
utils/json.lua
|
utils/json.lua
|
require "luv.string"
require "luv.table"
local type, pairs, table, string, tostring = type, pairs, table, string, tostring
module(...)
local function to (self, seen)
local seen = seen or {}
if "boolean" == type(self) then
return self and "true" or "false"
elseif "string" == type(self) then
return "\""..string.escape(self).."\""
elseif "number" == type(self) then
return tostring(self)
elseif "table" == type(self) then
table.insert(seen, self)
local res, first, k, v = "{", true
for k, v in pairs(self) do
local vType = type(v)
if "function" ~= vType and "userdata" ~= vType then
if first then
first = false
else
res = res..","
end
if ("table" == vType and not table.find(seen, v)) or "table" ~= vType then
if "string" == type(k) then
res = res.."\""..string.escape(k).."\":"..to(v, seen)
else
res = res..k..":"..to(v, seen)
end
end
end
end
table.removeValue(seen, self)
return res.."}"
else
return "null"
end
end
return {to=to}
|
require "luv.string"
require "luv.table"
local type, pairs, table, string, tostring = type, pairs, table, string, tostring
module(...)
local function to (self, seen)
local seen = seen or {}
if "boolean" == type(self) then
return self and "true" or "false"
elseif "string" == type(self) then
return string.format("%q", self)
elseif "number" == type(self) then
return tostring(self)
elseif "table" == type(self) then
table.insert(seen, self)
local res, first, k, v = "{", true
for k, v in pairs(self) do
local vType = type(v)
if "function" ~= vType and "userdata" ~= vType then
if first then
first = false
else
res = res..","
end
if ("table" == vType and not table.find(seen, v)) or "table" ~= vType then
if "string" == type(k) then
res = res..string.format("%q", k)..":"..to(v, seen)
else
res = res..k..":"..to(v, seen)
end
end
end
end
table.removeValue(seen, self)
return res.."}"
else
return "null"
end
end
return {to=to}
|
Fixed utils.json.
|
Fixed utils.json.
|
Lua
|
bsd-3-clause
|
metadeus/luv
|
58b1978c7e804897244a647fe911296acf434268
|
levent/loop.lua
|
levent/loop.lua
|
local class = require "levent.class"
local ev = require "levent.ev.c"
local tpack = table.pack
local tunpack = table.unpack
local function wrap_callback(f, ...)
if select("#", ...) > 0 then
local args = tpack(...)
return function()
return xpcall(f, debug.traceback, tunpack(args, 1, args.n))
end
else
return function()
return xpcall(f, debug.traceback)
end
end
end
local Watcher = class("Watcher")
function Watcher:_init(name, loop, ...)
self.loop = loop
local w = ev["new_" .. name]()
w:init(...)
self.cobj = w
self._cb = nil
self._args = nil
end
function Watcher:id()
return self.cobj:id()
end
function Watcher:start(func, ...)
assert(self._cb == nil, self.cobj)
self._cb = wrap_callback(func, ...)
self.cobj:start(self.loop.cobj)
end
function Watcher:stop()
self._cb = nil
self._args = nil
self.cobj:stop(self.loop.cobj)
end
function Watcher:run_callback(revents)
-- unused revents
local ok, msg = self._cb()
if not ok then
self.loop:handle_error(self, msg)
end
end
function Watcher:is_active()
return self.cobj:is_active()
end
function Watcher:is_pending()
return self.cobj:is_pending()
end
function Watcher:get_priority()
return self.cobj:get_priority()
end
function Watcher:set_priority(priority)
return self.cobj:set_priority(priority)
end
function Watcher:__tostring()
return tostring(self.cobj)
end
function Watcher:__gc()
self:stop()
end
local Loop = class("Loop")
function Loop:_init()
self.cobj = ev.default_loop()
self.watchers = setmetatable({}, {__mode="v"})
-- register prepare
self._callbacks = {}
self._prepare = self:_create_watcher("prepare")
self._prepare:start(function(revents)
self:_run_callback(revents)
end)
self.cobj:unref()
end
function Loop:run(--[[nowait, once]])
local flags = 0
self.cobj:run(flags, self.callback, self)
end
function Loop:_break(how)
if not how then
how = ev.EVBREAK_ALL
end
self.cobj:_break(how)
end
function Loop:verify()
return self.cobj:verify()
end
function Loop:now()
return self.cobj:now()
end
function Loop:_add_watchers(w)
self.watchers[w:id()] = w
end
function Loop:_create_watcher(name, ...)
local o = Watcher.new(name, self, ...)
self:_add_watchers(o)
return o
end
function Loop:io(fd, events)
return self:_create_watcher("io", fd, events)
end
function Loop:timer(after, rep)
return self:_create_watcher("timer", after, rep)
end
function Loop:signal(signum)
return self:_create_watcher("signal", signum)
end
function Loop:callback(id, revents)
local w = assert(self.watchers[id], id)
w:run_callback(revents)
end
function Loop:_run_callback(revents)
while #self._callbacks > 0 do
local callbacks = self._callbacks
self._callbacks = {}
for _, cb in ipairs(callbacks) do
self.cobj:unref()
local ok, msg = cb()
if not ok then
self:handle_error(self._prepare, msg)
end
end
end
end
function Loop:run_callback(func, ...)
self._callbacks[#self._callbacks + 1] = wrap_callback(func, ...)
self.cobj:ref()
end
function Loop:handle_error(watcher, msg)
print("error:", watcher, msg)
end
local loop = {}
function loop.new()
local obj = Loop.new()
for k,v in pairs(ev) do
if type(v) ~= "function" then
obj[k] = v
end
end
return obj
end
return loop
|
local class = require "levent.class"
local ev = require "levent.ev.c"
local tpack = table.pack
local tunpack = table.unpack
local function wrap_callback(f, ...)
if select("#", ...) > 0 then
local args = tpack(...)
return function()
return xpcall(f, debug.traceback, tunpack(args, 1, args.n))
end
else
return function()
return xpcall(f, debug.traceback)
end
end
end
local Watcher = class("Watcher")
function Watcher:_init(name, loop, ...)
self.loop = loop
local w = ev["new_" .. name]()
w:init(...)
self.cobj = w
self._cb = nil
self._args = nil
end
function Watcher:id()
return self.cobj:id()
end
function Watcher:start(func, ...)
assert(self._cb == nil, self.cobj)
self._cb = func
if select("#", ...) > 0 then
self._args = tpack(...)
end
self.cobj:start(self.loop.cobj)
end
function Watcher:stop()
self._cb = nil
self._args = nil
self.cobj:stop(self.loop.cobj)
end
function Watcher:run_callback(revents)
-- unused revents
local ok, msg
if self._args then
ok, msg = xpcall(self._cb, debug.traceback, tunpack(self._args, 1, self._args.n))
else
ok, msg = xpcall(self._cb, debug.traceback)
end
if not ok then
self.loop:handle_error(self, msg)
end
end
function Watcher:is_active()
return self.cobj:is_active()
end
function Watcher:is_pending()
return self.cobj:is_pending()
end
function Watcher:get_priority()
return self.cobj:get_priority()
end
function Watcher:set_priority(priority)
return self.cobj:set_priority(priority)
end
function Watcher:__tostring()
return tostring(self.cobj)
end
function Watcher:__gc()
self:stop()
end
local Loop = class("Loop")
function Loop:_init()
self.cobj = ev.default_loop()
self.watchers = setmetatable({}, {__mode="v"})
-- register prepare
self._callbacks = {}
self._prepare = self:_create_watcher("prepare")
self._prepare:start(function(revents)
self:_run_callback(revents)
end)
self.cobj:unref()
end
function Loop:run(--[[nowait, once]])
local flags = 0
self.cobj:run(flags, self.callback, self)
end
function Loop:_break(how)
if not how then
how = ev.EVBREAK_ALL
end
self.cobj:_break(how)
end
function Loop:verify()
return self.cobj:verify()
end
function Loop:now()
return self.cobj:now()
end
function Loop:_add_watchers(w)
self.watchers[w:id()] = w
end
function Loop:_create_watcher(name, ...)
local o = Watcher.new(name, self, ...)
self:_add_watchers(o)
return o
end
function Loop:io(fd, events)
return self:_create_watcher("io", fd, events)
end
function Loop:timer(after, rep)
return self:_create_watcher("timer", after, rep)
end
function Loop:signal(signum)
return self:_create_watcher("signal", signum)
end
function Loop:callback(id, revents)
local w = assert(self.watchers[id], id)
w:run_callback(revents)
end
function Loop:_run_callback(revents)
while #self._callbacks > 0 do
local callbacks = self._callbacks
self._callbacks = {}
for _, cb in ipairs(callbacks) do
self.cobj:unref()
local ok, msg = cb()
if not ok then
self:handle_error(self._prepare, msg)
end
end
end
end
function Loop:run_callback(func, ...)
self._callbacks[#self._callbacks + 1] = wrap_callback(func, ...)
self.cobj:ref()
end
function Loop:handle_error(watcher, msg)
print("error:", watcher, msg)
end
local loop = {}
function loop.new()
local obj = Loop.new()
for k,v in pairs(ev) do
if type(v) ~= "function" then
obj[k] = v
end
end
return obj
end
return loop
|
bugfix: cancel wait failed
|
bugfix: cancel wait failed
|
Lua
|
mit
|
xjdrew/levent
|
ea307d18185a43d6ce86e1185d96ca7751f18dd0
|
modules/vim/installed-config/plugin/lspconfig.lua
|
modules/vim/installed-config/plugin/lspconfig.lua
|
local nvim_lsp = require('lspconfig')
local null_ls = require('null-ls')
local cmp_nvim_lsp = require('cmp_nvim_lsp')
vim.fn.sign_define("DiagnosticSignError", { text = ' ', texthl = 'DiagnosticSignError' })
vim.fn.sign_define("DiagnosticSignWarn", { text = ' ', texthl = 'DiagnosticSignWarn' })
vim.fn.sign_define("DiagnosticSignInformation", { text = ' ', texthl = 'DiagnosticSignInfo' })
vim.fn.sign_define("DiagnosticSignHint", { text = ' ', texthl = 'DiagnosticSignHint' })
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'gy', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>fn', '<cmd>lua vim.diagnostic.goto_next()<cr>', opts)
buf_set_keymap('n', '<space>fp', '<cmd>lua vim.diagnostic.goto_prev()<cr>', opts)
buf_set_keymap('n', '<space>ff', '<cmd>lua vim.diagnostic.open_float()<cr>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ra', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', '<space>rf', '<cmd>lua vim.lsp.buf.formatting()<cr>', opts)
buf_set_keymap('v', '<space>rf', '<cmd>lua vim.lsp.buf.range_formatting()<cr>', opts)
end
-- Use a loop to conveniently call 'setup' on multiple servers and
-- map buffer local keybindings when the language server attaches
local servers = { 'ccls', 'tsserver', 'solargraph', 'bashls', 'pylsp' }
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
capabilities = capabilities,
on_attach = on_attach,
flags = {
debounce_text_changes = 150,
}
}
end
null_ls.setup({
debug = true,
on_attach = on_attach,
sources = {
null_ls.builtins.formatting.rubocop.with({
command = 'bundle',
args = vim.list_extend(
{ "exec", "rubocop" },
require("null-ls").builtins.diagnostics.rubocop._opts.args
)
}),
null_ls.builtins.diagnostics.rubocop.with({
command = 'bundle',
args = vim.list_extend(
{ "exec", "rubocop" },
require("null-ls").builtins.diagnostics.rubocop._opts.args
)
}),
null_ls.builtins.diagnostics.shellcheck,
null_ls.builtins.formatting.prettier,
null_ls.builtins.diagnostics.cppcheck,
null_ls.builtins.diagnostics.markdownlint,
null_ls.builtins.diagnostics.yamllint.with({ filetypes = {'yaml'} }),
null_ls.builtins.code_actions.shellcheck,
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.diagnostics.hadolint,
null_ls.builtins.diagnostics.flake8,
}
})
require('rust-tools').setup {
tools = { -- rust-tools options
hover_with_actions = false,
inlay_hints = {
parameter_hints_prefix = "◀ ",
other_hints_prefix = "▶ ",
},
runnables = { use_telescope = false },
},
server = {
on_attach = on_attach,
}
}
|
local nvim_lsp = require('lspconfig')
local null_ls = require('null-ls')
local cmp_nvim_lsp = require('cmp_nvim_lsp')
vim.fn.sign_define("DiagnosticSignError", { text = ' ', texthl = 'DiagnosticSignError' })
vim.fn.sign_define("DiagnosticSignWarn", { text = ' ', texthl = 'DiagnosticSignWarn' })
vim.fn.sign_define("DiagnosticSignInformation", { text = ' ', texthl = 'DiagnosticSignInfo' })
vim.fn.sign_define("DiagnosticSignHint", { text = ' ', texthl = 'DiagnosticSignHint' })
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'gy', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>fn', '<cmd>lua vim.diagnostic.goto_next()<cr>', opts)
buf_set_keymap('n', '<space>fp', '<cmd>lua vim.diagnostic.goto_prev()<cr>', opts)
buf_set_keymap('n', '<space>ff', '<cmd>lua vim.diagnostic.open_float()<cr>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ra', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', '<space>rf', '<cmd>lua vim.lsp.buf.formatting()<cr>', opts)
buf_set_keymap('v', '<space>rf', '<cmd>lua vim.lsp.buf.range_formatting()<cr>', opts)
end
-- Use a loop to conveniently call 'setup' on multiple servers and
-- map buffer local keybindings when the language server attaches
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
local flags = {
debounce_text_changes = 150,
}
-- Default configs
local servers = { 'ccls', 'tsserver', 'bashls', 'pylsp' }
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
capabilities = capabilities,
on_attach = on_attach,
flags = flags
}
end
-- Individual configs
nvim_lsp.solargraph.setup {
capabilities = capabilities,
on_attach = on_attach,
flags = flags,
init_options = {
formatting = false
}
}
-- Null-ls
null_ls.setup({
debug = false,
on_attach = on_attach,
diagnostics_format = '[#{c}] #{m} (#{s})',
sources = {
null_ls.builtins.formatting.rubocop.with({
command = 'bundle',
args = vim.list_extend(
{ "exec", "rubocop" },
require("null-ls").builtins.formatting.rubocop._opts.args
)
}),
null_ls.builtins.diagnostics.rubocop.with({
command = 'bundle',
args = vim.list_extend(
{ "exec", "rubocop" },
require("null-ls").builtins.diagnostics.rubocop._opts.args
)
}),
null_ls.builtins.diagnostics.shellcheck,
null_ls.builtins.formatting.prettier,
null_ls.builtins.diagnostics.cppcheck,
null_ls.builtins.diagnostics.markdownlint,
null_ls.builtins.diagnostics.yamllint.with({ filetypes = {'yaml'} }),
null_ls.builtins.code_actions.shellcheck,
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.diagnostics.hadolint,
null_ls.builtins.diagnostics.flake8,
}
})
-- Additional tools
require('rust-tools').setup {
tools = { -- rust-tools options
hover_with_actions = false,
inlay_hints = {
parameter_hints_prefix = "◀ ",
other_hints_prefix = "▶ ",
},
runnables = { use_telescope = false },
},
server = {
on_attach = on_attach,
}
}
|
Fix vim rubocop formatter
|
Fix vim rubocop formatter
|
Lua
|
mit
|
justinhoward/dotfiles,justinhoward/dotfiles
|
43b94fd8236df7de1a787cf22fcadc6dedee79ac
|
popups.lua
|
popups.lua
|
local mod = EPGP:NewModule("EPGP_Popups")
local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP")
local GPTooltip = EPGP:GetModule("EPGP_GPTooltip")
StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = {
text = L["Credit GP to %s"],
button1 = L["Full"],
button3 = L["Offspec"],
button2 = CANCEL,
timeout = 0,
whileDead = 1,
maxLetters = 16,
hideOnEscape = 1,
hasEditBox = 1,
hasItemFrame = 1,
OnAccept = function(self)
local parent = self:GetParent()
EPGP:IncGPBy(parent.name, parent.itemFrame.link, parent.editBox:GetNumber())
end,
OnCancel = function(self)
self:Hide();
ClearCursor();
end,
OnShow = function(self)
local itemFrame = getglobal(self:GetName().."ItemFrame")
local editBox = getglobal(self:GetName().."EditBox")
local button1 = getglobal(self:GetName().."Button1")
itemFrame:SetPoint("TOPLEFT", 55, -35)
editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10)
button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMLEFT", 94, -6)
editBox:SetText(GPTooltip:GetGPValue(itemFrame.link))
editBox:HighlightText()
end,
OnHide = function()
if ChatFrameEditBox:IsShown() then
ChatFrameEditBox:SetFocus();
end
end,
EditBoxOnEnterPressed = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
EPGP:IncGPBy(parent.name, parent.itemFrame.link, parent.editBox:GetNumber())
end
end,
EditBoxOnTextChanged = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
parent.button1:Enable()
parent.button3:Enable()
else
parent.button1:Disable()
parent.button3:Disable()
end
end,
EditBoxOnEscapePressed = function(self)
self:GetParent():Hide()
ClearCursor()
end
}
StaticPopupDialogs["EPGP_DECAY_EPGP"] = {
text = "",
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
hideOnEscape = 1,
whileDead = 1,
OnShow = function()
local text = getglobal(this:GetName().."Text")
text:SetFormattedText(L["Decay EP and GP by %d%%?"],
EPGP:GetDecayPercent())
end,
OnAccept = function()
EPGP:DecayEPGP()
end
}
local function Debug(fmt, ...)
DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...))
end
function mod:OnInitialize()
-- local playername = "Knucklehead"
-- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541)
-- local r, g, b = GetItemQualityColor(itemRarity);
-- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s",
-- itemName, itemLink, itemRarity, itemTexture)
-- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", {
-- texture = itemTexture,
-- name = itemName,
-- color = {r, g, b, 1},
-- link = itemLink
-- })
-- if dialog then
-- dialog.name = playername
-- end
end
|
local mod = EPGP:NewModule("EPGP_Popups")
local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP")
local GPTooltip = EPGP:GetModule("EPGP_GPTooltip")
StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = {
text = L["Credit GP to %s"],
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
whileDead = 1,
maxLetters = 16,
hideOnEscape = 1,
hasEditBox = 1,
hasItemFrame = 1,
OnAccept = function(self)
EPGP:IncGPBy(self.name, self.itemFrame.link,
self.editBox:GetNumber())
end,
OnCancel = function(self)
self:Hide();
ClearCursor();
end,
OnShow = function(self)
local itemFrame = getglobal(self:GetName().."ItemFrame")
local editBox = getglobal(self:GetName().."EditBox")
local button1 = getglobal(self:GetName().."Button1")
itemFrame:SetPoint("TOPLEFT", 35, -35)
editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10)
editBox:SetPoint("RIGHT", -35, 0)
button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMRIGHT", 85, -6)
editBox:SetText(GPTooltip:GetGPValue(itemFrame.link))
editBox:HighlightText()
end,
OnHide = function()
if ChatFrameEditBox:IsShown() then
ChatFrameEditBox:SetFocus();
end
end,
EditBoxOnEnterPressed = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
EPGP:IncGPBy(parent.name, parent.itemFrame.link, parent.editBox:GetNumber())
end
end,
EditBoxOnTextChanged = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
parent.button1:Enable()
parent.button3:Enable()
else
parent.button1:Disable()
parent.button3:Disable()
end
end,
EditBoxOnEscapePressed = function(self)
self:GetParent():Hide()
ClearCursor()
end
}
StaticPopupDialogs["EPGP_DECAY_EPGP"] = {
text = "",
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
hideOnEscape = 1,
whileDead = 1,
OnShow = function()
local text = getglobal(this:GetName().."Text")
text:SetFormattedText(L["Decay EP and GP by %d%%?"],
EPGP:GetDecayPercent())
end,
OnAccept = function()
EPGP:DecayEPGP()
end
}
local function Debug(fmt, ...)
DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...))
end
function mod:OnInitialize()
-- local playername = UnitName("player")
-- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541)
-- local r, g, b = GetItemQualityColor(itemRarity);
-- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s",
-- itemName, itemLink, itemRarity, itemTexture)
-- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", {
-- texture = itemTexture,
-- name = itemName,
-- color = {r, g, b, 1},
-- link = itemLink
-- })
-- if dialog then
-- dialog.name = playername
-- end
end
|
Fix GP popup to assign GP properly when the ACCEPT button is pressed.
|
Fix GP popup to assign GP properly when the ACCEPT button is pressed.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp
|
1a7af451d7d0b917a528579713e5d5e35379fc81
|
_Out/Server/NFDataCfg/ScriptModule/script_init.lua
|
_Out/Server/NFDataCfg/ScriptModule/script_init.lua
|
--package.path = '../../NFDataCfg/Script/?.lua;'
pLuaScriptModule = nil;
pPluginManager = nil;
function init_script_system(xPluginManager,xLuaScriptModule)
pPluginManager = xPluginManager;
pLuaScriptModule = xLuaScriptModule;
io.write("\nHello Lua pPluginManager:" .. tostring(pPluginManager) .. " pLuaScriptModule:" .. tostring(pLuaScriptModule) .."\n\n");
io.write();
end
function load_script_file(name)
for key, value in pairs(name) do
if type(value) == "table" then
local tblObject = nil;
for k, v in pairs(value) do
if package.loaded[v] then
else
local object = require(v);
if nil == object then
io.write("load_script_file " .. v .. " failed\n");
else
io.write("load_script_file " .. v .. " successed\n");
end
end
end
end
end
end
function reload_script_file( name )
if package.loaded[name] then
package.loaded[name] = nil
end
load_script_file( name )
end
function reload_script_table( name )
io.write("----Begin reload lua list----\n");
for key, value in pairs(name) do
if type(value) == "table" then
local tblObject = nil;
for k, v in pairs(value) do
reload_script_file(tostring(value))
end
end
end
io.write("----End reload lua list----\n");
end
function register_module(tbl, name)
if ScriptList then
for key, value in pairs(ScriptList) do
local tblObject = nil;
if type(value) == "table" then
for k, v in pairs(value) do
if v == name then
tblObject = tbl;
end
end
end
if tblObject ~= nil then
io.write("----register_module successed----\n");
ScriptList[key].tbl = tblObject;
end
end
end
if ScriptReloadList then
for key, value in pairs(ScriptReloadList) do
local tblObject = nil;
if type(value) == "table" then
for k, v in pairs(value) do
if v == name then
tblObject = tbl;
end
end
end
if tblObject ~= nil then
io.write("----register_module successed----\n");
ScriptReloadList[key].tbl = tblObject;
end
end
end
end
|
--package.path = '../../NFDataCfg/Script/?.lua;'
pLuaScriptModule = nil;
pPluginManager = nil;
function init_script_system(xPluginManager,xLuaScriptModule)
pPluginManager = xPluginManager;
pLuaScriptModule = xLuaScriptModule;
io.write("\nHello Lua pPluginManager:" .. tostring(pPluginManager) .. " pLuaScriptModule:" .. tostring(pLuaScriptModule) .."\n\n");
io.write();
end
function load_script_file(name)
for key, value in pairs(name) do
if type(value) == "table" then
local tblObject = nil;
for k, v in pairs(value) do
if package.loaded[v] then
else
local object = require(v);
if nil == object then
io.write("load_script_file " .. v .. " failed\n");
else
io.write("load_script_file " .. v .. " successed\n");
end
end
end
end
end
end
function reload_script_file( name )
if package.loaded[name] then
package.loaded[name] = nil
end
local object = require(name);
if nil == object then
io.write(" reload_script_file " .. name .. " failed\n");
else
io.write(" reload_script_file " .. name .. " successed\n");
end
end
function reload_script_table( name )
io.write("----Begin reload lua list----\n");
for key, value in pairs(name) do
if type(value) == "table" then
local tblObject = nil;
for k, v in pairs(value) do
io.write("reload script : " .. tostring(v) .. "\n");
reload_script_file(v)
end
end
end
io.write("----End reload lua list----\n");
end
function register_module(tbl, name)
if ScriptList then
for key, value in pairs(ScriptList) do
local tblObject = nil;
if type(value) == "table" then
for k, v in pairs(value) do
if v == name then
tblObject = tbl;
end
end
end
if tblObject ~= nil then
ScriptList[key].tbl = tblObject;
end
end
end
if ScriptReloadList then
for key, value in pairs(ScriptReloadList) do
local tblObject = nil;
if type(value) == "table" then
for k, v in pairs(value) do
if v == name then
tblObject = tbl;
end
end
end
if tblObject ~= nil then
ScriptReloadList[key].tbl = tblObject;
end
end
end
end
|
fixed ScriptModule
|
fixed ScriptModule
|
Lua
|
apache-2.0
|
lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame
|
635412bb786a2e8c2c6b4e4fae63ec386a16c96f
|
src/lluv/websocket/luasocket.lua
|
src/lluv/websocket/luasocket.lua
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Copyright (C) 2016 Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-websocket library.
--
------------------------------------------------------------------
---
-- Implement LuaSocket API on top of WebSocket
--
-- socket:bind(url, application)
-- e.g. socket:bind("ws://127.0.0.1:5555", "echo")
--
-- socket:connect(url, application)
-- e.g. socket:connect("ws://127.0.0.1:5555", "echo")
--
-- socket:receive([pat])
-- supports only 2 patterns
-- `*r` - return any recived data (can return not full frame)
-- `*l` - return entire frame
-- also `receive` returns `opcode` and `fin`
--
-- socket:send(frame[, opcode])
--
local trace -- = function(...) print(os.date("[LWS][%x %X]"), ...) end
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.luasocket"
local ws = require "lluv.websocket"
local unpack = unpack or table.unpack
local tconcat = table.concat
local tappend = function(t, v) t[#t + 1] = v return t end
local WsSocket = ut.class(socket._TcpSocket) do
local function is_sock(s)
local ts = type(s)
if ts == 'userdata' then return true end
if ts ~= 'table' then return false end
return
s.start_read and
s.write and
s.connect and
true
end
local function is_ws_sock(s)
return is_sock(s) and
s._client_handshake and
s._server_handshake and
true
end
function WsSocket:__init(p)
if is_sock(p) then
WsSocket.__base.__init(self, p)
else
self._ws_opt = p
WsSocket.__base.__init(self)
end
return self
end
function WsSocket:_reset()
if self._sock then self._sock:close() end
self._sock = ws.new(self._ws_opt)
end
function WsSocket:_start_read()
self._sock:start_read("*f", function(cli, err, data, opcode, fin)
if err then return self:_on_io_error(err) end
if data then self._buf:append{data, opcode, fin} end
if self:_waiting("read") then return self:_resume(true) end
end)
self._frame = {}
return self
end
function WsSocket:receive(mode)
while true do
local frame, err = WsSocket.__base.receive(self, '*r')
if not frame then return nil, err end
if mode == '*r' then return unpack(frame) end
local opcode = frame[2]
if opcode == ws.PING or opcode == ws.PONG then
return frame[1], opcode, true
end
if not self._opcode then
self._frame, self._opcode = {}, opcode
end
tappend(self._frame, frame[1])
if frame[3] then
local msg, opcode = tconcat(self._frame), self._opcode
self._frame, self._opcode = nil
return msg, opcode, true
end
end
end
function WsSocket:send(data, opcode, fin)
if not self._sock then return nil, self._err end
local terminated
local function fn(cli, err)
if trace then trace("SEND CB>", self, #data, opcode, fin, fn) end
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true)
end;
if trace then trace("SEND>", self, #data, opcode, fin, fn) end
self:_start("write")
self._sock:write(data, opcode, fin, fn)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
return nil, self._err
end
return ok, err
end
function WsSocket:_connect(url, proto)
self:_start("conn")
local terminated
self._sock:connect(url, proto, function(sock, err, headers)
if terminated then return end
return self:_resume(not err, err, headers)
end)
local ok, err, headers = self:_yield()
terminated = true
self:_stop("conn")
if not ok then
self:_reset()
return nil, err
end
return self, headers
end
function WsSocket:connect(host, port)
local ok, err = self:_connect(host, port)
if not ok then return nil, err end
local headers = err
ok, err = self:_start_read()
if not ok then return nil, err end
return self, headers
end
function WsSocket:accept()
local cli, err = self:_accept()
if not cli then return nil, err end
return cli:handshake()
end
function WsSocket:handshake()
if not self._sock then return nil, self._err end
local terminated
self:_start("write")
self._sock:handshake(function(cli, err, protocol, headers)
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true, nil, protocol, headers)
end)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
self._sock:stop_read()
return nil, self._err
end
local ok, err, protocol, headers = self:_start_read()
if not ok then return nil, err end
return self, protocol, headers
end
function WsSocket:__tostring()
return "lluv.ws.luasocket (" .. tostring(self._sock) .. ")"
end
end
return {
ws = WsSocket.new;
TEXT = ws.TEXT;
BINARY = ws.BINARY;
PING = ws.PING;
PONG = ws.PONG;
CONTINUATION = ws.CONTINUATION;
CLOSE = ws.CLOSE;
_WsSocket = WsSocket
}
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Copyright (C) 2016 Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-websocket library.
--
------------------------------------------------------------------
---
-- Implement LuaSocket API on top of WebSocket
--
-- socket:bind(url, application)
-- e.g. socket:bind("ws://127.0.0.1:5555", "echo")
--
-- socket:connect(url, application)
-- e.g. socket:connect("ws://127.0.0.1:5555", "echo")
--
-- socket:receive([pat])
-- supports only 2 patterns
-- `*r` - return any recived data (can return not full frame)
-- `*l` - return entire frame
-- also `receive` returns `opcode` and `fin`
--
-- socket:send(frame[, opcode])
--
local trace -- = function(...) print(os.date("[LWS][%x %X]"), ...) end
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.luasocket"
local ws = require "lluv.websocket"
local unpack = unpack or table.unpack
local tconcat = table.concat
local tappend = function(t, v) t[#t + 1] = v return t end
local WsSocket = ut.class(socket._TcpSocket) do
local function is_sock(s)
local ts = type(s)
if ts == 'userdata' then return true end
if ts ~= 'table' then return false end
return
s.start_read and
s.write and
s.connect and
true
end
local function is_ws_sock(s)
return is_sock(s) and
s._client_handshake and
s._server_handshake and
true
end
function WsSocket:__init(p)
if is_sock(p) then
WsSocket.__base.__init(self, p)
else
self._ws_opt = p
WsSocket.__base.__init(self)
end
return self
end
function WsSocket:_reset()
if self._sock then self._sock:close() end
self._sock = ws.new(self._ws_opt)
end
function WsSocket:_start_read()
self._sock:start_read("*f", function(cli, err, data, opcode, fin)
if err then return self:_on_io_error(err) end
if data then self._buf:append{data, opcode, fin} end
if self:_waiting("read") then return self:_resume(true) end
end)
self._frame = {}
return self
end
function WsSocket:receive(mode)
while true do
local frame, err = WsSocket.__base.receive(self, '*r')
if not frame then return nil, err end
if mode == '*r' then return unpack(frame) end
local opcode = frame[2]
if opcode == ws.PING or opcode == ws.PONG then
return frame[1], opcode, true
end
if not self._opcode then
self._frame, self._opcode = {}, opcode
end
tappend(self._frame, frame[1])
if frame[3] then
local msg, opcode = tconcat(self._frame), self._opcode
self._frame, self._opcode = nil
return msg, opcode, true
end
end
end
function WsSocket:send(data, opcode, fin)
if not self._sock then return nil, self._err end
local terminated
local function fn(cli, err)
if trace then trace("SEND CB>", self, #data, opcode, fin, fn) end
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true)
end;
if trace then trace("SEND>", self, #data, opcode, fin, fn) end
self:_start("write")
self._sock:write(data, opcode, fin, fn)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
return nil, self._err
end
return ok, err
end
function WsSocket:_connect(url, proto)
self:_start("conn")
local terminated
self._sock:connect(url, proto, function(sock, err, headers)
if terminated then return end
return self:_resume(not err, err, headers)
end)
local ok, err, headers = self:_yield()
terminated = true
self:_stop("conn")
if not ok then
self:_reset()
return nil, err
end
return self, headers
end
function WsSocket:connect(host, port)
local ok, err = self:_connect(host, port)
if not ok then return nil, err end
local headers = err
ok, err = self:_start_read()
if not ok then return nil, err end
return self, headers
end
function WsSocket:accept()
local cli, err = self:_accept()
if not cli then return nil, err end
return cli:handshake()
end
function WsSocket:handshake()
if not self._sock then return nil, self._err end
local terminated
self:_start("write")
self._sock:handshake(function(cli, err, protocol, headers)
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true, nil, protocol, headers)
end)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
self._sock:stop_read()
return nil, self._err
end
local ok, err, protocol, headers = self:_start_read()
if not ok then return nil, err end
return self, protocol, headers
end
function WsSocket:__tostring()
return "lluv.ws.luasocket (" .. tostring(self._sock) .. ")"
end
function WsSocket:close(code, reason)
if self._sock then
local terminated
local function fn(cli, clean, code, reason)
if trace then trace("CLOSE CB>", self, clean, code, reason) end
if terminated then return end
return self:_resume(clean, code, reason)
end;
if trace then trace("CLOSE>", self, code, reason, fn) end
self:_start("write")
self._sock:close(code, reason, fn)
local ok, code, reason = self:_yield()
terminated = true
self:_stop("write")
self._sock = nil
return ok, code, reason
end
end
end
return {
ws = WsSocket.new;
TEXT = ws.TEXT;
BINARY = ws.BINARY;
PING = ws.PING;
PONG = ws.PONG;
CONTINUATION = ws.CONTINUATION;
CLOSE = ws.CLOSE;
_WsSocket = WsSocket
}
|
Fix. LuaSocket API close method return code and reason.
|
Fix. LuaSocket API close method return code and reason.
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
d269a3c3b7896cfe5a03bc0fed8c56d96d563be2
|
src/luarocks/purge.lua
|
src/luarocks/purge.lua
|
--- Module implementing the LuaRocks "purge" command.
-- Remove all rocks from a given tree.
module("luarocks.purge", package.seeall)
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local repos = require("luarocks.repos")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
local remove = require("luarocks.remove")
help_summary = "Remove all installed rocks from a tree."
help_arguments = "--tree=<tree> [--old-versions]"
help = [[
This command removes rocks en masse from a given tree.
By default, it removes all rocks from a tree.
The --tree argument is mandatory: luarocks purge does not
assume a default tree.
--old-versions Keep the highest-numbered version of each
rock and remove the other ones. By default
it only removes old versions if they are
not needed as dependencies. This can be
overridden with the flag --force.
]]
function run(...)
local flags = util.parse_flags(...)
local tree = flags["tree"]
if type(tree) ~= "string" then
return nil, "The --tree argument is mandatory. "..util.see_help("purge")
end
local results = {}
local query = search.make_query("")
query.exact_name = false
if not fs.is_dir(tree) then
return nil, "Directory not found: "..tree
end
search.manifest_search(results, path.rocks_dir(tree), query)
local sort = function(a,b) return deps.compare_versions(b,a) end
if flags["old-versions"] then
sort = deps.compare_versions
end
for package, versions in util.sortedpairs(results) do
for version, repositories in util.sortedpairs(versions, sort) do
if flags["old-versions"] then
util.printout("Keeping "..package.." "..version.."...")
local ok, err = remove.remove_other_versions(package, version, flags["force"])
if not ok then
util.printerr(err)
end
break
else
util.printout("Removing "..package.." "..version.."...")
local ok, err = repos.delete_version(package, version, true)
if not ok then
util.printerr(err)
end
end
end
end
return manif.make_manifest(cfg.rocks_dir, "one")
end
|
--- Module implementing the LuaRocks "purge" command.
-- Remove all rocks from a given tree.
module("luarocks.purge", package.seeall)
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local repos = require("luarocks.repos")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
local remove = require("luarocks.remove")
help_summary = "Remove all installed rocks from a tree."
help_arguments = "--tree=<tree> [--old-versions]"
help = [[
This command removes rocks en masse from a given tree.
By default, it removes all rocks from a tree.
The --tree argument is mandatory: luarocks purge does not
assume a default tree.
--old-versions Keep the highest-numbered version of each
rock and remove the other ones. By default
it only removes old versions if they are
not needed as dependencies. This can be
overridden with the flag --force.
]]
function run(...)
local flags = util.parse_flags(...)
local tree = flags["tree"]
if type(tree) ~= "string" then
return nil, "The --tree argument is mandatory. "..util.see_help("purge")
end
local results = {}
local query = search.make_query("")
query.exact_name = false
if not fs.is_dir(tree) then
return nil, "Directory not found: "..tree
end
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
search.manifest_search(results, path.rocks_dir(tree), query)
local sort = function(a,b) return deps.compare_versions(b,a) end
if flags["old-versions"] then
sort = deps.compare_versions
end
for package, versions in util.sortedpairs(results) do
for version, repositories in util.sortedpairs(versions, sort) do
if flags["old-versions"] then
util.printout("Keeping "..package.." "..version.."...")
local ok, err = remove.remove_other_versions(package, version, flags["force"])
if not ok then
util.printerr(err)
end
break
else
util.printout("Removing "..package.." "..version.."...")
local ok, err = repos.delete_version(package, version, true)
if not ok then
util.printerr(err)
end
end
end
end
return manif.make_manifest(cfg.rocks_dir, "one")
end
|
Fix: Purge command did not check permission for the tree to operate on
|
Fix: Purge command did not check permission for the tree to operate on
|
Lua
|
mit
|
starius/luarocks,robooo/luarocks,usstwxy/luarocks,xiaq/luarocks,aryajur/luarocks,starius/luarocks,lxbgit/luarocks,rrthomas/luarocks,ignacio/luarocks,rrthomas/luarocks,xpol/luarocks,tst2005/luarocks,ignacio/luarocks,coderstudy/luarocks,tst2005/luarocks,xiaq/luarocks,xpol/luarocks,tst2005/luarocks,rrthomas/luarocks,luarocks/luarocks,xiaq/luarocks,leafo/luarocks,keplerproject/luarocks,lxbgit/luarocks,starius/luarocks,lxbgit/luarocks,xpol/luavm,coderstudy/luarocks,usstwxy/luarocks,coderstudy/luarocks,robooo/luarocks,tst2005/luarocks,aryajur/luarocks,aryajur/luarocks,xpol/luavm,xpol/luarocks,usstwxy/luarocks,keplerproject/luarocks,tarantool/luarocks,leafo/luarocks,starius/luarocks,xpol/luainstaller,leafo/luarocks,luarocks/luarocks,lxbgit/luarocks,tarantool/luarocks,xiaq/luarocks,aryajur/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luainstaller,ignacio/luarocks,rrthomas/luarocks,xpol/luavm,xpol/luarocks,keplerproject/luarocks,xpol/luainstaller,xpol/luainstaller,luarocks/luarocks,ignacio/luarocks,robooo/luarocks,keplerproject/luarocks,xpol/luavm,xpol/luavm,usstwxy/luarocks,coderstudy/luarocks
|
dcffb39eb1b54208d1cf516e7f9868e88a27cb12
|
lua_scripts/pathmaps/simple/00_default.lua
|
lua_scripts/pathmaps/simple/00_default.lua
|
-- Copyright (C) 2007 Lauri Leukkunen <lle@rahina.org>
-- Licensed under MIT license.
--
-- "simple" mode, to be used for software development & building
-- (as the name says, this is the simple solution; See/use the "devel"
-- mode when a more full-featured environment is needed)
-- Rule file interface version, mandatory.
--
rule_file_interface_version = "24"
----------------------------------
tools = tools_root
if (not tools) then
tools = "/"
end
simple_chain = {
next_chain = nil,
binary = nil,
rules = {
-- -----------------------------------------------
-- 1. The session directory
{dir = session_dir, use_orig_path = true},
-- -----------------------------------------------
-- 2. Development environment special destinations:
{prefix = "/sb2/wrappers",
replace_by = sbox_dir.."/share/scratchbox2/wrappers",
readonly = true},
{prefix = "/sb2/scripts",
replace_by = sbox_dir.."/share/scratchbox2/scripts",
readonly = true},
{prefix = sbox_user_home_dir, use_orig_path = true},
{prefix = sbox_dir .. "/share/scratchbox2",
use_orig_path = true},
{path = "/usr/bin/sb2-show",
use_orig_path = true, readonly = true},
-- -----------------------------------------------
-- 99. Other rules.
{prefix = "/usr/lib/perl", map_to = tools},
{prefix = "/usr/lib/gcc", map_to = tools},
{prefix = "/usr/lib", map_to = target_root},
{prefix = "/usr/include", map_to = target_root},
{prefix = "/home/user", map_to = target_root},
{prefix = "/home", use_orig_path = true},
{prefix = "/host_usr", map_to = target_root},
{prefix = "/tmp", use_orig_path = true},
{prefix = "/dev", use_orig_path = true},
{prefix = "/proc", custom_map_funct = sb2_procfs_mapper,
virtual_path = true},
{prefix = "/sys", use_orig_path = true},
--
-- Following 3 rules are needed because package
-- "resolvconf" makes resolv.conf to be symlink that
-- points to /etc/resolvconf/run/resolv.conf and
-- we want them all to come from host.
--
{prefix = "/var/run/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolv.conf", force_orig_path = true,
readonly = true},
{prefix = "/lib", map_to = target_root},
--
{prefix = tools, use_orig_path = true},
{path = "/", use_orig_path = true},
{prefix = "/", map_to = tools}
}
}
qemu_chain = {
next_chain = nil,
binary = basename(sbox_cputransparency_method),
rules = {
{prefix = "/usr/lib", map_to = target_root},
{prefix = "/usr/local/lib", map_to = target_root},
{prefix = "/tmp", use_orig_path = true},
{prefix = "/dev", use_orig_path = true},
{dir = "/proc", custom_map_funct = sb2_procfs_mapper,
virtual_path = true},
{prefix = "/sys", use_orig_path = true},
--
-- Following 3 rules are needed because package
-- "resolvconf" makes resolv.conf to be symlink that
-- points to /etc/resolvconf/run/resolv.conf and
-- we want them all to come from host.
--
{prefix = "/var/run/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolv.conf", force_orig_path = true,
readonly = true},
{prefix = "/lib", map_to = target_root},
--
{prefix = tools, use_orig_path = true},
{path = "/", use_orig_path = true},
{prefix = "/", map_to = tools}
}
}
export_chains = {
qemu_chain,
simple_chain
}
-- Exec policy rules.
-- If the permission token exists and contains "root",
-- use fakeroot
local fakeroot_ld_preload = ""
if sb.get_session_perm() == "root" then
fakeroot_ld_preload = ":"..host_ld_preload_fakeroot
end
default_exec_policy = {
name = "Default",
native_app_ld_preload_prefix = host_ld_preload..fakeroot_ld_preload,
native_app_ld_library_path_prefix =
host_ld_library_path_libfakeroot ..
host_ld_library_path_prefix ..
host_ld_library_path_libsb2,
native_app_ld_library_path_suffix = host_ld_library_path_suffix,
}
-- Note that the real path (mapped path) is used when looking up rules!
all_exec_policies_chain = {
next_chain = nil,
binary = nil,
rules = {
-- DEFAULT RULE (must exist):
{prefix = "/", exec_policy = default_exec_policy}
}
}
exec_policy_chains = {
all_exec_policies_chain
}
-- This table lists all exec policies - this is used when the current
-- process wants to locate the currently active policy
all_exec_policies = {
default_exec_policy,
}
|
-- Copyright (C) 2007 Lauri Leukkunen <lle@rahina.org>
-- Licensed under MIT license.
--
-- "simple" mode, to be used for software development & building
-- (as the name says, this is the simple solution; See/use the "devel"
-- mode when a more full-featured environment is needed)
-- Rule file interface version, mandatory.
--
rule_file_interface_version = "24"
----------------------------------
tools = tools_root
if (not tools) then
tools = "/"
end
simple_chain = {
next_chain = nil,
binary = nil,
rules = {
-- -----------------------------------------------
-- 1. The session directory
{dir = session_dir, use_orig_path = true},
-- -----------------------------------------------
-- 2. Development environment special destinations:
{prefix = "/sb2/wrappers",
replace_by = sbox_dir.."/share/scratchbox2/wrappers",
readonly = true},
{prefix = "/sb2/scripts",
replace_by = sbox_dir.."/share/scratchbox2/scripts",
readonly = true},
{prefix = sbox_user_home_dir, use_orig_path = true},
{prefix = sbox_dir .. "/share/scratchbox2",
use_orig_path = true},
{path = "/usr/bin/sb2-show",
use_orig_path = true, readonly = true},
-- -----------------------------------------------
-- 99. Other rules.
{prefix = "/usr/lib/perl", map_to = tools},
{prefix = "/usr/lib/gcc", map_to = tools},
{prefix = "/usr/lib/git-core", use_orig_path = true, readonly = true},
{prefix = "/usr/lib", map_to = target_root},
{prefix = "/usr/include", map_to = target_root},
{prefix = "/home/user", map_to = target_root},
{prefix = "/home", use_orig_path = true},
{prefix = "/host_usr", map_to = target_root},
{prefix = "/tmp", use_orig_path = true},
{prefix = "/dev", use_orig_path = true},
{prefix = "/proc", custom_map_funct = sb2_procfs_mapper,
virtual_path = true},
{prefix = "/sys", use_orig_path = true},
--
-- Following 3 rules are needed because package
-- "resolvconf" makes resolv.conf to be symlink that
-- points to /etc/resolvconf/run/resolv.conf and
-- we want them all to come from host.
--
{prefix = "/var/run/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolv.conf", force_orig_path = true,
readonly = true},
{prefix = "/lib", map_to = target_root},
--
{prefix = tools, use_orig_path = true},
{path = "/", use_orig_path = true},
{prefix = "/", map_to = tools}
}
}
qemu_chain = {
next_chain = nil,
binary = basename(sbox_cputransparency_method),
rules = {
{prefix = "/usr/lib", map_to = target_root},
{prefix = "/usr/local/lib", map_to = target_root},
{prefix = "/tmp", use_orig_path = true},
{prefix = "/dev", use_orig_path = true},
{dir = "/proc", custom_map_funct = sb2_procfs_mapper,
virtual_path = true},
{prefix = "/sys", use_orig_path = true},
--
-- Following 3 rules are needed because package
-- "resolvconf" makes resolv.conf to be symlink that
-- points to /etc/resolvconf/run/resolv.conf and
-- we want them all to come from host.
--
{prefix = "/var/run/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolvconf", force_orig_path = true,
readonly = true},
{prefix = "/etc/resolv.conf", force_orig_path = true,
readonly = true},
{prefix = "/lib", map_to = target_root},
--
{prefix = tools, use_orig_path = true},
{path = "/", use_orig_path = true},
{prefix = "/", map_to = tools}
}
}
export_chains = {
qemu_chain,
simple_chain
}
-- Exec policy rules.
-- If the permission token exists and contains "root",
-- use fakeroot
local fakeroot_ld_preload = ""
if sb.get_session_perm() == "root" then
fakeroot_ld_preload = ":"..host_ld_preload_fakeroot
end
default_exec_policy = {
name = "Default",
native_app_ld_preload_prefix = host_ld_preload..fakeroot_ld_preload,
native_app_ld_library_path_prefix =
host_ld_library_path_libfakeroot ..
host_ld_library_path_prefix ..
host_ld_library_path_libsb2,
native_app_ld_library_path_suffix = host_ld_library_path_suffix,
}
-- Note that the real path (mapped path) is used when looking up rules!
all_exec_policies_chain = {
next_chain = nil,
binary = nil,
rules = {
-- DEFAULT RULE (must exist):
{prefix = "/", exec_policy = default_exec_policy}
}
}
exec_policy_chains = {
all_exec_policies_chain
}
-- This table lists all exec policies - this is used when the current
-- process wants to locate the currently active policy
all_exec_policies = {
default_exec_policy,
}
|
fixes for running git within sbox2
|
fixes for running git within sbox2
Stop sbox2 from remapping paths for scripts in /usr/lib/git-core to targetfs.. otherwise some commands like 'git submodule' would not work (because git-submodule is a script, not an executable)
Signed-off-by: Lauri Aarnio <18c97056964064acc79deb3ed7547e2c4d053843@iki.fi>
|
Lua
|
lgpl-2.1
|
lbt/scratchbox2,loganchien/scratchbox2,ldbox/ldbox,BinChengfei/scratchbox2,madscientist42/scratchbox2,lbt/scratchbox2,h113331pp/scratchbox2,h113331pp/scratchbox2,BinChengfei/scratchbox2,loganchien/scratchbox2,lbt/scratchbox2,h113331pp/scratchbox2,lbt/scratchbox2,lbt/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,BinChengfei/scratchbox2,madscientist42/scratchbox2,BinChengfei/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,loganchien/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,OlegGirko/ldbox,ldbox/ldbox,OlegGirko/ldbox,OlegGirko/ldbox,madscientist42/scratchbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,loganchien/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,loganchien/scratchbox2,ldbox/ldbox,madscientist42/scratchbox2,loganchien/scratchbox2,OlegGirko/ldbox
|
371612b88da8d59ad25792bad2f2a86c6ccc0138
|
patt_movingspots.lua
|
patt_movingspots.lua
|
local PIXELS = 150
local spots_distance = PIXELS/spots_count
local spot_index = 0
local function subspot(nspot)
wsbuf:set(nspot*spots_distance+spot_index+1,254,254,254)
if nspot > 0 then
subspot(nspot-1)
end
end
local function run(wsbuf, spots_count)
if spots_count < 1 then spots_count = 1 end
wsbuf:fade(2,ws2812.FADE_OUT)
--recursion because for is broken?!?
subspot(spots_count-1)
spot_index = (spot_index + 1) % spots_distance
wsbuf:write()
return 100
end
return run
|
local spot_index = 0
local function run(wsbuf, spots_count)
if not (type(spots_count) == "number" and spots_count > 0) then
spots_count = 1
end
local spots_distance = wsbuf:size()/spots_count
wsbuf:fade(2,ws2812.FADE_OUT)
local pos = 0
for nspot = 0, spots_count -1 do
pos = spot_index+1+nspot*spots_distance
wsbuf:set(pos, 255 ,255, 255)
if pos < wsbuf:size() then wsbuf:set(pos+1, 64 ,64, 64) end
end
spot_index = (spot_index + 1) % spots_distance
return 40
end
return run
|
fix movingspots
|
fix movingspots
|
Lua
|
mit
|
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
|
bd01b31bbd9e47515e0c611d0fe32806bfe20c15
|
npl_mod/nwf/utils/string_util.lua
|
npl_mod/nwf/utils/string_util.lua
|
--[[
Title: string utilities
Author: zenghui
Date: 2017/3/6
]]
local util = commonlib.gettable("nwf.util.string");
function util.split(str, delimiter)
if type(delimiter) ~= "string" or string.len(delimiter) <= 0 then
return
end
local start = 1
local t = {}
while true do
local pos = string.find (str, delimiter, start, true) -- plain find
if not pos then
break
end
table.insert (t, string.sub (str, start, pos - 1))
start = pos + string.len (delimiter)
end
table.insert (t, string.sub (str, start))
return t
end
function util.upperFirstChar(str)
local firstChar = string.sub(str, 1, 1);
local c = string.byte(firstChar);
if(c>=97 and c<=122) then
firstChar = string.upper(firstChar);
end
return firstChar .. string.sub(str, 2, #str)
end
function util.new_guid()
local seed={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
local tb = {};
math.randomseed(tostring(os.time()):reverse():sub(1, 6));
for i = 1, 32 do
table.insert(tb, seed[math.random(1, 16)]);
end
return table.concat(tb);
end
|
--[[
Title: string utilities
Author: zenghui
Date: 2017/3/6
]]
local util = commonlib.gettable("nwf.util.string");
function util.split(str, delimiter)
if type(delimiter) ~= "string" or string.len(delimiter) <= 0 then
return
end
local start = 1
local t = {}
while true do
local pos = string.find (str, delimiter, start, true) -- plain find
if not pos then
break
end
table.insert (t, string.sub (str, start, pos - 1))
start = pos + string.len (delimiter)
end
table.insert (t, string.sub (str, start))
return t
end
function util.upperFirstChar(str)
local firstChar = string.sub(str, 1, 1);
local c = string.byte(firstChar);
if(c>=97 and c<=122) then
firstChar = string.upper(firstChar);
end
return firstChar .. string.sub(str, 2, #str)
end
local guid_seed = 0;
function util.new_guid()
local seed={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
local tb = {};
guid_seed = guid_seed + 1;
math.randomseed(tostring(os.time() + guid_seed):reverse():sub(1, 6));
for i = 1, 32 do
table.insert(tb, seed[math.random(1, 16)]);
end
return table.concat(tb);
end
|
fix string_util.new_guid bug
|
fix string_util.new_guid bug
|
Lua
|
mit
|
Links7094/nwf,Links7094/nwf,elvinzeng/nwf,elvinzeng/nwf
|
d6980b9c5f8db642076fd335b12a94c29feda5e8
|
src_trunk/resources/global/achievement_globals.lua
|
src_trunk/resources/global/achievement_globals.lua
|
-- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
function doesPlayerHaveAchievement(thePlayer, id)
if (getElementType(thePlayer)) then
local gameaccountID = getElementData(thePlayer, "gameaccountid")
if (gameaccountID) then
local result = mysql_query(handler, "SELECT id FROM achievements WHERE achievementid='" .. id .. "' AND account='" .. gameaccountID .. "'")
if (result) then
mysql_free_result(result)
end
if (mysql_num_rows(result)>0) then
return true
else
return false
end
end
end
end
function givePlayerAchievement(thePlayer, id)
if not (doesPlayerHaveAchievement(thePlayer, id)) then
local gameaccountID = getElementData(thePlayer, "gameaccountid")
if (gameaccountID) then
local time = getRealTime()
local days = time.monthday
local months = (time.month+1)
local years = (1900+time.year)
local date = days .. "/" .. months .. "/" .. years
local result = mysql_query(handler, "INSERT INTO achievements SET account='" .. gameaccountID .. "', achievementid='" .. id .. "', date='" .. date .. "'")
if (result) then
mysql_free_result(result)
local query = mysql_query(handler, "SELECT name, description, points FROM achievementslist WHERE id='" .. id .. "'")
if (mysql_num_rows(query)>0) then
local name = mysql_result(query, 1, 1)
local desc = mysql_result(query, 1, 2)
local points = mysql_result(query, 1, 3)
mysql_free_result(query)
triggerClientEvent(thePlayer, "onPlayerGetAchievement", thePlayer, name, desc, points)
return true
else
mysql_free_result(query)
return false
end
else
return false
end
end
end
end
addEvent("cGivePlayerAchievement", true)
addEventHandler("cGivePlayerAchievement", getRootElement(), givePlayerAchievement)
|
-- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
function doesPlayerHaveAchievement(thePlayer, id)
if (getElementType(thePlayer)) then
local gameaccountID = getElementData(thePlayer, "gameaccountid")
if (gameaccountID) then
local result = mysql_query(handler, "SELECT id FROM achievements WHERE achievementid='" .. id .. "' AND account='" .. gameaccountID .. "'")
if (mysql_num_rows(result)>0) then
mysql_free_result(result)
return true
else
mysql_free_result(result)
return false
end
end
end
end
function givePlayerAchievement(thePlayer, id)
if not (doesPlayerHaveAchievement(thePlayer, id)) then
local gameaccountID = getElementData(thePlayer, "gameaccountid")
if (gameaccountID) then
local time = getRealTime()
local days = time.monthday
local months = (time.month+1)
local years = (1900+time.year)
local date = days .. "/" .. months .. "/" .. years
local result = mysql_query(handler, "INSERT INTO achievements SET account='" .. gameaccountID .. "', achievementid='" .. id .. "', date='" .. date .. "'")
if (result) then
mysql_free_result(result)
local query = mysql_query(handler, "SELECT name, description, points FROM achievementslist WHERE id='" .. id .. "'")
if (mysql_num_rows(query)>0) then
local name = mysql_result(query, 1, 1)
local desc = mysql_result(query, 1, 2)
local points = mysql_result(query, 1, 3)
mysql_free_result(query)
triggerClientEvent(thePlayer, "onPlayerGetAchievement", thePlayer, name, desc, points)
return true
else
mysql_free_result(query)
return false
end
else
return false
end
end
end
end
addEvent("cGivePlayerAchievement", true)
addEventHandler("cGivePlayerAchievement", getRootElement(), givePlayerAchievement)
|
Fixed error in global
|
Fixed error in global
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1154 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
4532d4f146cc68c201b62a78d13c13e0c6baf13a
|
lualib/skynet/require.lua
|
lualib/skynet/require.lua
|
-- skynet module two-step initialize . When you require a skynet module :
-- 1. Run module main function as official lua module behavior.
-- 2. Run the functions register by skynet.init() during the step 1,
-- unless calling `require` in main thread .
-- If you call `require` in main thread ( service main function ), the functions
-- registered by skynet.init() do not execute immediately, they will be executed
-- by skynet.start() before start function.
local M = {}
local mainthread, ismain = coroutine.running()
assert(ismain, "skynet.require must initialize in main thread")
local context = {
[mainthread] = {},
}
do
local require = _G.require
function M.require(...)
local co, main = coroutine.running()
if main then
return require(...)
else
local old_init_list = context[co]
local init_list = {}
context[co] = init_list
local ret = require(...)
for _, f in ipairs(init_list) do
f()
end
context[co] = old_init_list
return ret
end
end
end
function M.init_all()
for _, f in ipairs(context[mainthread]) do
f()
end
context[mainthread] = nil
end
function M.init(f)
assert(type(f) == "function")
local co = coroutine.running()
table.insert(context[co], f)
end
return M
|
-- skynet module two-step initialize . When you require a skynet module :
-- 1. Run module main function as official lua module behavior.
-- 2. Run the functions register by skynet.init() during the step 1,
-- unless calling `require` in main thread .
-- If you call `require` in main thread ( service main function ), the functions
-- registered by skynet.init() do not execute immediately, they will be executed
-- by skynet.start() before start function.
local M = {}
local mainthread, ismain = coroutine.running()
assert(ismain, "skynet.require must initialize in main thread")
local context = {
[mainthread] = {},
}
do
local require = _G.require
local loaded = package.loaded
local loading = {}
function M.require(name)
local m = loaded[name]
if m ~= nil then
return m
end
local co, main = coroutine.running()
if main then
return require(name)
end
local filename = package.searchpath(name, package.path)
if not filename then
return require(name)
end
local modfunc = loadfile(filename)
if not modfunc then
return require(name)
end
local loading_queue = loading[name]
if loading_queue then
-- Module is in the init process (require the same mod at the same time in different coroutines) , waiting.
local skynet = require "skynet"
loading_queue[#loading_queue+1] = co
print ("Waiting " .. name)
skynet.wait(co)
local m = loaded[name]
print ("Waiting OK : " .. tostring(m))
if m == nil then
error(string.format("require %s failed", name))
end
return m
end
loading_queue = {}
loading[name] = loading_queue
local old_init_list = context[co]
local init_list = {}
context[co] = init_list
-- We should call modfunc in lua, because modfunc may yield by calling M.require recursive.
local m = modfunc(name, filename)
for _, f in ipairs(init_list) do
f()
end
context[co] = old_init_list
if m == nil then
m = true
end
package.loaded[name] = m
local waiting = #loading_queue
if waiting > 0 then
local skynet = require "skynet"
for i = 1, waiting do
skynet.wakeup(loading_queue[i])
end
end
loading[name] = nil
return m
end
end
function M.init_all()
for _, f in ipairs(context[mainthread]) do
f()
end
context[mainthread] = nil
end
function M.init(f)
assert(type(f) == "function")
local co = coroutine.running()
table.insert(context[co], f)
end
return M
|
Fix skynet.require recursion issue, See #1331
|
Fix skynet.require recursion issue, See #1331
|
Lua
|
mit
|
icetoggle/skynet,hongling0/skynet,xjdrew/skynet,xjdrew/skynet,icetoggle/skynet,xjdrew/skynet,cloudwu/skynet,sanikoyes/skynet,wangyi0226/skynet,pigparadise/skynet,icetoggle/skynet,sanikoyes/skynet,hongling0/skynet,pigparadise/skynet,korialuo/skynet,wangyi0226/skynet,korialuo/skynet,hongling0/skynet,wangyi0226/skynet,cloudwu/skynet,korialuo/skynet,cloudwu/skynet,sanikoyes/skynet,pigparadise/skynet
|
d32ee229b5c402f102e10ee118665f83a86621a9
|
src/db.lua
|
src/db.lua
|
-- Imports / module wrapper
local Pkg = {}
local std = _G
local error = error
local print = print
local type = type
local tostring = tostring
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local string = string
local table = table
local util = require("util")
local Set = require("set").Set
setfenv(1, Pkg)
OUT = "$$OUT"
IN = "$$IN"
OPT = "$$OPT"
local sigSymbols = {[OUT] = "f", [IN] = "B", [OPT] = "?"}
local function fmtSignature(args, signature)
local result = ""
local multi = false
for _, arg in ipairs(args) do
if multi then result = result .. ", " end
result = result .. arg .. ": " .. sigSymbols[signature[arg]]
multi = true
end
return result
end
local Signature = {}
function Signature.__tostring(signature)
local args = {}
for arg in pairs(signature) do
args[#args + 1] = arg
end
return fmtSignature(args, signature)
end
function getSignature(bindings, bound)
local signature = setmetatable({}, Signature)
for _, binding in ipairs(bindings) do
if bound[binding.variable] or binding.constant then
signature[binding.field] = IN
else
signature[binding.field] = OUT
end
end
return signature
end
local Schema = {}
function Schema.__tostring(schema)
return "Schema<" .. (schema.name or "UNNAMED") .. ", (" .. fmtSignature(schema.args, schema.signature) .. ")>"
end
local function schema(args)
local schema = {args = {}, signature = setmetatable({}, Signature)}
setmetatable(schema, Schema)
if args.name then
schema.name = args.name
end
local mode = OUT
for _, arg in ipairs(args) do
if arg == OUT or arg == IN or arg == OPT then
mode = arg
else
schema.args[#schema.args + 1] = arg
schema.signature[arg] = mode
end
end
return schema
end
local function rename(name, schema)
local neue = util.shallowCopy(schema)
neue.name = name
return neue
end
local schemas = {
unary = schema{"return", IN, "a"},
unaryFilter = schema{IN, "a"},
binary = schema{"return", IN, "a", "b"},
binaryFilter = schema{IN, "a", "b"},
moveIn = schema{"a", IN, "b"},
moveOut = schema{"b", IN, "a"}
}
local expressions = {
["+"] = {rename("plus", schemas.binary)},
["-"] = {rename("minus", schemas.binary)},
["*"] = {rename("multiply", schemas.binary)},
["/"] = {rename("divide", schemas.binary)},
["<"] = {rename("less_than", schemas.binary), rename("is_less_than", schemas.binaryFilter)},
["<="] = {rename("less_than_or_equal", schemas.binary), rename("is_less_than_or_equal", schemas.binaryFilter)},
[">"] = {rename("greater_than", schemas.binary), rename("is_greater_than", schemas.binaryFilter)},
[">="] = {rename("greater_than_or_equal", schemas.binary), rename("is_greater_than_or_equal", schemas.binaryFilter)},
["="] = {rename("equal", schemas.binary), rename("is_equal", schemas.binaryFilter), rename("move", schemas.moveIn), rename("move", schemas.moveOut)},
["!="] = {rename("not_equal", schemas.binary), rename("is_not_equal", schemas.binaryFilter)},
is = {schemas.unary},
sin = {schemas.unary},
cos = {schemas.unary},
tan = {schemas.unary},
time = {schema{"return", OPT, "seconds", "minutes", "hours"}}
}
function getSchemas(name)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
return expressions[name]
end
function getSchema(name, signature)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
if not signature then error("Must specify signature to disambiguate expression alternatives") end
local result
for _, schema in ipairs(expressions[name]) do
local match = true
local required = Set:new()
for arg, mode in pairs(schema.signature) do
if mode == OUT or mode == IN then
required:add(arg)
end
end
for arg, mode in pairs(signature) do
required:remove(arg)
if schema.signature[arg] ~= mode and schema.signature[arg] ~= OPT then
match = false
break
end
end
if match and required:length() == 0 then
result = schema
break
end
end
if not result then
local available = {}
for _, schema in ipairs(expressions[name]) do
available[#available + 1] = string.format("%s(%s)", name, fmtSignature(schema.args, schema.signature))
end
error(string.format("No matching signature for expression %s(%s); Available signatures:\n %s", name, signature, table.concat(available, "\n ")))
end
return result
end
function getArgs(schema, bindings)
local map = {}
for _, binding in ipairs(bindings) do
map[binding.field] = binding.variable or binding.constant
end
local args = {}
local fields = {}
for _, arg in ipairs(schema.args) do
if map[arg] then
args[#args + 1] = map[arg]
fields[#fields + 1] = arg
end
end
return args, fields
end
return Pkg
|
-- Imports / module wrapper
local Pkg = {}
local std = _G
local error = error
local print = print
local type = type
local tostring = tostring
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local string = string
local table = table
local util = require("util")
local Set = require("set").Set
setfenv(1, Pkg)
OUT = "$$OUT"
IN = "$$IN"
OPT = "$$OPT"
local sigSymbols = {[OUT] = "f", [IN] = "B", [OPT] = "?"}
local function fmtSignature(args, signature)
local result = ""
local multi = false
for _, arg in ipairs(args) do
if multi then result = result .. ", " end
result = result .. arg .. ": " .. sigSymbols[signature[arg]]
multi = true
end
return result
end
local Signature = {}
function Signature.__tostring(signature)
local args = {}
for arg in pairs(signature) do
args[#args + 1] = arg
end
return fmtSignature(args, signature)
end
function getSignature(bindings, bound)
local signature = setmetatable({}, Signature)
for _, binding in ipairs(bindings) do
if bound[binding.variable] or binding.constant then
signature[binding.field] = IN
else
signature[binding.field] = OUT
end
end
return signature
end
local Schema = {}
function Schema.__tostring(schema)
return "Schema<" .. (schema.name or "UNNAMED") .. ", (" .. fmtSignature(schema.args, schema.signature) .. ")>"
end
local function schema(args, name)
local schema = {args = {}, signature = setmetatable({}, Signature), name = name}
setmetatable(schema, Schema)
if args.name then
schema.name = args.name
end
local mode = OUT
for _, arg in ipairs(args) do
if arg == OUT or arg == IN or arg == OPT then
mode = arg
else
schema.args[#schema.args + 1] = arg
schema.signature[arg] = mode
end
end
return schema
end
local function rename(name, schema)
local neue = util.shallowCopy(schema)
neue.name = name
return neue
end
local schemas = {
unary = schema{"return", IN, "a"},
unaryFilter = schema{IN, "a"},
binary = schema{"return", IN, "a", "b"},
binaryFilter = schema{IN, "a", "b"},
moveIn = schema{"a", IN, "b"},
moveOut = schema{"b", IN, "a"}
}
local expressions = {
["+"] = {rename("plus", schemas.binary)},
["-"] = {rename("minus", schemas.binary)},
["*"] = {rename("multiply", schemas.binary)},
["/"] = {rename("divide", schemas.binary)},
["<"] = {rename("less_than", schemas.binary), rename("is_less_than", schemas.binaryFilter)},
["<="] = {rename("less_than_or_equal", schemas.binary), rename("is_less_than_or_equal", schemas.binaryFilter)},
[">"] = {rename("greater_than", schemas.binary), rename("is_greater_than", schemas.binaryFilter)},
[">="] = {rename("greater_than_or_equal", schemas.binary), rename("is_greater_than_or_equal", schemas.binaryFilter)},
["="] = {rename("equal", schemas.binary), rename("is_equal", schemas.binaryFilter), rename("move", schemas.moveIn), rename("move", schemas.moveOut)},
["!="] = {rename("not_equal", schemas.binary), rename("is_not_equal", schemas.binaryFilter)},
is = {rename("is", schemas.unary)},
sin = {rename("sin", schemas.unary)},
cos = {rename("cos", schemas.unary)},
tan = {rename("tan", schemas.unary)},
length = {rename("length", schemas.unary)},
time = {schema({"return", OPT, "seconds", "minutes", "hours"}, "time")}
}
function getSchemas(name)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
return expressions[name]
end
function getSchema(name, signature)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
if not signature then error("Must specify signature to disambiguate expression alternatives") end
local result
for _, schema in ipairs(expressions[name]) do
local match = true
local required = Set:new()
for arg, mode in pairs(schema.signature) do
if mode == OUT or mode == IN then
required:add(arg)
end
end
for arg, mode in pairs(signature) do
required:remove(arg)
if schema.signature[arg] ~= mode and schema.signature[arg] ~= OPT then
match = false
break
end
end
if match and required:length() == 0 then
result = schema
break
end
end
if not result then
local available = {}
for _, schema in ipairs(expressions[name]) do
available[#available + 1] = string.format("%s(%s)", name, fmtSignature(schema.args, schema.signature))
end
error(string.format("No matching signature for expression %s(%s); Available signatures:\n %s", name, signature, table.concat(available, "\n ")))
end
return result
end
function getArgs(schema, bindings)
local map = {}
for _, binding in ipairs(bindings) do
map[binding.field] = binding.variable or binding.constant
end
local args = {}
local fields = {}
for _, arg in ipairs(schema.args) do
if map[arg] then
args[#args + 1] = map[arg]
fields[#fields + 1] = arg
end
end
return args, fields
end
return Pkg
|
Fix unary schemas and add length schema
|
Fix unary schemas and add length schema
|
Lua
|
apache-2.0
|
shamrin/Eve,shamrin/Eve,nmsmith/Eve,witheve/lueve,shamrin/Eve,witheve/Eve,witheve/Eve,nmsmith/Eve,witheve/lueve,nmsmith/Eve,witheve/Eve
|
6a035b16175ce727f2954dcb2b5aade63cb3aec4
|
game/scripts/vscripts/heroes/hero_sai/divine_flesh.lua
|
game/scripts/vscripts/heroes/hero_sai/divine_flesh.lua
|
LinkLuaModifier("modifier_sai_divine_flesh_on", "heroes/hero_sai/divine_flesh.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_sai_divine_flesh_off", "heroes/hero_sai/divine_flesh.lua", LUA_MODIFIER_MOTION_NONE)
sai_divine_flesh = class({
GetIntrinsicModifierName = function() return "modifier_sai_divine_flesh_off" end,
})
if IsServer() then
function sai_divine_flesh:OnToggle()
local caster = self:GetCaster()
if self:GetToggleState() then
caster:RemoveModifierByName("modifier_sai_divine_flesh_off")
caster:AddNewModifier(caster, self, "modifier_sai_divine_flesh_on", nil)
else
caster:RemoveModifierByName("modifier_sai_divine_flesh_on")
caster:AddNewModifier(caster, self, "modifier_sai_divine_flesh_off", nil)
end
end
end
modifier_sai_divine_flesh_on = class({
GetEffectName = function() return "particles/arena/units/heroes/hero_sai/divine_flesh.vpcf" end,
})
function modifier_sai_divine_flesh_on:DeclareFunctions()
return {
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS
}
end
function modifier_sai_divine_flesh_on:GetModifierPhysicalArmorBonus()
return self:GetAbility():GetSpecialValueFor("active_bonus_armor")
end
function modifier_sai_divine_flesh_on:GetModifierMagicalResistanceBonus()
return self:GetAbility():GetSpecialValueFor("active_magic_resistance_pct")
end
if IsServer() then
function modifier_sai_divine_flesh_on:OnCreated()
self:StartIntervalThink(self:GetAbility():GetSpecialValueFor("think_interval"))
self:OnIntervalThink()
end
function modifier_sai_divine_flesh_on:OnIntervalThink()
local ability = self:GetAbility()
local parent = self:GetParent()
local damage = parent:GetMaxHealth() * ability:GetSpecialValueFor("active_self_damage_pct") * 0.01 * ability:GetSpecialValueFor("think_interval")
ApplyDamage({
victim = parent,
attacker = parent,
damage = damage,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_NO_DAMAGE_MULTIPLIERS + DOTA_DAMAGE_FLAG_HPLOSS,
ability = ability
})
end
end
modifier_sai_divine_flesh_off = class({
IsHidden = function() return true end,
})
function modifier_sai_divine_flesh_off:DeclareFunctions()
return {MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE}
end
function modifier_sai_divine_flesh_off:GetModifierHealthRegenPercentage()
local ability = self:GetAbility()
local parent = self:GetParent()
local sai_invulnerability = parent:FindAbilityByName("sai_invulnerability")
return sai_invulnerability and sai_invulnerability:GetToggleState() and ability:GetSpecialValueFor("health_regeneration_pct") * sai_invulnerability:GetSpecialValueFor("divine_flesh_regen_mult") or ability:GetSpecialValueFor("health_regeneration_pct")
end
|
LinkLuaModifier("modifier_sai_divine_flesh_on", "heroes/hero_sai/divine_flesh.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_sai_divine_flesh_off", "heroes/hero_sai/divine_flesh.lua", LUA_MODIFIER_MOTION_NONE)
sai_divine_flesh = class({
GetIntrinsicModifierName = function() return "modifier_sai_divine_flesh_off" end,
})
if IsServer() then
function sai_divine_flesh:OnToggle()
local caster = self:GetCaster()
if self:GetToggleState() then
caster:RemoveModifierByName("modifier_sai_divine_flesh_off")
caster:AddNewModifier(caster, self, "modifier_sai_divine_flesh_on", nil)
else
caster:RemoveModifierByName("modifier_sai_divine_flesh_on")
caster:AddNewModifier(caster, self, "modifier_sai_divine_flesh_off", nil)
end
end
end
modifier_sai_divine_flesh_on = class({
GetEffectName = function() return "particles/arena/units/heroes/hero_sai/divine_flesh.vpcf" end,
})
function modifier_sai_divine_flesh_on:DeclareFunctions()
return {
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS
}
end
function modifier_sai_divine_flesh_on:GetModifierPhysicalArmorBonus()
return self:GetAbility():GetSpecialValueFor("active_bonus_armor")
end
function modifier_sai_divine_flesh_on:GetModifierMagicalResistanceBonus()
return self:GetAbility():GetSpecialValueFor("active_magic_resistance_pct")
end
if IsServer() then
function modifier_sai_divine_flesh_on:OnCreated()
self:StartIntervalThink(self:GetAbility():GetSpecialValueFor("think_interval"))
self:OnIntervalThink()
end
function modifier_sai_divine_flesh_on:OnIntervalThink()
local ability = self:GetAbility()
local parent = self:GetParent()
local damage = parent:GetMaxHealth() * ability:GetSpecialValueFor("active_self_damage_pct") * 0.01 * ability:GetSpecialValueFor("think_interval")
ApplyDamage({
victim = parent,
attacker = parent,
damage = damage,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_NO_DAMAGE_MULTIPLIERS + DOTA_DAMAGE_FLAG_HPLOSS,
ability = ability
})
end
end
modifier_sai_divine_flesh_off = class({
IsHidden = function() return true end,
})
function modifier_sai_divine_flesh_off:DeclareFunctions()
return { MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE }
end
function modifier_sai_divine_flesh_off:GetModifierHealthRegenPercentage()
return self.health_regeneration_pct or self:GetSharedKey("health_regeneration_pct") or 0
end
if IsServer() then
function modifier_sai_divine_flesh_off:OnCreated()
self:StartIntervalThink(0.1)
self:OnIntervalThink()
end
function modifier_sai_divine_flesh_off:OnIntervalThink()
local ability = self:GetAbility()
local parent = self:GetParent()
local sai_invulnerability = parent:FindAbilityByName("sai_invulnerability")
local isUnderInvulnerability = sai_invulnerability and sai_invulnerability:GetToggleState()
self.health_regeneration_pct = ability:GetSpecialValueFor("health_regeneration_pct")
if isUnderInvulnerability then
self.health_regeneration_pct = self.health_regeneration_pct * sai_invulnerability:GetSpecialValueFor("divine_flesh_regen_mult")
end
self:SetSharedKey("health_regeneration_pct", self.health_regeneration_pct)
end
end
|
fix(sai): turned off Divine Flesh now displays correct values on client
|
fix(sai): turned off Divine Flesh now displays correct values on client
|
Lua
|
mit
|
ark120202/aabs
|
ca4faf595aed12b8de59eb1400e794b1db68d1d6
|
src/pathfindingutils/src/Shared/PathfindingUtils.lua
|
src/pathfindingutils/src/Shared/PathfindingUtils.lua
|
--[=[
Utilities involving pathfinding in Roblox
@class PathfindingUtils
]=]
local require = require(script.Parent.loader).load(script)
local Promise = require("Promise")
local Draw = require("Draw")
local Maid = require("Maid")
local PathfindingUtils = {}
--[=[
Computes a path wrapped in a promise.
@param path Path
@param start Vector3
@param finish Vector3
@return Promise<Path>
]=]
function PathfindingUtils.promiseComputeAsync(path, start, finish)
assert(path, "Bad path")
assert(start, "Bad start")
assert(finish, "Bad finish")
return Promise.spawn(function(resolve, _)
path:ComputeAsync(start, finish)
resolve(path)
end)
end
--[=[
Checks occlusion wrapped in a promise
@param path Path
@param startIndex number
@return Promise<number>
]=]
function PathfindingUtils.promiseCheckOcclusion(path, startIndex)
return Promise.spawn(function(resolve, _)
resolve(path:CheckOcclusionAsync(startIndex))
end)
end
--[=[
Visualizes the current waypoints in the path. Will put the visualization in
Draw libraries default parent.
@param path Path
@return MaidTask
]=]
function PathfindingUtils.visualizePath(path)
local maid = Maid.new()
local parent = Instance.new("Folder")
parent.Name = "PathVisualization"
maid:GiveTask(parent)
for index, waypoint in pairs(path:GetWaypoints()) do
if waypoint.Action == Enum.PathWaypointAction.Walk then
local point = Draw.point(waypoint.Position, Color3.new(0.5, 1, 0.5), parent)
point.Name = ("%03d_WalkPoint"):format(index)
maid:GiveTask(point)
elseif waypoint.Action == Enum.PathWaypointAction.Jump then
local point = Draw.point(waypoint.Position, Color3.new(0.5, 0.5, 1), parent)
point.Name = ("%03d_JumpPoint"):format(index)
maid:GiveTask(point)
end
end
parent.Parent = Draw.getDefaultParent()
return maid
end
return PathfindingUtils
|
--[=[
Utilities involving pathfinding in Roblox
@class PathfindingUtils
]=]
local require = require(script.Parent.loader).load(script)
local Promise = require("Promise")
local Draw = require("Draw")
local Maid = require("Maid")
local PathfindingUtils = {}
--[=[
Computes a path wrapped in a promise.
@param path Path
@param start Vector3
@param finish Vector3
@return Promise<Path>
]=]
function PathfindingUtils.promiseComputeAsync(path, start, finish)
assert(path, "Bad path")
assert(start, "Bad start")
assert(finish, "Bad finish")
return Promise.spawn(function(resolve, reject)
local ok, err = pcall(function()
path:ComputeAsync(start, finish)
end)
if not ok then
reject(err or "Failed to compute path")
return
end
return resolve(path)
end)
end
--[=[
Checks occlusion wrapped in a promise
@param path Path
@param startIndex number
@return Promise<number>
]=]
function PathfindingUtils.promiseCheckOcclusion(path, startIndex)
return Promise.spawn(function(resolve, _)
resolve(path:CheckOcclusionAsync(startIndex))
end)
end
--[=[
Visualizes the current waypoints in the path. Will put the visualization in
Draw libraries default parent.
@param path Path
@return MaidTask
]=]
function PathfindingUtils.visualizePath(path)
local maid = Maid.new()
local parent = Instance.new("Folder")
parent.Name = "PathVisualization"
maid:GiveTask(parent)
for index, waypoint in pairs(path:GetWaypoints()) do
if waypoint.Action == Enum.PathWaypointAction.Walk then
local point = Draw.point(waypoint.Position, Color3.new(0.5, 1, 0.5), parent)
point.Name = ("%03d_WalkPoint"):format(index)
maid:GiveTask(point)
elseif waypoint.Action == Enum.PathWaypointAction.Jump then
local point = Draw.point(waypoint.Position, Color3.new(0.5, 0.5, 1), parent)
point.Name = ("%03d_JumpPoint"):format(index)
maid:GiveTask(point)
end
end
parent.Parent = Draw.getDefaultParent()
return maid
end
return PathfindingUtils
|
fix: Wrap promiseComputeAsync with pcall, as path finding can fail on long path call requests
|
fix: Wrap promiseComputeAsync with pcall, as path finding can fail on long path call requests
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
9e87c18ad42fc5ce3b0e7ec295d3028c4ec12836
|
check/plugin.lua
|
check/plugin.lua
|
--[[
Copyright 2012 Rackspace
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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext, '0') -- Try the 0 verb first for Powershell
if assocExe == nil then
assocExe, err = virgo.win32_get_associated_exe(ext, 'open')
end
if assocExe ~= nil then
-- If Powershell is the EXE then add a parameter for the exec policy
local justExe = path.basename(assocExe)
-- On windows if the associated exe is %1 it references itself
if assocExe ~= "%1" then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
-- Force Bypass for this child powershell
if justExe == "powershell.exe" then
table.insert(exeArgs, 1, 'Bypass')
table.insert(exeArgs, 1, '-ExecutionPolicy')
end
end
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
-- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of
-- closing the pipe after the process runs.
local child = self:_runChild(exePath, exeArgs, cenv, callback)
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
--[[
Copyright 2012 Rackspace
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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
local closeStdin = false
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext, '0') -- Try the 0 verb first for Powershell
if assocExe == nil then
assocExe, err = virgo.win32_get_associated_exe(ext, 'open')
end
if assocExe ~= nil then
-- If Powershell is the EXE then add a parameter for the exec policy
local justExe = path.basename(assocExe)
-- On windows if the associated exe is %1 it references itself
if assocExe ~= "%1" then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
-- Force Bypass for this child powershell
if justExe == "powershell.exe" then
table.insert(exeArgs, 1, 'Bypass')
table.insert(exeArgs, 1, '-ExecutionPolicy')
closeStdin = true -- NEEDED for Powershell 2.0 to exit
end
end
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
-- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of
-- closing the pipe after the process runs.
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if closeStdin then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
Fix: close stdin for Powershell plugins * Some versions require stdin to be closed before exiting
|
Fix: close stdin for Powershell plugins
* Some versions require stdin to be closed before exiting
|
Lua
|
apache-2.0
|
christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
|
030656f586214202b432a08e335087d6b5ff5759
|
cherry/screens/name-picker.lua
|
cherry/screens/name-picker.lua
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local animation = require 'cherry.libs.animation'
local group = require 'cherry.libs.group'
local gesture = require 'cherry.libs.gesture'
local Banner = require 'cherry.components.banner'
local Button = require 'cherry.components.button'
local Panel = require 'cherry.components.panel'
local Text = require 'cherry.components.text'
--------------------------------------------------------------------------------
local NamePicker = {}
--------------------------------------------------------------------------------
function NamePicker:new()
local namePicker = {}
setmetatable(namePicker, { __index = NamePicker })
return namePicker
end
--------------------------------------------------------------------------------
local function existsUserName(name)
local exists = false
local user = App.user:current()
for i = 1, App.user:nbUsers() do
local userName = App.user:getUser(i).name
if(userName ~= nil and userName == name) then
exists = true
user = i
end
end
return exists, user
end
--------------------------------------------------------------------------------
local function usersHeight()
local height = 0
for _ = 1, App.user:nbUsers() do
height = height + display.contentHeight * 0.075
end
return display.contentHeight * 0.15 + height
end
--------------------------------------------------------------------------------
function NamePicker:display(next)
self:refreshAction()
self:createBlur()
if(App.user:nbUsers() < 6) then
self:createTextBoard(next)
else
self.hideCreation = true
end
if(App.user:nbUsers() > 1) then
self:createPlayersBoard(next)
end
end
--------------------------------------------------------------------------------
function NamePicker:createBlur()
self.blurBG = display.newImageRect(
App.hud,
App.images.blurBG,
display.contentWidth,
display.contentHeight
)
self.blurBG.alpha = 0
transition.to(self.blurBG, {
alpha = 1,
time = 300
})
self.blurBG.x = display.contentWidth * 0.5
self.blurBG.y = display.contentHeight * 0.5
end
--------------------------------------------------------------------------------
function NamePicker:createTextBoard(next)
self.text = App.user:name() or 'Player' .. string.sub(os.time(), -5)
self.textBoard = self:createBoard({
title = 'New player',
panelheight = display.contentHeight * 0.18,
y = display.contentHeight * 0.2
})
Button:icon({
parent = self.textBoard,
type = 'selected',
x = 0,
y = self.textBoard.panel.height * 0.5,
action = function()
if(self.createNewUser) then
App.user:newProfile(self.text)
else
App.user:switchToProfile(self.userNum)
end
self:close(next)
end
})
self:createInputText()
end
--------------------------------------------------------------------------------
function NamePicker:createPlayersBoard(next)
local height = usersHeight()
local title = 'Previous player'
local y = display.contentHeight * 0.68
if(self.hideCreation == true) then
title = 'Who are you ?'
y = display.contentHeight * 0.5
end
self.playersBoard = self:createBoard({
title = title,
panelheight = height,
y = y
})
self:addPreviousUsers(next)
end
--------------------------------------------------------------------------------
function NamePicker:close(next)
group.destroy(self.textBoard, true)
group.destroy(self.playersBoard, true)
group.destroy(self.blurBG, false)
if(next) then next() end
end
--------------------------------------------------------------------------------
function NamePicker:refreshAction()
local exists, userNum = existsUserName(self.text)
self.createNewUser = not exists
self.userNum = userNum
end
--------------------------------------------------------------------------------
function NamePicker:createBoard(options)
local panelheight = options.panelheight
local title = options.title
local y = options.y
local board = display.newGroup()
board.x = display.contentWidth * 0.5
board.y = y
App.hud:insert(board)
gesture.disabledTouch(board) -- not to click behind
board.panel = Panel:vertical({
parent = board,
width = display.contentWidth * 0.7,
height = panelheight,
x = 0,
y = 0
})
board.banner = Banner:simple({
parent = board,
text = title,
fontSize = 70,
width = display.contentWidth*0.55,
height = display.contentHeight*0.075,
x = 0,
y = -board.panel.height*0.49
})
animation.easeDisplay(board)
board:toFront()
return board
end
--------------------------------------------------------------------------------
function NamePicker:createInputText()
local function textListener( event )
if ( event.phase == 'editing' ) then
self.text = event.text
self:refreshAction()
end
end
-- Create text field
self.inputText = native.newTextField(
0, self.textBoard.banner.y + display.contentHeight * 0.085,
display.contentWidth * 0.6, 80
)
self.inputText.font = native.newFont( _G.FONT, 80 )
self.inputText.text = self.text
native.setKeyboardFocus( self.inputText )
self.inputText:addEventListener( 'userInput', textListener )
self.textBoard:insert(self.inputText)
end
--------------------------------------------------------------------------------
function NamePicker:addPreviousUsers(next)
for i = 1, App.user:nbUsers() do
local playerName = App.user:getUser(i).name
local user = display.newGroup()
self.playersBoard:insert(user)
user.x = 0
user.y = self.playersBoard.banner.y + i * display.contentHeight * 0.09
local panel = Panel:small({
parent = user,
x = 0,
y = 0
})
local nameDisplay = Text:create({
parent = user,
value = playerName,
x = 0,
y = 0,
grow = true,
color = '#000000',
fontSize = 43
})
panel.width = nameDisplay:width() + 60
gesture.onTouch(user, function()
animation.touchEffect(user, {
onComplete = function()
App.user:switchToProfile(i)
self:close(next)
end
})
end)
end
end
--------------------------------------------------------------------------------
return NamePicker
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local animation = require 'cherry.libs.animation'
local group = require 'cherry.libs.group'
local gesture = require 'cherry.libs.gesture'
local Banner = require 'cherry.components.banner'
local Button = require 'cherry.components.button'
local Panel = require 'cherry.components.panel'
local Text = require 'cherry.components.text'
--------------------------------------------------------------------------------
local NamePicker = {}
--------------------------------------------------------------------------------
function NamePicker:new()
local namePicker = {}
setmetatable(namePicker, { __index = NamePicker })
return namePicker
end
--------------------------------------------------------------------------------
local function randomName()
return 'Player' .. string.sub(os.time(), -5)
end
local function existsUserName(name)
if(not name or #name == 0) then
return false, App.user:current()
end
for i = 1, App.user:nbUsers() do
local userName = App.user:getUser(i).name
if(string.lower(userName) == string.lower(name)) then
return true, i
end
end
return false, App.user:current()
end
--------------------------------------------------------------------------------
local function usersHeight()
local height = 0
for _ = 1, App.user:nbUsers() do
height = height + display.contentHeight * 0.075
end
return display.contentHeight * 0.15 + height
end
--------------------------------------------------------------------------------
function NamePicker:display(next)
self:createBlur()
if(App.user:nbUsers() < 6) then
self:createTextBoard(next)
else
self.hideCreation = true
end
if(App.user:nbUsers() > 1) then
self:createPlayersBoard(next)
end
self:refreshAction()
end
--------------------------------------------------------------------------------
function NamePicker:createBlur()
self.blurBG = display.newImageRect(
App.hud,
App.images.blurBG,
display.contentWidth,
display.contentHeight
)
self.blurBG.alpha = 0
transition.to(self.blurBG, {
alpha = 1,
time = 300
})
self.blurBG.x = display.contentWidth * 0.5
self.blurBG.y = display.contentHeight * 0.5
end
--------------------------------------------------------------------------------
function NamePicker:createTextBoard(next)
self.text = App.user:name() or randomName()
self.textBoard = self:createBoard({
title = 'New player',
panelheight = display.contentHeight * 0.18,
y = display.contentHeight * 0.2
})
Button:icon({
parent = self.textBoard,
type = 'selected',
x = 0,
y = self.textBoard.panel.height * 0.5,
action = function()
if(#self.text == 0) then
self.text = randomName()
self.inputText.text = self.text
return
end
if(self.createNewUser) then
App.user:newProfile(self.text)
else
App.user:switchToProfile(self.userNum)
end
self:close(next)
end
})
self:createInputText()
end
--------------------------------------------------------------------------------
function NamePicker:createPlayersBoard(next)
local height = usersHeight()
local title = 'Previous player'
local y = display.contentHeight * 0.68
if(self.hideCreation == true) then
title = 'Who are you ?'
y = display.contentHeight * 0.5
end
self.playersBoard = self:createBoard({
title = title,
panelheight = height,
y = y
})
self:addPreviousUsers(next)
end
--------------------------------------------------------------------------------
function NamePicker:close(next)
group.destroy(self.textBoard, true)
group.destroy(self.playersBoard, true)
group.destroy(self.blurBG, false)
if(next) then next() end
end
--------------------------------------------------------------------------------
function NamePicker:refreshAction()
local exists, userNum = existsUserName(self.text)
self.createNewUser = not exists
self.userNum = userNum
end
--------------------------------------------------------------------------------
function NamePicker:createBoard(options)
local panelheight = options.panelheight
local title = options.title
local y = options.y
local board = display.newGroup()
board.x = display.contentWidth * 0.5
board.y = y
App.hud:insert(board)
gesture.disabledTouch(board) -- not to click behind
board.panel = Panel:vertical({
parent = board,
width = display.contentWidth * 0.7,
height = panelheight,
x = 0,
y = 0
})
board.banner = Banner:simple({
parent = board,
text = title,
fontSize = 70,
width = display.contentWidth*0.55,
height = display.contentHeight*0.075,
x = 0,
y = -board.panel.height*0.49
})
animation.easeDisplay(board)
board:toFront()
return board
end
--------------------------------------------------------------------------------
function NamePicker:createInputText()
local function textListener( event )
if ( event.phase == 'editing' ) then
self.text = event.text
self:refreshAction()
end
end
-- Create text field
self.inputText = native.newTextField(
0, self.textBoard.banner.y + display.contentHeight * 0.085,
display.contentWidth * 0.6, 80
)
self.inputText.font = native.newFont( _G.FONT, 80 )
self.inputText.text = self.text
native.setKeyboardFocus( self.inputText )
self.inputText:addEventListener( 'userInput', textListener )
self.textBoard:insert(self.inputText)
end
--------------------------------------------------------------------------------
function NamePicker:addPreviousUsers(next)
for i = 1, App.user:nbUsers() do
local playerName = App.user:getUser(i).name
local user = display.newGroup()
self.playersBoard:insert(user)
user.x = 0
user.y = self.playersBoard.banner.y + i * display.contentHeight * 0.09
local panel = Panel:small({
parent = user,
x = 0,
y = 0
})
local nameDisplay = Text:create({
parent = user,
value = playerName,
x = 0,
y = 0,
grow = true,
color = '#000000',
fontSize = 43
})
panel.width = nameDisplay:width() + 60
gesture.onTouch(user, function()
animation.touchEffect(user, {
onComplete = function()
App.user:switchToProfile(i)
self:close(next)
end
})
end)
end
end
--------------------------------------------------------------------------------
return NamePicker
|
fixes for name-picker
|
fixes for name-picker
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
fbe40aa2d7272c447895fabf3768f09aaa0158b7
|
core/font.lua
|
core/font.lua
|
SILE.registerCommand("font", function(options, content)
if (type(content)=="function" or content[1]) then
SILE.settings.pushState()
end
if (options.family) then SILE.settings.set("font.family", options.family) end
if (options.size) then
local size = SILE.parserBits.dimensioned_string:match(options.size)
if not size then SU.error("Couldn't parse font size "..options.size) end
SILE.settings.set("font.size", size)
end
if (options.weight) then SILE.settings.set("font.weight", 0+options.weight) end
if (options.style) then SILE.settings.set("font.style", options.style) end
if (options.variant) then SILE.settings.set("font.variant", options.variant) end
if (options.features) then SILE.settings.set("font.features", options.features) end
if (options.language) then
SILE.settings.set("document.language", options.language)
SILE.languageSupport.loadLanguage(options.language)
end
if (options.script) then SILE.settings.set("font.script", options.script)
elseif SILE.settings.get("document.language") then
local lang = SILE.languageSupport.languages[SILE.settings.get("document.language")]
if lang and lang.defaultScript then
SILE.settings.set("font.script", lang.defaultScript)
end
end
if (type(content)=="function" or content[1]) then
SILE.process(content)
SILE.settings.popState()
end
end, "Set current font family, size, weight, style, variant, script, direction and language")
SILE.settings.declare({name = "font.family", type = "string", default = "Gentium"})
SILE.settings.declare({name = "font.size", type = "number or integer", default = 10})
SILE.settings.declare({name = "font.weight", type = "integer", default = 200})
SILE.settings.declare({name = "font.variant", type = "string", default = "normal"})
SILE.settings.declare({name = "font.script", type = "string", default = ""})
SILE.settings.declare({name = "font.style", type = "string", default = "normal"})
SILE.settings.declare({name = "font.features", type = "string", default = ""})
SILE.settings.declare({name = "document.language", type = "string", default = "en"})
SILE.fontCache = {}
local _key = function(options)
return table.concat({options.font;options.size;options.weight;options.style;options.variant;options.features},";")
end
SILE.font = {loadDefaults = function(options)
if not options.font then options.font = SILE.settings.get("font.family") end
if not options.size then options.size = SILE.settings.get("font.size") end
if not options.weight then options.weight = SILE.settings.get("font.weight") end
if not options.style then options.style = SILE.settings.get("font.style") end
if not options.variant then options.variant = SILE.settings.get("font.variant") end
if not options.language then options.language = SILE.settings.get("document.language") end
if not options.script then options.script = SILE.settings.get("font.script") end
if not options.direction then options.direction = SILE.typesetter.frame.direction end
if not options.features then options.features = SILE.settings.get("font.features") end
return options
end,
cache = function(options, callback)
if not SILE.fontCache[_key(options)] then
SILE.fontCache[_key(options)] = callback(options)
end
return SILE.fontCache[_key(options)]
end,
_key = _key
}
|
SILE.registerCommand("font", function(options, content)
if (type(content)=="function" or content[1]) then
SILE.settings.pushState()
end
if (options.family) then SILE.settings.set("font.family", options.family) end
if (options.size) then
local size = SILE.parserBits.dimensioned_string:match(options.size)
if not size then SU.error("Couldn't parse font size "..options.size) end
SILE.settings.set("font.size", size)
end
if (options.weight) then SILE.settings.set("font.weight", 0+options.weight) end
if (options.style) then SILE.settings.set("font.style", options.style) end
if (options.variant) then SILE.settings.set("font.variant", options.variant) end
if (options.features) then SILE.settings.set("font.features", options.features) end
if (options.language) then
SILE.settings.set("document.language", options.language)
SILE.languageSupport.loadLanguage(options.language)
end
if (options.script) then SILE.settings.set("font.script", options.script)
elseif SILE.settings.get("document.language") then
local lang = SILE.languageSupport.languages[SILE.settings.get("document.language")]
if lang and lang.defaultScript then
SILE.settings.set("font.script", lang.defaultScript)
end
end
if (type(content)=="function" or content[1]) then
SILE.process(content)
SILE.settings.popState()
end
end, "Set current font family, size, weight, style, variant, script, direction and language")
SILE.settings.declare({name = "font.family", type = "string", default = "Gentium"})
SILE.settings.declare({name = "font.size", type = "number or integer", default = 10})
SILE.settings.declare({name = "font.weight", type = "integer", default = 200})
SILE.settings.declare({name = "font.variant", type = "string", default = "normal"})
SILE.settings.declare({name = "font.script", type = "string", default = ""})
SILE.settings.declare({name = "font.style", type = "string", default = "normal"})
SILE.settings.declare({name = "font.features", type = "string", default = ""})
SILE.settings.declare({name = "document.language", type = "string", default = "en"})
SILE.fontCache = {}
local _key = function(options)
return table.concat({options.font;options.size;options.weight;options.style;options.variant;options.features},";")
end
SILE.font = {loadDefaults = function(options)
if not options.font then options.font = SILE.settings.get("font.family") end
if not options.size then options.size = SILE.settings.get("font.size") end
if not options.weight then options.weight = SILE.settings.get("font.weight") end
if not options.style then options.style = SILE.settings.get("font.style") end
if not options.variant then options.variant = SILE.settings.get("font.variant") end
if not options.language then options.language = SILE.settings.get("document.language") end
if not options.script then options.script = SILE.settings.get("font.script") end
if not options.direction then options.direction = SILE.typesetter.frame and SILE.typesetter.frame.direction or "LTR" end
if not options.features then options.features = SILE.settings.get("font.features") end
return options
end,
cache = function(options, callback)
if not SILE.fontCache[_key(options)] then
SILE.fontCache[_key(options)] = callback(options)
end
return SILE.fontCache[_key(options)]
end,
_key = _key
}
|
Bug fix.
|
Bug fix.
|
Lua
|
mit
|
neofob/sile,simoncozens/sile,shirat74/sile,neofob/sile,shirat74/sile,shirat74/sile,anthrotype/sile,simoncozens/sile,alerque/sile,alerque/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,shirat74/sile,WAKAMAZU/sile_fe,alerque/sile,anthrotype/sile,anthrotype/sile,anthrotype/sile,alerque/sile,neofob/sile,simoncozens/sile,neofob/sile
|
8bf7e449038151bf992acf9a45afb5c0c2703aa9
|
mods/coloredwood/wood.lua
|
mods/coloredwood/wood.lua
|
-- Woods portion of Colored Wood mod by Vanessa Ezekowitz ~~ 2012-07-17
-- based on my unified dyes modding template.
--
-- License: WTFPL
coloredwood.enable_stairsplus = true
if minetest.setting_getbool("coloredwood_enable_stairsplus") == false or not minetest.get_modpath("moreblocks") then
coloredwood.enable_stairsplus = false
end
local colored_block_modname = "coloredwood"
local colored_block_description = "Wood Planks"
local neutral_block = "default:wood"
local colored_block_sunlight = "false"
local colored_block_walkable = "true"
local colored_block_groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2}
local colored_block_sound = "default.node_sound_wood_defaults()"
-- Show the wood planks in the crafting guide:
-- Value copy the groups table to another one to pass to stairsplus:register_all()
-- oherwise stairsplus:register_all() will add the ["not_in_creative_inventory"] = 1 key/value to the groups
-- of the original table and force the coloredwood planks to be removed from the crafting guide.
local stairsplus_groups = {}
if coloredwood.enable_stairsplus then
for k, v in pairs(colored_block_groups) do
stairsplus_groups[k] = v
end
end
for shade = 1, 3 do
local shadename = coloredwood.shades[shade]
local shadename2 = coloredwood.shades2[shade]
for hue = 1, 12 do
local huename = coloredwood.hues[hue]
local huename2 = coloredwood.hues2[hue]
local colorname = colored_block_modname..":wood_"..shadename..huename
local pngname = colored_block_modname.."_wood_"..shadename..huename..".png"
local nodedesc = shadename2..huename2..colored_block_description
local s50colorname = colored_block_modname..":wood_"..shadename..huename.."_s50"
local s50pngname = colored_block_modname.."_wood_"..shadename..huename.."_s50.png"
local s50nodedesc = shadename2..huename2..colored_block_description.." (50% Saturation)"
minetest.register_node(colorname, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
minetest.register_node(s50colorname, {
description = s50nodedesc,
tiles = { s50pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
-- stairsplus:register_all(modname, subname, recipeitem, {fields})
stairsplus:register_all(
"coloredwood",
"wood_"..shadename..huename,
colorname,
{
groups = colored_block_groups,
tiles = { pngname },
description = nodedesc,
drop = "wood_"..shadename..huename,
}
)
stairsplus:register_all(
"coloredwood",
"wood_"..shadename..huename.."_s50",
s50colorname,
{
groups = colored_block_groups,
tiles = { s50pngname },
description = s50nodedesc,
drop = "wood_"..shadename..huename.."_s50",
}
)
end
minetest.register_craft({
type = "fuel",
recipe = colorname,
burntime = 7,
})
minetest.register_craft({
type = "fuel",
recipe = s50colorname,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:"..shadename..huename
},
})
minetest.register_craft( {
type = "shapeless",
output = s50colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:"..shadename..huename.."_s50"
},
})
end
end
-- Generate the "light" shades separately, since they don"t have a low-sat version.
for hue = 1, 12 do
local huename = coloredwood.hues[hue]
local huename2 = coloredwood.hues2[hue]
local colorname = colored_block_modname..":wood_light_"..huename
local pngname = colored_block_modname.."_wood_light_"..huename..".png"
local nodedesc = "Light "..huename2..colored_block_description
minetest.register_node(colorname, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
stairsplus:register_all(
"coloredwood",
"wood_light_"..huename,
colorname,
{
groups = colored_block_groups,
tiles = { pngname },
description = nodedesc,
drop = "wood_light_"..huename,
}
)
end
minetest.register_craft({
type = "fuel",
recipe = colorname,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:light_"..huename
},
})
end
-- ============================================================
-- The 5 levels of greyscale.
--
-- Oficially these are 0, 25, 50, 75, and 100% relative to white,
-- but in practice, they"re actually 7.5%, 25%, 50%, 75%, and 95%.
-- (otherwise black and white would wash out).
for grey = 1,5 do
local greyname = coloredwood.greys[grey]
local greyname2 = coloredwood.greys2[grey]
local greyname3 = coloredwood.greys3[grey]
local greyshadename = colored_block_modname..":wood_"..greyname
local pngname = colored_block_modname.."_wood_"..greyname..".png"
local nodedesc = greyname2..colored_block_description
minetest.register_node(greyshadename, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
stairsplus:register_all(
"coloredwood",
"wood_"..greyname,
greyshadename,
{
groups = colored_block_groups,
tiles = { pngname },
description = nodedesc,
drop = "wood_"..greyname,
}
)
end
minetest.register_craft({
type = "fuel",
recipe = greyshadename,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = greyshadename.." 2",
recipe = {
neutral_block,
neutral_block,
greyname3
},
})
end
|
-- Woods portion of Colored Wood mod by Vanessa Ezekowitz ~~ 2012-07-17
-- based on my unified dyes modding template.
--
-- License: WTFPL
coloredwood.enable_stairsplus = true
if minetest.setting_getbool("coloredwood_enable_stairsplus") == false or not minetest.get_modpath("moreblocks") then
coloredwood.enable_stairsplus = false
end
local colored_block_modname = "coloredwood"
local colored_block_description = "Wood Planks"
local neutral_block = "default:wood"
local colored_block_sunlight = "false"
local colored_block_walkable = "true"
local colored_block_groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2}
local colored_block_sound = "default.node_sound_wood_defaults()"
-- Show the wood planks in the crafting guide:
-- Value copy the groups table to another one to pass to stairsplus:register_all()
-- oherwise stairsplus:register_all() will add the ["not_in_creative_inventory"] = 1 key/value to the groups
-- of the original table and force the coloredwood planks to be removed from the crafting guide.
local stairsplus_groups = {}
if coloredwood.enable_stairsplus then
for k, v in pairs(colored_block_groups) do
stairsplus_groups[k] = v
end
end
for shade = 1, 3 do
local shadename = coloredwood.shades[shade]
local shadename2 = coloredwood.shades2[shade]
for hue = 1, 12 do
local huename = coloredwood.hues[hue]
local huename2 = coloredwood.hues2[hue]
local colorname = colored_block_modname..":wood_"..shadename..huename
local pngname = colored_block_modname.."_wood_"..shadename..huename..".png"
local nodedesc = shadename2..huename2..colored_block_description
local s50colorname = colored_block_modname..":wood_"..shadename..huename.."_s50"
local s50pngname = colored_block_modname.."_wood_"..shadename..huename.."_s50.png"
local s50nodedesc = shadename2..huename2..colored_block_description.." (50% Saturation)"
minetest.register_node(colorname, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
minetest.register_node(s50colorname, {
description = s50nodedesc,
tiles = { s50pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
-- stairsplus:register_all(modname, subname, recipeitem, {fields})
stairsplus:register_all(
"coloredwood",
"wood_"..shadename..huename,
colorname,
{
groups = stairsplus_groups, -- Modif MFF
tiles = { pngname },
description = nodedesc,
drop = "wood_"..shadename..huename,
}
)
stairsplus:register_all(
"coloredwood",
"wood_"..shadename..huename.."_s50",
s50colorname,
{
groups = stairsplus_groups, -- Modif MFF
tiles = { s50pngname },
description = s50nodedesc,
drop = "wood_"..shadename..huename.."_s50",
}
)
end
minetest.register_craft({
type = "fuel",
recipe = colorname,
burntime = 7,
})
minetest.register_craft({
type = "fuel",
recipe = s50colorname,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:"..shadename..huename
},
})
minetest.register_craft( {
type = "shapeless",
output = s50colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:"..shadename..huename.."_s50"
},
})
end
end
-- Generate the "light" shades separately, since they don"t have a low-sat version.
for hue = 1, 12 do
local huename = coloredwood.hues[hue]
local huename2 = coloredwood.hues2[hue]
local colorname = colored_block_modname..":wood_light_"..huename
local pngname = colored_block_modname.."_wood_light_"..huename..".png"
local nodedesc = "Light "..huename2..colored_block_description
minetest.register_node(colorname, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
stairsplus:register_all(
"coloredwood",
"wood_light_"..huename,
colorname,
{
groups = stairsplus_groups, -- Modif MFF
tiles = { pngname },
description = nodedesc,
drop = "wood_light_"..huename,
}
)
end
minetest.register_craft({
type = "fuel",
recipe = colorname,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = colorname.." 2",
recipe = {
neutral_block,
neutral_block,
"unifieddyes:light_"..huename
},
})
end
-- ============================================================
-- The 5 levels of greyscale.
--
-- Oficially these are 0, 25, 50, 75, and 100% relative to white,
-- but in practice, they"re actually 7.5%, 25%, 50%, 75%, and 95%.
-- (otherwise black and white would wash out).
for grey = 1,5 do
local greyname = coloredwood.greys[grey]
local greyname2 = coloredwood.greys2[grey]
local greyname3 = coloredwood.greys3[grey]
local greyshadename = colored_block_modname..":wood_"..greyname
local pngname = colored_block_modname.."_wood_"..greyname..".png"
local nodedesc = greyname2..colored_block_description
minetest.register_node(greyshadename, {
description = nodedesc,
tiles = { pngname },
sunlight_propagates = colored_block_sunlight,
paramtype = "light",
walkable = colored_block_walkable,
groups = colored_block_groups,
sounds = colored_block_sound
})
if coloredwood.enable_stairsplus then
stairsplus:register_all(
"coloredwood",
"wood_"..greyname,
greyshadename,
{
groups = stairsplus_groups, -- Modif MFF
tiles = { pngname },
description = nodedesc,
drop = "wood_"..greyname,
}
)
end
minetest.register_craft({
type = "fuel",
recipe = greyshadename,
burntime = 7,
})
minetest.register_craft( {
type = "shapeless",
output = greyshadename.." 2",
recipe = {
neutral_block,
neutral_block,
greyname3
},
})
end
|
Revert coloredwood parts
|
Revert coloredwood parts
Fix the coloredwood "woods" no longer appear in inventory issue (thank you Le_Docteur for the reporting)
|
Lua
|
unlicense
|
MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server
|
696cf07f73aa76b165e9ff0a9d64bc76c39f0538
|
scripts/lua/policies/security.lua
|
scripts/lua/policies/security.lua
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module security
-- A module to load all and execute the security policies
-- @author David Green (greend), Alex Song (songs)
local _M = {}
local request = require "lib/request"
local utils = require "lib/utils"
--- Allow or block a request by calling a loaded security policy
-- @param securityObj an object out of the security array in a given tenant / api / resource
function process(securityObj)
local ok, result = pcall(require, utils.concatStrings({'policies/security/', securityObj.type}))
if not ok then
request.err(500, 'An unexpected error ocurred while processing the security policy: ' .. securityObj.type)
end
return result.process(securityObj)
end
-- Wrap process in code to load the correct module
_M.process = process
return _M
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module security
-- A module to load all and execute the security policies
-- @author David Green (greend), Alex Song (songs)
local _M = {}
local request = require "lib/request"
local utils = require "lib/utils"
--- Allow or block a request by calling a loaded security policy
-- @param securityObj an object out of the security array in a given tenant / api / resource
function process(securityObj)
local ok, result = pcall(require, utils.concatStrings({'policies/security/', securityObj.type}))
if not ok then
ngx.log(ngx.ERR, 'An unexpected error ocurred while processing the security policy: ' .. securityObj.type)
request.err(500, 'Gateway error.')
end
return result.process(securityObj)
end
-- Wrap process in code to load the correct module
_M.process = process
return _M
|
Fix error path message due to bad security policy name
|
Fix error path message due to bad security policy name
|
Lua
|
apache-2.0
|
openwhisk/apigateway,openwhisk/apigateway,alexsong93/openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway
|
5bed42ea26123b09dee034d048afc8f7fa02adbe
|
fblualib/util/fb/util/timing.lua
|
fblualib/util/fb/util/timing.lua
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Trace timing.
--
-- This modules implements a handler for the tracing facility that
-- logs the probe key, time, and nesting level for all probes matching
-- certain patterns. It can then print the log (with timing information)
-- prettily to standard output.
local pl = require('pl.import_into')()
local printf = pl.utils.printf
local util = require('fb.util')
local trace = require('fb.util.trace')
local M = {}
local Recorder = pl.class()
local timing_module = 'fb:timing'
function Recorder:_init(max_size)
self.events = util.Deque()
self.max_size = max_size
self.registered_patterns = pl.List()
self.patterns = pl.List()
self.enabled = false
self.record_func = pl.func.bind1(self.record, self)
end
function Recorder:_enable()
-- always listen to our own events
trace.add_handler(self.record_func, timing_module)
for _, p in ipairs(self.patterns) do
local pattern, fail = unpack(p, 1, 2)
trace.add_handler(self.record_func, pattern, fail)
end
self.registered_patterns:extend(self.patterns)
self.patterns = {}
self.enabled = true
end
function Recorder:_disable()
trace.remove_handler(self.record_func)
self.registered_patterns:extend(self.patterns)
self.patterns = self.registered_patterns
self.registered_patterns = {}
self.enabled = false
end
-- Record an event, used as handler
function Recorder:record(key, args, nest)
if self.enabled then
self.events:push_back({key, args.time, nest})
self:set_max_size()
end
end
-- Set max size (if max_size is not nil) and ensure that the current size
-- is under max_size.
function Recorder:set_max_size(max_size)
if max_size then
self.max_size = max_size
end
if self.max_size and #self.events > self.max_size then
self.events:pop_front(#self.events - self.max_size)
end
end
-- Return an integer indicating the current position in the log.
-- This can be passed to dump() to indicate a starting position.
function Recorder:mark()
return self.events.last + 1
end
-- Clear all events, reset the start time, reinitialize, enable
function Recorder:start(name)
self:reset()
self.name = (name or 'default_path'):gsub('[:%s]', '_')
return self:resume()
end
-- Resume recording after being stopped. Current timing information is
-- kept (and the time between stop() and resume() will be accounted for
-- in the output); use start() to restart from scratch.
function Recorder:resume()
self:_enable()
trace.trace(string.format('%s:start:%s', timing_module, self.name))
return self:mark()
end
-- Stop recording.
function Recorder:stop()
if self.enabled then
trace.trace(string.format('%s:stop:%s', timing_module, self.name))
self:_disable()
end
end
-- Finish; this is a convenience function that calls stop() and dumps
-- the output; the arguments are the same as for dump().
function Recorder:finish(...)
self:stop()
self:dump(...)
self:reset()
end
-- Dump the log to stdout.
-- If pattern_str is not nil, only the records matching the pattern will
-- be dumped. If start is not nil, only the records after the requested
-- start position (returned by mark()) will be dumped.
function Recorder:dump(pattern_str, start)
if not self.name then return end
pattern_str = pattern_str or ''
if start then
start = math.max(start, self.events.first)
else
start = self.events.first
end
local pattern = trace.parse_key(pattern_str, trace.PATTERN)
local start_time, last_time
printf('%-62.62s %8s %8s\n', self.name, 'pt', 'cum')
for i = start, self.events.last do
local event = self.events:get_stable(i)
local key, time, nest = unpack(event)
if pattern_str == '' or
trace.key_matches(key, pattern) or
trace.key_matches(key, timing_module) then
if not start_time then
start_time = time
last_time = time
end
local indent = string.rep(' ', nest)
printf('%-62.62s %8d %8d\n',
indent .. trace.format_key(key),
(time - last_time) * 1e6,
(time - start_time) * 1e6)
last_time = time
end
end
end
-- Reset the recorder to a pristine state.
function Recorder:reset()
self:stop()
self.events:clear()
self.name = nil
self.patterns = pl.List()
self.registered_patterns = pl.List()
end
-- Add a pattern (Lua string pattern matched against the string key)
function Recorder:add_pattern(pattern_str, fail)
table.insert(self.patterns, {pattern_str, fail})
if self.enabled then
-- enable() always updates the registration
self:_enable()
end
end
local recorder = Recorder()
-- Add recording for a pattern
for _, fn in ipairs({'set_max_size', 'mark', 'reset', 'dump',
'start', 'stop', 'resume', 'reset', 'finish',
'add_pattern'}) do
M[fn] = pl.func.bind1(recorder[fn], recorder)
end
return M
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Trace timing.
--
-- This modules implements a handler for the tracing facility that
-- logs the probe key, time, and nesting level for all probes matching
-- certain patterns. It can then print the log (with timing information)
-- prettily to standard output.
local pl = require('pl.import_into')()
local printf = pl.utils.printf
local util = require('fb.util')
local trace = require('fb.util.trace')
local M = {}
local Recorder = pl.class()
local timing_module = 'fb:timing'
function Recorder:_init(max_size)
self.events = util.Deque()
self.max_size = max_size
self.registered_patterns = pl.List()
self.patterns = pl.List()
self.enabled = false
self.record_func = pl.func.bind1(self.record, self)
end
function Recorder:_enable()
-- always listen to our own events
trace.add_handler(self.record_func, timing_module)
for _, p in ipairs(self.patterns) do
local pattern, fail = unpack(p, 1, 2)
trace.add_handler(self.record_func, pattern, fail)
end
self.registered_patterns:extend(self.patterns)
self.patterns = {}
self.enabled = true
end
function Recorder:_disable()
trace.remove_handler(self.record_func)
self.registered_patterns:extend(self.patterns)
self.patterns = self.registered_patterns
self.registered_patterns = {}
self.enabled = false
end
-- Record an event, used as handler
function Recorder:record(key, args, nest)
if self.enabled then
self.events:push_back({key, args.time, nest})
self:set_max_size()
end
end
-- Set max size (if max_size is not nil) and ensure that the current size
-- is under max_size.
function Recorder:set_max_size(max_size)
if max_size then
self.max_size = max_size
end
if self.max_size and #self.events > self.max_size then
self.events:pop_front(#self.events - self.max_size)
end
end
-- Return an integer indicating the current position in the log.
-- This can be passed to dump() to indicate a starting position.
function Recorder:mark()
return self.events.last + 1
end
-- Clear all events, reset the start time, reinitialize, enable
function Recorder:start(name)
self:_reset_events()
self.name = (name or 'default_path'):gsub('[:%s]', '_')
return self:resume()
end
-- Resume recording after being stopped. Current timing information is
-- kept (and the time between stop() and resume() will be accounted for
-- in the output); use start() to restart from scratch.
function Recorder:resume()
self:_enable()
trace.trace(string.format('%s:start:%s', timing_module, self.name))
return self:mark()
end
-- Stop recording.
function Recorder:stop()
if self.enabled then
trace.trace(string.format('%s:stop:%s', timing_module, self.name))
self:_disable()
end
end
-- Finish; this is a convenience function that calls stop() and dumps
-- the output; the arguments are the same as for dump().
function Recorder:finish(...)
self:stop()
self:dump(...)
self:_reset_events()
end
-- Dump the log to stdout.
-- If pattern_str is not nil, only the records matching the pattern will
-- be dumped. If start is not nil, only the records after the requested
-- start position (returned by mark()) will be dumped.
function Recorder:dump(pattern_str, start)
if not self.name then return end
pattern_str = pattern_str or ''
if start then
start = math.max(start, self.events.first)
else
start = self.events.first
end
local pattern = trace.parse_key(pattern_str, trace.PATTERN)
local start_time, last_time
printf('%-62.62s %8s %8s\n', self.name, 'pt', 'cum')
for i = start, self.events.last do
local event = self.events:get_stable(i)
local key, time, nest = unpack(event)
if pattern_str == '' or
trace.key_matches(key, pattern) or
trace.key_matches(key, timing_module) then
if not start_time then
start_time = time
last_time = time
end
local indent = string.rep(' ', nest)
printf('%-62.62s %8d %8d\n',
indent .. trace.format_key(key),
(time - last_time) * 1e6,
(time - start_time) * 1e6)
last_time = time
end
end
end
function Recorder:_reset_events()
self:stop()
self.events:clear()
self.name = nil
end
-- Reset the recorder to a pristine state.
function Recorder:reset()
self:_reset_events()
self.patterns = pl.List()
self.registered_patterns = pl.List()
end
-- Add a pattern (Lua string pattern matched against the string key)
function Recorder:add_pattern(pattern_str, fail)
table.insert(self.patterns, {pattern_str, fail})
if self.enabled then
-- enable() always updates the registration
self:_enable()
end
end
local recorder = Recorder()
-- Add recording for a pattern
for _, fn in ipairs({'set_max_size', 'mark', 'reset', 'dump',
'start', 'stop', 'resume', 'reset', 'finish',
'add_pattern'}) do
M[fn] = pl.func.bind1(recorder[fn], recorder)
end
return M
|
Fix bug in fb.util.timing: start should not reset patterns
|
Fix bug in fb.util.timing: start should not reset patterns
Summary:
You should be able to run start() / finish() as many times as you want on
the same set of patterns.
Test Plan: ran trace_test.llar, the output looks good
Reviewed By: kma@fb.com
Subscribers: tulloch, soumith, pamelavagata
FB internal diff: D1698086
Signature: t1:1698086:1416607574:39695bdbff2bf5a31e71db8b72e6c516fb691b5d
|
Lua
|
bsd-3-clause
|
raphaelamorim/fblualib,facebook/fblualib,szagoruyko/fblualib,facebook/fblualib,soumith/fblualib,szagoruyko/fblualib,raphaelamorim/fblualib,soumith/fblualib
|
1b376b7a54d50679b44e6d387dd60f3dd184eb23
|
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.on_commit(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd("root", v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
end
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
keys.rmempty = false
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
if value then
fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
end
return m, m2
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.on_commit(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd("root", v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
end
if fs.access("/etc/config/dropbear") then
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
keys.rmempty = false
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
if value then
fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
end
end
return m, m2
|
modules/admin-full: fix System -> Administration menu if dropbear is not installed
|
modules/admin-full: fix System -> Administration menu if dropbear is not installed
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
|
94639475f712cc4f310044dafe27b82ddd71cffc
|
wyx/ui/CheckButton.lua
|
wyx/ui/CheckButton.lua
|
local Class = require 'lib.hump.class'
local Frame = getClass 'wyx.ui.Frame'
local Button = getClass 'wyx.ui.Button'
-- CheckButton
-- a clickable Frame
local CheckButton = Class{name='CheckButton',
inherits=Button,
function(self, ...)
Button.construct(self, ...)
self._checked = false
end
}
-- destructor
function CheckButton:destroy()
self:_clearCheckedCallback()
self._checked = nil
Button.destroy(self)
end
-- clear the callback
function CheckButton:_clearCheckedCallback()
self._checkedCallback = nil
if self._checkedCallbackArgs then
for k,v in self._checkedCallbackArgs do self._checkedCallbackArgs[k] = nil end
self._checkedCallbackArgs = nil
end
end
-- set the checkedCallback function and arguments
-- this will be called when the button is checked or unchecked
function CheckButton:setCheckedCallback(func, ...)
verify('function', func)
self:_clearCheckedCallback()
self._checkedCallback = func
local numArgs = select('#', ...)
if numArgs > 0 then self._checkedCallbackArgs = {...} end
end
-- override Button:onRelease()
function CheckButton:onRelease(button, mods)
Button.onRelease(button, mods)
if button == 'l' then
self._checked = not self._checked
if self._checkedCallback then
local args = self._checkedCallbackArgs
if args then
self._checkedCallback(self._checked, unpack(args))
else
self._checkedCallback(self._checked)
end
end
end
end
-- override Frame:onHoverIn()
function CheckButton:onHoverIn(x, y)
if self._checked then return end
Button.onHoverIn(self, x, y)
end
-- override Frame:onHoverOut()
function CheckButton:onHoverOut(x, y)
if self._checked then return end
Button.onHoverOut(self, x, y)
end
-- override Frame:switchToNormalStyle()
function CheckButton:switchToNormalStyle()
if self._checked then return end
Button.switchToNormalStyle(self)
end
-- override Frame:switchToHoverStyle()
function CheckButton:switchToHoverStyle()
if self._checked then return end
Button.switchToHoverStyle(self)
end
-- the class
return CheckButton
|
local Class = require 'lib.hump.class'
local Frame = getClass 'wyx.ui.Frame'
local Button = getClass 'wyx.ui.Button'
-- CheckButton
-- a clickable Frame
local CheckButton = Class{name='CheckButton',
inherits=Button,
function(self, ...)
Button.construct(self, ...)
self._checked = false
end
}
-- destructor
function CheckButton:destroy()
self:_clearCheckedCallback()
self._checked = nil
Button.destroy(self)
end
-- clear the callback
function CheckButton:_clearCheckedCallback()
self._checkedCallback = nil
if self._checkedCallbackArgs then
for k,v in self._checkedCallbackArgs do self._checkedCallbackArgs[k] = nil end
self._checkedCallbackArgs = nil
end
end
-- set the checkedCallback function and arguments
-- this will be called when the button is checked or unchecked
function CheckButton:setCheckedCallback(func, ...)
verify('function', func)
self:_clearCheckedCallback()
self._checkedCallback = func
local numArgs = select('#', ...)
if numArgs > 0 then self._checkedCallbackArgs = {...} end
end
-- override Button:onRelease()
function CheckButton:onRelease(button, mods)
if button == 'l' then self:_toggleCheck() end
Button.onRelease(button, mods)
end
function CheckButton:check() self:_toggleCheck(true) end
function CheckButton:uncheck() self:_toggleCheck(false) end
function CheckButton:_toggleCheck(on)
if nil == on then on = not self._checked end
self._checked = on
if self._checkedCallback then
local args = self._checkedCallbackArgs
if args then
self._checkedCallback(self._checked, unpack(args))
else
self._checkedCallback(self._checked)
end
end
if not self._checked then self._hovered = true end
self._needsUpdate = true
end
-- override Frame:onHoverIn()
function CheckButton:onHoverIn(x, y)
if self._checked then return end
Button.onHoverIn(self, x, y)
end
-- override Frame:onHoverOut()
function CheckButton:onHoverOut(x, y)
if self._checked then return end
Button.onHoverOut(self, x, y)
end
-- override Frame:switchToNormalStyle()
function CheckButton:switchToNormalStyle()
if self._checked then return end
Button.switchToNormalStyle(self)
end
-- override Frame:switchToHoverStyle()
function CheckButton:switchToHoverStyle()
if self._checked then return end
Button.switchToHoverStyle(self)
end
-- the class
return CheckButton
|
fix CheckButton
|
fix CheckButton
|
Lua
|
mit
|
scottcs/wyx
|
8273d3d273b50d7fce59332bc35b6faa523f4c0d
|
applications/luci-minidlna/luasrc/controller/minidlna.lua
|
applications/luci-minidlna/luasrc/controller/minidlna.lua
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <juhosg@openwrt.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.minidlna", package.seeall)
function index()
if not nixio.fs.access("/etc/config/minidlna") then
return
end
local page
page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA"))
page.i18n = "minidlna"
page.dependent = true
entry({"admin", "services", "minidlna_status"}, call("minidlna_status"))
end
function minidlna_status()
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local port = tonumber(uci:get_first("minidlna", "minidlna", "port"))
local status = {
running = (sys.call("pidof minidlna >/dev/null") == 0),
audio = 0,
video = 0,
image = 0
}
if status.running then
local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true)
if fd then
local ln
repeat
ln = fd:read("*l")
if ln and ln:match("files:") then
local ftype, fcount = ln:match("(.+) files: (%d+)")
status[ftype:lower()] = tonumber(fcount) or 0
end
until not ln
fd:close()
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(status)
end
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <juhosg@openwrt.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.minidlna", package.seeall)
function index()
if not nixio.fs.access("/etc/config/minidlna") then
return
end
local page
page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA"))
page.i18n = "minidlna"
page.dependent = true
entry({"admin", "services", "minidlna_status"}, call("minidlna_status"))
end
function minidlna_status()
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local port = tonumber(uci:get_first("minidlna", "minidlna", "port"))
local status = {
running = (sys.call("pidof minidlna >/dev/null") == 0),
audio = 0,
video = 0,
image = 0
}
if status.running then
local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true)
if fd then
local html = fd:read("*a")
if html then
status.audio = (tonumber(html:match("Audio files: (%d+)")) or 0)
status.video = (tonumber(html:match("Video files: (%d+)")) or 0)
status.image = (tonumber(html:match("Image files: (%d+)")) or 0)
end
fd:close()
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(status)
end
|
applications/luci-minidlna: fix status parsing
|
applications/luci-minidlna: fix status parsing
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8658 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
64c41adeb2ea8cfcbb30935dbdba83329c83964e
|
filters/hugo.lua
|
filters/hugo.lua
|
-- Remove TeX/LaTeX RawInlines
function RawInline(el)
if el.format:match 'tex' or el.format:match 'latex' then
-- replace RawInlines ("latex") w/ a space
return pandoc.Space()
end
end
-- Remove TeX/LaTeX RawBlocks
function RawBlock(el)
if el.format:match 'tex' or el.format:match 'latex' then
-- use empty Para instead of just returning an empty list,
-- which turns up in the result as HTML comment?!
return pandoc.Para{}
end
end
-- Encapsulate TeX Math
function Math(el)
if el.mathtype:match 'InlineMath' then
return {
pandoc.RawInline('markdown', '<span>'),
el,
pandoc.RawInline('markdown', '</span>')
}
end
if el.mathtype:match 'DisplayMath' then
return {
pandoc.RawInline('markdown', '<div>'),
el,
pandoc.RawInline('markdown', '</div>')
}
end
end
-- Nest an image in a Div to center it and allow manual scaling
--
-- This is essentially the construct that Hugo would create for
-- shortcode `{{% figure src="path" title="text" width="60%" %}}`
-- Now we can just write `{width="60%}` instead ...
function Image(el)
local width = el.attributes["width"] or "auto"
local height = el.attributes["height"] or "auto"
local style = string.format("width:%s;height:%s;", width, height)
local alt = pandoc.utils.stringify(el.caption)
return {
pandoc.RawInline('markdown', '<div class="center" style="' .. style .. '">'),
pandoc.RawInline('markdown', '<figure>'),
pandoc.RawInline('markdown', '<img src="' .. el.src .. '" alt="' .. alt ..'">'),
pandoc.RawInline('markdown', '<figcaption><h4>'),
pandoc.Str(alt),
pandoc.RawInline('markdown', '</h4></figcaption>'),
pandoc.RawInline('markdown', '</figure>'),
pandoc.RawInline('markdown', '</div>')
}
end
-- Replace native Divs with "real" Divs or Shortcodes
function Div(el)
-- Replace "showme" Div with "expand" Shortcode
if el.classes[1] == "showme" then
return
{ pandoc.RawBlock("markdown", '{{% expand "Show Me" %}}'), pandoc.RawBlock("markdown", "<div class='showme'>") } ..
el.content ..
{ pandoc.RawBlock("markdown", "</div>"), pandoc.RawBlock("markdown", "{{% /expand %}}") }
end
-- Transform all other native Divs to "real" Divs digestible to Hugo
return
{ pandoc.RawBlock("markdown", "<div class='" .. el.classes[1] .. "'>") } ..
el.content ..
{ pandoc.RawBlock("markdown", "</div>") }
end
-- Replace native Spans with "real" Spans or Shortcodes
function Span(el)
-- Replace "bsp" Span with "button" Shortcode
if el.classes[1] == "bsp" then
return
{ pandoc.RawInline("markdown", "{{% button %}}") } ..
el.content ..
{ pandoc.RawInline("markdown", "{{% /button %}}") }
end
-- Transform all other native Spans to "real" Spans digestible to Hugo
return
{ pandoc.RawInline("markdown", "<span class='" .. el.classes[1] .. "'>") } ..
el.content ..
{ pandoc.RawInline("markdown", "</span>") }
end
-- Handle citations
-- use "#id_KEY" as target => needs be be defined in the document
-- i.e. the shortcode/partial "bib.html" needs to create this targets
local keys = {}
function Cite(el)
-- translate a citation into a link
local citation_to_link = function(citation)
local id = citation.id
local suffix = pandoc.utils.stringify(citation.suffix)
-- remember this id, needs to be added to the meta data
keys[id] = true
-- create a link into the current document
return pandoc.Link("[" .. id .. suffix .. "]", "#id_" .. id)
end
-- replace citation with list of links
return el.citations:map(citation_to_link)
end
function Meta(md)
-- meta data "readings"
md.readings = md.readings or pandoc.MetaList(pandoc.List())
-- has a "readings" element "x" a "key" with value "k"?
local has_id = function(k)
return function(x) return pandoc.utils.stringify(x.key) == k end
end
-- collect all "keys" which are not in "readings"
for k, _ in pairs(keys) do
if #md.readings:filter(has_id(k)) == 0 then
md.readings:insert(pandoc.MetaMap{key = pandoc.MetaInlines{pandoc.Str(k)}})
end
end
return md
end
|
-- Remove TeX/LaTeX RawInlines
function RawInline(el)
if el.format:match 'tex' or el.format:match 'latex' then
-- replace RawInlines ("latex") w/ a space
return pandoc.Space()
end
end
-- Remove TeX/LaTeX RawBlocks
function RawBlock(el)
if el.format:match 'tex' or el.format:match 'latex' then
-- use empty Para instead of just returning an empty list,
-- which turns up in the result as HTML comment?!
return pandoc.Para{}
end
end
-- Encapsulate TeX Math
function Math(el)
if el.mathtype:match 'InlineMath' then
return {
pandoc.RawInline('markdown', '<span>'),
el,
pandoc.RawInline('markdown', '</span>')
}
end
if el.mathtype:match 'DisplayMath' then
return {
pandoc.RawInline('markdown', '<div>'),
el,
pandoc.RawInline('markdown', '</div>')
}
end
end
-- Nest an image in a Div to center it and allow manual scaling
--
-- This is essentially the construct that Hugo would create for
-- shortcode `{{% figure src="path" title="text" width="60%" %}}`
-- Now we can just write `{width="60%}` instead ...
function Image(el)
local width = el.attributes["width"] or "auto"
local height = el.attributes["height"] or "auto"
local style = string.format("width:%s;height:%s;", width, height)
local alt = pandoc.utils.stringify(el.caption)
return {
pandoc.RawInline('markdown', '<div class="center" style="' .. style .. '">'),
pandoc.RawInline('markdown', '<figure>'),
pandoc.RawInline('markdown', '<img src="' .. el.src .. '" alt="' .. alt ..'">'),
pandoc.RawInline('markdown', '<figcaption><h4>'),
pandoc.Str(alt),
pandoc.RawInline('markdown', '</h4></figcaption>'),
pandoc.RawInline('markdown', '</figure>'),
pandoc.RawInline('markdown', '</div>')
}
end
-- Replace native Divs with "real" Divs or Shortcodes
function Div(el)
-- Replace "showme" Div with "expand" Shortcode
if el.classes[1] == "showme" then
return
{ pandoc.RawBlock("markdown", '{{% expand "Show Me" %}}'), pandoc.RawBlock("markdown", "<div class='showme'>") } ..
el.content ..
{ pandoc.RawBlock("markdown", "</div>"), pandoc.RawBlock("markdown", "{{% /expand %}}") }
end
-- Transform all other native Divs to "real" Divs digestible to Hugo
return
{ pandoc.RawBlock("markdown", "<div class='" .. el.classes[1] .. "'>") } ..
el.content ..
{ pandoc.RawBlock("markdown", "</div>") }
end
-- Replace native Spans with "real" Spans or Shortcodes
function Span(el)
-- Replace "bsp" Span with "button" Shortcode
if el.classes[1] == "bsp" then
return
{ pandoc.RawInline("markdown", "{{% button-crossreference %}}") } ..
el.content ..
{ pandoc.RawInline("markdown", "{{% /button-crossreference %}}") }
end
-- Transform all other native Spans to "real" Spans digestible to Hugo
return
{ pandoc.RawInline("markdown", "<span class='" .. el.classes[1] .. "'>") } ..
el.content ..
{ pandoc.RawInline("markdown", "</span>") }
end
-- Handle citations
-- use "#id_KEY" as target => needs be be defined in the document
-- i.e. the shortcode/partial "bib.html" needs to create this targets
local keys = {}
function Cite(el)
-- translate a citation into a link
local citation_to_link = function(citation)
local id = citation.id
local suffix = pandoc.utils.stringify(citation.suffix)
-- remember this id, needs to be added to the meta data
keys[id] = true
-- create a link into the current document
return pandoc.Link("[" .. id .. suffix .. "]", "#id_" .. id)
end
-- replace citation with list of links
return el.citations:map(citation_to_link)
end
function Meta(md)
-- meta data "readings"
md.readings = md.readings or pandoc.MetaList(pandoc.List())
-- has a "readings" element "x" a "key" with value "k"?
local has_id = function(k)
return function(x) return pandoc.utils.stringify(x.key) == k end
end
-- collect all "keys" which are not in "readings"
for k, _ in pairs(keys) do
if #md.readings:filter(has_id(k)) == 0 then
md.readings:insert(pandoc.MetaMap{key = pandoc.MetaInlines{pandoc.Str(k)}})
end
end
return md
end
|
[FIX] Crossreference Tags are now no longer appearing as clickable buttons (#11)
|
[FIX] Crossreference Tags are now no longer appearing as clickable buttons (#11)
|
Lua
|
mit
|
cagix/pandoc-lecture
|
8507a4b786b07b1552823e7d84907b7f49460fab
|
lamp-placer_0.15.0/control.lua
|
lamp-placer_0.15.0/control.lua
|
local LAMP_DISTANCE = 8
local EXTRA = 10
local function droppedItem(event)
if not event.entity or not event.entity.stack then
return
end
if event.entity.stack.name == "lamp-placer" then
event.entity.stack.clear()
end
end
local function isInRange(position, x, y, range)
local diffX = math.abs(position.x - x)
local diffY = math.abs(position.y - y)
local diff = math.max(diffX, diffY)
return diff <= range
end
local function findElectricity(poles, x, y)
for _, entity in ipairs(poles) do
if isInRange(entity.position, x, y, entity.prototype.supply_area_distance) then
return true
end
end
return false
end
local function findLamp(lamps, x, y)
for _, entity in ipairs(lamps) do
if isInRange(entity.position, x, y, LAMP_DISTANCE) then
return true
end
end
end
local function round(value)
return math.floor(value + 0.5)
end
local function on_player_selected_area(event)
if event.item ~= "lamp-placer" then
return
end
local player = game.players[event.player_index]
local surface = player.surface
local destroyed_info = {}
local area = event.area
-- local searchEntities = event.entities
local searchEntities = surface.find_entities({ { event.area.left_top.x - EXTRA, event.area.left_top.y - EXTRA },
{ event.area.right_bottom.x + EXTRA, event.area.right_bottom.y + EXTRA } })
local lamps = {}
local electricity = {}
for _, entity in ipairs(searchEntities) do
if entity.type == "electric-pole" then
table.insert(electricity, entity)
end
if entity.type == "lamp" then
table.insert(lamps, entity)
end
end
local placables = 0
local electricities = 0
local noLamps = 0
local force = player.force
for x = round(event.area.left_top.x) + 0.5, round(event.area.right_bottom.x) - 0.5 do
for y = round(event.area.left_top.y) + 0.5, round(event.area.right_bottom.y) - 0.5 do
local position = { x = x, y = y }
local placable = surface.can_place_entity({ name = "small-lamp", position = position, force = force })
if placable then
placables = placables + 1
-- Check if there is electricity in area
local electricityFound = findElectricity(electricity, x, y)
if electricityFound then
electricities = electricities + 1
-- Check if there is an existing lamp in area
local lampFound = findLamp(lamps, x, y)
if not lampFound then
noLamps = noLamps + 1
local newLamp = surface.create_entity({ name = "entity-ghost", inner_name = "small-lamp", expires = false, position = { x, y }, force = force })
table.insert(lamps, newLamp)
end
end
end
end
end
player.print("Placed " .. noLamps .. " lamps on " .. placables .. " placable positions. " .. electricities .. " of which had electricity.")
end
script.on_event(defines.events.on_player_selected_area, on_player_selected_area)
script.on_event(defines.events.on_player_alt_selected_area, on_player_selected_area)
script.on_event(defines.events.on_player_dropped_item, droppedItem)
|
local LAMP_DISTANCE = 8
local EXTRA = 10
local function droppedItem(event)
if not event.entity or not event.entity.stack then
return
end
if event.entity.stack.name == "lamp-placer" then
event.entity.stack.clear()
end
end
local function isInRange(position, x, y, range)
local diffX = math.abs(position.x - x)
local diffY = math.abs(position.y - y)
local diff = math.max(diffX, diffY)
return diff <= range
end
local function findElectricity(poles, x, y)
for _, entity in ipairs(poles) do
if isInRange(entity.position, x, y, entity.prototype.supply_area_distance) then
return true
end
end
return false
end
local function findLamp(lamps, x, y)
for _, entity in ipairs(lamps) do
if isInRange(entity.position, x, y, LAMP_DISTANCE) then
return true
end
end
end
local function round(value)
return math.floor(value + 0.5)
end
local function on_player_selected_area(event)
if event.item ~= "lamp-placer" then
return
end
local player = game.players[event.player_index]
local surface = player.surface
-- local searchEntities = event.entities
local searchEntities = surface.find_entities({ { event.area.left_top.x - EXTRA, event.area.left_top.y - EXTRA },
{ event.area.right_bottom.x + EXTRA, event.area.right_bottom.y + EXTRA } })
local lamps = {}
local electricity = {}
for _, entity in ipairs(searchEntities) do
if entity.type == "electric-pole" then
table.insert(electricity, entity)
end
if entity.type == "lamp" then
table.insert(lamps, entity)
end
end
local placables = 0
local electricities = 0
local noLamps = 0
local force = player.force
for x = round(event.area.left_top.x) + 0.5, round(event.area.right_bottom.x) - 0.5 do
for y = round(event.area.left_top.y) + 0.5, round(event.area.right_bottom.y) - 0.5 do
local position = { x = x, y = y }
local placable = surface.can_place_entity({ name = "small-lamp", position = position, force = force })
if placable then
placables = placables + 1
-- Check if there is electricity in area
local electricityFound = findElectricity(electricity, x, y)
if electricityFound then
electricities = electricities + 1
-- Check if there is an existing lamp in area
local lampFound = findLamp(lamps, x, y)
if not lampFound then
noLamps = noLamps + 1
local newLamp = surface.create_entity({ name = "entity-ghost",
inner_name = "small-lamp", expires = false, position = { x, y }, force = force })
table.insert(lamps, newLamp)
end
end
end
end
end
player.print("Placed " .. noLamps .. " lamps on " .. placables ..
" placable positions. " .. electricities .. " of which had electricity.")
end
script.on_event(defines.events.on_player_selected_area, on_player_selected_area)
script.on_event(defines.events.on_player_alt_selected_area, on_player_selected_area)
script.on_event(defines.events.on_player_dropped_item, droppedItem)
|
Lamp Placer: Fix Luacheck warnings
|
Lamp Placer: Fix Luacheck warnings
|
Lua
|
mit
|
Zomis/FactorioMods
|
7a32750bbfa68baa0da1307237ce0af22cd1f55c
|
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 <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
if section.type and section.type == "bridge" then
network:value("br-"..section[".name"],section[".name"])
else
network:value(section[".name"])
end
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = 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
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
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 <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
network:value(section[".name"])
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = 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
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
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
|
Revert "* luci/olsr: fix names of interfaces with type bridge"
|
Revert "* luci/olsr: fix names of interfaces with type bridge"
This reverts commit 500499c2a0d7c5eeeddb621a8b96fad10523485b.
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2511 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
8devices/carambola2-luci,ch3n2k/luci,Flexibity/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,vhpham80/luci,alxhh/piratenluci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,stephank/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,gwlim/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,Flexibity/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,phi-psi/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,jschmidlapp/luci,phi-psi/luci,gwlim/luci,vhpham80/luci,phi-psi/luci,phi-psi/luci,alxhh/piratenluci,Flexibity/luci,alxhh/piratenluci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,saraedum/luci-packages-old,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,phi-psi/luci,alxhh/piratenluci,gwlim/luci,jschmidlapp/luci,vhpham80/luci,stephank/luci,Canaan-Creative/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,yeewang/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,Flexibity/luci,Flexibity/luci,ch3n2k/luci,ch3n2k/luci,zwhfly/openwrt-luci,stephank/luci,saraedum/luci-packages-old,Canaan-Creative/luci,gwlim/luci,alxhh/piratenluci,zwhfly/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,freifunk-gluon/luci,gwlim/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,stephank/luci,freifunk-gluon/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,yeewang/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,projectbismark/luci-bismark,Canaan-Creative/luci,Flexibity/luci,gwlim/luci,freifunk-gluon/luci,saraedum/luci-packages-old,stephank/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old
|
6d532d692d3406356da16d3e74b3e453f245606a
|
lib/resty/chash/server.lua
|
lib/resty/chash/server.lua
|
local jchash = require "resty.chash.jchash"
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
else
copy = orig
end
return copy
end
local function svname(server)
-- @server: {addr, port}
-- @return: concat the addr and port with ":" as seperator
return tostring(server[1] .. ":" .. tostring(server[2]))
end
local function init_name2id(servers)
-- map server name to ID
local map = {}
for id, s in ipairs(servers) do
-- name is just the concat of addr and port
map[ svname(s) ] = id
end
return map
end
local function update_name2id(old_servers, new_servers)
-- new servers may have some servers of the same name in the old ones.
-- we could assign the same id(if in range) to the server of same name,
-- and as to new servers whose name are new will be assigned to
-- one of the IDs there're available
local old_name2id = init_name2id(old_servers)
local new_name2id = init_name2id(new_servers)
local new_size = #new_servers -- new_size is also the maxmuim ID
local old_size = #old_servers
local unused_ids = {}
for old_id, old_sv in ipairs(old_servers) do
if old_id <= new_size then
local old_sv_name = svname(old_sv)
if new_name2id[ old_sv_name ] then
-- restore the old_id
new_name2id[ old_sv_name ] = old_id
else
-- old_id can be recycled
unused_ids[#unused_ids + 1] = old_id
end
else
-- ID that exceed maxmium ID is of no use, we should mark it nil.
-- the next next loop (assigning unused_ids) will make use of this mark
old_name2id[ svname(old_sv) ] = nil
end
end
for i = old_size + 1, new_size do -- only loop when old_size < new_size
unused_ids[#unused_ids + 1] = i
end
-- assign the unused_ids to the real new servers
local index = 1
for _, new_sv in ipairs(new_servers) do
local new_sv_name = svname(new_sv)
if not old_name2id[ new_sv_name ] then
-- it's a new server, or an old server whose old ID is too big
assert(index <= #unused_ids, "no enough IDs for new server")
new_name2id[ new_sv_name ] = unused_ids[index]
index = index + 1
end
end
assert(index == #unused_ids + 1, "recycled IDs are not exhausted")
return new_name2id
end
local _M = {}
local mt = { __index = _M }
function _M.new(servers)
local name2id = init_name2id(servers)
local ins = { servers = deepcopy(servers), name2id = name2id, size=#servers }
return setmetatable(ins, mt)
end
-- instance methods
function _M.lookup(self, key)
-- @key: user defined string, eg. uri
-- @return: tuple {addr, port}
local id = jchash.hash_short_str(key, self.size)
return self.servers[id]
end
function _M.update_servers(self, new_servers)
-- @new_servers: remove all old servers, and use the new servers
-- but we would keep the server whose name is not changed
-- in the same `id` slot, so consistence is maintained.
local old_servers = self.servers
self.servers = deepcopy(new_servers)
self.size = #new_servers
self.name2id = update_name2id(old_servers, self.servers)
end
return _M
|
local jchash = require "resty.chash.jchash"
local ok, new_table = pcall(require, "table.new")
if not ok then
new_table = function (narr, nrec) return {} end
end
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
else
copy = orig
end
return copy
end
local function svname(server)
-- @server: {addr, port}
-- @return: concat the addr and port with ":" as seperator
return tostring(server[1] .. ":" .. tostring(server[2]))
end
local function init_name2id(servers)
-- map server name to ID
local map = {}
for id, s in ipairs(servers) do
-- name is just the concat of addr and port
map[ svname(s) ] = id
end
return map
end
local function update_name2id(old_servers, new_servers)
-- new servers may have some servers of the same name in the old ones.
-- we could assign the same id(if in range) to the server of same name,
-- and as to new servers whose name are new will be assigned to
-- one of the IDs there're available
local old_name2id = init_name2id(old_servers)
local new_name2id = init_name2id(new_servers)
local new_size = #new_servers -- new_size is also the maxmuim ID
local old_size = #old_servers
local unused_ids = {}
for old_id, old_sv in ipairs(old_servers) do
if old_id <= new_size then
local old_sv_name = svname(old_sv)
if new_name2id[ old_sv_name ] then
-- restore the old_id
new_name2id[ old_sv_name ] = old_id
else
-- old_id can be recycled
unused_ids[#unused_ids + 1] = old_id
end
else
-- ID that exceed maxmium ID is of no use, we should mark it nil.
-- the next next loop (assigning unused_ids) will make use of this mark
old_name2id[ svname(old_sv) ] = nil
end
end
for i = old_size + 1, new_size do -- only loop when old_size < new_size
unused_ids[#unused_ids + 1] = i
end
-- assign the unused_ids to the real new servers
local index = 1
for _, new_sv in ipairs(new_servers) do
local new_sv_name = svname(new_sv)
if not old_name2id[ new_sv_name ] then
-- it's a new server, or an old server whose old ID is too big
assert(index <= #unused_ids, "no enough IDs for new server")
new_name2id[ new_sv_name ] = unused_ids[index]
index = index + 1
end
end
assert(index == #unused_ids + 1, "recycled IDs are not exhausted")
return new_name2id
end
local _M = {}
local mt = { __index = _M }
function _M.new(servers)
if not servers then
return
end
local name2id = init_name2id(servers)
local ins = { servers = deepcopy(servers), name2id = name2id, size=#servers }
return setmetatable(ins, mt)
end
-- instance methods
function _M.lookup(self, key)
-- @key: user defined string, eg. uri
-- @return: tuple {addr, port}
local id = jchash.hash_short_str(key, self.size)
return self.servers[id]
end
function _M.update_servers(self, new_servers)
-- @new_servers: remove all old servers, and use the new servers
-- but we would keep the server whose name is not changed
-- in the same `id` slot, so consistence is maintained.
if not new_servers then
return
end
local old_servers = self.servers
local new_servers = deepcopy(new_servers)
self.size = #new_servers
self.name2id = update_name2id(old_servers, new_servers)
self.servers = new_table(self.size, 0)
for _, s in ipairs(new_servers) do
self.servers[self.name2id[ svname(s) ]] = s
end
end
function _M.debug(self)
print("*****************")
print("* size: " .. tostring(self.size))
print("* servers: ")
for _, s in ipairs(self.servers) do
print(svname(s))
end
print("* name2id map:")
for k, v in pairs(self.name2id) do
print(k .. " = " .. v)
end
end
return _M
|
fix bug: updating servers didn't rearrange the servers' list
|
fix bug: updating servers didn't rearrange the servers' list
|
Lua
|
mit
|
ruoshan/lua-resty-jump-consistent-hash,ruoshan/lua-resty-jump-consistent-hash
|
c443fe3355ec4b6cab1b615da2342f03555122f6
|
build/Helpers.lua
|
build/Helpers.lua
|
-- This module checks for the all the project dependencies.
newoption {
trigger = "arch",
description = "Choose a particular architecture / bitness",
allowed = {
{ "x86", "x86 32-bits" },
{ "x64", "x64 64-bits" },
{ "AnyCPU", "Any CPU (.NET)" },
}
}
newoption {
trigger = "no-cxx11-abi",
description = "disable C++-11 ABI on GCC 4.9+"
}
newoption {
trigger = "disable-tests",
description = "disable tests from being included"
}
newoption {
trigger = "disable-examples",
description = "disable examples from being included"
}
newoption {
trigger = "debug",
description = "enable debug mode"
}
explicit_target_architecture = _OPTIONS["arch"]
function get_mono_path()
local mono = "mono"
local result, errorcode = os.outputof(mono .. " --version")
if result == nil and os.ishost("macosx") then
mono = "/Library/Frameworks/Mono.framework/Versions/Current/bin/" .. mono
result, errorcode = os.outputof(mono .. " --version")
end
if result == nil then
print("Could not find Mono executable, please make sure it is in PATH.")
os.exit(1)
end
return mono
end
function is_64_bits_mono_runtime()
local result, errorcode = os.outputof(get_mono_path() .. " --version")
local arch = string.match(result, "Architecture:%s*([%w]+)")
return arch == "amd64"
end
function target_architecture()
if _ACTION == "netcore" then
return "AnyCPU"
end
-- Default to 64-bit on Windows and Mono architecture otherwise.
if explicit_target_architecture ~= nil then
return explicit_target_architecture
end
if os.ishost("windows") then return "x64" end
return is_64_bits_mono_runtime() and "x64" or "x86"
end
if not _OPTIONS["arch"] then
_OPTIONS["arch"] = target_architecture()
end
-- Uncomment to enable Roslyn compiler.
--[[
premake.override(premake.tools.dotnet, "gettoolname", function(base, cfg, tool)
if tool == "csc" then
return "csc"
end
return base(cfg, tool)
end)
]]
basedir = path.getdirectory(_PREMAKE_COMMAND)
premake.path = premake.path .. ";" .. path.join(basedir, "modules")
depsdir = path.getabsolute("../deps");
srcdir = path.getabsolute("../src");
incdir = path.getabsolute("../include");
bindir = path.getabsolute("../bin");
examplesdir = path.getabsolute("../examples");
testsdir = path.getabsolute("../tests");
local function get_build_dir()
if _ARGS[1] then
return _ARGS[1]
end
return _ACTION == "gmake2" and "gmake" or _ACTION
end
builddir = path.getabsolute("./" .. get_build_dir());
if _ACTION ~= "netcore" then
objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}_%{cfg.platform}");
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}");
else
objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}");
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}");
end
gendir = libdir;
msvc_buildflags = { "/MP", "/wd4267" }
msvc_cpp_defines = { }
generate_build_config = true
function string.starts(str, start)
if str == nil then return end
return string.sub(str, 1, string.len(start)) == start
end
function SafePath(path)
return "\"" .. path .. "\""
end
function SetupNativeProject()
location ("%{wks.location}/projects")
filter { "configurations:Debug" }
defines { "DEBUG" }
filter { "configurations:Release" }
defines { "NDEBUG" }
optimize "On"
-- Compiler-specific options
filter { "action:vs*" }
buildoptions { msvc_buildflags }
defines { msvc_cpp_defines }
filter { "system:linux" }
buildoptions { gcc_buildflags }
links { "stdc++" }
filter { "toolset:clang", "system:not macosx" }
linkoptions { "-fuse-ld=/usr/bin/ld.lld" }
filter { "system:macosx", "language:C++" }
buildoptions { gcc_buildflags, "-stdlib=libc++" }
links { "c++" }
filter { "system:not windows", "language:C++" }
cppdialect "C++14"
buildoptions { "-fpermissive" }
-- OS-specific options
filter { "system:windows" }
defines { "WIN32", "_WINDOWS" }
-- For context: https://github.com/premake/premake-core/issues/935
filter {"system:windows", "action:vs*"}
systemversion("latest")
filter {}
end
function SetupManagedProject()
language "C#"
location ("%{wks.location}/projects")
buildoptions {"/langversion:7.3"}
buildoptions {"/platform:".._OPTIONS["arch"]}
dotnetframework "4.7.2"
if not os.istarget("macosx") then
filter { "action:vs* or netcore" }
location "."
filter {}
end
filter { "action:netcore" }
dotnetframework "netstandard2.0"
filter {}
end
function IncludeDir(dir)
local deps = os.matchdirs(dir .. "/*")
for i,dep in ipairs(deps) do
local fp = path.join(dep, "premake5.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
include(dep)
return
end
fp = path.join(dep, "premake4.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
--print(string.format(" including %s", dep))
include(dep)
end
end
end
function StaticLinksOpt(libnames)
local path = table.concat(cc.configset.libdirs, ";")
local formats
if os.is("windows") then
formats = { "%s.lib" }
else
formats = { "lib%s.a" }
end
table.insert(formats, "%s");
local existing_libnames = {}
for _, libname in ipairs(libnames) do
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
if os.pathsearch(name, path) then
table.insert(existing_libnames, libname)
end
end
end
links(existing_libnames)
end
function UseClang()
local compiler = os.getenv("CXX") or ""
return string.match(compiler, "clang")
end
function GccVersion()
local compiler = os.getenv("CXX")
if compiler == nil then
compiler = "gcc"
end
local out = os.outputof(compiler.." -v")
local version = string.match(out, "gcc version [0-9\\.]+")
if version == nil then
version = string.match(out, "clang version [0-9\\.]+")
end
return string.sub(version, 13)
end
function UseCxx11ABI()
if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then
return true
end
return false
end
function EnableNativeProjects()
if _ACTION == "netcore" then
return false
end
if string.starts(_ACTION, "vs") and not os.ishost("windows") then
return false
end
return true
end
|
-- This module checks for the all the project dependencies.
newoption {
trigger = "arch",
description = "Choose a particular architecture / bitness",
allowed = {
{ "x86", "x86 32-bits" },
{ "x64", "x64 64-bits" },
{ "AnyCPU", "Any CPU (.NET)" },
}
}
newoption {
trigger = "no-cxx11-abi",
description = "disable C++-11 ABI on GCC 4.9+"
}
newoption {
trigger = "disable-tests",
description = "disable tests from being included"
}
newoption {
trigger = "disable-examples",
description = "disable examples from being included"
}
newoption {
trigger = "debug",
description = "enable debug mode"
}
explicit_target_architecture = _OPTIONS["arch"]
function get_mono_path()
local mono = "mono"
local result, errorcode = os.outputof(mono .. " --version")
if result == nil and os.ishost("macosx") then
mono = "/Library/Frameworks/Mono.framework/Versions/Current/bin/" .. mono
result, errorcode = os.outputof(mono .. " --version")
end
if result == nil then
print("Could not find Mono executable, please make sure it is in PATH.")
os.exit(1)
end
return mono
end
function is_64_bits_mono_runtime()
local result, errorcode = os.outputof(get_mono_path() .. " --version")
local arch = string.match(result, "Architecture:%s*([%w]+)")
return arch == "amd64"
end
function target_architecture()
if _ACTION == "netcore" then
return "AnyCPU"
end
-- Default to 64-bit on Windows and Mono architecture otherwise.
if explicit_target_architecture ~= nil then
return explicit_target_architecture
end
if os.ishost("windows") then return "x64" end
return is_64_bits_mono_runtime() and "x64" or "x86"
end
if not _OPTIONS["arch"] then
_OPTIONS["arch"] = target_architecture()
end
-- Uncomment to enable Roslyn compiler.
--[[
premake.override(premake.tools.dotnet, "gettoolname", function(base, cfg, tool)
if tool == "csc" then
return "csc"
end
return base(cfg, tool)
end)
]]
basedir = path.getdirectory(_PREMAKE_COMMAND)
premake.path = premake.path .. ";" .. path.join(basedir, "modules")
depsdir = path.getabsolute("../deps");
srcdir = path.getabsolute("../src");
incdir = path.getabsolute("../include");
bindir = path.getabsolute("../bin");
examplesdir = path.getabsolute("../examples");
testsdir = path.getabsolute("../tests");
local function get_build_dir()
if _ARGS[1] then
return _ARGS[1]
end
if not _ACTION then
return ""
end
return _ACTION == "gmake2" and "gmake" or _ACTION
end
builddir = path.getabsolute("./" .. get_build_dir());
if _ACTION ~= "netcore" then
objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}_%{cfg.platform}");
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}");
else
objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}");
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}");
end
gendir = libdir;
msvc_buildflags = { "/MP", "/wd4267" }
msvc_cpp_defines = { }
generate_build_config = true
function string.starts(str, start)
if str == nil then return end
return string.sub(str, 1, string.len(start)) == start
end
function SafePath(path)
return "\"" .. path .. "\""
end
function SetupNativeProject()
location ("%{wks.location}/projects")
filter { "configurations:Debug" }
defines { "DEBUG" }
filter { "configurations:Release" }
defines { "NDEBUG" }
optimize "On"
-- Compiler-specific options
filter { "action:vs*" }
buildoptions { msvc_buildflags }
defines { msvc_cpp_defines }
filter { "system:linux" }
buildoptions { gcc_buildflags }
links { "stdc++" }
filter { "toolset:clang", "system:not macosx" }
linkoptions { "-fuse-ld=/usr/bin/ld.lld" }
filter { "system:macosx", "language:C++" }
buildoptions { gcc_buildflags, "-stdlib=libc++" }
links { "c++" }
filter { "system:not windows", "language:C++" }
cppdialect "C++14"
buildoptions { "-fpermissive" }
-- OS-specific options
filter { "system:windows" }
defines { "WIN32", "_WINDOWS" }
-- For context: https://github.com/premake/premake-core/issues/935
filter {"system:windows", "action:vs*"}
systemversion("latest")
filter {}
end
function SetupManagedProject()
language "C#"
location ("%{wks.location}/projects")
buildoptions {"/langversion:7.3"}
buildoptions {"/platform:".._OPTIONS["arch"]}
dotnetframework "4.7.2"
if not os.istarget("macosx") then
filter { "action:vs* or netcore" }
location "."
filter {}
end
filter { "action:netcore" }
dotnetframework "netstandard2.0"
filter {}
end
function IncludeDir(dir)
local deps = os.matchdirs(dir .. "/*")
for i,dep in ipairs(deps) do
local fp = path.join(dep, "premake5.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
include(dep)
return
end
fp = path.join(dep, "premake4.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
--print(string.format(" including %s", dep))
include(dep)
end
end
end
function StaticLinksOpt(libnames)
local path = table.concat(cc.configset.libdirs, ";")
local formats
if os.is("windows") then
formats = { "%s.lib" }
else
formats = { "lib%s.a" }
end
table.insert(formats, "%s");
local existing_libnames = {}
for _, libname in ipairs(libnames) do
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
if os.pathsearch(name, path) then
table.insert(existing_libnames, libname)
end
end
end
links(existing_libnames)
end
function UseClang()
local compiler = os.getenv("CXX") or ""
return string.match(compiler, "clang")
end
function GccVersion()
local compiler = os.getenv("CXX")
if compiler == nil then
compiler = "gcc"
end
local out = os.outputof(compiler.." -v")
local version = string.match(out, "gcc version [0-9\\.]+")
if version == nil then
version = string.match(out, "clang version [0-9\\.]+")
end
return string.sub(version, 13)
end
function UseCxx11ABI()
if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then
return true
end
return false
end
function EnableNativeProjects()
if _ACTION == "netcore" then
return false
end
if string.starts(_ACTION, "vs") and not os.ishost("windows") then
return false
end
return true
end
|
Fix minor issue when invoking Premake without an action.
|
Fix minor issue when invoking Premake without an action.
|
Lua
|
mit
|
mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp
|
a4eaf0ca6ff586a302b60cc8bda6255bc8217f42
|
src/servicebag/src/Shared/ServiceBag.lua
|
src/servicebag/src/Shared/ServiceBag.lua
|
---
-- @classmod ServiceBag
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local BaseObject = require("BaseObject")
local ServiceBag = setmetatable({}, BaseObject)
ServiceBag.ClassName = "ServiceBag"
ServiceBag.__index = ServiceBag
-- parentProvider is optional
function ServiceBag.new(parentProvider)
local self = setmetatable(BaseObject.new(), ServiceBag)
self._services = {}
self._parentProvider = parentProvider
self._servicesToInitialize = {}
self._initializing = false
self._servicesToStart = {}
self._destroying = Signal.new()
self._maid:GiveTask(self._destroying)
return self
end
function ServiceBag.isServiceBag(serviceBag)
return type(serviceBag) == "table"
and serviceBag.ClassName == "ServiceBag"
end
function ServiceBag:GetService(serviceType)
if typeof(serviceType) == "Instance" then
serviceType = require(serviceType)
end
local service = self._services[serviceType]
if service then
-- Ensure initialized if we're during inint phase
if self._servicesToInitialize and self._initializing then
local index = table.find(self._servicesToInitialize, service)
if index then
local foundService = assert(table.remove(self._servicesToInitialize, index), "No service removed")
assert(foundService == service, "foundService ~= service")
self:_initService(service)
end
end
return self._services[serviceType]
end
if self._parentProvider then
return self._parentProvider:GetService(serviceType)
end
-- Try to add the service if we're still initializing services
self:_addService(serviceType)
return self._services[serviceType]
end
function ServiceBag:Init()
assert(not self._initializing, "Already initializing")
assert(self._servicesToInitialize, "Already initialized")
self._initializing = true
while next(self._servicesToInitialize) do
local service = table.remove(self._servicesToInitialize)
self:_initService(service)
end
self._servicesToInitialize = nil
self._initializing = false
end
function ServiceBag:Start()
assert(self._servicesToStart, "Already started")
assert(not self._initializing, "Still initializing")
while next(self._servicesToStart) do
local service = table.remove(self._servicesToStart)
if service.Start then
service:Start()
end
end
self._servicesToStart = nil
end
--- Adds a service to this provider only
function ServiceBag:_addService(serviceType)
assert(self._servicesToInitialize, "Already finished initializing, cannot add more services")
-- Already added
if self._services[serviceType] then
return
end
-- Construct a new version of this service so we're isolated
local service = setmetatable({}, { __index = serviceType })
self._services[serviceType] = service
if self._initializing then
-- let's initialize immediately
self:_initService(service)
else
table.insert(self._servicesToInitialize, serviceType)
end
end
function ServiceBag:_initService(service)
if service.Init then
service:Init(self)
end
table.insert(self._servicesToStart, service)
end
function ServiceBag:CreateScope()
local provider = ServiceBag.new(self)
self._services[provider] = provider
-- Remove from parent provider
self._maid[provider] = provider._destroying:Connect(function()
self._maid[provider] = nil
self._services[provider] = nil
end)
return provider
end
function ServiceBag:Destroy()
local super = getmetatable(ServiceBag)
self._destroying:Fire()
local services = self._services
local key, service = next(services)
while service ~= nil do
services[key] = nil
if service.Destroy then
service:Destroy()
end
key, service = next(services)
end
super.Destroy(self)
end
return ServiceBag
|
---
-- @classmod ServiceBag
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local BaseObject = require("BaseObject")
local ServiceBag = setmetatable({}, BaseObject)
ServiceBag.ClassName = "ServiceBag"
ServiceBag.__index = ServiceBag
-- parentProvider is optional
function ServiceBag.new(parentProvider)
local self = setmetatable(BaseObject.new(), ServiceBag)
self._services = {}
self._parentProvider = parentProvider
self._serviceTypesToInitialize = {}
self._initializing = false
self._serviceTypesToStart = {}
self._destroying = Signal.new()
self._maid:GiveTask(self._destroying)
return self
end
function ServiceBag.isServiceBag(serviceBag)
return type(serviceBag) == "table"
and serviceBag.ClassName == "ServiceBag"
end
function ServiceBag:GetService(serviceType)
if typeof(serviceType) == "Instance" then
serviceType = require(serviceType)
end
local service = self._services[serviceType]
if service then
-- Ensure initialized if we're during init phase
if self._serviceTypesToInitialize and self._initializing then
local index = table.find(self._serviceTypesToInitialize, service)
if index then
local foundServiceType = assert(table.remove(self._serviceTypesToInitialize, index), "No service removed")
assert(foundServiceType == service, "foundServiceType ~= service")
self:_initService(foundServiceType)
end
end
return self._services[serviceType]
end
if self._parentProvider then
return self._parentProvider:GetService(serviceType)
end
-- Try to add the service if we're still initializing services
self:_addServiceType(serviceType)
return self._services[serviceType]
end
function ServiceBag:Init()
assert(not self._initializing, "Already initializing")
assert(self._serviceTypesToInitialize, "Already initialized")
self._initializing = true
while next(self._serviceTypesToInitialize) do
local serviceType = table.remove(self._serviceTypesToInitialize)
self:_initService(serviceType)
end
self._serviceTypesToInitialize = nil
self._initializing = false
end
function ServiceBag:Start()
assert(self._serviceTypesToStart, "Already started")
assert(not self._initializing, "Still initializing")
while next(self._serviceTypesToStart) do
local serviceType = table.remove(self._serviceTypesToStart)
local service = assert(self._services[serviceType], "No service")
if service.Start then
service:Start()
end
end
self._serviceTypesToStart = nil
end
--- Adds a service to this provider only
function ServiceBag:_addServiceType(serviceType)
assert(self._serviceTypesToInitialize, "Already finished initializing, cannot add more services")
-- Already added
if self._services[serviceType] then
return
end
-- Construct a new version of this service so we're isolated
local service = setmetatable({}, { __index = serviceType })
self._services[serviceType] = service
if self._initializing then
-- let's initialize immediately
self:_initService(serviceType)
else
table.insert(self._serviceTypesToInitialize, serviceType)
end
end
function ServiceBag:_initService(serviceType)
local service = assert(self._services[serviceType], "No service")
if service.Init then
service:Init(self)
end
table.insert(self._serviceTypesToStart, serviceType)
end
function ServiceBag:CreateScope()
local provider = ServiceBag.new(self)
self._services[provider] = provider
-- Remove from parent provider
self._maid[provider] = provider._destroying:Connect(function()
self._maid[provider] = nil
self._services[provider] = nil
end)
return provider
end
function ServiceBag:Destroy()
local super = getmetatable(ServiceBag)
self._destroying:Fire()
local services = self._services
local key, service = next(services)
while service ~= nil do
services[key] = nil
if service.Destroy then
service:Destroy()
end
key, service = next(services)
end
super.Destroy(self)
end
return ServiceBag
|
fix: Enforce service retrieve returning correct memory address and initializing a separate table
|
fix: Enforce service retrieve returning correct memory address and initializing a separate table
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
d0ee708f83df69663ebab036dbb5a6ef938e4f6c
|
libs/format.lua
|
libs/format.lua
|
local md5 = require('./libs/md5')
local fmt = {
ae = function(s)
local r = ''
for i=1,#s do
local v = s:sub(i, i):byte(1)
if v == 32 then -- Special case for space
r = r .. string.char(227, 128, 128)
elseif v >= 33 and v <= 95 then -- ! to _
r = r .. string.char(239, 188, v - 33 + 129)
elseif v >= 96 and v <= 127 then -- ` to ~
r = r .. string.char(239, 189, v - 96 + 128)
else
r = r .. string.char(v)
end
end
return r
end,
sb = function(s)
return s:gsub('[a-zA-Z]', function(r)
if math.random(2) == 1 then
return r:upper()
else
return r:lower()
end
end)
end,
sp = function(s)
return s:gsub('(.)', '%1 '):gsub(' +$', '')
end,
ro = function(s)
local ws = {}
for w in s:gmatch('%S+') do
ws[#ws + 1] = w
end
for i=1,#ws do
local r = math.random(#ws)
ws[i], ws[r] = ws[r], ws[i]
end
return table.concat(ws, ' ')
end
}
-- Eventual TODO: Nested formats
return function(str)
return str:gsub('{(%S+)%s+(%S.-)}', function(ops, param)
for op in ops:gmatch('[^+]+') do
if fmt[op] then
param = fmt[op](param)
end
end
return param
end)
end
|
local md5 = require('./libs/md5')
local fmt = {
ae = function(s) -- Convert any ascii to fullwidth
local r = ''
for i=1,#s do
local v = s:sub(i, i):byte(1)
if v == 32 then -- Special case for space
r = r .. string.char(227, 128, 128)
elseif v >= 33 and v <= 95 then -- ! to _
r = r .. string.char(239, 188, v - 33 + 129)
elseif v >= 96 and v <= 127 then -- ` to ~
r = r .. string.char(239, 189, v - 96 + 128)
else
r = r .. string.char(v)
end
end
return r
end,
sb = function(s) -- Retarded spongebob
return s:gsub('[a-zA-Z]', function(r)
if math.random(2) == 1 then
return r:upper()
else
return r:lower()
end
end)
end,
sp = function(s) -- Adds spaces after every characters
return s:gsub('(.)', function(c)
if c:byte(1) < 127 then
return c..' '
end
end):gsub(' +$', '')
end,
ro = function(s) -- Randomly shuffles words
local ws = {}
for w in s:gmatch('%S+') do
ws[#ws + 1] = w
end
for i=1,#ws do
local r = math.random(#ws)
ws[i], ws[r] = ws[r], ws[i]
end
return table.concat(ws, ' ')
end
}
-- Eventual TODO: Nested formats
return function(str)
return str:gsub('{(%S+)%s+(%S.-)}', function(ops, param)
for op in ops:gmatch('[^+]+') do
if fmt[op] then
param = fmt[op](param)
end
end
return param
end)
end
|
format.lua: quick fix for sp unicode support
|
format.lua: quick fix for sp unicode support
|
Lua
|
mit
|
LazyShpee/discord-egobot
|
541ccdc6134a6340afcf9e0f9612f2a86e733ed6
|
share/lua/intf/modules/common.lua
|
share/lua/intf/modules/common.lua
|
--[[ This code is public domain (since it really isn't very interesting) ]]--
module("common",package.seeall)
-- Iterate over a table in the keys' alphabetical order
function pairs_sorted(t)
local s = {}
for k,_ in pairs(t) do table.insert(s,k) end
table.sort(s)
local i = 0
return function () i = i + 1; return s[i], t[s[i]] end
end
-- Return a function such as skip(foo)(a,b,c) = foo(b,c)
function skip(foo)
return function(discard,...) return foo(...) end
end
-- Return a function such as setarg(foo,a)(b,c) = foo(a,b,c)
function setarg(foo,a)
return function(...) return foo(a,...) end
end
-- Trigger a hotkey
function hotkey(arg)
local id = vlc.misc.action_id( arg )
if id ~= nil then
vlc.var.set( vlc.object.libvlc(), "key-action", id )
return true
else
return false
end
end
-- Take a video snapshot
function snapshot()
local vout = vlc.object.vout()
if not vout then return end
vlc.var.set(vout,"video-snapshot",nil)
end
-- Naive (non recursive) table copy
function table_copy(t)
c = {}
for i,v in pairs(t) do c[i]=v end
return c
end
-- tonumber() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tonumber(str)
local i, d = string.match(str, "([+-]?%d*)%.?(%d*)")
if i == nil or i == "" then
i = "0"
end
if d == nil or d == "" then
d = "0"
end
return tonumber(i) + tonumber(d)/(10^string.len(d))
end
-- strip leading and trailing spaces
function strip(str)
return string.gsub(str, "^%s*(.-)%s*$", "%1")
end
-- print a table (recursively)
function table_print(t,prefix)
local prefix = prefix or ""
if not t then
print(prefix.."/!\\ nil")
return
end
for a,b in pairs_sorted(t) do
print(prefix..tostring(a),b)
if type(b)==type({}) then
table_print(b,prefix.."\t")
end
end
end
-- print the list of callbacks registered in lua
-- useful for debug purposes
function print_callbacks()
print "callbacks:"
table_print(vlc.callbacks)
end
-- convert a duration (in seconds) to a string
function durationtostring(duration)
return string.format("%02d:%02d:%02d",
math.floor(duration/3600),
math.floor(duration/60)%60,
math.floor(duration%60))
end
-- realpath
function realpath(path)
return string.gsub(string.gsub(string.gsub(string.gsub(path,"/%.%./[^/]+","/"),"/[^/]+/%.%./","/"),"/%./","/"),"//","/")
end
-- parse the time from a string and return the seconds
-- time format: [+ or -][<int><H or h>:][<int><M or m or '>:][<int><nothing or S or s or ">]
function parsetime(timestring)
local seconds = 0
local hourspattern = "(%d+)[hH]"
local minutespattern = "(%d+)[mM']"
local secondspattern = "(%d+)[sS\"]?$"
local _, _, hoursmatch = string.find(timestring, hourspattern)
if hoursmatch ~= nil then
seconds = seconds + tonumber(hoursmatch) * 3600
end
local _, _, minutesmatch = string.find(timestring, minutespattern)
if minutesmatch ~= nil then
seconds = seconds + tonumber(minutesmatch) * 60
end
local _, _, secondsmatch = string.find(timestring, secondspattern)
if secondsmatch ~= nil then
seconds = seconds + tonumber(secondsmatch)
end
if string.sub(timestring,1,1) == "-" then
seconds = seconds * -1
end
return seconds
end
-- seek
function seek(value)
local input = vlc.object.input()
if input ~= nil and value ~= nil then
if string.sub(value,-1) == "%" then
local number = us_tonumber(string.sub(value,1,-2))
if number ~= nil then
local posPercent = number/100.
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"position",vlc.var.get(input,"position") + posPercent)
else
vlc.var.set(input,"position",posPercent)
end
end
else
local posTime = parsetime(value)
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"time",vlc.var.get(input,"time") + posTime)
else
vlc.var.set(input,"time",posTime)
end
end
end
end
function volume(value)
if type(value)=="string" and string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.volume.set(vlc.volume.get()+tonumber(value))
else
vlc.volume.set(tostring(value))
end
end
|
--[[ This code is public domain (since it really isn't very interesting) ]]--
module("common",package.seeall)
-- Iterate over a table in the keys' alphabetical order
function pairs_sorted(t)
local s = {}
for k,_ in pairs(t) do table.insert(s,k) end
table.sort(s)
local i = 0
return function () i = i + 1; return s[i], t[s[i]] end
end
-- Return a function such as skip(foo)(a,b,c) = foo(b,c)
function skip(foo)
return function(discard,...) return foo(...) end
end
-- Return a function such as setarg(foo,a)(b,c) = foo(a,b,c)
function setarg(foo,a)
return function(...) return foo(a,...) end
end
-- Trigger a hotkey
function hotkey(arg)
local id = vlc.misc.action_id( arg )
if id ~= nil then
vlc.var.set( vlc.object.libvlc(), "key-action", id )
return true
else
return false
end
end
-- Take a video snapshot
function snapshot()
local vout = vlc.object.vout()
if not vout then return end
vlc.var.set(vout,"video-snapshot",nil)
end
-- Naive (non recursive) table copy
function table_copy(t)
c = {}
for i,v in pairs(t) do c[i]=v end
return c
end
-- tonumber() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tonumber(str)
local s, i, d = string.match(str, "^([+-]?)(%d*)%.?(%d*)$")
if not s or not i or not d then
return nil
end
if s == "-" then
s = -1
else
s = 1
end
if i == "" then
i = "0"
end
if d == nil or d == "" then
d = "0"
end
return s * (tonumber(i) + tonumber(d)/(10^string.len(d)))
end
-- strip leading and trailing spaces
function strip(str)
return string.gsub(str, "^%s*(.-)%s*$", "%1")
end
-- print a table (recursively)
function table_print(t,prefix)
local prefix = prefix or ""
if not t then
print(prefix.."/!\\ nil")
return
end
for a,b in pairs_sorted(t) do
print(prefix..tostring(a),b)
if type(b)==type({}) then
table_print(b,prefix.."\t")
end
end
end
-- print the list of callbacks registered in lua
-- useful for debug purposes
function print_callbacks()
print "callbacks:"
table_print(vlc.callbacks)
end
-- convert a duration (in seconds) to a string
function durationtostring(duration)
return string.format("%02d:%02d:%02d",
math.floor(duration/3600),
math.floor(duration/60)%60,
math.floor(duration%60))
end
-- realpath
function realpath(path)
return string.gsub(string.gsub(string.gsub(string.gsub(path,"/%.%./[^/]+","/"),"/[^/]+/%.%./","/"),"/%./","/"),"//","/")
end
-- parse the time from a string and return the seconds
-- time format: [+ or -][<int><H or h>:][<int><M or m or '>:][<int><nothing or S or s or ">]
function parsetime(timestring)
local seconds = 0
local hourspattern = "(%d+)[hH]"
local minutespattern = "(%d+)[mM']"
local secondspattern = "(%d+)[sS\"]?$"
local _, _, hoursmatch = string.find(timestring, hourspattern)
if hoursmatch ~= nil then
seconds = seconds + tonumber(hoursmatch) * 3600
end
local _, _, minutesmatch = string.find(timestring, minutespattern)
if minutesmatch ~= nil then
seconds = seconds + tonumber(minutesmatch) * 60
end
local _, _, secondsmatch = string.find(timestring, secondspattern)
if secondsmatch ~= nil then
seconds = seconds + tonumber(secondsmatch)
end
if string.sub(timestring,1,1) == "-" then
seconds = seconds * -1
end
return seconds
end
-- seek
function seek(value)
local input = vlc.object.input()
if input ~= nil and value ~= nil then
if string.sub(value,-1) == "%" then
local number = us_tonumber(string.sub(value,1,-2))
if number ~= nil then
local posPercent = number/100.
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"position",vlc.var.get(input,"position") + posPercent)
else
vlc.var.set(input,"position",posPercent)
end
end
else
local posTime = parsetime(value)
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"time",vlc.var.get(input,"time") + posTime)
else
vlc.var.set(input,"time",posTime)
end
end
end
end
function volume(value)
if type(value)=="string" and string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.volume.set(vlc.volume.get()+tonumber(value))
else
vlc.volume.set(tostring(value))
end
end
|
lua: fix sign errors in us_tonumber()
|
lua: fix sign errors in us_tonumber()
|
Lua
|
lgpl-2.1
|
jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc
|
92fc9cd62f680a36c02be7a9c1364cc215c7d10e
|
libs/web/luasrc/template.lua
|
libs/web/luasrc/template.lua
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
luci.fs.chmod(luci.fs.dirname(compiledir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
* Fixed last commit
|
* Fixed last commit
|
Lua
|
apache-2.0
|
RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,kuoruan/luci,remakeelectric/luci,mumuqz/luci,wongsyrone/luci-1,nwf/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,chris5560/openwrt-luci,male-puppies/luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,keyidadi/luci,florian-shellfire/luci,oyido/luci,jorgifumi/luci,openwrt-es/openwrt-luci,keyidadi/luci,shangjiyu/luci-with-extra,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,teslamint/luci,thess/OpenWrt-luci,joaofvieira/luci,deepak78/new-luci,hnyman/luci,harveyhu2012/luci,NeoRaider/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,schidler/ionic-luci,thess/OpenWrt-luci,obsy/luci,jorgifumi/luci,nwf/openwrt-luci,openwrt/luci,daofeng2015/luci,openwrt/luci,cshore/luci,jlopenwrtluci/luci,oyido/luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,dwmw2/luci,teslamint/luci,bittorf/luci,hnyman/luci,opentechinstitute/luci,opentechinstitute/luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,dismantl/luci-0.12,lcf258/openwrtcn,jlopenwrtluci/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,Noltari/luci,thesabbir/luci,slayerrensky/luci,daofeng2015/luci,oneru/luci,aa65535/luci,forward619/luci,MinFu/luci,florian-shellfire/luci,sujeet14108/luci,florian-shellfire/luci,thesabbir/luci,daofeng2015/luci,jchuang1977/luci-1,wongsyrone/luci-1,cappiewu/luci,981213/luci-1,rogerpueyo/luci,RuiChen1113/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,slayerrensky/luci,cshore/luci,NeoRaider/luci,fkooman/luci,urueedi/luci,dismantl/luci-0.12,david-xiao/luci,fkooman/luci,tcatm/luci,deepak78/new-luci,palmettos/test,ff94315/luci-1,artynet/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,Hostle/luci,obsy/luci,lcf258/openwrtcn,ollie27/openwrt_luci,Noltari/luci,deepak78/new-luci,teslamint/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,lcf258/openwrtcn,bittorf/luci,lbthomsen/openwrt-luci,taiha/luci,harveyhu2012/luci,sujeet14108/luci,mumuqz/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,harveyhu2012/luci,teslamint/luci,obsy/luci,Hostle/luci,mumuqz/luci,shangjiyu/luci-with-extra,marcel-sch/luci,dwmw2/luci,hnyman/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,MinFu/luci,artynet/luci,tobiaswaldvogel/luci,opentechinstitute/luci,male-puppies/luci,MinFu/luci,jlopenwrtluci/luci,teslamint/luci,LuttyYang/luci,bittorf/luci,lbthomsen/openwrt-luci,slayerrensky/luci,Hostle/luci,bright-things/ionic-luci,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,thesabbir/luci,ollie27/openwrt_luci,nmav/luci,nmav/luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,rogerpueyo/luci,rogerpueyo/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,david-xiao/luci,david-xiao/luci,dismantl/luci-0.12,keyidadi/luci,cshore/luci,kuoruan/lede-luci,ollie27/openwrt_luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,palmettos/test,jorgifumi/luci,dwmw2/luci,palmettos/cnLuCI,zhaoxx063/luci,981213/luci-1,bittorf/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,kuoruan/luci,palmettos/cnLuCI,slayerrensky/luci,forward619/luci,cshore-firmware/openwrt-luci,aa65535/luci,NeoRaider/luci,Wedmer/luci,aa65535/luci,taiha/luci,deepak78/new-luci,chris5560/openwrt-luci,jchuang1977/luci-1,thesabbir/luci,981213/luci-1,chris5560/openwrt-luci,zhaoxx063/luci,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,bittorf/luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,lcf258/openwrtcn,zhaoxx063/luci,nmav/luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,mumuqz/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,jchuang1977/luci-1,RuiChen1113/luci,taiha/luci,bittorf/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,schidler/ionic-luci,maxrio/luci981213,981213/luci-1,RuiChen1113/luci,tobiaswaldvogel/luci,zhaoxx063/luci,sujeet14108/luci,schidler/ionic-luci,thesabbir/luci,palmettos/cnLuCI,kuoruan/luci,Noltari/luci,cappiewu/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,nwf/openwrt-luci,deepak78/new-luci,artynet/luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,tcatm/luci,schidler/ionic-luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,nmav/luci,daofeng2015/luci,wongsyrone/luci-1,sujeet14108/luci,kuoruan/luci,oneru/luci,dismantl/luci-0.12,marcel-sch/luci,florian-shellfire/luci,tcatm/luci,dwmw2/luci,urueedi/luci,david-xiao/luci,Sakura-Winkey/LuCI,deepak78/new-luci,thesabbir/luci,sujeet14108/luci,oneru/luci,MinFu/luci,artynet/luci,urueedi/luci,nmav/luci,kuoruan/luci,nwf/openwrt-luci,dismantl/luci-0.12,oneru/luci,kuoruan/lede-luci,forward619/luci,LuttyYang/luci,tcatm/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,NeoRaider/luci,marcel-sch/luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,cappiewu/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,marcel-sch/luci,wongsyrone/luci-1,keyidadi/luci,openwrt/luci,openwrt-es/openwrt-luci,sujeet14108/luci,Noltari/luci,maxrio/luci981213,oyido/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,LuttyYang/luci,joaofvieira/luci,MinFu/luci,kuoruan/luci,bright-things/ionic-luci,artynet/luci,cshore/luci,jlopenwrtluci/luci,dwmw2/luci,thesabbir/luci,rogerpueyo/luci,dismantl/luci-0.12,aa65535/luci,hnyman/luci,ollie27/openwrt_luci,joaofvieira/luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,maxrio/luci981213,remakeelectric/luci,tobiaswaldvogel/luci,maxrio/luci981213,thess/OpenWrt-luci,david-xiao/luci,jchuang1977/luci-1,cshore/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,cappiewu/luci,artynet/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,palmettos/test,shangjiyu/luci-with-extra,jchuang1977/luci-1,Wedmer/luci,rogerpueyo/luci,urueedi/luci,LuttyYang/luci,joaofvieira/luci,male-puppies/luci,oneru/luci,openwrt/luci,mumuqz/luci,forward619/luci,david-xiao/luci,forward619/luci,nwf/openwrt-luci,Noltari/luci,marcel-sch/luci,zhaoxx063/luci,david-xiao/luci,wongsyrone/luci-1,mumuqz/luci,Wedmer/luci,RuiChen1113/luci,oyido/luci,thess/OpenWrt-luci,artynet/luci,aa65535/luci,ff94315/luci-1,obsy/luci,obsy/luci,jlopenwrtluci/luci,maxrio/luci981213,palmettos/cnLuCI,tcatm/luci,fkooman/luci,urueedi/luci,oneru/luci,taiha/luci,remakeelectric/luci,jorgifumi/luci,fkooman/luci,daofeng2015/luci,schidler/ionic-luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,openwrt-es/openwrt-luci,obsy/luci,palmettos/test,tobiaswaldvogel/luci,LuttyYang/luci,harveyhu2012/luci,nmav/luci,Wedmer/luci,tcatm/luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,oneru/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,Wedmer/luci,cshore-firmware/openwrt-luci,obsy/luci,sujeet14108/luci,bright-things/ionic-luci,oyido/luci,keyidadi/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,marcel-sch/luci,cappiewu/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,kuoruan/lede-luci,ff94315/luci-1,NeoRaider/luci,fkooman/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,obsy/luci,slayerrensky/luci,jorgifumi/luci,male-puppies/luci,jchuang1977/luci-1,kuoruan/luci,kuoruan/lede-luci,jorgifumi/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,remakeelectric/luci,oneru/luci,deepak78/new-luci,ff94315/luci-1,taiha/luci,thess/OpenWrt-luci,male-puppies/luci,cshore/luci,dwmw2/luci,openwrt/luci,remakeelectric/luci,chris5560/openwrt-luci,slayerrensky/luci,daofeng2015/luci,marcel-sch/luci,aa65535/luci,palmettos/test,cappiewu/luci,keyidadi/luci,forward619/luci,cappiewu/luci,teslamint/luci,ollie27/openwrt_luci,nmav/luci,florian-shellfire/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,keyidadi/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,aa65535/luci,florian-shellfire/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,Wedmer/luci,male-puppies/luci,rogerpueyo/luci,palmettos/cnLuCI,bright-things/ionic-luci,lcf258/openwrtcn,nmav/luci,taiha/luci,mumuqz/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,Hostle/luci,taiha/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,opentechinstitute/luci,florian-shellfire/luci,urueedi/luci,NeoRaider/luci,zhaoxx063/luci,palmettos/cnLuCI,nwf/openwrt-luci,oyido/luci,oyido/luci,bright-things/ionic-luci,LuttyYang/luci,lcf258/openwrtcn,remakeelectric/luci,oyido/luci,palmettos/test,thess/OpenWrt-luci,lcf258/openwrtcn,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,forward619/luci,dismantl/luci-0.12,bright-things/ionic-luci,fkooman/luci,981213/luci-1,thess/OpenWrt-luci,bright-things/ionic-luci,tcatm/luci,joaofvieira/luci,harveyhu2012/luci,opentechinstitute/luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,Sakura-Winkey/LuCI,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,Noltari/luci,jorgifumi/luci,shangjiyu/luci-with-extra,MinFu/luci,ff94315/luci-1,taiha/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,forward619/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,bittorf/luci,maxrio/luci981213,opentechinstitute/luci,kuoruan/lede-luci,male-puppies/luci,ff94315/luci-1,Hostle/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,Wedmer/luci,Wedmer/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,harveyhu2012/luci,florian-shellfire/luci,NeoRaider/luci,zhaoxx063/luci,remakeelectric/luci,ff94315/luci-1,cshore/luci,Hostle/luci,tcatm/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,chris5560/openwrt-luci,RuiChen1113/luci,david-xiao/luci,kuoruan/lede-luci,fkooman/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,bittorf/luci,teslamint/luci,urueedi/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,981213/luci-1,cshore-firmware/openwrt-luci,fkooman/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,palmettos/test,palmettos/test
|
9094f9cbf5f556368a132132f27e69abd61908f1
|
lua/sys/init.lua
|
lua/sys/init.lua
|
-- luacheck: globals unpack vim
local nvim = require'nvim'
local stdpath = nvim.fn.stdpath
local function system_name()
local name = 'unknown'
if nvim.has('win32unix') or nvim.has('win32') then
name = 'windows'
elseif nvim.has('mac') then
name = 'mac'
elseif nvim.has('unix') then
name = 'linux'
end
return name
end
local function homedir()
local var = system_name() == 'windows' and 'USERPROFILE' or 'HOME'
local home = nvim.env[var]
return home:gsub('\\', '/')
end
local function basedir()
return stdpath('config'):gsub('\\', '/')
end
local function cachedir()
return stdpath('cache'):gsub('\\', '/')
end
local function datadir()
return stdpath('data'):gsub('\\', '/')
end
local function luajit_version()
local version = nvim.split(nvim.exec('version', true), '\n', true)
local luajit = ''
for _,val in pairs(version) do
if val:match('LuaJIT') then
luajit = nvim.split(val, ' ', true)[2]
break
end
end
return luajit
end
local sys = {
name = system_name(),
home = homedir(),
base = basedir(),
data = datadir(),
cache = cachedir(),
luajit = luajit_version(),
}
function sys.tmp(filename)
local tmpdir = sys.name == 'windows' and 'c:/temp/' or '/tmp/'
return tmpdir .. filename
end
return sys
|
-- luacheck: globals unpack vim
local nvim = require'nvim'
local stdpath = nvim.fn.stdpath
local function system_name()
local name = 'unknown'
if nvim.has('win32unix') or nvim.has('win32') then
name = 'windows'
elseif nvim.has('mac') then
name = 'mac'
elseif nvim.has('unix') then
name = 'linux'
end
return name
end
local function homedir()
local var = system_name() == 'windows' and 'USERPROFILE' or 'HOME'
local home = nvim.env[var]
return home:gsub('\\', '/')
end
local function basedir()
return stdpath('config'):gsub('\\', '/')
end
local function cachedir()
return stdpath('cache'):gsub('\\', '/')
end
local function datadir()
return stdpath('data'):gsub('\\', '/')
end
local function luajit_version()
return nvim.split(jit.version, ' ', true)[2]
end
local sys = {
name = system_name(),
home = homedir(),
base = basedir(),
data = datadir(),
cache = cachedir(),
luajit = luajit_version(),
}
function sys.tmp(filename)
local tmpdir = sys.name == 'windows' and 'c:/temp/' or '/tmp/'
return tmpdir .. filename
end
return sys
|
fix: luajit version
|
fix: luajit version
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
e0520140de0b9e9481fe6c92878c6a988f0874bd
|
modules/textadept/macros.lua
|
modules/textadept/macros.lua
|
-- Copyright 2018 Mitchell mitchell.att.foicica.com. See LICENSE.
--[[ This comment is for LuaDoc.
---
-- A module for recording, playing, saving, and loading keyboard macros.
-- Menu commands are also recorded.
-- At this time, typing into multiple cursors during macro playback is not
-- supported.
module('textadept.macros')]]
local M = {}
local recording, macro
-- Commands bound to keys to ignore during macro recording, as the command(s)
-- ultimately executed will be recorded in some form.
local ignore
events.connect(events.INITIALIZED, function()
local m_tools = textadept.menu.menubar[_L['_Tools']]
ignore = {
textadept.menu.menubar[_L['_Search']][_L['_Find']][2],
ui.find.find_incremental,
m_tools[_L['Select Co_mmand']][2],
m_tools[_L['_Macros']][_L['Start/Stop _Recording']][2]
}
end)
-- Event handlers for recording macro-able events.
local function event_recorder(event)
return function(...) macro[#macro + 1] = {event, ...} end
end
local event_recorders = {
[events.KEYPRESS] = function(code, shift, control, alt, meta)
local key = code < 256 and string.char(code) or keys.KEYSYMS[code]
if key then
-- Note: this is a simplified version of key handling.
local key_seq = (control and 'c' or '')..(alt and 'a' or '')..
(meta and OSX and 'm' or '')..(shift and 's' or '')..key
for i = 1, #ignore do if keys[key_seq] == ignore[i] then return end end
end
macro[#macro + 1] = {events.KEYPRESS, code, shift, control, alt, meta}
end,
[events.MENU_CLICKED] = event_recorder(events.MENU_CLICKED),
[events.CHAR_ADDED] = event_recorder(events.CHAR_ADDED),
[events.FIND] = event_recorder(events.FIND),
[events.REPLACE] = event_recorder(events.REPLACE),
[events.UPDATE_UI] = function()
if #keys.keychain == 0 then ui.statusbar_text = _L['Macro recording'] end
end
}
---
-- Toggles between starting and stopping macro recording.
-- @name record
function M.record()
if not recording then
macro = {}
for event, f in pairs(event_recorders) do events.connect(event, f, 1) end
ui.statusbar_text = _L['Macro recording']
else
for event, f in pairs(event_recorders) do events.disconnect(event, f) end
ui.statusbar_text = _L['Macro stopped recording']
end
recording = not recording
end
---
-- Plays a recorded or loaded macro.
-- @see load
-- @name play
function M.play()
if recording or not macro then return end
events.emit(events.KEYPRESS, 27) -- needed to initialize for some reason
for i = 1, #macro do
if macro[i][1] == events.CHAR_ADDED then
local f = buffer[buffer.selection_empty and 'add_text' or 'replace_sel']
f(buffer, utf8.char(macro[i][2]))
end
events.emit(table.unpack(macro[i]))
end
end
---
-- Saves a recorded macro to file *filename* or the user-selected file.
-- @param filename Optional filename to save the recorded macro to. If `nil`,
-- the user is prompted for one.
-- @name save
function M.save(filename)
if recording or not macro then return end
filename = filename or ui.dialogs.filesave{
title = _L['Save Macro'], with_directory = _USERHOME, with_extension = 'm'
}
if not filename then return end
local f = assert(io.open(filename, 'w'))
f:write('return {\n')
for i = 1, #macro do
f:write('{"', macro[i][1], '",')
for j = 2, #macro[i] do
if type(macro[i][j]) == 'string' then f:write('"') end
f:write(tostring(macro[i][j]))
f:write(type(macro[i][j]) == 'string' and '",' or ',')
end
f:write('},\n')
end
f:write('}\n')
f:close()
end
---
-- Loads a macro from file *filename* or the user-selected file.
-- @param filename Optional macro file to load. If `nil`, the user is prompted
-- for one.
-- @name load
function M.load(filename)
if recording then return end
filename = filename or ui.dialogs.fileselect{
title = _L['Load Macro'], with_directory = _USERHOME, with_extension = 'm'
}
if filename then macro = assert(loadfile(filename, 't', {}))() end
end
return M
|
-- Copyright 2018 Mitchell mitchell.att.foicica.com. See LICENSE.
--[[ This comment is for LuaDoc.
---
-- A module for recording, playing, saving, and loading keyboard macros.
-- Menu commands are also recorded.
-- At this time, typing into multiple cursors during macro playback is not
-- supported.
module('textadept.macros')]]
local M = {}
local recording, macro
-- Commands bound to keys to ignore during macro recording, as the command(s)
-- ultimately executed will be recorded in some form.
local ignore
events.connect(events.INITIALIZED, function()
local m_tools = textadept.menu.menubar[_L['_Tools']]
ignore = {
textadept.menu.menubar[_L['_Search']][_L['_Find']][2],
ui.find.find_incremental,
m_tools[_L['Select Co_mmand']][2],
m_tools[_L['_Macros']][_L['Start/Stop _Recording']][2]
}
end)
-- Event handlers for recording macro-able events.
local function event_recorder(event)
return function(...) macro[#macro + 1] = {event, ...} end
end
local event_recorders = {
[events.KEYPRESS] = function(code, shift, control, alt, meta)
local key = code < 256 and string.char(code) or keys.KEYSYMS[code]
if key then
-- Note: this is a simplified version of key handling.
shift = shift and (code >= 256 or code == 9)
local key_seq = (control and 'c' or '')..(alt and 'a' or '')..
(meta and OSX and 'm' or '')..(shift and 's' or '')..key
for i = 1, #ignore do if keys[key_seq] == ignore[i] then return end end
end
macro[#macro + 1] = {events.KEYPRESS, code, shift, control, alt, meta}
end,
[events.MENU_CLICKED] = event_recorder(events.MENU_CLICKED),
[events.CHAR_ADDED] = event_recorder(events.CHAR_ADDED),
[events.FIND] = event_recorder(events.FIND),
[events.REPLACE] = event_recorder(events.REPLACE),
[events.UPDATE_UI] = function()
if #keys.keychain == 0 then ui.statusbar_text = _L['Macro recording'] end
end
}
---
-- Toggles between starting and stopping macro recording.
-- @name record
function M.record()
if not recording then
macro = {}
for event, f in pairs(event_recorders) do events.connect(event, f, 1) end
ui.statusbar_text = _L['Macro recording']
else
for event, f in pairs(event_recorders) do events.disconnect(event, f) end
ui.statusbar_text = _L['Macro stopped recording']
end
recording = not recording
end
---
-- Plays a recorded or loaded macro.
-- @see load
-- @name play
function M.play()
if recording or not macro then return end
events.emit(events.KEYPRESS, 27) -- needed to initialize for some reason
for i = 1, #macro do
if macro[i][1] == events.CHAR_ADDED then
local f = buffer[buffer.selection_empty and 'add_text' or 'replace_sel']
f(buffer, utf8.char(macro[i][2]))
end
events.emit(table.unpack(macro[i]))
end
end
---
-- Saves a recorded macro to file *filename* or the user-selected file.
-- @param filename Optional filename to save the recorded macro to. If `nil`,
-- the user is prompted for one.
-- @name save
function M.save(filename)
if recording or not macro then return end
filename = filename or ui.dialogs.filesave{
title = _L['Save Macro'], with_directory = _USERHOME, with_extension = 'm'
}
if not filename then return end
local f = assert(io.open(filename, 'w'))
f:write('return {\n')
for i = 1, #macro do
f:write('{"', macro[i][1], '",')
for j = 2, #macro[i] do
if type(macro[i][j]) == 'string' then f:write('"') end
f:write(tostring(macro[i][j]))
f:write(type(macro[i][j]) == 'string' and '",' or ',')
end
f:write('},\n')
end
f:write('}\n')
f:close()
end
---
-- Loads a macro from file *filename* or the user-selected file.
-- @param filename Optional macro file to load. If `nil`, the user is prompted
-- for one.
-- @name load
function M.load(filename)
if recording then return end
filename = filename or ui.dialogs.fileselect{
title = _L['Load Macro'], with_directory = _USERHOME, with_extension = 'm'
}
if filename then macro = assert(loadfile(filename, 't', {}))() end
end
return M
|
Fixed macro toggling with some key combinations.
|
Fixed macro toggling with some key combinations.
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
d3d26222f47c2ba6b3828d7316916fd72193444b
|
MMOCoreORB/bin/scripts/object/building/corellia/ply_corl_house_s_s01_fp1.lua
|
MMOCoreORB/bin/scripts/object/building/corellia/ply_corl_house_s_s01_fp1.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_corellia_ply_corl_house_s_s01_fp1 = object_building_corellia_shared_ply_corl_house_s_s01_fp1:new {
}
ObjectTemplates:addTemplate(object_building_corellia_ply_corl_house_s_s01_fp1, "object/building/corellia/ply_corl_house_s_s01_fp1.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_corellia_ply_corl_house_s_s01_fp1 = object_building_corellia_shared_ply_corl_house_s_s01_fp1:new {
-- Used as tavern for: Endor Smuggler Outpost.
planetMapCategory = "tavern",
skillMods = {
{"private_med_wound_mind", 20},
{"private_buff_mind", 100},
{"private_med_battle_fatigue", 5},
{"private_medical_rating", 100},
{"private_med_wound_health", 100},
{"private_med_wound_action", 100}
},
}
ObjectTemplates:addTemplate(object_building_corellia_ply_corl_house_s_s01_fp1, "object/building/corellia/ply_corl_house_s_s01_fp1.iff")
|
[fixed] Ent buffing in Tavern at Smuggler OP on Endor.(clean sceneobject db might be needed) Mantis #5788
|
[fixed] Ent buffing in Tavern at Smuggler OP on Endor.(clean sceneobject
db might be needed) Mantis #5788
Change-Id: I33fd30e98fe32161564d0f10ce244057b63a6a93
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
e436c36a6026a14fe90218c3a3506e00264aaa01
|
lua/pipe.lua
|
lua/pipe.lua
|
--- Inter-task communication via pipes
local mod = {}
local memory = require "memory"
local ffi = require "ffi"
local serpent = require "Serpent"
local libmoon = require "libmoon"
local log = require "log"
ffi.cdef [[
// dummy
struct spsc_ptr_queue { };
struct mpmc_ptr_queue { };
struct spsc_ptr_queue* pipe_spsc_new(int size);
void pipe_spsc_enqueue(struct spsc_ptr_queue* queue, void* data);
uint8_t pipe_spsc_try_enqueue(struct spsc_ptr_queue* queue, void* data);
void* pipe_spsc_try_dequeue(struct spsc_ptr_queue* queue);
size_t pipe_spsc_count(struct spsc_ptr_queue* queue);
struct mpmc_ptr_queue* pipe_mpmc_new(int size);
void pipe_mpmc_enqueue(struct mpmc_ptr_queue* queue, void* data);
uint8_t pipe_mpmc_try_enqueue(struct mpmc_ptr_queue* queue, void* data);
void* pipe_mpmc_try_dequeue(struct mpmc_ptr_queue* queue);
size_t pipe_mpmc_count(struct mpmc_ptr_queue* queue);
// DPDK SPSC ring
struct rte_ring { };
struct rte_ring* create_ring(uint32_t count, int32_t socket);
int ring_enqueue(struct rte_ring* r, struct rte_mbuf** obj, int n);
int ring_dequeue(struct rte_ring* r, struct rte_mbuf** obj, int n);
]]
local C = ffi.C
mod.packetRing = {}
local packetRing = mod.packetRing
packetRing.__index = packetRing
function mod:newPacketRing(size, socket)
size = size or 8192
socket = socket or -1
return setmetatable({
ring = C.create_ring(size, socket)
}, packetRing)
end
function mod:newPacketRingFromRing(ring)
return setmetatable({
ring = ring
}, packetRing)
end
-- FIXME: this is work-around for some bug with the serialization of nested objects
function mod:sendToPacketRing(ring, bufs)
C.ring_enqueue(ring, bufs.array, bufs.size);
end
function packetRing:send(bufs)
C.ring_enqueue(self.ring, bufs.array, bufs.size);
end
function packetRing:sendN(bufs, n)
C.ring_enqueue(self.ring, bufs.array, n);
end
function packetRing:recv(bufs)
error("NYI")
end
function packetRing:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').packetRing"), true
end
mod.slowPipe = {}
local slowPipe = mod.slowPipe
slowPipe.__index = slowPipe
--- Create a new slow pipe.
--- Slow pipes are called slow pipe because they are slow (duh).
--- Any objects passed to it will be *serialized* as strings.
--- This means that it supports arbitrary Lua objects following libmoon's usual serialization rules.
--- Use a 'fast pipe' if you need fast inter-task communication. Fast pipes are restricted to LuaJIT FFI objects.
--- Rule of thumb: use a slow pipe if you don't need more than a few thousand messages per second,
--- e.g. to pass aggregated data or statistics between tasks. Use fast pipes if you intend to do something for
--- every (or almost every) packet you process.
function mod:newSlowPipe()
return setmetatable({
pipe = C.pipe_mpmc_new(512)
}, slowPipe)
end
function slowPipe:send(...)
local vals = serpent.dump({ ... })
local buf = memory.alloc("char*", #vals + 1)
ffi.copy(buf, vals)
C.pipe_mpmc_enqueue(self.pipe, buf)
end
function slowPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.pipe_mpmc_try_dequeue(self.pipe)
if buf ~= nil then
local result = loadstring(ffi.string(buf))()
memory.free(buf)
return unpackAll(result)
end
wait = wait - 10
if wait < 0 then
break
end
libmoon.sleepMicrosIdle(10)
end
end
function slowPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function slowPipe:count()
return tonumber(C.pipe_mpmc_count(self.pipe))
end
function slowPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').slowPipe"), true
end
mod.fastPipe = {}
local fastPipe = mod.fastPipe
fastPipe.__index = fastPipe
--- Create a new fast pipe.
--- A pipe can only be used by exactly two tasks: a single reader and a single writer.
--- Fast pipes are fast, but only accept FFI cdata pointers and nothing else.
--- Use a slow pipe to pass arbitrary objects.
--- TODO: add a MPMC variant (pull requests welcome)
function mod:newFastPipe(size)
return setmetatable({
pipe = C.pipe_spsc_new(size or 512)
}, fastPipe)
end
function fastPipe:send(obj)
C.pipe_spsc_enqueue(self.pipe, obj)
end
function fastPipe:trySend(obj)
return C.pipe_spsc_try_enqueue(self.pipe, obj) ~= 0
end
-- FIXME: this is work-around for some bug with the serialization of nested objects
function mod:sendToFastPipe(pipe, obj)
return C.pipe_spsc_try_enqueue(pipe, obj) ~= 0
end
function fastPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.pipe_spsc_try_dequeue(self.pipe)
if buf ~= nil then
return buf
end
wait = wait - 10
if wait < 0 then
break
end
libmoon.sleepMicrosIdle(10)
end
end
function fastPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function fastPipe:count()
return tonumber(C.pipe_spsc_count(self.pipe))
end
function fastPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').fastPipe"), true
end
return mod
|
--- Inter-task communication via pipes
local mod = {}
local memory = require "memory"
local ffi = require "ffi"
local serpent = require "Serpent"
local libmoon = require "libmoon"
local log = require "log"
local S = require "syscall"
ffi.cdef [[
// dummy
struct spsc_ptr_queue { };
struct mpmc_ptr_queue { };
struct spsc_ptr_queue* pipe_spsc_new(int size);
void pipe_spsc_enqueue(struct spsc_ptr_queue* queue, void* data);
uint8_t pipe_spsc_try_enqueue(struct spsc_ptr_queue* queue, void* data);
void* pipe_spsc_try_dequeue(struct spsc_ptr_queue* queue);
size_t pipe_spsc_count(struct spsc_ptr_queue* queue);
struct mpmc_ptr_queue* pipe_mpmc_new(int size);
void pipe_mpmc_enqueue(struct mpmc_ptr_queue* queue, void* data);
uint8_t pipe_mpmc_try_enqueue(struct mpmc_ptr_queue* queue, void* data);
void* pipe_mpmc_try_dequeue(struct mpmc_ptr_queue* queue);
size_t pipe_mpmc_count(struct mpmc_ptr_queue* queue);
// DPDK SPSC ring
struct rte_ring { };
struct rte_ring* create_ring(uint32_t count, int32_t socket);
int ring_enqueue(struct rte_ring* r, struct rte_mbuf** obj, int n);
int ring_dequeue(struct rte_ring* r, struct rte_mbuf** obj, int n);
]]
local C = ffi.C
mod.packetRing = {}
local packetRing = mod.packetRing
packetRing.__index = packetRing
function mod:newPacketRing(size, socket)
size = size or 8192
socket = socket or -1
return setmetatable({
ring = C.create_ring(size, socket)
}, packetRing)
end
function mod:newPacketRingFromRing(ring)
return setmetatable({
ring = ring
}, packetRing)
end
local ENOBUFS = S.c.E.NOBUFS
-- FIXME: this is work-around for some bug with the serialization of nested objects
function mod:sendToPacketRing(ring, bufs)
return C.ring_enqueue(ring, bufs.array, bufs.size) ~= -ENOBUFS
end
-- try to enqueue packets in a ring, returns true on success
function packetRing:send(bufs)
return C.ring_enqueue(self.ring, bufs.array, bufs.size) ~= -ENOBUFS
end
-- try to enqueue packets in a ring, returns true on success
function packetRing:sendN(bufs, n)
return C.ring_enqueue(self.ring, bufs.array, n) ~= -ENOBUFS
end
function packetRing:recv(bufs)
error("NYI")
end
function packetRing:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').packetRing"), true
end
mod.slowPipe = {}
local slowPipe = mod.slowPipe
slowPipe.__index = slowPipe
--- Create a new slow pipe.
--- Slow pipes are called slow pipe because they are slow (duh).
--- Any objects passed to it will be *serialized* as strings.
--- This means that it supports arbitrary Lua objects following libmoon's usual serialization rules.
--- Use a 'fast pipe' if you need fast inter-task communication. Fast pipes are restricted to LuaJIT FFI objects.
--- Rule of thumb: use a slow pipe if you don't need more than a few thousand messages per second,
--- e.g. to pass aggregated data or statistics between tasks. Use fast pipes if you intend to do something for
--- every (or almost every) packet you process.
function mod:newSlowPipe()
return setmetatable({
pipe = C.pipe_mpmc_new(512)
}, slowPipe)
end
function slowPipe:send(...)
local vals = serpent.dump({ ... })
local buf = memory.alloc("char*", #vals + 1)
ffi.copy(buf, vals)
C.pipe_mpmc_enqueue(self.pipe, buf)
end
function slowPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.pipe_mpmc_try_dequeue(self.pipe)
if buf ~= nil then
local result = loadstring(ffi.string(buf))()
memory.free(buf)
return unpackAll(result)
end
wait = wait - 10
if wait < 0 then
break
end
libmoon.sleepMicrosIdle(10)
end
end
function slowPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function slowPipe:count()
return tonumber(C.pipe_mpmc_count(self.pipe))
end
function slowPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').slowPipe"), true
end
mod.fastPipe = {}
local fastPipe = mod.fastPipe
fastPipe.__index = fastPipe
--- Create a new fast pipe.
--- A pipe can only be used by exactly two tasks: a single reader and a single writer.
--- Fast pipes are fast, but only accept FFI cdata pointers and nothing else.
--- Use a slow pipe to pass arbitrary objects.
--- TODO: add a MPMC variant (pull requests welcome)
function mod:newFastPipe(size)
return setmetatable({
pipe = C.pipe_spsc_new(size or 512)
}, fastPipe)
end
function fastPipe:send(obj)
C.pipe_spsc_enqueue(self.pipe, obj)
end
function fastPipe:trySend(obj)
return C.pipe_spsc_try_enqueue(self.pipe, obj) ~= 0
end
-- FIXME: this is work-around for some bug with the serialization of nested objects
function mod:sendToFastPipe(pipe, obj)
return C.pipe_spsc_try_enqueue(pipe, obj) ~= 0
end
function fastPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.pipe_spsc_try_dequeue(self.pipe)
if buf ~= nil then
return buf
end
wait = wait - 10
if wait < 0 then
break
end
libmoon.sleepMicrosIdle(10)
end
end
function fastPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function fastPipe:count()
return tonumber(C.pipe_spsc_count(self.pipe))
end
function fastPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').fastPipe"), true
end
return mod
|
fix dpdk ring buffer pipe with watermarks
|
fix dpdk ring buffer pipe with watermarks
|
Lua
|
mit
|
emmericp/libmoon,emmericp/libmoon,scholzd/libmoon,libmoon/libmoon,libmoon/libmoon,scholzd/libmoon,scholzd/libmoon,libmoon/libmoon,emmericp/libmoon
|
87f9d22a7257cb7eed46d2979c54aafccfa270a1
|
src/nodish/net/socket.lua
|
src/nodish/net/socket.lua
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local stream = require'nodish.stream'
local ev = require'ev'
local loop = ev.Loop.default
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local watchers = {}
self.watchers = watchers
stream.readable(self)
stream.writable(self)
local sock
local connecting = false
local connected = false
local closing = false
self:once('error',function()
self:destroy()
self:emit('close')
end)
local on_connect = function()
connecting = false
connected = true
-- provide read mehod for stream
self._read = function()
local data,err = sock:read()
local closed
if data and #data == 0 then
closed = true
end
return data,err,closed
end
self:add_read_watcher(sock:getfd())
-- provide write method for stream
self._write = function(_,data)
return sock:write(data)
end
self:add_write_watcher(sock:getfd())
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
assert(not sock)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ALREADY then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ISCONN then
io:stop(loop)
watchers.connect = nil
on_connect()
else
self:emit(tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
self:emit(tostring(err))
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
local writable_write = self.write
self.write = function(_,data)
if connecting then
self:once('connect',function()
writable_write(_,data)
end)
elseif connected then
writable_write(_,data)
else
self:emit('error','wrong state')
end
return self
end
local writable_fin = self.fin
self.fin = function(_,data)
self:once('finish',function()
sock:shutdown(S.c.SHUT.RD)
end)
writable_fin(_,data)
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local stream = require'nodish.stream'
local ev = require'ev'
local loop = ev.Loop.default
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local watchers = {}
self.watchers = watchers
stream.readable(self)
stream.writable(self)
local sock
local connecting = false
local connected = false
local closing = false
self:once('error',function()
self:destroy()
self:emit('close')
end)
local on_connect = function()
connecting = false
connected = true
-- provide read mehod for stream
self._read = function()
if not sock then
return '',nil,true
end
local data,err = sock:read()
local closed
if data and #data == 0 then
closed = true
end
return data,err,closed
end
self:add_read_watcher(sock:getfd())
-- provide write method for stream
self._write = function(_,data)
return sock:write(data)
end
self:add_write_watcher(sock:getfd())
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
assert(not sock)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ALREADY then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ISCONN then
io:stop(loop)
watchers.connect = nil
on_connect()
else
self:emit(tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
self:emit(tostring(err))
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
local writable_write = self.write
self.write = function(_,data)
if connecting then
self:once('connect',function()
writable_write(_,data)
end)
elseif connected then
writable_write(_,data)
else
self:emit('error','wrong state')
end
return self
end
local writable_fin = self.fin
self.fin = function(_,data)
self:once('finish',function()
sock:shutdown(S.c.SHUT.RD)
end)
writable_fin(_,data)
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
fix _read where sock is nil
|
fix _read where sock is nil
|
Lua
|
mit
|
lipp/nodish
|
f1c465e09db1595438b65dfe9b892d3dc855a0de
|
plugins/madrust-announce.lua
|
plugins/madrust-announce.lua
|
PLUGIN = PLUGIN or {} -- accommodates testing
PLUGIN.Title = "madrust-announce"
PLUGIN.Description = "Announcment broadcaster with optional reddit integration."
PLUGIN.Version = "0.1"
PLUGIN.Author = "W. Brian Gourlie"
function PLUGIN:Init()
print("init madrust-announce")
self.config = self:InitConfig()
self.subredditAnnouncement = nil
self:AddChatCommand("announce", self.CmdAnnounce)
if self:AnnouncementHasSubredditDependency(self.config.announcement) then
local checkfn = function()
self:RetrieveSubredditAnnouncement(function(announcement)
if self.subredditAnnouncement ~= announcement then
self.subredditAnnouncement = announcement
for _, line in pairs(self:GetInterpolatedAnnouncement()) do
rust.BroadcastChat(self.config.announcer, line)
end
end
end)
end
-- initial check
checkfn()
-- continue check every n seconds, where n = config.check_interval
self.checkTimer = timer.Repeat(self.config.subreddit.check_interval, checkfn)
end
end
function PLUGIN:Unload()
if self.checkTimer then self.checkTimer:Destroy() end
end
function PLUGIN:OnUserConnect(netuser)
self:CmdAnnounce(netuser)
end
function PLUGIN:CmdAnnounce(netuser, cmd, args)
for _, line in pairs(self:GetInterpolatedAnnouncement()) do
rust.SendChatToUser(netuser, self.config.announcer, line)
end
end
function PLUGIN:GetInterpolatedAnnouncement()
local interpolated = {}
for index, line in pairs(self.config.announcement) do
interpolated[index] = line:gsub("%%subredditAnnouncement%%", self.subredditAnnouncement)
end
return interpolated
end
function PLUGIN:RedditUserIsAdmin(redditUser)
return self.config.subreddit.admins[redditUser] == true
end
-- TODO: move to some sort of util api
function PLUGIN:EscapePatternChars(text)
return string.gsub(text, "(.)",
function(c)
if string.match(c, "[%[%]%(%)%.%%]") then return "%" .. c end
end)
end
function PLUGIN:ExtractAnnouncement(linkTitle)
local prefixPattern = "^" .. self:EscapePatternChars(self.config.subreddit.announcement_prefix) .. "%s*(.+)"
return string.match(linkTitle, prefixPattern)
end
function PLUGIN:RetrieveSubredditAnnouncement(callback)
print(string.format("requesting subreddit data from %q", self.config.subreddit.name))
local requestUrl = string.format("http://www.reddit.com/r/%s/.json", self.config.subreddit.name)
webrequest.Send (requestUrl,
function(respCode, response)
print(string.format("received subreddit response [HTTP %d]", respCode))
local listings = self:LoadListingsIntoTable(response)
local announcementFound = false
for _, listing in pairs(listings) do
local announcement = self:ExtractAnnouncement(listing.title)
if announcement and self:RedditUserIsAdmin(listing.author) then
announcementFound = true
callback(announcement)
break
end
end
if not(announcementFound) then
callback(self.config.msg_no_announcements)
end
end)
end
function PLUGIN:InitConfig()
local conf = self:LoadConfigIntoTable()
-- verify required settings exist
if not conf.announcement then
error("Configuration is missing for required setting \"announcement\"")
end
if type(conf.announcement) ~= "table" then
error("announcement must be an array.")
end
local hasSubredditDependency = self:AnnouncementHasSubredditDependency(conf.announcement)
if hasSubredditDependency then
-- some of the subreddit fields are required if interpolating reddit data
if not conf.subreddit then
error("Configuration is missing required setting \"subreddit\"")
end
if not conf.subreddit.name then
error("Configuration is missing required setting \"subreddit.name\"")
end
if not conf.subreddit.admins then
error("Configuration is missing required setting \"subreddit.admins\"")
end
-- apply default settings for reddit specific settings if not specified
if not conf.subreddit.announcement_prefix then conf.subreddit.announcement_prefix = "[ANNOUNCEMENT]" end
if not conf.subreddit.check_interval then conf.subreddit.check_interval = 3600 end
end
-- apply default settings for general settings if not specified
if not conf.announcer then conf.announcer = "[ANNOUNCE]" end
if not conf.msg_no_announcements then conf.msg_no_announcements = "There are no recent announcements." end
-- makes sure we have expected types
if type(conf.announcer) ~= "string" then
error("\"announcer\" must be a string")
end
if type(conf.msg_no_announcements) ~= "string" then
error("\"msg_no_announcements\" must be a string")
end
local config =
{
announcer = conf.announcer,
msg_no_announcements = conf.msg_no_announcements
}
if hasSubredditDependency then
if type(conf.subreddit.announcement_prefix) ~= "string" then
error("\"subreddit.announcement_prefix\" must be a string")
end
if type(conf.subreddit.check_interval) ~= "number" then
error("\"subreddit.check_interval\" must be a number")
end
if type(conf.subreddit.name) ~= "string" then
error("\"subreddit.name\" must be a string")
end
if type(conf.subreddit.admins) ~= "table" then
error("\"subreddit.admins\" must be an array")
end
-- hacky way to determine if at least admin has been specified
local adminSpecified = false
for i, admin in pairs(conf.subreddit.admins) do
adminSpecified = true
break
end
if not adminSpecified then
error("You must specify at least one subreddit admin.")
return false
end
local subreddit_admins = {}
-- convert the table such that the names are keys for fast lookup
for _, admin in pairs(conf.subreddit.admins) do
subreddit_admins[admin] = true
end
config.subreddit =
{
name = conf.subreddit.name,
check_interval = conf.subreddit.check_interval,
announcement_prefix = conf.subreddit.announcement_prefix,
admins = subreddit_admins
}
end
return config
end
-- Parse the subbredit json, massage it into saner model
function PLUGIN:LoadListingsIntoTable(listingsJson)
local resp = json.decode(listingsJson)
local listings = {}
for index, listing in pairs(resp.data.children) do
listings[index] =
{
author = listing.data.author,
title = listing.data.title,
created_utc = listing.data.created_utc,
id = listing.data.id
}
end
return listings
end
function PLUGIN:AnnouncementHasSubredditDependency(announcement)
for _, line in pairs(announcement) do
if line:match("%%subredditAnnouncement%%") then return true end
end
return false
end
-- TODO: move to some sort of util api
function PLUGIN:LoadConfigIntoTable()
local _file = util.GetDatafile( "cfg_madrust_announce" )
local _txt = _file:GetText()
local _conf = json.decode(_txt)
if not _conf or not _conf.conf then
error("Configuration is missing or malformed.")
end
return _conf.conf
end
|
PLUGIN = PLUGIN or {} -- accommodates testing
PLUGIN.Title = "madrust-announce"
PLUGIN.Description = "Announcment broadcaster with optional reddit integration."
PLUGIN.Version = "0.1"
PLUGIN.Author = "W. Brian Gourlie"
function PLUGIN:Init()
print("init madrust-announce")
self.config = self:InitConfig()
self.subredditAnnouncement = nil
self:AddChatCommand("announce", self.CmdAnnounce)
if self:AnnouncementHasSubredditDependency(self.config.announcement) then
local checkfn = function()
self:RetrieveSubredditAnnouncement(function(announcement)
if self.subredditAnnouncement ~= announcement then
self.subredditAnnouncement = announcement
for _, line in pairs(self:GetInterpolatedAnnouncement()) do
rust.BroadcastChat(self.config.announcer, line)
end
end
end)
end
-- initial check
checkfn()
-- continue check every n seconds, where n = config.check_interval
self.checkTimer = timer.Repeat(self.config.subreddit.check_interval, checkfn)
end
end
function PLUGIN:Unload()
if self.checkTimer then self.checkTimer:Destroy() end
end
function PLUGIN:OnUserConnect(netuser)
self:CmdAnnounce(netuser)
end
function PLUGIN:CmdAnnounce(netuser, cmd, args)
for _, line in pairs(self:GetInterpolatedAnnouncement()) do
rust.SendChatToUser(netuser, self.config.announcer, line)
end
end
function PLUGIN:GetInterpolatedAnnouncement()
local interpolated = {}
for index, line in pairs(self.config.announcement) do
interpolated[index] = line:gsub("%%subredditAnnouncement%%", self.subredditAnnouncement)
end
return interpolated
end
function PLUGIN:RedditUserIsAdmin(redditUser)
return self.config.subreddit.admins[redditUser] == true
end
-- TODO: move to some sort of util api
function PLUGIN:EscapePatternChars(text)
return string.gsub(text, "(.)",
function(c)
if string.match(c, "[%[%]%(%)%.%%]") then return "%" .. c end
end)
end
function PLUGIN:ExtractAnnouncement(linkTitle)
local prefixPattern = "^" .. self:EscapePatternChars(self.config.subreddit.announcement_prefix) .. "%s*(.+)"
return string.match(linkTitle, prefixPattern)
end
function PLUGIN:RetrieveSubredditAnnouncement(callback)
print(string.format("requesting subreddit data from %q", self.config.subreddit.name))
local requestUrl = string.format("http://www.reddit.com/r/%s/.json", self.config.subreddit.name)
webrequest.Send (requestUrl,
function(respCode, response)
print(string.format("received subreddit response [HTTP %d]", respCode))
local listings = self:LoadListingsIntoTable(response)
local announcementFound = false
for _, listing in pairs(listings) do
local announcement = self:ExtractAnnouncement(listing.title)
if announcement and self:RedditUserIsAdmin(listing.author) then
announcementFound = true
callback(announcement)
break
end
end
if not(announcementFound) then
callback(self.config.msg_no_announcements)
end
end)
end
function PLUGIN:InitConfig()
local conf = self:LoadConfigIntoTable()
-- verify required settings exist
if not conf.announcement then
error("Configuration is missing for required setting \"announcement\"")
end
if type(conf.announcement) ~= "table" then
error("announcement must be an array.")
end
local hasSubredditDependency = self:AnnouncementHasSubredditDependency(conf.announcement)
if hasSubredditDependency then
-- some of the subreddit fields are required if interpolating reddit data
if not conf.subreddit then
error("Configuration is missing required setting \"subreddit\"")
end
if not conf.subreddit.name then
error("Configuration is missing required setting \"subreddit.name\"")
end
if not conf.subreddit.admins then
error("Configuration is missing required setting \"subreddit.admins\"")
end
-- apply default settings for reddit specific settings if not specified
if not conf.subreddit.announcement_prefix then conf.subreddit.announcement_prefix = "[ANNOUNCEMENT]" end
if not conf.subreddit.check_interval then conf.subreddit.check_interval = 3600 end
end
-- apply default settings for general settings if not specified
if not conf.announcer then conf.announcer = "[ANNOUNCE]" end
if not conf.msg_no_announcements then conf.msg_no_announcements = "There are no recent announcements." end
-- makes sure we have expected types
if type(conf.announcer) ~= "string" then
error("\"announcer\" must be a string")
end
if type(conf.msg_no_announcements) ~= "string" then
error("\"msg_no_announcements\" must be a string")
end
local config =
{
announcer = conf.announcer,
announcement = conf.announcement,
msg_no_announcements = conf.msg_no_announcements
}
if hasSubredditDependency then
if type(conf.subreddit.announcement_prefix) ~= "string" then
error("\"subreddit.announcement_prefix\" must be a string")
end
if type(conf.subreddit.check_interval) ~= "number" then
error("\"subreddit.check_interval\" must be a number")
end
if type(conf.subreddit.name) ~= "string" then
error("\"subreddit.name\" must be a string")
end
if type(conf.subreddit.admins) ~= "table" then
error("\"subreddit.admins\" must be an array")
end
-- hacky way to determine if at least admin has been specified
local adminSpecified = false
for i, admin in pairs(conf.subreddit.admins) do
adminSpecified = true
break
end
if not adminSpecified then
error("You must specify at least one subreddit admin.")
return false
end
local subreddit_admins = {}
-- convert the table such that the names are keys for fast lookup
for _, admin in pairs(conf.subreddit.admins) do
subreddit_admins[admin] = true
end
config.subreddit =
{
name = conf.subreddit.name,
check_interval = conf.subreddit.check_interval,
announcement_prefix = conf.subreddit.announcement_prefix,
admins = subreddit_admins
}
end
return config
end
-- Parse the subbredit json, massage it into saner model
function PLUGIN:LoadListingsIntoTable(listingsJson)
local resp = json.decode(listingsJson)
local listings = {}
for index, listing in pairs(resp.data.children) do
listings[index] =
{
author = listing.data.author,
title = listing.data.title,
created_utc = listing.data.created_utc,
id = listing.data.id
}
end
return listings
end
function PLUGIN:AnnouncementHasSubredditDependency(announcement)
for _, line in pairs(announcement) do
if line:match("%%subredditAnnouncement%%") then return true end
end
return false
end
-- TODO: move to some sort of util api
function PLUGIN:LoadConfigIntoTable()
local _file = util.GetDatafile( "cfg_madrust_announce" )
local _txt = _file:GetText()
local _conf = json.decode(_txt)
if not _conf or not _conf.conf then
error("Configuration is missing or malformed.")
end
return _conf.conf
end
|
Bugfix.
|
Bugfix.
|
Lua
|
mit
|
bgourlie/madrust-oxide-plugins
|
f25ab5ba52736cbd518e806e1281adc6a34d9634
|
lua/entities/gmod_wire_expression2/core/strfunc.lua
|
lua/entities/gmod_wire_expression2/core/strfunc.lua
|
local function nicename( word )
local ret = word:lower()
if ret == "normal" then return "number" end
return ret
end
local function checkFuncName( self, funcname )
if self.funcs[funcname] then
return self.funcs[funcname], self.funcs_ret[funcname]
elseif wire_expression2_funcs[funcname] then
return wire_expression2_funcs[funcname][3], wire_expression2_funcs[funcname][2]
end
end
registerCallback("construct", function(self) self.strfunc_cache = {} end)
local insert = table.insert
local concat = table.concat
local function findFunc( self, funcname, typeids, typeids_str )
local func, func_return_type, vararg
self.prf = self.prf + 40
local str = funcname .. "(" .. typeids_str .. ")"
for i=1,#self.strfunc_cache do
local t = self.strfunc_cache[i]
if t[1] == str then
return t[2], t[3]
end
end
self.prf = self.prf + 40
if #typeids > 0 then
if not func then
func, func_return_type = checkFuncName( self, str )
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2) .. ")" )
end
if not func then
for i=#typeids,1,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. concat(typeids,"",1,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(...)" )
if func then vararg = true end
end
end
if not func then
for i=#typeids,2,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":...)" )
if func then vararg = true end
end
end
else
func, func_return_type = checkFuncName( self, funcname .. "()" )
end
if func then
local t = { str, func, func_return_type }
insert( self.strfunc_cache, 1, t )
if #self.strfunc_cache == 21 then self.strfunc_cache[21] = nil end
end
return func, func_return_type, vararg
end
__e2setcost(20)
registerOperator( "sfun", "", "", function(self, args)
local op1, funcargs, typeids, typeids_str, returntype = args[2], args[3], args[4], args[5], args[6]
local funcname = op1[1](self,op1)
local func, func_return_type, vararg = findFunc( self, funcname, typeids, typeids_str )
if not func then error( "No function with the specified arguments exists", 0 ) end
if returntype ~= "" and func_return_type ~= returntype then
error( "Mismatching return types. Got " .. nicename(wire_expression_types2[returntype][1]) .. ", expected " .. nicename(wire_expression_types2[func_return_type][1] ), 0 )
end
self.prf = self.prf + 40
if vararg then
funcargs[1] = function(self,arg) return arg[1] end
funcargs[#funcargs+1] = typeids
funcargs.TraceName = "FUN"
end
if returntype ~= "" then
return func( self, funcargs )
else
func( self, funcargs )
end
end)
|
local function nicename( word )
local ret = word:lower()
if ret == "normal" then return "number" end
return ret
end
local function checkFuncName( self, funcname )
if self.funcs[funcname] then
return self.funcs[funcname], self.funcs_ret[funcname]
elseif wire_expression2_funcs[funcname] then
return wire_expression2_funcs[funcname][3], wire_expression2_funcs[funcname][2]
end
end
registerCallback("construct", function(self) self.strfunc_cache = {} end)
local insert = table.insert
local concat = table.concat
local function findFunc( self, funcname, typeids, typeids_str )
local func, func_return_type, vararg
self.prf = self.prf + 40
local str = funcname .. "(" .. typeids_str .. ")"
for i=1,#self.strfunc_cache do
local t = self.strfunc_cache[i]
if t[1] == str then
return t[2], t[3], t[4]
end
end
self.prf = self.prf + 40
if #typeids > 0 then
if not func then
func, func_return_type = checkFuncName( self, str )
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2) .. ")" )
end
if not func then
for i=#typeids,1,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. concat(typeids,"",1,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(...)" )
if func then vararg = true end
end
end
if not func then
for i=#typeids,2,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":...)" )
if func then vararg = true end
end
end
else
func, func_return_type = checkFuncName( self, funcname .. "()" )
end
if func then
local t = { str, func, func_return_type, vararg }
insert( self.strfunc_cache, 1, t )
if #self.strfunc_cache == 21 then self.strfunc_cache[21] = nil end
end
return func, func_return_type, vararg
end
__e2setcost(20)
registerOperator( "sfun", "", "", function(self, args)
local op1, funcargs, typeids, typeids_str, returntype = args[2], args[3], args[4], args[5], args[6]
local funcname = op1[1](self,op1)
local func, func_return_type, vararg = findFunc( self, funcname, typeids, typeids_str )
if not func then error( "No function with the specified arguments exists", 0 ) end
if returntype ~= "" and func_return_type ~= returntype then
error( "Mismatching return types. Got " .. nicename(wire_expression_types2[returntype][1]) .. ", expected " .. nicename(wire_expression_types2[func_return_type][1] ), 0 )
end
self.prf = self.prf + 40
if vararg then funcargs[#funcargs+1] = typeids end -- if this is a vararg func, we need to send the typeids as well
if returntype ~= "" then
local ret = func( self, funcargs )
if vararg then funcargs[#funcargs] = nil end -- clean up
return ret
else
func( self, funcargs )
if vararg then funcargs[#funcargs] = nil end -- clean up
end
end)
|
fixed strfuncs erroring after e2 reload
|
fixed strfuncs erroring after e2 reload
fixed strfuncs erroring after e2 reload
fixed strfunc "print"("test") not printing the 1st argument after the
1st call
Fixes #436
|
Lua
|
apache-2.0
|
Grocel/wire,immibis/wiremod,garrysmodlua/wire,wiremod/wire,NezzKryptic/Wire,CaptainPRICE/wire,mms92/wire,mitterdoo/wire,rafradek/wire,bigdogmat/wire,Python1320/wire,thegrb93/wire,notcake/wire,dvdvideo1234/wire,sammyt291/wire,plinkopenguin/wiremod
|
50928da588711262bfad7fbaec8398bfa0360219
|
open-legends.lua
|
open-legends.lua
|
-- open legends screen when in fortress mode
--@ module = true
--[[=begin
open-legends
============
Open a legends screen when in fortress mode.
Compatible with `exportlegends`.
=end]]
gui = require 'gui'
utils = require 'utils'
Wrapper = defclass(Wrapper, gui.Screen)
Wrapper.focus_path = 'legends'
function Wrapper:onRender()
self._native.parent:render()
end
function Wrapper:onIdle()
self._native.parent:logic()
end
function Wrapper:onHelp()
self._native.parent:help()
end
function Wrapper:onInput(keys)
if self._native.parent.cur_page == 0 and keys.LEAVESCREEN then
self:dismiss()
dfhack.screen.dismiss(self._native.parent)
return
end
gui.simulateInput(self._native.parent, keys)
end
function show(force)
if not dfhack.isWorldLoaded() then
qerror('no world loaded')
end
local view = df.global.gview.view
while view do
if df.viewscreen_legendsst:is_instance(view) then
qerror('legends screen already displayed')
end
view = view.child
end
local old_view = dfhack.gui.getCurViewscreen()
if not dfhack.world.isFortressMode(df.global.gametype) and not dfhack.world.isAdventureMode(df.global.gametype) and not force then
qerror('mode not tested: ' .. df.game_type[df.global.gametype] .. ' (use "force" to force)')
end
local ok, err = pcall(function()
dfhack.screen.show(df.viewscreen_legendsst:new())
Wrapper():show()
end)
if not ok then
while dfhack.gui.getCurViewscreen(true) ~= old_view do
dfhack.screen.dismiss(dfhack.gui.getCurViewscreen(true))
end
qerror('Failed to set up legends screen: ' .. tostring(err))
end
end
if not moduleMode then
local iargs = utils.invert{...}
show(iargs.force)
end
|
-- open legends screen when in fortress mode
--@ module = true
--[[=begin
open-legends
============
Open a legends screen when in fortress mode.
Compatible with `exportlegends`.
=end]]
gui = require 'gui'
utils = require 'utils'
Wrapper = defclass(Wrapper, gui.Screen)
Wrapper.focus_path = 'legends'
region_details_backup = {}
function Wrapper:onRender()
self._native.parent:render()
end
function Wrapper:onIdle()
self._native.parent:logic()
end
function Wrapper:onHelp()
self._native.parent:help()
end
function Wrapper:onInput(keys)
if self._native.parent.cur_page == 0 and keys.LEAVESCREEN then
local v = df.global.world.world_data.region_details
while (#v > 0) do v:erase(0) end
for _,item in pairs(region_details_backup) do
v:insert(0, item)
end
self:dismiss()
dfhack.screen.dismiss(self._native.parent)
return
end
gui.simulateInput(self._native.parent, keys)
end
function show(force)
if not dfhack.isWorldLoaded() then
qerror('no world loaded')
end
local view = df.global.gview.view
while view do
if df.viewscreen_legendsst:is_instance(view) then
qerror('legends screen already displayed')
end
view = view.child
end
local old_view = dfhack.gui.getCurViewscreen()
if not dfhack.world.isFortressMode(df.global.gametype) and not dfhack.world.isAdventureMode(df.global.gametype) and not force then
qerror('mode not tested: ' .. df.game_type[df.global.gametype] .. ' (use "force" to force)')
end
local ok, err = pcall(function()
dfhack.screen.show(df.viewscreen_legendsst:new())
Wrapper():show()
end)
if ok then
local v = df.global.world.world_data.region_details
while (#v > 0) do
table.insert(region_details_backup, 1, v[0])
v:erase(0)
end
else
while dfhack.gui.getCurViewscreen(true) ~= old_view do
dfhack.screen.dismiss(dfhack.gui.getCurViewscreen(true))
end
qerror('Failed to set up legends screen: ' .. tostring(err))
end
end
if not moduleMode then
local iargs = utils.invert{...}
show(iargs.force)
end
|
fix game-breaking open-legends bug backup world.world_data.region_details after loading clear and restore from backup before exiting
|
fix game-breaking open-legends bug
backup world.world_data.region_details after loading
clear and restore from backup before exiting
|
Lua
|
unlicense
|
DFHack/lethosor-scripts,lethosor/dfhack-scripts
|
47e3bd444e00278215c4021320492ba7e401f58b
|
modules/xcode/xcode_project.lua
|
modules/xcode/xcode_project.lua
|
---
-- xcode/xcode4_project.lua
-- Generate an Xcode project file.
-- Author Jason Perkins
-- Modified by Mihai Sebea
-- Copyright (c) 2009-2015 Jason Perkins and the Premake project
---
local p = premake
local m = p.modules.xcode
local xcode = p.modules.xcode
local project = p.project
local config = p.config
local fileconfig = p.fileconfig
local tree = p.tree
--
-- Create a tree corresponding to what is shown in the Xcode project browser
-- pane, with nodes for files and folders, resources, frameworks, and products.
--
-- @param prj
-- The project being generated.
-- @returns
-- A tree, loaded with metadata, which mirrors Xcode's view of the project.
--
function xcode.buildprjtree(prj)
local tr = project.getsourcetree(prj, nil , false)
tr.project = prj
-- create a list of build configurations and assign IDs
tr.configs = {}
for cfg in project.eachconfig(prj) do
cfg.xcode = {}
cfg.xcode.targetid = xcode.newid(prj.xcode.projectnode.name, cfg.buildcfg, "target")
cfg.xcode.projectid = xcode.newid(tr.name, cfg.buildcfg)
table.insert(tr.configs, cfg)
end
-- convert localized resources from their filesystem layout (English.lproj/MainMenu.xib)
-- to Xcode's display layout (MainMenu.xib/English).
tree.traverse(tr, {
onbranch = function(node)
if path.getextension(node.name) == ".lproj" then
local lang = path.getbasename(node.name) -- "English", "French", etc.
-- create a new language group for each file it contains
for _, filenode in ipairs(node.children) do
local grpnode = node.parent.children[filenode.name]
if not grpnode then
grpnode = tree.insert(node.parent, tree.new(filenode.name))
grpnode.kind = "vgroup"
end
-- convert the file node to a language node and add to the group
filenode.name = path.getbasename(lang)
tree.insert(grpnode, filenode)
end
-- remove this directory from the tree
tree.remove(node)
end
end
})
-- the special folder "Frameworks" lists all linked frameworks
tr.frameworks = tree.new("Frameworks")
for cfg in project.eachconfig(prj) do
for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do
local name = path.getname(link)
if xcode.isframework(name) and not tr.frameworks.children[name] then
node = tree.insert(tr.frameworks, tree.new(name))
node.path = link
end
end
end
-- only add it to the tree if there are frameworks to link
if #tr.frameworks.children > 0 then
tree.insert(tr, tr.frameworks)
end
-- the special folder "Products" holds the target produced by the project; this
-- is populated below
tr.products = tree.insert(tr, tree.new("Products"))
-- the special folder "Projects" lists sibling project dependencies
tr.projects = tree.new("Projects")
for _, dep in ipairs(project.getdependencies(prj)) do
-- create a child node for the dependency's xcodeproj
local xcpath = xcode.getxcodeprojname(dep)
local xcnode = tree.insert(tr.projects, tree.new(path.getname(xcpath)))
xcnode.path = xcpath
xcnode.project = dep
xcnode.productgroupid = xcode.newid(xcnode.name, "prodgrp")
xcnode.productproxyid = xcode.newid(xcnode.name, "prodprox")
xcnode.targetproxyid = xcode.newid(xcnode.name, "targprox")
xcnode.targetdependid = xcode.newid(xcnode.name, "targdep")
-- create a grandchild node for the dependency's link target
local lprj = premake.workspace.findproject(prj.workspace, dep.name)
local cfg = project.findClosestMatch(lprj, prj.configurations[1])
node = tree.insert(xcnode, tree.new(cfg.linktarget.name))
node.path = cfg.linktarget.fullpath
node.cfg = cfg
-- don't link the dependency if it's a dependency only
for _, deponly in ipairs(project.getdependencies(prj, "dependOnly")) do
if dep == deponly then
node.nobuild = true
break
end
end
end
if #tr.projects.children > 0 then
tree.insert(tr, tr.projects)
end
-- Final setup
tree.traverse(tr, {
onnode = function(node)
-- assign IDs to every node in the tree
node.id = xcode.newid(node.name, nil, node.path)
node.isResource = xcode.isItemResource(prj, node)
-- assign build IDs to buildable files
if xcode.getbuildcategory(node) and not node.nobuild then
node.buildid = xcode.newid(node.name, "build", node.path)
end
-- remember key files that are needed elsewhere
if string.endswith(node.name, "Info.plist") then
tr.infoplist = node
end
end
}, true)
-- Plug in the product node into the Products folder in the tree. The node
-- was built in xcode.prepareWorkspace() in xcode_common.lua; it contains IDs
-- that are necessary for inter-project dependencies
node = tree.insert(tr.products, prj.xcode.projectnode)
node.kind = "product"
node.path = node.cfg.buildtarget.fullpath
node.cfgsection = xcode.newid(node.name, "cfg")
node.resstageid = xcode.newid(node.name, "rez")
node.sourcesid = xcode.newid(node.name, "src")
node.fxstageid = xcode.newid(node.name, "fxs")
return tr
end
---
-- Generate an Xcode .xcodeproj for a Premake project.
---
m.elements.project = function(prj)
return {
m.header,
}
end
function m.generateProject(prj)
local tr = xcode.buildprjtree(prj)
p.callArray(m.elements.project, prj)
xcode.PBXBuildFile(tr)
xcode.PBXContainerItemProxy(tr)
xcode.PBXFileReference(tr)
xcode.PBXFrameworksBuildPhase(tr)
xcode.PBXGroup(tr)
xcode.PBXNativeTarget(tr)
xcode.PBXProject(tr)
xcode.PBXReferenceProxy(tr)
xcode.PBXResourcesBuildPhase(tr)
xcode.PBXShellScriptBuildPhase(tr)
xcode.PBXSourcesBuildPhase(tr)
xcode.PBXTargetDependency(tr)
xcode.PBXVariantGroup(tr)
xcode.XCBuildConfiguration(tr)
xcode.XCBuildConfigurationList(tr)
xcode.footer(prj)
end
function m.header(prj)
p.w('// !$*UTF8*$!')
p.push('{')
p.w('archiveVersion = 1;')
p.w('classes = {')
p.w('};')
p.w('objectVersion = 46;')
p.push('objects = {')
p.w()
end
function xcode.footer(prj)
p.pop('};')
p.w('rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;')
p.pop('}')
end
|
---
-- xcode/xcode4_project.lua
-- Generate an Xcode project file.
-- Author Jason Perkins
-- Modified by Mihai Sebea
-- Copyright (c) 2009-2015 Jason Perkins and the Premake project
---
local p = premake
local m = p.modules.xcode
local xcode = p.modules.xcode
local project = p.project
local config = p.config
local fileconfig = p.fileconfig
local tree = p.tree
--
-- Create a tree corresponding to what is shown in the Xcode project browser
-- pane, with nodes for files and folders, resources, frameworks, and products.
--
-- @param prj
-- The project being generated.
-- @returns
-- A tree, loaded with metadata, which mirrors Xcode's view of the project.
--
function xcode.buildprjtree(prj)
local tr = project.getsourcetree(prj, nil , false)
tr.project = prj
-- create a list of build configurations and assign IDs
tr.configs = {}
for cfg in project.eachconfig(prj) do
cfg.xcode = {}
cfg.xcode.targetid = xcode.newid(prj.xcode.projectnode.name, cfg.buildcfg, "target")
cfg.xcode.projectid = xcode.newid(tr.name, cfg.buildcfg)
table.insert(tr.configs, cfg)
end
-- convert localized resources from their filesystem layout (English.lproj/MainMenu.xib)
-- to Xcode's display layout (MainMenu.xib/English).
tree.traverse(tr, {
onbranch = function(node)
if path.getextension(node.name) == ".lproj" then
local lang = path.getbasename(node.name) -- "English", "French", etc.
-- create a new language group for each file it contains
for _, filenode in ipairs(node.children) do
local grpnode = node.parent.children[filenode.name]
if not grpnode then
grpnode = tree.insert(node.parent, tree.new(filenode.name))
grpnode.kind = "vgroup"
end
-- convert the file node to a language node and add to the group
filenode.name = path.getbasename(lang)
tree.insert(grpnode, filenode)
end
-- remove this directory from the tree
tree.remove(node)
end
end
})
-- the special folder "Frameworks" lists all linked frameworks
tr.frameworks = tree.new("Frameworks")
for cfg in project.eachconfig(prj) do
for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do
local name = path.getname(link)
if xcode.isframework(name) and not tr.frameworks.children[name] then
node = tree.insert(tr.frameworks, tree.new(name))
node.path = link
end
end
end
-- only add it to the tree if there are frameworks to link
if #tr.frameworks.children > 0 then
tree.insert(tr, tr.frameworks)
end
-- the special folder "Products" holds the target produced by the project; this
-- is populated below
tr.products = tree.insert(tr, tree.new("Products"))
-- the special folder "Projects" lists sibling project dependencies
tr.projects = tree.new("Projects")
for _, dep in ipairs(project.getdependencies(prj, "linkOnly")) do
xcode.addDependency(prj, tr, dep, true)
end
for _, dep in ipairs(project.getdependencies(prj, "dependOnly")) do
xcode.addDependency(prj, tr, dep, false)
end
if #tr.projects.children > 0 then
tree.insert(tr, tr.projects)
end
-- Final setup
tree.traverse(tr, {
onnode = function(node)
-- assign IDs to every node in the tree
node.id = xcode.newid(node.name, nil, node.path)
node.isResource = xcode.isItemResource(prj, node)
-- assign build IDs to buildable files
if xcode.getbuildcategory(node) and not node.nobuild then
node.buildid = xcode.newid(node.name, "build", node.path)
end
-- remember key files that are needed elsewhere
if string.endswith(node.name, "Info.plist") then
tr.infoplist = node
end
end
}, true)
-- Plug in the product node into the Products folder in the tree. The node
-- was built in xcode.prepareWorkspace() in xcode_common.lua; it contains IDs
-- that are necessary for inter-project dependencies
node = tree.insert(tr.products, prj.xcode.projectnode)
node.kind = "product"
node.path = node.cfg.buildtarget.fullpath
node.cfgsection = xcode.newid(node.name, "cfg")
node.resstageid = xcode.newid(node.name, "rez")
node.sourcesid = xcode.newid(node.name, "src")
node.fxstageid = xcode.newid(node.name, "fxs")
return tr
end
function xcode.addDependency(prj, tr, dep, build)
-- create a child node for the dependency's xcodeproj
local xcpath = xcode.getxcodeprojname(dep)
local xcnode = tree.insert(tr.projects, tree.new(path.getname(xcpath)))
xcnode.path = xcpath
xcnode.project = dep
xcnode.productgroupid = xcode.newid(xcnode.name, "prodgrp")
xcnode.productproxyid = xcode.newid(xcnode.name, "prodprox")
xcnode.targetproxyid = xcode.newid(xcnode.name, "targprox")
xcnode.targetdependid = xcode.newid(xcnode.name, "targdep")
-- create a grandchild node for the dependency's link target
local lprj = premake.workspace.findproject(prj.workspace, dep.name)
local cfg = project.findClosestMatch(lprj, prj.configurations[1])
node = tree.insert(xcnode, tree.new(cfg.linktarget.name))
node.path = cfg.linktarget.fullpath
node.cfg = cfg
-- don't link the dependency if it's a dependency only
if build == false then
node.nobuild = true
end
end
---
-- Generate an Xcode .xcodeproj for a Premake project.
---
m.elements.project = function(prj)
return {
m.header,
}
end
function m.generateProject(prj)
local tr = xcode.buildprjtree(prj)
p.callArray(m.elements.project, prj)
xcode.PBXBuildFile(tr)
xcode.PBXContainerItemProxy(tr)
xcode.PBXFileReference(tr)
xcode.PBXFrameworksBuildPhase(tr)
xcode.PBXGroup(tr)
xcode.PBXNativeTarget(tr)
xcode.PBXProject(tr)
xcode.PBXReferenceProxy(tr)
xcode.PBXResourcesBuildPhase(tr)
xcode.PBXShellScriptBuildPhase(tr)
xcode.PBXSourcesBuildPhase(tr)
xcode.PBXTargetDependency(tr)
xcode.PBXVariantGroup(tr)
xcode.XCBuildConfiguration(tr)
xcode.XCBuildConfigurationList(tr)
xcode.footer(prj)
end
function m.header(prj)
p.w('// !$*UTF8*$!')
p.push('{')
p.w('archiveVersion = 1;')
p.w('classes = {')
p.w('};')
p.w('objectVersion = 46;')
p.push('objects = {')
p.w()
end
function xcode.footer(prj)
p.pop('};')
p.w('rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;')
p.pop('}')
end
|
Fixed the xcode "dependson" linking issue in a more efficient way.
|
Fixed the xcode "dependson" linking issue in a more efficient way.
|
Lua
|
bsd-3-clause
|
sleepingwit/premake-core,jstewart-amd/premake-core,LORgames/premake-core,mandersan/premake-core,dcourtois/premake-core,noresources/premake-core,dcourtois/premake-core,tvandijck/premake-core,bravnsgaard/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,LORgames/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,starkos/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,mendsley/premake-core,noresources/premake-core,starkos/premake-core,noresources/premake-core,resetnow/premake-core,mandersan/premake-core,noresources/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,resetnow/premake-core,mandersan/premake-core,TurkeyMan/premake-core,premake/premake-core,Blizzard/premake-core,soundsrc/premake-core,noresources/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,premake/premake-core,mandersan/premake-core,starkos/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,TurkeyMan/premake-core,mendsley/premake-core,Blizzard/premake-core,premake/premake-core,resetnow/premake-core,premake/premake-core,resetnow/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,starkos/premake-core,tvandijck/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,tvandijck/premake-core,dcourtois/premake-core,starkos/premake-core,starkos/premake-core,noresources/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,premake/premake-core,resetnow/premake-core,soundsrc/premake-core,LORgames/premake-core,LORgames/premake-core,mandersan/premake-core,dcourtois/premake-core,Blizzard/premake-core,mendsley/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,starkos/premake-core,premake/premake-core,premake/premake-core,mendsley/premake-core,noresources/premake-core,sleepingwit/premake-core
|
da9fad4752204d2dd1fd698df6d99d972fdd9d95
|
src/actions/clean/_clean.lua
|
src/actions/clean/_clean.lua
|
--
-- _clean.lua
-- The "clean" action: removes all generated files.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
premake.actions.clean = { }
local clean = premake.actions.clean
local project = premake5.project
--
-- Clean a solution or project specific directory. Uses information in the
-- project object to build the target path.
--
-- @param obj
-- A solution or project object.
-- @param pattern
-- A filename pattern to clean; see premake.project.getfilename() for
-- a description of the format.
--
function clean.directory(obj, pattern, removeParentsIfEmpty)
if pattern == '.' then
return false -- avoid deleting everything
end
local fname = premake.project.getfilename(obj, pattern)
os.rmdir(fname)
if removeParentsIfEmpty then
os.rmdirParentsIfEmpty(fname)
end
return true
end
--
-- Clean a solution or project specific file. Uses information in the project
-- object to build the target filename.
--
-- @param obj
-- A solution or project object.
-- @param pattern
-- A filename pattern to clean; see premake.project.getfilename() for
-- a description of the format.
--
function clean.file(obj, pattern)
local fname = premake.project.getfilename(obj, pattern)
os.remove(fname)
end
--
-- Register the "clean" action.
--
newaction {
trigger = "clean",
description = "Remove all binaries and generated files",
isnextgen = true,
onsolution = function(sln)
for action in premake.action.each() do
if action.oncleansolution then
action.oncleansolution(sln)
end
end
end,
onproject = function(prj)
for action in premake.action.each() do
if action.oncleanproject then
action.oncleanproject(prj)
end
end
if (prj.objectsdir) then
clean.directory(prj, prj.objectsdir)
end
-- build a list of supported target platforms that also includes a generic build
local platforms = prj.solution.platforms or { }
if not table.contains(platforms, "Native") then
platforms = table.join(platforms, { "Native" })
end
for _, platform in ipairs(platforms) do
for cfg in project.eachconfig(prj) do
if cfg.objdir then
clean.directory(prj, cfg.objdir, true)
end
if cfg.linktarget then
clean.directory(prj, cfg.linktarget.directory, true)
end
-- call action.oncleantarget() with the undecorated target name
local target = cfg.project.basedir
for action in premake.action.each() do
if action.oncleantarget then
action.oncleantarget(target)
end
end
end
end
end
}
|
--
-- _clean.lua
-- The "clean" action: removes all generated files.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
premake.actions.clean = { }
local clean = premake.actions.clean
local project = premake5.project
--
-- Clean a solution or project specific directory. Uses information in the
-- project object to build the target path.
--
-- @param obj
-- A solution or project object.
-- @param pattern
-- A filename pattern to clean; see premake.project.getfilename() for
-- a description of the format.
--
function clean.directory(obj, pattern, removeParentsIfEmpty)
if pattern == '.' then
return false -- avoid deleting everything
end
local fname = premake.project.getfilename(obj, pattern)
os.rmdir(fname)
if removeParentsIfEmpty then
os.rmdirParentsIfEmpty(fname)
end
return true
end
--
-- Clean a solution or project specific file. Uses information in the project
-- object to build the target filename.
--
-- @param obj
-- A solution or project object.
-- @param pattern
-- A filename pattern to clean; see premake.project.getfilename() for
-- a description of the format.
--
function clean.file(obj, pattern)
local fname = premake.project.getfilename(obj, pattern)
os.remove(fname)
end
--
-- Register the "clean" action.
--
newaction {
trigger = "clean",
description = "Remove all binaries and generated files",
isnextgen = true,
onsolution = function(sln)
for action in premake.action.each() do
if action.oncleansolution then
action.oncleansolution(sln)
end
end
end,
onproject = function(prj)
for action in premake.action.each() do
if action.oncleanproject then
action.oncleanproject(prj)
end
end
if (prj.objectsdir) then
clean.directory(prj, prj.objectsdir)
end
-- build a list of supported target platforms that also includes a generic build
local platforms = prj.solution.platforms or { }
if not table.contains(platforms, "Native") then
platforms = table.join(platforms, { "Native" })
end
if not prj.isUsage then
for cfg in project.eachconfig(prj) do
if cfg.objdir then
clean.directory(prj, cfg.objdir, true)
end
if cfg.linktarget then
clean.directory(prj, cfg.linktarget.directory, true)
end
-- call action.oncleantarget() with the undecorated target name
local target = cfg.project.basedir
for action in premake.action.each() do
if action.oncleantarget then
action.oncleantarget(target)
end
end
end
end
end
}
|
Fix clean action
|
Fix clean action
--HG--
branch : all
|
Lua
|
bsd-3-clause
|
annulen/premake-dev-rgeary,annulen/premake-dev-rgeary,annulen/premake-dev-rgeary
|
3abb134399b143548bb1579ac51e1f8c1420b4d9
|
OS/DiskOS/Editors/code.lua
|
OS/DiskOS/Editors/code.lua
|
local eapi = select(1,...) --The editor library is provided as an argument
local ce = {} --Code editor
local buffer = {""} --A table containing lines of code
local screenW, screenH = screenSize()
local lume = require("C://Libraries/lume")
local clua = require("C://Libraries/colorize_lua")
local cluacolors = {
text = 8,
keyword = 11,
number = 13,
comment = 14,
str = 13
}
ce.bgc = 6--Background Color
ce.cx, ce.cy = 1, 1 --Cursor Position
ce.tw, ce.th = termSize() --The terminal size
ce.th = ce.th-2 --Because of the top and bottom bars
ce.vx, ce.vy = 1,1 --View postions
ce.btimer = 0 --The cursor blink timer
ce.btime = 0.5 --The cursor blink time
ce.bflag = true --The cursor is blinking atm ?
--A usefull print function with color support !
function ce:colorPrint(tbl)
pushColor()
for i=1, #tbl, 2 do
local col = tbl[i]
local txt = tbl[i+1]
color(col)
print(txt,false,true)--Disable auto newline
end
--print("")--A new line
popColor()
end
--Check the position of the cursor so the view includes it
function ce:checkPos()
--X position checking--
if self.cx > self.tw + (self.vx-1) then --Passed the screen to the right
self.vx = self.cx - (self.tw-1)
elseif self.cx < self.vx then --Passed the screen to the left
self.vx = self.cx
end
--Y position checking--
if self.cy > #buffer then self.cy = #buffer end --Passed the end of the file
if self.cy > self.th + self.vy-1 then --Passed the screen to the bottom
self.vy = self.cy - (self.th-1)
elseif self.cy < self.vy then --Passed the screen to the top
if self.cy < 1 then
self.cy = 1
else
self.vy = self.cy
end
end
end
--Draw the cursor blink
function ce:drawBlink()
if self.bflag then
rect((self.cx-self.vx+1)*4-2,(self.cy-self.vy+1)*8+2, 4,5, false, 5)
end
end
--Draw the code on the screen
function ce:drawBuffer()
local cbuffer = clua(lume.clone(lume.slice(buffer,self.vy,self.vy+self.th)),cluacolors)
rect(1,9,screenW,screenH-8*2,false,self.bgc)
for k, l in ipairs(cbuffer) do
printCursor(-(self.vx-2),k+1,0)
self:colorPrint(l)
end
self:drawBlink()
end
function ce:drawLine()
local cline = clua({buffer[self.cy]},cluacolors)
rect(1,(self.cy-self.vy+2)*8-7, screenW,7, false,self.bgc)
printCursor(-(self.vx-2),(self.cy-self.vy+1)+1,self.bgc)
self:colorPrint(cline[1])
self:drawBlink()
end
function ce:textinput(t)
buffer[self.cy] = buffer[self.cy]:sub(0,self.cx-1)..t..buffer[self.cy]:sub(self.cx,-1)
self.cx = self.cx + t:len()
self:checkPos()
self:drawLine()
end
ce.keymap = {
["return"] = function(self)
self.cx, self.cy = 1, self.cy+1
if self.cy > #buffer then
table.insert(buffer,"")
else
buffer = lume.concat(lume.slice(buffer,0,self.cy-1),{""},lume.slice(buffer,self.cy,-1))
end
self:checkPos()
self:drawBuffer()
end
}
function ce:entered()
eapi:drawUI()
ce:drawBuffer()
end
function ce:leaved()
end
function ce:touchpressed() textinput(true) end
function ce:update(dt)
--Blink timer
self.btimer = self.btimer + dt
if self.btimer >= self.btime then
self.btimer = self.btimer - self.btime
self.bflag = not self.bflag
self:drawLine() --Redraw the current line
end
end
return ce
|
local eapi = select(1,...) --The editor library is provided as an argument
local ce = {} --Code editor
local buffer = {""} --A table containing lines of code
local screenW, screenH = screenSize()
local lume = require("C://Libraries/lume")
local clua = require("C://Libraries/colorize_lua")
local cluacolors = {
text = 8,
keyword = 11,
number = 13,
comment = 14,
str = 13
}
ce.bgc = 6--Background Color
ce.cx, ce.cy = 1, 1 --Cursor Position
ce.tw, ce.th = termSize() --The terminal size
ce.th = ce.th-2 --Because of the top and bottom bars
ce.vx, ce.vy = 1,1 --View postions
ce.btimer = 0 --The cursor blink timer
ce.btime = 0.5 --The cursor blink time
ce.bflag = true --The cursor is blinking atm ?
--A usefull print function with color support !
function ce:colorPrint(tbl)
pushColor()
for i=1, #tbl, 2 do
local col = tbl[i]
local txt = tbl[i+1]
color(col)
print(txt,false,true)--Disable auto newline
end
--print("")--A new line
popColor()
end
--Check the position of the cursor so the view includes it
function ce:checkPos()
local flag = false --Flag if the whole buffer requires redrawing
--Y position checking--
if self.cy > #buffer then self.cy = #buffer end --Passed the end of the file
if self.cy > self.th + self.vy-1 then --Passed the screen to the bottom
self.vy = self.cy - (self.th-1); flag = true
elseif self.cy < self.vy then --Passed the screen to the top
if self.cy < 1 then self.cy = 1 end
self.vy = self.cy; flag = true
end
--X position checking--
if buffer[self.cy]:len() < self.cx-1 then self.cx = buffer[self.cy]:len()+1 end --Passed the end of the line !
if self.cx > self.tw + (self.vx-1) then --Passed the screen to the right
self.vx = self.cx - (self.tw-1); flag = true
elseif self.cx < self.vx then --Passed the screen to the left
if self.cx < 1 then self.cx = 1 end
self.vx = self.cx; flag = true
end
return flag
end
--Draw the cursor blink
function ce:drawBlink()
if self.bflag then
rect((self.cx-self.vx+1)*4-2,(self.cy-self.vy+1)*8+2, 4,5, false, 5)
end
end
--Draw the code on the screen
function ce:drawBuffer()
local cbuffer = clua(lume.clone(lume.slice(buffer,self.vy,self.vy+self.th-1)),cluacolors)
rect(1,9,screenW,screenH-8*2,false,self.bgc)
for k, l in ipairs(cbuffer) do
printCursor(-(self.vx-2),k+1,0)
self:colorPrint(l)
end
self:drawBlink()
end
function ce:drawLine()
local cline = clua({buffer[self.cy]},cluacolors)
rect(1,(self.cy-self.vy+2)*8-7, screenW,7, false,self.bgc)
printCursor(-(self.vx-2),(self.cy-self.vy+1)+1,self.bgc)
self:colorPrint(cline[1])
self:drawBlink()
end
function ce:textinput(t)
buffer[self.cy] = buffer[self.cy]:sub(0,self.cx-1)..t..buffer[self.cy]:sub(self.cx,-1)
self.cx = self.cx + t:len()
if self:checkPos() then self:drawBuffer() else self:drawLine() end
end
ce.keymap = {
["return"] = function(self)
local newLine = buffer[self.cy]:sub(self.cx,-1)
buffer[self.cy] = buffer[self.cy]:sub(0,self.cx-1)
self.cx, self.cy = 1, self.cy+1
if self.cy > #buffer then
table.insert(buffer,newLine)
else
buffer = lume.concat(lume.slice(buffer,0,self.cy-1),{newLine},lume.slice(buffer,self.cy,-1)) --Insert between 2 different lines
end
self:checkPos()
self:drawBuffer()
end,
["left"] = function(self)
local flag = false
self.cx = self.cx -1
if self.cx < 1 then
if self.cy > 1 then
self.cy = self.cy -1
self.cx = buffer[self.cy]:len()+1
flag = true
end
end
if self:checkPos() or flag then self:drawBuffer() else self:drawLine() end
end,
["right"] = function(self)
local flag = false
self.cx = self.cx +1
if self.cx > buffer[self.cy]:len()+1 then
if buffer[self.cy+1] then
self.cy = self.cy +1
self.cx = 1
flag = true
end
end
if self:checkPos() or flag then self:drawBuffer() else self:drawLine() end
end,
["up"] = function(self)
self.cy = self.cy -1
self:checkPos()
self:drawBuffer()
end,
["down"] = function(self)
self.cy = self.cy +1
self:checkPos()
self:drawBuffer()
end,
["backspace"] = function(self)
if self.cx == 1 then
if self.cy > 1 then
self.cx = buffer[self.cy-1]:len()+1
buffer[self.cy-1] = buffer[self.cy-1] .. buffer[self.cy]
buffer = lume.concat(lume.slice(buffer,0,self.cy-1),lume.slice(buffer,self.cy+1,-1))
self.cy = self.cy-1
self:checkPos()
self:drawBuffer()
end
else
buffer[self.cy] = buffer[self.cy]:sub(0,self.cx-2) .. buffer[self.cy]:sub(self.cx, -1)
self.cx = self.cx-1
if self:checkPos() then self:drawBuffer() else self:drawLine() end
end
end
}
function ce:entered()
eapi:drawUI()
ce:drawBuffer()
end
function ce:leaved()
end
function ce:touchpressed() textinput(true) end
function ce:update(dt)
--Blink timer
self.btimer = self.btimer + dt
if self.btimer >= self.btime then
self.btimer = self.btimer - self.btime
self.bflag = not self.bflag
self:drawLine() --Redraw the current line
end
end
return ce
|
Up, Down, Left, Right, Backspace, better Return, Bugfixes !
|
Up, Down, Left, Right, Backspace, better Return, Bugfixes !
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7cf964c363ad6df4fa8e4f8376a7f8fd116d8c05
|
lib/file.lua
|
lib/file.lua
|
local Object = require('core').Object
local String = require('string')
local Fs = require('fs')
local Path = require('path')
local Levels = require('./utils').Levels
local Utils = require('./utils')
local function _noop(err)
if err then
error('Logger error: ' .. err.message)
end
end
local FileLogger = Object:extend()
function FileLogger:initialize(options)
self.type = options.type
self.level = nil
if type(options.level) == 'string' and Levels[String.lower(options.level)] then
self.level = Levels[String.lower(options.level)]
end
self.dateformat = nil
if options.dateformat and type(options.dateformat) == 'string' then
self.dateformat = options.dateformat
end
if type(options.path) ~= 'string' then
error('path: ' .. Utils.dump(options.path) .. ' is not a string')
end
local is_absolute = options.path:sub(1, 1) == Path.sep
if not is_absolute then
self.path = Path.join(process.env.PWD, options.path)
else
self.path = options.path
end
local dirname = Path.dirname(self.path)
if not Fs.existsSync(dirname) then
Fs.mkdir(dirname, '0740')
end
self.fd = Fs.openSync(self.path, 'a+', '0640')
end
function FileLogger:log(parent_level, level, s, ...)
local final_level = self.level or parent_level
if level.value <= final_level.value then
Fs.write(self.fd, 0, Utils.finalString(self.dateformat, level, s, ...) .. '\n', _noop)
end
end
function FileLogger:close()
Fs.closeSync(self.fd)
end
return FileLogger
|
local Object = require('core').Object
local String = require('string')
local Fs = require('fs')
local Path = require('path')
local Levels = require('./utils').Levels
local Utils = require('./utils')
local function _noop(err)
if err then
error('Logger error: ' .. err.message)
end
end
local FileLogger = Object:extend()
function FileLogger:initialize(options)
self.type = options.type
self.level = nil
if type(options.level) == 'string' and Levels[String.lower(options.level)] then
self.level = Levels[String.lower(options.level)]
end
self.dateformat = nil
if options.dateformat and type(options.dateformat) == 'string' then
self.dateformat = options.dateformat
end
if type(options.path) ~= 'string' then
error('path: ' .. Utils.dump(options.path) .. ' is not a string')
end
local is_absolute = options.path:sub(1, 1) == Path.sep
if not is_absolute then
self.path = Path.join(process.env.PWD, options.path)
else
self.path = options.path
end
local dirname = Path.dirname(self.path)
if not Fs.existsSync(dirname) then
-- TODO: recursiv mkdir
Fs.mkdir(dirname, '0740', function()
self.fd = Fs.openSync(self.path, 'a+', '0640')
end)
else
self.fd = Fs.openSync(self.path, 'a+', '0640')
end
end
function FileLogger:log(parent_level, level, s, ...)
local final_level = self.level or parent_level
if level.value <= final_level.value then
Fs.write(self.fd, 0, Utils.finalString(self.dateformat, level, s, ...) .. '\n', _noop)
end
end
function FileLogger:close()
Fs.closeSync(self.fd)
end
return FileLogger
|
fix async mkdir
|
fix async mkdir
|
Lua
|
mit
|
gsick/luvit-logger
|
0a71272487780612dc905e44912dc7530230a9e9
|
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 <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
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 <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
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
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6514 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.