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
|
---|---|---|---|---|---|---|---|---|---|
c671058015174f54d07b49aaf5b0fbad5263b15e
|
core/cairo-output.lua
|
core/cairo-output.lua
|
local lgi = require("lgi");
local cairo = lgi.cairo
local pango = lgi.Pango
if (not SILE.outputters) then SILE.outputters = {} end
local cr
local move -- See https://github.com/pavouk/lgi/issues/48
local sgs
SILE.outputters.cairo = {
init = function()
local surface = cairo.PdfSurface.create(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2])
cr = cairo.Context.create(surface)
move = cr.move_to
sgs = cr.show_glyph_string
end,
newPage = function()
cr:show_page();
end,
finish = function()
end,
setColor = function (self, color)
cr:set_source_rgb(color.r, color.g, color.b)
end,
showGlyphString = function(f,pgs, options)
sgs(cr, f,pgs)
end,
drawPNG = function (src, x,y,w,h)
local image = cairo.ImageSurface.create_from_png(src)
if not image then SU.error("Could not load image "..src) end
local src_width = image:get_width()
local src_height = image:get_height()
if not (src_width > 0) then SU.error("Something went wrong loading image "..src) end
cr:save()
cr:set_source_surface(image, 0,0)
local p = cr:get_source()
local matrix, sx, sy
if w or h then
if w > 0 then sx = src_width / w end
if h > 0 then sy = src_height / h end
matrix = cairo.Matrix.create_scale(sx or sy, sy or sx)
else
matrix = cairo.Matrix.create_identity()
end
matrix:translate(-x,-y)
p:set_matrix(matrix)
cr:paint()
cr:restore()
end,
moveTo = function (x,y)
move(cr, x,y)
end,
rule = function (x,y,w,d)
cr:rectangle(x,y,w,d)
cr:fill()
end,
debugFrame = function (self,f)
cr:set_source_rgb(0.8,0,0)
cr:set_line_width(0.5);
cr:rectangle(f:left(), f:top(), f:width(), f:height());
cr:stroke();
cr:move_to(f:left() - 10, f:top() -2);
cr:show_text(f.id);
cr:set_source_rgb(0,0,0);
end,
debugHbox = function(typesetter, hbox, scaledWidth)
cr:set_source_rgb(0.9,0.9,0.9);
cr:rectangle(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-(hbox.height), scaledWidth, hbox.height+hbox.depth);
if (hbox.depth) then cr:rectangle(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-(hbox.height), scaledWidth, hbox.height); end
cr:set_source_rgb(0,0,0);
end
}
SILE.outputter = SILE.outputters.cairo
|
local lgi = require("lgi");
local cairo = lgi.cairo
local pango = lgi.Pango
local fm = lgi.PangoCairo.FontMap.get_default()
local pango_context = lgi.Pango.FontMap.create_context(fm)
if (not SILE.outputters) then SILE.outputters = {} end
local cr
local move -- See https://github.com/pavouk/lgi/issues/48
local sgs
SILE.outputters.cairo = {
init = function()
local surface = cairo.PdfSurface.create(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2])
cr = cairo.Context.create(surface)
move = cr.move_to
sgs = cr.show_glyph_string
end,
newPage = function()
cr:show_page();
end,
finish = function()
end,
setColor = function (self, color)
cr:set_source_rgb(color.r, color.g, color.b)
end,
showGlyphString = function(f,pgs, options)
sgs(cr, f,pgs)
end,
setFont = function (f,font)
end,
drawPNG = function (src, x,y,w,h)
local image = cairo.ImageSurface.create_from_png(src)
if not image then SU.error("Could not load image "..src) end
local src_width = image:get_width()
local src_height = image:get_height()
if not (src_width > 0) then SU.error("Something went wrong loading image "..src) end
cr:save()
cr:set_source_surface(image, 0,0)
local p = cr:get_source()
local matrix, sx, sy
if w or h then
if w > 0 then sx = src_width / w end
if h > 0 then sy = src_height / h end
matrix = cairo.Matrix.create_scale(sx or sy, sy or sx)
else
matrix = cairo.Matrix.create_identity()
end
matrix:translate(-x,-y)
p:set_matrix(matrix)
cr:paint()
cr:restore()
end,
moveTo = function (x,y)
move(cr, x,y)
end,
rule = function (x,y,w,d)
cr:rectangle(x,y,w,d)
cr:fill()
end,
debugFrame = function (self,f)
cr:set_source_rgb(0.8,0,0)
cr:set_line_width(0.5);
cr:rectangle(f:left(), f:top(), f:width(), f:height());
cr:stroke();
cr:move_to(f:left() - 10, f:top() -2);
cr:show_text(f.id);
cr:set_source_rgb(0,0,0);
end,
debugHbox = function(typesetter, hbox, scaledWidth)
cr:set_source_rgb(0.9,0.9,0.9);
cr:set_line_width(0.5);
cr:rectangle(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-(hbox.height), scaledWidth, hbox.height+hbox.depth);
if (hbox.depth) then cr:rectangle(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-(hbox.height), scaledWidth, hbox.height); end
cr:stroke();
cr:set_source_rgb(0,0,0);
cr:move_to(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY);
end
}
SILE.outputter = SILE.outputters.cairo
|
Various fixes.
|
Various fixes.
|
Lua
|
mit
|
shirat74/sile,shirat74/sile,anthrotype/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,Nathan22Miles/sile,alerque/sile,Nathan22Miles/sile,alerque/sile,Nathan22Miles/sile,anthrotype/sile,anthrotype/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,simoncozens/sile,anthrotype/sile,Nathan22Miles/sile,simoncozens/sile,neofob/sile,Nathan22Miles/sile,neofob/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,alerque/sile,shirat74/sile,shirat74/sile,neofob/sile
|
8b2e29eed92a6b25b62194b1ce4b638f71bc231a
|
src/system/RenderableSystem.lua
|
src/system/RenderableSystem.lua
|
--RenderableSystem.lua
--[[
The RenderableSystem maintains references to several game-objects, each called a Scene.
This facilitates the swapping of viewscreens such as different maps, interface screens, and so on.
The RenderableSystem draws the root game object, then its children in sequence, recursively
]]--
local System = require 'src/System'
local Stack = require 'src/structure/Stack'
local RenderableSystem = System:extend("RenderableSystem",{
renderable_cache = nil,
last_publish_count = nil,
dirty = 10000,
font = nil,
planet_width = 1512
})
function RenderableSystem:init ( registry, targetCollection )
RenderableSystem.super.init(self, registry, targetCollection)
self.renderable_cache = {translation = {x = Stack:new(),y = Stack:new()}}
--love.graphics.setNewFont("assets/InputSansNarrow-Light.ttf",12)
end
function RenderableSystem:update( dt )
local function updateHeirarchy ( root , dt)
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "animation" then
renderable.render.ani:update(dt)
end
end
end
--Update children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
updateHeirarchy(self.registry:get(gid), dt)
end
end
updateHeirarchy(self.registry:get(self.targetCollection:getRoot()), dt)
end
function RenderableSystem:renderComponent ( cached )
--Pop the coordinate system
local delta = cached.t
if cached.r == "PLZ_PUSH" and delta then
love.graphics.push()
self.renderable_cache.translation.x:push(delta.x)
self.renderable_cache.translation.y:push(delta.y)
love.graphics.translate(delta.x, delta.y)
end
--Do draw
--Renderable
local renderable = cached
if renderable ~= nil and cached.r ~= "PLZ_PUSH" and cached.r ~= "PLZ_POP" then
local xOffset = (love.graphics:getWidth() < self.planet_width) and self.planet_width * self:getScreenWidthOffsets(renderable) or 0
love.graphics.push()
love.graphics.translate(xOffset,0)
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
local centerX,centerY = renderable.polygon:getPrintLoc()
local polyWidth = renderable.polygon:getDimensions().w
local fontH = love.graphics:getFont():getHeight()
love.graphics.printf(
renderable.text,
-1 * fontH / 2,
centerY,
polyWidth - 8,
'center')
else
love.graphics.print(renderable.text)
end
end
love.graphics.pop()
end
if cached.r == "PLZ_POP" and delta == "PLOXPOPIT" then
love.graphics.pop()
self.renderable_cache.translation.x:pop()
self.renderable_cache.translation.y:pop()
end
end
function RenderableSystem:getScreenWidthOffsets(renderable)
if not renderable then return 0 end
local tx = (self.renderable_cache.translation.x:total() or 0) *-1
local rw = 0
if renderable.polygon then
rw = renderable.polygon:getDimensions().w
elseif renderable.render then
if renderable.render.rtype == "sprite" then
_, _, rw = renderable.render.quad:getViewport()
elseif renderable.render.rtype == "animation" then
rw = renderable.render.ani.frameWidth
end
end
tx = tx - rw
return math.ceil(tx/ self.planet_width)
end
function RenderableSystem:drawHeirarchy ( root, big_list )
--Pop the coordinate system
local delta
if root:hasComponent('Transform') then
delta = root:getComponent('Transform')
if delta.x == 0 and delta.y == 0 then
delta = nil
else
table.insert(big_list, {r = "PLZ_PUSH", t = delta})
love.graphics.push()
love.graphics.translate(delta.x, delta.y)
end
end
--Do draw
--Renderable
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
end
table.insert(big_list, renderable )
--Draw children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
self:drawHeirarchy(self.registry:get(gid), big_list)
end
--Unpop the coordinate system
if delta ~= nil then
love.graphics.pop()
table.insert(big_list, {r = "PLZ_POP", t = "PLOXPOPIT"})
end
return big_list
end
function RenderableSystem:draw ()
if self.cache == nil or self.dirty > 3 then
self.cache = self:drawHeirarchy(self.registry:get(self.targetCollection:getRoot()), {})
self.dirty = 0
end
for i = 1, #self.cache do
self:renderComponent(self.cache[i])
end
self.dirty = self.dirty + 1
end
return RenderableSystem
|
--RenderableSystem.lua
--[[
The RenderableSystem maintains references to several game-objects, each called a Scene.
This facilitates the swapping of viewscreens such as different maps, interface screens, and so on.
The RenderableSystem draws the root game object, then its children in sequence, recursively
]]--
local System = require 'src/System'
local Stack = require 'src/structure/Stack'
local RenderableSystem = System:extend("RenderableSystem",{
renderable_cache = nil,
last_publish_count = nil,
dirty = 10000,
font = nil,
planet_width = 1512
})
function RenderableSystem:init ( registry, targetCollection )
RenderableSystem.super.init(self, registry, targetCollection)
self.renderable_cache = {translation = {x = Stack:new(),y = Stack:new()}}
--love.graphics.setNewFont("assets/InputSansNarrow-Light.ttf",12)
end
function RenderableSystem:update( dt )
local function updateHeirarchy ( root , dt)
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "animation" then
renderable.render.ani:update(dt)
end
end
end
--Update children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
updateHeirarchy(self.registry:get(gid), dt)
end
end
updateHeirarchy(self.registry:get(self.targetCollection:getRoot()), dt)
end
function RenderableSystem:renderComponent ( cached )
--Pop the coordinate system
local delta = cached.t
if cached.r == "PLZ_PUSH" and delta then
love.graphics.push()
self.renderable_cache.translation.x:push(delta.x)
self.renderable_cache.translation.y:push(delta.y)
love.graphics.translate(delta.x, delta.y)
end
--Do draw
--Renderable
local renderable = cached
if renderable ~= nil and cached.r ~= "PLZ_PUSH" and cached.r ~= "PLZ_POP" then
local xOffset = (love.graphics:getWidth() < self.planet_width) and self.planet_width * self:getScreenWidthOffsets(renderable) or 0
love.graphics.push()
love.graphics.translate(xOffset,0)
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
local minX = 100000000
local maxX = -100000000
local minY = 100000000
for i = 1, #renderable.polygon.vertices do
if i % 2 == 0 then
--y
if renderable.polygon.vertices[i] < minY then
minY = renderable.polygon.vertices[i]
end
else
--x
if renderable.polygon.vertices[i] < minX then
minX = renderable.polygon.vertices[i]
elseif renderable.polygon.vertices[i] > maxX then
maxX = renderable.polygon.vertices[i]
end
end
end
love.graphics.printf(renderable.text,
minX,
minY,
maxX - minX,'center')
else
love.graphics.print(renderable.text)
end
end
love.graphics.pop()
end
if cached.r == "PLZ_POP" and delta == "PLOXPOPIT" then
love.graphics.pop()
self.renderable_cache.translation.x:pop()
self.renderable_cache.translation.y:pop()
end
end
function RenderableSystem:getScreenWidthOffsets(renderable)
if not renderable then return 0 end
local tx = (self.renderable_cache.translation.x:total() or 0) *-1
local rw = 0
if renderable.polygon then
rw = renderable.polygon:getDimensions().w
elseif renderable.render then
if renderable.render.rtype == "sprite" then
_, _, rw = renderable.render.quad:getViewport()
elseif renderable.render.rtype == "animation" then
rw = renderable.render.ani.frameWidth
end
end
tx = tx - rw
return math.ceil(tx/ self.planet_width)
end
function RenderableSystem:drawHeirarchy ( root, big_list )
--Pop the coordinate system
local delta
if root:hasComponent('Transform') then
delta = root:getComponent('Transform')
if delta.x == 0 and delta.y == 0 then
delta = nil
else
table.insert(big_list, {r = "PLZ_PUSH", t = delta})
love.graphics.push()
love.graphics.translate(delta.x, delta.y)
end
end
--Do draw
--Renderable
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
end
table.insert(big_list, renderable )
--Draw children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
self:drawHeirarchy(self.registry:get(gid), big_list)
end
--Unpop the coordinate system
if delta ~= nil then
love.graphics.pop()
table.insert(big_list, {r = "PLZ_POP", t = "PLOXPOPIT"})
end
return big_list
end
function RenderableSystem:draw ()
if self.cache == nil or self.dirty > 3 then
self.cache = self:drawHeirarchy(self.registry:get(self.targetCollection:getRoot()), {})
self.dirty = 0
end
for i = 1, #self.cache do
self:renderComponent(self.cache[i])
end
self.dirty = self.dirty + 1
end
return RenderableSystem
|
fix text
|
fix text
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
6dfb195a71282d2cdd46bb061068e4fbbcf1193e
|
mods/soundset/init.lua
|
mods/soundset/init.lua
|
minetest.log("action","[mod soundset] Loading...")
sounds = {}
sounds.file = minetest.get_worldpath() .. "/sounds_config.txt"
sounds.gaindefault = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
sounds.gainplayers = {}
sounds.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
minetest.log("action", "invalid param, see /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
minetest.log("action", "invalid param, /setsound " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.log("action", "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if sounds.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "ambience " .. param_name .. " already set to " .. value)
minetest.log("action", name ..", ambience " .. param_name .. " already set to " .. value)
return
end
sounds.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
minetest.log("action", name ..", sound " .. param_name .. " set to " .. value)
local input = io.open(sounds.file, "w")
if input then
input:write(minetest.serialize(sounds.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. sounds.file)
end
end
sounds.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
local gain = sounds.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/50
end
local function load_sounds_config()
local file = io.open(sounds.file, "r")
if file then
sounds.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if sounds.gainplayers == nil then
sounds.gainplayers = {}
end
end
load_sounds_config()
minetest.register_chatcommand("setsound", {
params = "<music|ambience|mobs|other> <number>",
description = "set volume sound <music|ambience|mobs|other>",
privs = {},
func = sounds.set_sound,
})
minetest.register_chatcommand("getsound", {
params = "",
description = "print volume sound <music|ambience|mobs|other>",
privs = {},
func = function(name, param)
local conf = ""
for k, v in pairs(sounds.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if sounds.gainplayers[name] == nil then
sounds.gainplayers[name] = sounds.gaindefault
end
end)
minetest.log("action","[mod soundset] Loaded")
|
minetest.log("action","[mod soundset] Loading...")
sounds = {}
sounds.file = minetest.get_worldpath() .. "/sounds_config.txt"
sounds.gainplayers = {}
sounds.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
minetest.log("action", "invalid param, see /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
minetest.log("action", "invalid param, /setsound " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.log("action", "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if sounds.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value)
minetest.log("action", name ..", volume " .. param_name .. " already set to " .. value)
return
end
sounds.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
minetest.log("action", name ..", sound " .. param_name .. " set to " .. value)
local input = io.open(sounds.file, "w")
if input then
input:write(minetest.serialize(sounds.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. sounds.file)
end
end
sounds.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
local gain = sounds.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/50
end
local function load_sounds_config()
local file = io.open(sounds.file, "r")
if file then
sounds.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if sounds.gainplayers == nil then
sounds.gainplayers = {}
end
end
load_sounds_config()
minetest.register_chatcommand("setsound", {
params = "<music|ambience|mobs|other> <number>",
description = "set volume sound <music|ambience|mobs|other>",
privs = {},
func = sounds.set_sound,
})
minetest.register_chatcommand("getsound", {
params = "",
description = "print volume sound <music|ambience|mobs|other>",
privs = {},
func = function(name, param)
local conf = ""
for k, v in pairs(sounds.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if sounds.gainplayers[name] == nil then
sounds.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
end
end)
minetest.log("action","[mod soundset] Loaded")
|
fixed strange bug with table=table
|
fixed strange bug with table=table
error --> sounds.gainplayers[name] = sounds.gaindefault
"""
local _ = {}
_[1] = {["other"] = 50, ["ambience"] = 50, ["music"] = 70, ["mobs"] = 30}
return {["azerty"] = _[1], ["crabman3"] = _[1]}
"""
fixed --> sounds.gainplayers[name]= { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
and delete unused variable sounds.gaindefault
|
Lua
|
unlicense
|
paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun
|
1501a65316fb9394d8f276c5ec65db66fa90cd00
|
eval.lua
|
eval.lua
|
require 'torch'
require 'nn'
require 'LanguageModel'
require 'util.DataLoader'
torch.setdefaulttensortype('torch.FloatTensor')
local utils = require 'util.utils'
local cmd = torch.CmdLine()
cmd:option('-checkpoint', '')
cmd:option('-split', 'val')
cmd:option('-gpu', 0)
cmd:option('-gpu_backend', 'cuda')
cmd:option('-input_h5', '')
cmd:option('-seq_length', 0)
cmd:option('-batch_size', 0)
local opt = cmd:parse(arg)
-- Set up GPU stuff
local dtype = 'torch.FloatTensor'
if opt.gpu >= 0 and opt.gpu_backend == 'cuda' then
require 'cutorch'
require 'cunn'
cutorch.setDevice(opt.gpu + 1)
dtype = 'torch.CudaTensor'
print(string.format('Running with CUDA on GPU %d', opt.gpu))
elseif opt.gpu >= 0 and opt.gpu_backend == 'opencl' then
require 'cltorch'
require 'clnn'
cltorch.setDevice(opt.gpu + 1)
dtype = torch.Tensor():cl():type()
print(string.format('Running with OpenCL on GPU %d', opt.gpu))
else
-- Memory benchmarking is only supported in CUDA mode
print 'Running in CPU mode'
end
-- Load the checkpoint and model
local checkpoint = torch.load(opt.checkpoint)
local model = checkpoint.model
model:type(dtype)
local crit = nn.CrossEntropyCriterion():type(dtype)
if opt.input_h5 ~= '' then checkpoint.opt.input_h5 = opt.input_h5 end
if opt.seq_length > 0 then checkpoint.opt.seq_length = opt.seq_length end
if opt.batch_size > 0 then checkpoint.opt.batch_size = opt.batch_size end
if checkpoint.opt.seq_offset == nil then checkpoint.opt.seq_offset = 0 end
-- Load the vocab and data
local loader = DataLoader(checkpoint.opt)
local N, T = checkpoint.opt.batch_size, checkpoint.opt.seq_length
-- Evaluate the model on the specified split
model:evaluate()
model:resetStates()
local num = loader.split_sizes[opt.split]
local loss = 0
local lossstring = ''
for i = 1, num do
print(string.format('%s batch %d / %d %s', opt.split, i, num, lossstring))
local x, y = loader:nextBatch(opt.split)
x = x:type(dtype)
y = y:type(dtype):view(N * T)
local scores = model:forward(x):view(N * T, -1)
loss = loss + crit:forward(scores, y)
lossstring = string.format('average loss = %f', loss / i)
end
loss = loss / num
print(string.format('%s loss = %f', opt.split, loss))
|
require 'torch'
require 'nn'
require 'LanguageModel'
require 'util.DataLoader'
torch.setdefaulttensortype('torch.FloatTensor')
local utils = require 'util.utils'
local cmd = torch.CmdLine()
cmd:option('-checkpoint', '')
cmd:option('-split', 'val')
cmd:option('-gpu', 0)
cmd:option('-gpu_backend', 'cuda')
cmd:option('-input_h5', '')
cmd:option('-seq_length', 0)
cmd:option('-batch_size', 0)
local opt = cmd:parse(arg)
-- Set up GPU stuff
local dtype = 'torch.FloatTensor'
if opt.gpu >= 0 and opt.gpu_backend == 'cuda' then
require 'cutorch'
require 'cunn'
cutorch.setDevice(opt.gpu + 1)
dtype = 'torch.CudaTensor'
print(string.format('Running with CUDA on GPU %d', opt.gpu))
elseif opt.gpu >= 0 and opt.gpu_backend == 'opencl' then
require 'cltorch'
require 'clnn'
cltorch.setDevice(opt.gpu + 1)
dtype = torch.Tensor():cl():type()
print(string.format('Running with OpenCL on GPU %d', opt.gpu))
else
-- Memory benchmarking is only supported in CUDA mode
print 'Running in CPU mode'
end
-- Load the checkpoint and model
local checkpoint = torch.load(opt.checkpoint)
local model = checkpoint.model
model:type(dtype)
local crit = nn.CrossEntropyCriterion():type(dtype)
if opt.input_h5 ~= '' then checkpoint.opt.input_h5 = opt.input_h5 end
if opt.seq_length > 0 then checkpoint.opt.seq_length = opt.seq_length end
if opt.batch_size > 0 then checkpoint.opt.batch_size = opt.batch_size end
if checkpoint.opt.seq_offset == nil then checkpoint.opt.seq_offset = 0 end
checkpoint.opt.shuffle_data = 0
-- Load the vocab and data
local loader = DataLoader(checkpoint.opt)
local N, T = checkpoint.opt.batch_size, checkpoint.opt.seq_length
-- Evaluate the model on the specified split
model:evaluate()
model:resetStates()
local num = loader.split_sizes[opt.split]
local loss = 0
local lossstring = ''
for i = 1, num do
print(string.format('%s batch %d / %d %s', opt.split, i, num, lossstring))
local x, y = loader:nextBatch(opt.split)
x = x:type(dtype)
y = y:type(dtype):view(N * T)
local scores = model:forward(x):view(N * T, -1)
loss = loss + crit:forward(scores, y)
lossstring = string.format('average loss = %f', loss / i)
end
loss = loss / num
print(string.format('%s loss = %f', opt.split, loss))
|
Fix eval for shuffle_data
|
Fix eval for shuffle_data
|
Lua
|
mit
|
antihutka/torch-rnn
|
1707347788b27b5c35bad86691c5caac47b2a788
|
src_trunk/resources/realism-system/c_headbob.lua
|
src_trunk/resources/realism-system/c_headbob.lua
|
function bobHead()
local logged = getElementData(getLocalPlayer(), "loggedin")
if (logged==1) then
for key, value in ipairs(getElementsByType("player")) do
if value == getLocalPlayer() then
local scrWidth, scrHeight = guiGetScreenSize()
local sx = scrWidth/2
local sy = scrHeight/2
local x, y, z = getWorldFromScreenPosition(sx, sy, 10)
setPedLookAt(value, x, y, z, 3000)
else
--local rot = getPedCameraRotation(value)
--local rott = getPedRotation(value)
--local x, y, z = getElementPosition(value)
--local vx = x + math.sin(math.rad(rot)) * 5
--local vy = y + math.cos(math.rad(rot)) * 5
--setPedLookAt(value, vx, vy, z)
end
end
end
end
addEventHandler("onClientRender", getRootElement(), bobHead)
function resetCam()
setCameraTarget(getLocalPlayer())
end
addCommandHandler("resetcam", resetCam)
|
function bobHead()
local logged = getElementData(getLocalPlayer(), "loggedin")
if (logged==1) then
local scrWidth, scrHeight = guiGetScreenSize()
local sx = scrWidth/2
local sy = scrHeight/2
local x, y, z = getWorldFromScreenPosition(sx, sy, 10)
setPedLookAt(value, x, y, z, 3000)
end
end
addEventHandler("onClientRender", getRootElement(), bobHead)
function resetCam()
setCameraTarget(getLocalPlayer())
end
addCommandHandler("resetcam", resetCam)
|
FPS fix for head movement
|
FPS fix for head movement
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1641 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
84218f2c4142ccbaa14a2cf16da4ad890f157a1a
|
init.lua
|
init.lua
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app
main(unpack(args))
-- Start the event loop
uv.run()
end, debug.traceback)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
-- When the loop exits, close all unclosed uv handles.
uv.walk(function (handle)
if handle and not handle:is_closing() then handle:close() end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app
main(unpack(args))
-- Start the event loop
uv.run()
end, debug.traceback)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
-- When the loop exits, close all unclosed uv handles (flushing any streams found).
uv.walk(function (handle)
if handle then
local function close()
if not handle:is_closing() then handle:close() end
end
if handle.shutdown then
handle:shutdown(close)
else
close()
end
end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
Flush streams on exit (fixes https://github.com/luvit/lit/issues/222)
|
Flush streams on exit (fixes https://github.com/luvit/lit/issues/222)
|
Lua
|
apache-2.0
|
luvit/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit
|
0e11f80cc7d1fcf53e7eb798956fad5c109e5476
|
OvaleCooldown.lua
|
OvaleCooldown.lua
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
local OvaleCooldown = Ovale:NewModule("OvaleCooldown")
Ovale.OvaleCooldown = OvaleCooldown
--<private-static-properties>
-- Forward declarations for module dependencies.
local OvaleData = nil
local OvaleGUID = nil
local OvalePaperDoll = nil
local OvaleStance = nil
local OvaleState = nil
local API_UnitHealth = UnitHealth
local API_UnitHealthMax = UnitHealthMax
local API_UnitClass = UnitClass
-- Player's class.
local self_class = select(2, API_UnitClass("player"))
--</private-static-properties>
--<public-static-methods>
function OvaleCooldown:OnInitialize()
-- Resolve module dependencies.
OvaleData = Ovale.OvaleData
OvaleGUID = Ovale.OvaleGUID
OvalePaperDoll = Ovale.OvalePaperDoll
OvaleStance = Ovale.OvaleStance
OvaleState = Ovale.OvaleState
end
function OvaleCooldown:OnEnable()
OvaleState:RegisterState(self, self.statePrototype)
end
function OvaleCooldown:OnDisable()
OvaleState:UnregisterState(self)
end
-- Return the GCD after the given spellId is cast.
-- If no spellId is given, then returns the GCD after a "yellow-hit" ability has been cast.
function OvaleCooldown:GetGCD(spellId)
-- Base global cooldown.
local isCaster = false
if self_class == "DEATHKNIGHT" then
cd = 1.0
elseif self_class == "DRUID" and OvaleStance:IsStance("druid_cat_form") then
cd = 1.0
elseif self_class == "MONK" then
cd = 1.0
elseif self_class == "ROGUE" then
cd = 1.0
else
isCaster = true
cd = 1.5
end
-- Use SpellInfo() information if available.
if spellId and OvaleData.spellInfo[spellId] then
local si = OvaleData.spellInfo[spellId]
if si.gcd then
cd = si.gcd
end
if si.haste then
if si.haste == "melee" then
cd = cd / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.haste == "spell" then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
elseif isCaster then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
-- Clamp GCD at 1s.
cd = (cd > 1) and cd or 1
return cd
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleCooldown.statePrototype = {
cd = nil,
}
--</public-static-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleCooldown:InitializeState(state)
state.cd = {}
end
-- Reset the state to the current conditions.
function OvaleCooldown:ResetState(state)
for _, cd in pairs(state.cd) do
cd.start = nil
cd.duration = nil
cd.enable = 0
end
end
-- Apply the effects of the spell on the player's state, assuming the spellcast completes.
function OvaleCooldown:ApplySpellAfterCast(state, spellId, targetGUID, startCast, endCast, nextCast, isChanneled, nocd, spellcast)
local si = OvaleData.spellInfo[spellId]
if si then
local cd = state:GetCD(spellId)
if cd then
cd.start = isChanneled and startCast or endCast
cd.duration = si.cd or 0
cd.enable = 1
-- Test for no cooldown.
if nocd then
cd.duration = 0
else
-- There is no cooldown if the buff named by "buffnocd" parameter is present.
if si.buffnocd then
local aura = state:GetAura("player", si.buffnocd)
if state:IsActiveAura(aura) then
Ovale:Logf("buffnocd stacks = %s, start = %s, ending = %s, startCast = %f", aura.stacks, aura.start, aura.ending, startCast)
if aura.start <= startCast and startCast < aura.ending then
cd.duration = 0
end
end
end
-- There is no cooldown if the target's health percent is below what's specified
-- with the "targetlifenocd" parameter.
local target = OvaleGUID:GetUnitId(targetGUID)
if target and si.targetlifenocd then
local healthPercent = API_UnitHealth(target) / API_UnitHealthMax(target) * 100
if healthPercent < si.targetlifenocd then
cd.duration = 0
end
end
end
-- Adjust cooldown duration if it is affected by haste: "cd_haste=melee" or "cd_haste=spell".
if cd.duration > 0 and si.cd_haste then
if si.cd_haste == "melee" then
cd.duration = cd.duration / state:GetMeleeHasteMultiplier()
elseif si.cd_haste == "spell" then
cd.duration = cd.duration / state:GetSpellHasteMultiplier()
end
end
Ovale:Logf("Spell %d cooldown info: start=%f, duration=%f", spellId, cd.start, cd.duration)
end
end
end
--</public-static-methods>
--<state-methods>
do
local statePrototype = OvaleCooldown.statePrototype
-- Return the table holding the simulator's cooldown information for the given spell.
statePrototype.GetCD = function(state, spellId)
if spellId then
local si = OvaleData.spellInfo[spellId]
if si and si.cd then
local cdname = si.sharedcd and si.sharedcd or spellId
if not state.cd[cdname] then
state.cd[cdname] = {}
end
return state.cd[cdname]
end
end
return nil
end
-- Return the cooldown for the spell in the simulator.
statePrototype.GetSpellCooldown = function(state, spellId)
local start, duration, enable
local cd = state:GetCD(state, spellId)
if cd and cd.start then
start = cd.start
duration = cd.duration
enable = cd.enable
else
start, duration, enable = OvaleData:GetSpellCooldown(spellId)
end
return start, duration, enable
end
-- Force the cooldown of a spell to reset at the specified time.
statePrototype.ResetSpellCooldown = function(state, spellId, atTime)
if atTime >= state.currentTime then
local cd = state:GetCD(state, spellId)
cd.start = state.currentTime
cd.duration = atTime - state.currentTime
cd.enable = 1
end
end
end
--</state-methods>
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
local OvaleCooldown = Ovale:NewModule("OvaleCooldown")
Ovale.OvaleCooldown = OvaleCooldown
--<private-static-properties>
-- Forward declarations for module dependencies.
local OvaleData = nil
local OvaleGUID = nil
local OvalePaperDoll = nil
local OvaleStance = nil
local OvaleState = nil
local API_UnitHealth = UnitHealth
local API_UnitHealthMax = UnitHealthMax
local API_UnitClass = UnitClass
-- Player's class.
local self_class = select(2, API_UnitClass("player"))
--</private-static-properties>
--<public-static-methods>
function OvaleCooldown:OnInitialize()
-- Resolve module dependencies.
OvaleData = Ovale.OvaleData
OvaleGUID = Ovale.OvaleGUID
OvalePaperDoll = Ovale.OvalePaperDoll
OvaleStance = Ovale.OvaleStance
OvaleState = Ovale.OvaleState
end
function OvaleCooldown:OnEnable()
OvaleState:RegisterState(self, self.statePrototype)
end
function OvaleCooldown:OnDisable()
OvaleState:UnregisterState(self)
end
-- Return the GCD after the given spellId is cast.
-- If no spellId is given, then returns the GCD after a "yellow-hit" ability has been cast.
function OvaleCooldown:GetGCD(spellId)
-- Base global cooldown.
local isCaster = false
if self_class == "DEATHKNIGHT" then
cd = 1.0
elseif self_class == "DRUID" and OvaleStance:IsStance("druid_cat_form") then
cd = 1.0
elseif self_class == "MONK" then
cd = 1.0
elseif self_class == "ROGUE" then
cd = 1.0
else
isCaster = true
cd = 1.5
end
-- Use SpellInfo() information if available.
if spellId and OvaleData.spellInfo[spellId] then
local si = OvaleData.spellInfo[spellId]
if si.gcd then
cd = si.gcd
end
if si.haste then
if si.haste == "melee" then
cd = cd / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.haste == "spell" then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
elseif isCaster then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
-- Clamp GCD at 1s.
cd = (cd > 1) and cd or 1
return cd
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleCooldown.statePrototype = {
cd = nil,
}
--</public-static-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleCooldown:InitializeState(state)
state.cd = {}
end
-- Reset the state to the current conditions.
function OvaleCooldown:ResetState(state)
for _, cd in pairs(state.cd) do
cd.start = nil
cd.duration = nil
cd.enable = 0
end
end
-- Apply the effects of the spell on the player's state, assuming the spellcast completes.
function OvaleCooldown:ApplySpellAfterCast(state, spellId, targetGUID, startCast, endCast, nextCast, isChanneled, nocd, spellcast)
local si = OvaleData.spellInfo[spellId]
if si then
local cd = state:GetCD(spellId)
if cd then
cd.start = isChanneled and startCast or endCast
cd.duration = si.cd or 0
cd.enable = 1
-- Test for no cooldown.
if nocd then
cd.duration = 0
else
-- There is no cooldown if the buff named by "buffnocd" parameter is present.
if si.buffnocd then
local aura = state:GetAura("player", si.buffnocd)
if state:IsActiveAura(aura) then
Ovale:Logf("buffnocd stacks = %s, start = %s, ending = %s, startCast = %f", aura.stacks, aura.start, aura.ending, startCast)
if aura.start <= startCast and startCast < aura.ending then
cd.duration = 0
end
end
end
-- There is no cooldown if the target's health percent is below what's specified
-- with the "targetlifenocd" parameter.
local target = OvaleGUID:GetUnitId(targetGUID)
if target and si.targetlifenocd then
local healthPercent = API_UnitHealth(target) / API_UnitHealthMax(target) * 100
if healthPercent < si.targetlifenocd then
cd.duration = 0
end
end
end
-- Adjust cooldown duration if it is affected by haste: "cd_haste=melee" or "cd_haste=spell".
if cd.duration > 0 and si.cd_haste then
if si.cd_haste == "melee" then
cd.duration = cd.duration / state:GetMeleeHasteMultiplier()
elseif si.cd_haste == "spell" then
cd.duration = cd.duration / state:GetSpellHasteMultiplier()
end
end
Ovale:Logf("Spell %d cooldown info: start=%f, duration=%f", spellId, cd.start, cd.duration)
end
end
end
--</public-static-methods>
--<state-methods>
do
local statePrototype = OvaleCooldown.statePrototype
-- Return the table holding the simulator's cooldown information for the given spell.
statePrototype.GetCD = function(state, spellId)
if spellId then
local si = OvaleData.spellInfo[spellId]
if si and si.cd then
local cdname = si.sharedcd and si.sharedcd or spellId
if not state.cd[cdname] then
state.cd[cdname] = {}
end
return state.cd[cdname]
end
end
return nil
end
-- Return the cooldown for the spell in the simulator.
statePrototype.GetSpellCooldown = function(state, spellId)
local start, duration, enable
local cd = state:GetCD(spellId)
if cd and cd.start then
start = cd.start
duration = cd.duration
enable = cd.enable
else
start, duration, enable = OvaleData:GetSpellCooldown(spellId)
end
return start, duration, enable
end
-- Force the cooldown of a spell to reset at the specified time.
statePrototype.ResetSpellCooldown = function(state, spellId, atTime)
if atTime >= state.currentTime then
local start, duration, enable = state:GetSpellCooldown(spellId)
if start + duration > state.currentTime then
local cd = state:GetCD(spellId)
if cd then
cd.start = state.currentTime
cd.duration = atTime - state.currentTime
cd.enable = 1
end
end
end
end
end
--</state-methods>
|
Fix arguments passed to state:GetCD().
|
Fix arguments passed to state:GetCD().
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1208 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale
|
f1681464939a42534b6a26f07dd51083e6c4dcb8
|
make/premake4.lua
|
make/premake4.lua
|
solution "Reaping2"
location "../build"
configurations { "Debug", "Release" }
configuration { "Debug" }
targetdir "../bin/debug"
configuration { "Release" }
targetdir "../bin/release"
if _ACTION == "clean" then
os.rmdir("../bin")
end
project "main"
language "C++"
kind "ConsoleApp"
libdirs { "../deps/boost_1_54_0/stage/lib", "../deps/glfw-3.0.3/build/src/Release", "../deps/glfw-3.0.3/build/src/Debug" }
includedirs { "../src", "../deps/boost_1_54_0", "../deps/glfw-3.0.3/include" }
links { "glfw3", "opengl32" }
linkoptions { "/nodefaultlib:libmsvcrt.lib", "/nodefaultlib:libmsvcrtd.lib" }
files { "../src/**.h", "../src/**.cpp" }
configuration { "Debug*" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
configuration { "Release*" }
defines { "NDEBUG" }
flags { "Optimize" }
|
solution "Reaping2"
location "../build"
configurations { "Debug", "Release" }
configuration { "Debug" }
targetdir "../bin/debug"
configuration { "Release" }
targetdir "../bin/release"
if _ACTION == "clean" then
os.rmdir("../bin")
end
project "main"
language "C++"
kind "ConsoleApp"
libdirs { "../deps/boost_1_54_0/stage/lib", "../deps/glfw-3.0.3/build/src/Release", "../deps/glfw-3.0.3/build/src/Debug", "../deps/glfw-3.0.3/build/src" }
includedirs { "../src", "../deps/boost_1_54_0", "../deps/glfw-3.0.3/include" }
links { "glfw3", "boost_system" }
if os.is("windows") then
links { "opengl32" }
linkoptions { "/nodefaultlib:libmsvcrt.lib", "/nodefaultlib:libmsvcrtd.lib" }
else
links { "Xi", "Xrandr", "GL" }
end
files { "../src/**.h", "../src/**.cpp" }
configuration { "Debug*" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
configuration { "Release*" }
defines { "NDEBUG" }
flags { "Optimize" }
|
linux compile fix, yay apt-get install libxrandr-dev, libxi-dev, cmake you'll also have to install premake4
|
linux compile fix, yay
apt-get install libxrandr-dev, libxi-dev, cmake
you'll also have to install premake4
|
Lua
|
mit
|
weanti/Reaping2,HalalUr/Reaping2,HalalUr/Reaping2,Reaping2/Reaping2,MrPepperoni/Reaping2-1,weanti/Reaping2,ishtoo/Reaping2,abannerth/Reaping2,Reaping2/Reaping2,MrPepperoni/Reaping2-1,abannerth/Reaping2,ishtoo/Reaping2
|
852a4e5ec0d4177c788208b9b8c0988053d206a9
|
lua/filters/fieldfix.lua
|
lua/filters/fieldfix.lua
|
-- From: https://github.com/hynd/heka-tsutils-plugins
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Performs some basic mutations on message Fields - add if not present, override,
remove, rename and parse. New messages will be emitted with a new Type.
The Parse function can be used to extract field data embedded in another field,
ie; in a StatsD bucket name. See Config for more information.
Config:
- msg_type (string, optional, default "fieldfix")
String to set as the new message Type (which will also have
'heka.sandbox.' automatically and unavoidably prefixed)
- payload_keep (bool, default false)
If true, maintain the original Payloads in the new messages.
- payload (string, optional)
If payload_keep is false, this allows overrides the Payload's value.
Support string-interpolation (see "fields_override", below).
- fields_if_missing (string, optional)
Space delimited string of Fields to supplement (ie; add if they're not
already present). Field name and value should be delimited with a '='.
- fields_override (string, optional)
Space delimited string of Fields to always ensure exists, overriding
existing values if necessary. Field name and value should be delimited
with a '='.
Supports string-interpolation, i.e. replace chunks of the form %{foo} with
the value of the field foo.
For example, if fields[foo] is 'hello' and fields[bar] is 'world', then the
interpolation msg=%{foo}_%{bar} will result in fields[msg] as 'hello_world'.
Note that the interpolation will only be done with the original field
values, and not any that have been configured to get renamed or inserted.
- fields_remove (string, optional)
Space delimited string of Fields to remove. Only the field name is
required.
- fields_rename (string, optional)
Space delimited string of Fields to rename. Old and new name should be
delimited with a '='.
Note: that it's possibly to make any Field value in the above configuration a
compound value by wrapping it in double quotes, i.e.
fields_override = 'msg="hello world" cluster=wibble'
*Example Heka Configuration*
.. code-block:: ini
[FieldFixFilter]
type = "SandboxFilter"
filename = "lua/filters/fieldfix.lua"
preserve_data = false
[FieldFixFilter.config]
fields_if_missing = "source=myhost target=remotehost"
fields_override = "cluster=wibble"
fields_remove = "product"
--]]
require "string"
local msg_type = read_config("msg_type") or "fieldfix"
local payload_keep = read_config("payload_keep") or false
local payload = read_config("payload")
local add_str = read_config("fields_if_missing") or ""
local override_str = read_config("fields_override") or ""
local remove_str = read_config("fields_remove") or ""
local rename_str = read_config("fields_rename") or ""
-- convert a space-delimited string into a table of kv's,
-- either splitting each token on '=', or setting the value
-- to 'true'
local function create_table(str)
local t = {}
if str:len() > 0 then
local fields = {}
-- Expressions with quoted strings
for f in str:gmatch("[%S]+=\"[^\"]+\"") do
fields[#fields+1] = f
end
-- Expressions without quoted strings
for f in str:gmatch("[%S]+=[^\"][%S]*") do
fields[#fields+1] = f
end
for i=1,#fields do
-- Also need to remove the quotes from the final value
local k, v = fields[i]:match("([%S]+)=\"?([^\"]+)\"?")
if k ~= nil then
t[k] = v
else
t[f] = true
end
end
end
return t
end
-- build tables
local add = create_table(add_str)
local remove = create_table(remove_str)
local override = create_table(override_str)
local rename = create_table(rename_str)
-- For a given value
local function interpolate_field_values(v)
local out = v
if string.find(v, "%%{[%w%p]-}") then
out = string.gsub(v, "%%{([%w%p]-)}", interpolate_func)
end
return out
end
-- Used for interpolating message fields into series name.
local function interpolate_func(key)
local val = read_message("Fields["..key.."]")
if val then
return val
end
return "%{"..key.."}"
end
function process_message ()
local message = {
Timestamp = read_message("Timestamp"),
Type = msg_type,
EnvVersion = read_message("EnvVersion"),
Fields = {}
}
if payload_keep then
-- Use existing payload
message.Payload = read_message("Payload")
else
-- Override existing payload
if payload then message.Payload = interpolate_field_values(payload) end
end
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- Fields to remove
if remove[name] then
-- Fields to rename
elseif rename[name] then
message.Fields[rename[name]] = value
-- Add untouched
else
message.Fields[name] = value
end
end
-- Fields to supplement
for k,v in pairs(add) do
if not message.Fields[k] then
message.Fields[k] = v
end
end
-- Fields to override
for k,v in pairs(override) do
message.Fields[k] = interpolate_field_values(v)
end
inject_message(message)
return 0
end
function timer_event(ns)
end
|
-- From: https://github.com/hynd/heka-tsutils-plugins
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Performs some basic mutations on message Fields - add if not present, override,
remove, rename and parse. New messages will be emitted with a new Type.
The Parse function can be used to extract field data embedded in another field,
ie; in a StatsD bucket name. See Config for more information.
Config:
- msg_type (string, optional, default "fieldfix")
String to set as the new message Type (which will also have
'heka.sandbox.' automatically and unavoidably prefixed)
- payload_keep (bool, default false)
If true, maintain the original Payloads in the new messages.
- payload (string, optional)
If payload_keep is false, this allows overrides the Payload's value.
Support string-interpolation (see "fields_override", below).
- fields_if_missing (string, optional)
Space delimited string of Fields to supplement (ie; add if they're not
already present). Field name and value should be delimited with a '='.
- fields_override (string, optional)
Space delimited string of Fields to always ensure exists, overriding
existing values if necessary. Field name and value should be delimited
with a '='.
Supports string-interpolation, i.e. replace chunks of the form %{foo} with
the value of the field foo.
For example, if fields[foo] is 'hello' and fields[bar] is 'world', then the
interpolation msg=%{foo}_%{bar} will result in fields[msg] as 'hello_world'.
Note that the interpolation will only be done with the original field
values, and not any that have been configured to get renamed or inserted.
- fields_remove (string, optional)
Space delimited string of Fields to remove. Only the field name is
required.
- fields_rename (string, optional)
Space delimited string of Fields to rename. Old and new name should be
delimited with a '='.
Note: that it's possibly to make any Field value in the above configuration a
compound value by wrapping it in double quotes, i.e.
fields_override = 'msg="hello world" cluster=wibble'
*Example Heka Configuration*
.. code-block:: ini
[FieldFixFilter]
type = "SandboxFilter"
filename = "lua/filters/fieldfix.lua"
preserve_data = false
[FieldFixFilter.config]
fields_if_missing = "source=myhost target=remotehost"
fields_override = "cluster=wibble"
fields_remove = "product"
--]]
require "string"
local msg_type = read_config("msg_type") or "fieldfix"
local payload_keep = read_config("payload_keep") or false
local payload = read_config("payload")
local add_str = read_config("fields_if_missing") or ""
local override_str = read_config("fields_override") or ""
local remove_str = read_config("fields_remove") or ""
local rename_str = read_config("fields_rename") or ""
-- convert a space-delimited string into a table of kv's,
-- either splitting each token on '=', or setting the value
-- to 'true'
local function create_table(str)
local t = {}
if str:len() > 0 then
local fields = {}
-- Expressions with quoted strings
for f in str:gmatch("[%S]+=\"[^\"]+\"") do
fields[#fields+1] = f
end
-- Expressions without quoted strings
for f in str:gmatch("[%S]+=[^\"][%S]*") do
fields[#fields+1] = f
end
for i=1,#fields do
-- Also need to remove the quotes from the final value
local k, v = fields[i]:match("([%S]+)=\"?([^\"]+)\"?")
if k ~= nil then
t[k] = v
else
t[f] = true
end
end
end
return t
end
-- build tables
local add = create_table(add_str)
local remove = create_table(remove_str)
local override = create_table(override_str)
local rename = create_table(rename_str)
-- Used for interpolating message fields into series name.
local function interpolate_func(key)
local val = read_message("Fields["..key.."]")
if val then
return val
end
return "%{"..key.."}"
end
-- For a given value
local function interpolate_field_values(v)
local out = tostring(v)
if string.find(out, "%%{[%w%p]-}") then
out = string.gsub(out, "%%{([%w%p]-)}", interpolate_func)
end
return out
end
function process_message ()
local message = {
Timestamp = read_message("Timestamp"),
Type = msg_type,
EnvVersion = read_message("EnvVersion"),
Fields = {}
}
if payload_keep then
-- Use existing payload
message.Payload = read_message("Payload")
else
-- Override existing payload
if payload then message.Payload = interpolate_field_values(payload) end
end
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- Fields to remove
if remove[name] then
-- Fields to rename
elseif rename[name] then
message.Fields[rename[name]] = value
-- Add untouched
else
message.Fields[name] = value
end
end
-- Fields to supplement
for k,v in pairs(add) do
if not message.Fields[k] then
message.Fields[k] = v
end
end
-- Fields to override
for k,v in pairs(override) do
message.Fields[k] = interpolate_field_values(v)
end
inject_message(message)
return 0
end
function timer_event(ns)
end
|
lua/filters: fieldfix- define helper fn above fn call
|
lua/filters: fieldfix- define helper fn above fn call
|
Lua
|
apache-2.0
|
wxdublin/heka-clever-plugins
|
1034bc67f7bee6833ec79a4cd58d1a4ea583f845
|
lib/acid/rangeset.lua
|
lib/acid/rangeset.lua
|
--example, how to use
-- local ranges, err, errmsg = rangeset.new({{1, 2, "foo"}, {4, 5, "bar"}})
-- local v, err, errmsg = ranges:get(1)
--
local bisect = require('acid.bisect')
local strutil = require('acid.strutil')
local tableutil = require('acid.tableutil')
local _M = { _VERSION = '1.0' }
local mt = { __index = _M }
local function cmp_boundary(l, r)
if l == nil then
return -1
end
if r == nil then
return -1
end
if l < r then
return -1
elseif l > r then
return 1
else
return 0
end
end
local function cmp(a, b)
if cmp_boundary(a[1], b[2]) >= 0 then
return 1
end
if cmp_boundary(b[1], a[2]) >= 0 then
return -1
end
return 0
end
local function cmp_val(a, b, none_cmp_finite)
if a == nil then
if b == nil then
return 0
else
return none_cmp_finite
end
else
if b == nil then
return -none_cmp_finite
else
if a < b then
return -1
elseif a > b then
return 1
else
return 0
end
end
end
end
local function has(range, val)
return (cmp_val(range[1], val, -1) <= 0
and cmp_val(val, range[2], 1) < 0)
end
function _M.new_rangedict(ranges)
local rngs = tableutil.dup(ranges, true)
for i = 1, #rngs - 1, 1 do
local curr = rngs[i]
local nxt = rngs[i + 1]
if cmp(curr, nxt) ~= -1 then
return nil, "ValueError", "range must be smaller than next one"
end
end
return setmetatable(rngs, mt), nil, nil
end
function _M.get(self, pos)
local rng = {pos, nil}
local opts = {
cmp = cmp
}
local ok, idx = bisect.search(self, rng, opts)
if not ok or not has(self[idx], pos) then
return nil, "KeyError", strutil.to_str(pos, " not in range")
end
return self[idx][3], nil, nil
end
return _M
|
--example, how to use
-- local ranges, err, errmsg = rangeset.new({{1, 2, "foo"}, {4, 5, "bar"}})
-- local v, err, errmsg = ranges:get(1)
--
local bisect = require('acid.bisect')
local strutil = require('acid.strutil')
local tableutil = require('acid.tableutil')
local _M = { _VERSION = '1.0' }
local mt = { __index = _M }
local function cmp_boundary(l, r)
if l == nil then
return -1
end
if r == nil then
return -1
end
if l < r then
return -1
elseif l > r then
return 1
else
return 0
end
end
local function cmp(a, b)
if cmp_boundary(a[1], b[2]) >= 0 then
return 1
end
if cmp_boundary(b[1], a[2]) >= 0 then
return -1
end
return 0
end
local function cmp_val(a, b, none_cmp_finite)
if a == nil then
if b == nil then
return 0
else
return none_cmp_finite
end
else
if b == nil then
return -none_cmp_finite
else
if a < b then
return -1
elseif a > b then
return 1
else
return 0
end
end
end
end
local function cmp_pos(key, a)
if a[1] ~= nil and a[1] > key then
return -1
elseif a[2] ~= nil and a[2] <= key then
return 1
else
return 0
end
end
local function has(range, val)
return (cmp_val(range[1], val, -1) <= 0
and cmp_val(val, range[2], 1) < 0)
end
function _M.new_rangedict(ranges)
local rngs = tableutil.dup(ranges, true)
for i = 1, #rngs - 1, 1 do
local curr = rngs[i]
local nxt = rngs[i + 1]
if cmp(curr, nxt) ~= -1 then
return nil, "ValueError", "range must be smaller than next one"
end
end
return setmetatable(rngs, mt), nil, nil
end
function _M.get(self, pos)
local opts = {
cmp = cmp_pos
}
local ok, idx = bisect.search(self, pos, opts)
if not ok or not has(self[idx], pos) then
return nil, "KeyError", strutil.to_str(pos, " not in range")
end
return self[idx][3], nil, nil
end
return _M
|
fix rangeset cmp func
|
fix rangeset cmp func
|
Lua
|
mit
|
baishancloud/lua-acid,baishancloud/lua-acid,baishancloud/lua-acid
|
7e42653f80dfeb8d8aef044cb78e85cced125eb5
|
lualib/http/httpc.lua
|
lualib/http/httpc.lua
|
local skynet = require "skynet"
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local dns = require "skynet.dns"
local string = string
local table = table
local httpc = {}
local function request(interface, method, host, url, recvheader, header, content)
local read = interface.read
local write = interface.write
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n", method, url, header_content, #content)
write(data)
write(content)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = internal.recvheader(read, tmpline, "")
if not body then
error(socket.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = internal.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
else
-- no content-length, read all
body = body .. interface.readall()
end
end
return code, body
end
local async_dns
function httpc.dns(server,port)
async_dns = true
dns.server(server,port)
end
local function check_protocol(host)
local protocol = host:match("^[Hh][Tt][Tt][Pp][Ss]?://")
if protocol then
host = string.gsub(host, "^"..protocol, "")
protocol = string.lower(protocol)
if protocol == "https://" then
return "https", host
elseif protocol == "http://" then
return "http", host
else
error(string.format("Invalid protocol: %s", protocol))
end
else
return "http", host
end
end
local SSLCTX_CLIENT = nil
local function gen_interface(protocol, fd)
if protocol == "http" then
return {
init = nil,
close = nil,
read = socket.readfunc(fd),
write = socket.writefunc(fd),
readall = function ()
return socket.readall(fd)
end,
}
elseif protocol == "https" then
local tls = require "http.tlshelper"
SSLCTX_CLIENT = SSLCTX_CLIENT or tls.newctx()
local tls_ctx = tls.newtls("client", SSLCTX_CLIENT)
return {
init = tls.init_requestfunc(fd, tls_ctx),
close = tls.closefunc(tls_ctx),
read = tls.readfunc(fd, tls_ctx),
write = tls.writefunc(fd, tls_ctx),
readall = tls.readallfunc(fd, tls_ctx),
}
else
error(string.format("Invalid protocol: %s", protocol))
end
end
function httpc.request(method, host, url, recvheader, header, content)
local protocol
local timeout = httpc.timeout -- get httpc.timeout before any blocked api
protocol, host = check_protocol(host)
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = protocol=="http" and 80 or protocol=="https" and 443
else
port = tonumber(port)
end
if async_dns and not hostname:match(".*%d+$") then
hostname = dns.resolve(hostname)
end
local fd = socket.connect(hostname, port, timeout)
if not fd then
error(string.format("%s connect error host:%s, port:%s, timeout:%s", protocol, hostname, port, timeout))
return
end
-- print("protocol hostname port", protocol, hostname, port)
local interface = gen_interface(protocol, fd)
local finish
if timeout then
skynet.timeout(timeout, function()
if not finish then
socket.shutdown(fd) -- shutdown the socket fd, need close later.
if interface.close then
interface.close()
end
end
end)
end
if interface.init then
interface.init()
end
local ok , statuscode, body = pcall(request, interface, method, host, url, recvheader, header, content)
finish = true
socket.close(fd)
if interface.close then
interface.close()
end
if ok then
return statuscode, body
else
error(statuscode)
end
end
function httpc.get(...)
return httpc.request("GET", ...)
end
local function escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
function httpc.post(host, url, form, recvheader)
local header = {
["content-type"] = "application/x-www-form-urlencoded"
}
local body = {}
for k,v in pairs(form) do
table.insert(body, string.format("%s=%s",escape(k),escape(v)))
end
return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end
return httpc
|
local skynet = require "skynet"
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local dns = require "skynet.dns"
local string = string
local table = table
local httpc = {}
local function request(interface, method, host, url, recvheader, header, content)
local read = interface.read
local write = interface.write
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n", method, url, header_content, #content)
write(data)
write(content)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = internal.recvheader(read, tmpline, "")
if not body then
error(socket.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = internal.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
elseif code == 204 or code == 304 or code < 200 then
body = ""
-- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response
else
-- no content-length, read all
body = body .. interface.readall()
end
end
return code, body
end
local async_dns
function httpc.dns(server,port)
async_dns = true
dns.server(server,port)
end
local function check_protocol(host)
local protocol = host:match("^[Hh][Tt][Tt][Pp][Ss]?://")
if protocol then
host = string.gsub(host, "^"..protocol, "")
protocol = string.lower(protocol)
if protocol == "https://" then
return "https", host
elseif protocol == "http://" then
return "http", host
else
error(string.format("Invalid protocol: %s", protocol))
end
else
return "http", host
end
end
local SSLCTX_CLIENT = nil
local function gen_interface(protocol, fd)
if protocol == "http" then
return {
init = nil,
close = nil,
read = socket.readfunc(fd),
write = socket.writefunc(fd),
readall = function ()
return socket.readall(fd)
end,
}
elseif protocol == "https" then
local tls = require "http.tlshelper"
SSLCTX_CLIENT = SSLCTX_CLIENT or tls.newctx()
local tls_ctx = tls.newtls("client", SSLCTX_CLIENT)
return {
init = tls.init_requestfunc(fd, tls_ctx),
close = tls.closefunc(tls_ctx),
read = tls.readfunc(fd, tls_ctx),
write = tls.writefunc(fd, tls_ctx),
readall = tls.readallfunc(fd, tls_ctx),
}
else
error(string.format("Invalid protocol: %s", protocol))
end
end
function httpc.request(method, host, url, recvheader, header, content)
local protocol
local timeout = httpc.timeout -- get httpc.timeout before any blocked api
protocol, host = check_protocol(host)
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = protocol=="http" and 80 or protocol=="https" and 443
else
port = tonumber(port)
end
if async_dns and not hostname:match(".*%d+$") then
hostname = dns.resolve(hostname)
end
local fd = socket.connect(hostname, port, timeout)
if not fd then
error(string.format("%s connect error host:%s, port:%s, timeout:%s", protocol, hostname, port, timeout))
return
end
-- print("protocol hostname port", protocol, hostname, port)
local interface = gen_interface(protocol, fd)
local finish
if timeout then
skynet.timeout(timeout, function()
if not finish then
socket.shutdown(fd) -- shutdown the socket fd, need close later.
if interface.close then
interface.close()
end
end
end)
end
if interface.init then
interface.init()
end
local ok , statuscode, body = pcall(request, interface, method, host, url, recvheader, header, content)
finish = true
socket.close(fd)
if interface.close then
interface.close()
end
if ok then
return statuscode, body
else
error(statuscode)
end
end
function httpc.get(...)
return httpc.request("GET", ...)
end
local function escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
function httpc.post(host, url, form, recvheader)
local header = {
["content-type"] = "application/x-www-form-urlencoded"
}
local body = {}
for k,v in pairs(form) do
table.insert(body, string.format("%s=%s",escape(k),escape(v)))
end
return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end
return httpc
|
fix #1057
|
fix #1057
|
Lua
|
mit
|
wangyi0226/skynet,sanikoyes/skynet,ag6ag/skynet,korialuo/skynet,icetoggle/skynet,pigparadise/skynet,korialuo/skynet,JiessieDawn/skynet,korialuo/skynet,xcjmine/skynet,xjdrew/skynet,jxlczjp77/skynet,hongling0/skynet,jxlczjp77/skynet,jxlczjp77/skynet,hongling0/skynet,bigrpg/skynet,bigrpg/skynet,cloudwu/skynet,pigparadise/skynet,icetoggle/skynet,sanikoyes/skynet,xcjmine/skynet,JiessieDawn/skynet,ag6ag/skynet,hongling0/skynet,ag6ag/skynet,pigparadise/skynet,xcjmine/skynet,JiessieDawn/skynet,xjdrew/skynet,cloudwu/skynet,wangyi0226/skynet,xjdrew/skynet,wangyi0226/skynet,sanikoyes/skynet,bigrpg/skynet,cloudwu/skynet,icetoggle/skynet
|
49f3c59faf5069d6b3e88d5b465d3ed3cda83e15
|
quest/bathelor_113_wilderness.lua
|
quest/bathelor_113_wilderness.lua
|
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (113, 'quest.bathelor_113_wilderness');
require("base.common")
module("quest.bathelor_113_wilderness", package.seeall)
GERMAN = Player.german
ENGLISH = Player.english
-- Insert the quest title here, in both languages
Title = {}
Title[GERMAN] = "Feuer und Flamme"
Title[ENGLISH] = "A spark to a flame"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Gehe zu jeden einzelnen Schrein der Fnf in ihren Tempel."
Description[ENGLISH][1] = "Go to each of the shrines in the Temple of the Five."
Description[GERMAN][2] = "Geh zu Bathelor, am Lagerfeuer westlich des Tempels der Fnf. Er hat bestimmt noch eine Aufgabe fr dich."
Description[ENGLISH][2] = "Go back to Bathelor at the campfire, west of the Temple of the Five, he is sure to have another task for you."
Description[GERMAN][3] = " Besorge zehn Scheite Naldorholz und bring sie Bathelor. Flle hierfr einen Naldorbaum mit einen Beil."
Description[ENGLISH][3] = "Obtain ten logs of naldor wood and bring them to Bathelor. You can cut down a naldor tree with a hatchet."
Description[GERMAN][4] = "Du hast alle Aufgaben von Bathelor erfllt. Lobet Brgon!"
Description[ENGLISH][4] = "You have fulfilled all the tasks for Bathelor. Praise Brgon!"
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
QuestTarget = {}
QuestTarget[1] = {position(549, 138, 0), position(551, 133, 0), position(556, 135, 0), position(556, 141, 0), position(551, 143, 0), position(519, 128, 0)} -- Shrines
QuestTarget[2] = {position(519, 128, 0)}
QuestTarget[3] = {position(519, 128, 0), position(511, 119, 0)} -- tree
QuestTarget[4] = {position(519, 128, 0)}
-- Insert the quest status which is reached at the end of the quest
FINAL_QUEST_STATUS = 4
function QuestTitle(user)
return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return base.common.GetNLS(user, german, english)
end
function QuestTargets(user, status)
return QuestTarget[status]
end
function QuestFinalStatus()
return FINAL_QUEST_STATUS
end
|
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (113, 'quest.bathelor_113_wilderness');
require("base.common")
module("quest.bathelor_113_wilderness", package.seeall)
GERMAN = Player.german
ENGLISH = Player.english
-- Insert the quest title here, in both languages
Title = {}
Title[GERMAN] = "Feuer und Flamme"
Title[ENGLISH] = "A spark to a flame"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Gehe zu jeden einzelnen Schrein der Fnf in ihren Tempel."
Description[ENGLISH][1] = "Go to each of the shrines in the Temple of the Five."
Description[GERMAN][2] = "Du hast jeden der Schreine der Fnf in ihrem Tempel besucht. Gehe zu Bathelor und berichte ihm."
Description[ENGLISH][2] = "You visited every shrine. Go back to Bathelor."
Description[GERMAN][3] = "Geh zu Bathelor, am Lagerfeuer westlich des Tempels der Fnf. Er hat bestimmt noch eine Aufgabe fr dich."
Description[ENGLISH][3] = "Go back to Bathelor at the campfire, west of the Temple of the Five, he is sure to have another task for you."
Description[GERMAN][4] = " Besorge zehn Scheite Naldorholz und bring sie Bathelor. Flle hierfr einen Naldorbaum mit einen Beil."
Description[ENGLISH][4] = "Obtain ten logs of naldor wood and bring them to Bathelor. You can cut down a naldor tree with a hatchet."
Description[GERMAN][5] = "Du hast alle Aufgaben von Bathelor erfllt. Lobet Brgon!"
Description[ENGLISH][5] = "You have fulfilled all the tasks for Bathelor. Praise Brgon!"
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
QuestTarget = {}
QuestTarget[1] = {position(549, 138, 0), position(551, 133, 0), position(556, 135, 0), position(556, 141, 0), position(551, 143, 0), position(519, 128, 0)} -- Shrines
QuestTarget[2] = {position(519, 128, 0)}
QuestTarget[3] = {position(519, 128, 0)}
QuestTarget[4] = {position(519, 128, 0), position(511, 119, 0)} -- tree
QuestTarget[5] = {position(519, 128, 0)}
-- Insert the quest status which is reached at the end of the quest
FINAL_QUEST_STATUS = 5
function QuestTitle(user)
return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return base.common.GetNLS(user, german, english)
end
function QuestTargets(user, status)
return QuestTarget[status]
end
function QuestFinalStatus()
return FINAL_QUEST_STATUS
end
|
Fixing the queststatus of bathelor
|
Fixing the queststatus of bathelor
|
Lua
|
agpl-3.0
|
LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
|
65f589a7703c2e714f2059f7cc5799808a9daee2
|
src/SparseClassifier.lua
|
src/SparseClassifier.lua
|
--
-- User: pat
-- Date: 9/1/15
--
package.path = package.path .. ";src/?.lua"
require 'CmdArgs'
require 'EncoderFactory'
require 'rnn'
require 'UniversalSchemaEncoder'
require 'UniversalSchemaRelationPooling'
require 'UniversalSchemaEntityEncoder'
require 'UniversalSchemaJointEncoder'
require 'TransEEncoder'
require 'PositiveOnlyUniversalSchema'
local SparseClassifier, parent = torch.class('SparseClassifier', 'UniversalSchemaEncoder')
local kb_rels = {}
local kb_file = 'data/revised-split/torch/vocabs/kb-indices.txt'
io.write('Loading kb map... ')
local new_id = 1
for line in io.lines(kb_file) do
local token, id = string.match(line, "([^\t]+)\t([^\t]+)")
if token and id then
id = tonumber(id)
if id > 1 then kb_rels[id] = new_id; new_id = new_id + 1 end
end
end
print('Done')
function SparseClassifier:__init(params, row_table, row_encoder, col_table, col_encoder, use_entities)
self.__index = self
self.params = params
self.opt_config = { learningRate = self.params.learningRate, epsilon = self.params.epsilon,
beta1 = self.params.beta1, beta2 = self.params.beta2,
momentum = self.params.momentum, learningRateDecay = self.params.decay
}
self.opt_state = {}
self.train_data = self:load_train_data(params.train, use_entities)
-- either load model from file or initialize new one
if params.loadModel ~= '' then
local loaded_model = torch.load(params.loadModel)
self.net = self:to_cuda(loaded_model.net)
self.opt_state = loaded_model.opt_state
for key, val in pairs(loaded_model.opt_state) do
if (torch.type(val) == 'torch.DoubleTensor') then self.opt_state[key] = self:to_cuda(val) end
end
else
self.net = self:build_network()
end
-- set the criterion
self.crit = nn.ClassNLLCriterion()
self:to_cuda(self.crit)
end
function SparseClassifier:build_network()
local net = nn.Sequential()
:add(nn.SparseLinear(self.train_data.num_cols, 41))
:add(nn.LogSoftMax(2, self.train_data.num_cols))
-- put the networks on cuda
self:to_cuda(net)
return net
end
function SparseClassifier:gen_subdata_batches_three_col(data, sub_data, batches, max_neg, shuffle)
local start = 1
local kb_indices = {}
local kb_mapped = {}
-- only keep kb exampels
for i = 1, sub_data.row:size(1) do
if kb_rels[sub_data.row[i]] then
table.insert(kb_mapped, kb_rels[sub_data.row[i]])
table.insert(kb_indices, i)
end
i = i + 1
end
sub_data.row = torch.Tensor(kb_mapped)
local index = torch.LongTensor(kb_indices)
print({index, sub_data.col})
sub_data.col = sub_data.col:index(index)
local rand_order = shuffle and torch.randperm(sub_data.row:size(1)):long() or torch.range(1, sub_data.row:size(1)):long()
while start <= sub_data.row:size(1) do
local size = math.min(self.params.batchSize, sub_data.row:size(1) - start + 1)
local batch_indices = rand_order:narrow(1, start, size)
local row_batch = self.params.rowEncoder == 'lookup-table' and sub_data.row:index(1, batch_indices) or sub_data.row_seq:index(1, batch_indices)
local col_batch = self.params.colEncoder == 'lookup-table' and sub_data.col:index(1, batch_indices) or sub_data.col_seq:index(1, batch_indices)
table.insert(batches, { data = col_batch, label = row_batch })
start = start + size
end
end
function SparseClassifier:score_subdata(sub_data)
local batches = {}
if sub_data.ep then self:gen_subdata_batches_four_col(sub_data, sub_data, batches, 0, false)
else self:gen_subdata_batches_three_col(sub_data, sub_data, batches, 0, false) end
local scores = {}
for i = 1, #batches do
local row_batch, col_batch, _ = unpack(batches[i].data)
if self.params.colEncoder == 'lookup-table' then col_batch = col_batch:view(col_batch:size(1), 1) end
if self.params.rowEncoder == 'lookup-table' then row_batch = row_batch:view(row_batch:size(1), 1) end
local encoded_rel = self.col_encoder(self:to_cuda(col_batch)):squeeze():clone()
local encoded_ep = self.row_encoder(self:to_cuda(row_batch))
local score = self:to_cuda(nn.PairwiseDistance(self.params.p))({encoded_ep[1] + encoded_rel, encoded_ep[2]})
table.insert(scores, score)
end
return scores, sub_data.label:view(sub_data.label:size(1))
end
|
--
-- User: pat
-- Date: 9/1/15
--
package.path = package.path .. ";src/?.lua"
require 'CmdArgs'
require 'EncoderFactory'
require 'rnn'
require 'UniversalSchemaEncoder'
require 'UniversalSchemaRelationPooling'
require 'UniversalSchemaEntityEncoder'
require 'UniversalSchemaJointEncoder'
require 'TransEEncoder'
require 'PositiveOnlyUniversalSchema'
local SparseClassifier, parent = torch.class('SparseClassifier', 'UniversalSchemaEncoder')
function SparseClassifier:__init(params, row_table, row_encoder, col_table, col_encoder, use_entities)
self.kb_rels = {}
local kb_file = 'data/revised-split/torch/vocabs/kb-indices.txt'
io.write('Loading kb map... ')
local new_id = 1
for line in io.lines(kb_file) do
local token, id = string.match(line, "([^\t]+)\t([^\t]+)")
if token and id then
id = tonumber(id)
if id > 1 then self.kb_rels[id] = new_id; new_id = new_id + 1 end
end
end
print('Done')
self.__index = self
self.params = params
self.opt_config = { learningRate = self.params.learningRate, epsilon = self.params.epsilon,
beta1 = self.params.beta1, beta2 = self.params.beta2,
momentum = self.params.momentum, learningRateDecay = self.params.decay
}
self.opt_state = {}
self.train_data = self:load_train_data(params.train, use_entities)
-- either load model from file or initialize new one
if params.loadModel ~= '' then
local loaded_model = torch.load(params.loadModel)
self.net = self:to_cuda(loaded_model.net)
self.opt_state = loaded_model.opt_state
for key, val in pairs(loaded_model.opt_state) do
if (torch.type(val) == 'torch.DoubleTensor') then self.opt_state[key] = self:to_cuda(val) end
end
else
self.net = self:build_network()
end
-- set the criterion
self.crit = nn.ClassNLLCriterion()
self:to_cuda(self.crit)
end
function SparseClassifier:build_network()
local net = nn.Sequential()
:add(nn.SparseLinear(self.train_data.num_cols, 41))
:add(nn.LogSoftMax(2, self.train_data.num_cols))
-- put the networks on cuda
self:to_cuda(net)
return net
end
function SparseClassifier:gen_subdata_batches_three_col(data, sub_data, batches, max_neg, shuffle)
local start = 1
local kb_indices = {}
local kb_mapped = {}
-- only keep kb exampels
for i = 1, sub_data.row:size(1) do
if self.kb_rels[sub_data.row[i]] then
table.insert(kb_mapped, self.kb_rels[sub_data.row[i]])
table.insert(kb_indices, i)
end
i = i + 1
end
sub_data.row = torch.Tensor(kb_mapped)
local index = torch.LongTensor(kb_indices)
print({index, sub_data.col})
sub_data.col = sub_data.col:index(index)
local rand_order = shuffle and torch.randperm(sub_data.row:size(1)):long() or torch.range(1, sub_data.row:size(1)):long()
while start <= sub_data.row:size(1) do
local size = math.min(self.params.batchSize, sub_data.row:size(1) - start + 1)
local batch_indices = rand_order:narrow(1, start, size)
local row_batch = self.params.rowEncoder == 'lookup-table' and sub_data.row:index(1, batch_indices) or sub_data.row_seq:index(1, batch_indices)
local col_batch = self.params.colEncoder == 'lookup-table' and sub_data.col:index(1, batch_indices) or sub_data.col_seq:index(1, batch_indices)
table.insert(batches, { data = col_batch, label = row_batch })
start = start + size
end
end
function SparseClassifier:score_subdata(sub_data)
local batches = {}
if sub_data.ep then self:gen_subdata_batches_four_col(sub_data, sub_data, batches, 0, false)
else self:gen_subdata_batches_three_col(sub_data, sub_data, batches, 0, false) end
local scores = {}
for i = 1, #batches do
local row_batch, col_batch, _ = unpack(batches[i].data)
if self.params.colEncoder == 'lookup-table' then col_batch = col_batch:view(col_batch:size(1), 1) end
if self.params.rowEncoder == 'lookup-table' then row_batch = row_batch:view(row_batch:size(1), 1) end
local encoded_rel = self.col_encoder(self:to_cuda(col_batch)):squeeze():clone()
local encoded_ep = self.row_encoder(self:to_cuda(row_batch))
local score = self:to_cuda(nn.PairwiseDistance(self.params.p))({encoded_ep[1] + encoded_rel, encoded_ep[2]})
table.insert(scores, score)
end
return scores, sub_data.label:view(sub_data.label:size(1))
end
|
fix sparse ruining everythin
|
fix sparse ruining everythin
|
Lua
|
mit
|
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
|
b0eafeead56e81bbd9dda2656cdc841e863710fd
|
commands/auth.lua
|
commands/auth.lua
|
local core = require('core')()
local prompt = require('prompt')(require('pretty-print'))
local fs = require('coro-fs')
local env = require('env')
local log = require('log').log
local pathJoin = require('luvi').path.join
local config = core.config
local dirty = false
local function confirm(name, value)
if not value then
value = config[name]
end
if not value then
value = prompt(name)
else
log(name, value)
end
if value ~= config[name] then
config[name] = value
dirty = true
end
return value
end
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(env.get("HOME"), ".gitconfig"))
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. '.' .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
confirm("username", args[2])
confirm("name", args[3] or getConfig("user.name"))
confirm("email", args[4] or getConfig("user.email"))
local path = (env.get("HOME") or env.get("HOMEPATH")) .. '/.ssh/id_rsa'
if fs.access(path, "r") then
config.privateKey = path
end
confirm("privateKey")
core.authUser()
if dirty then config.save() end
|
local core = require('core')()
local prompt = require('prompt')(require('pretty-print'))
local fs = require('coro-fs')
local env = require('env')
local log = require('log').log
local pathJoin = require('luvi').path.join
local config = core.config
local dirty = false
local function confirm(name, value)
if not value then
value = config[name]
end
if not value then
value = prompt(name)
else
log(name, value)
end
if value ~= config[name] then
config[name] = value
dirty = true
end
return value
end
local home = env.get("HOME") or env.get("HOMEPATH") or ""
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(home, ".gitconfig"))
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. '.' .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
confirm("username", args[2])
confirm("name", args[3] or getConfig("user.name"))
confirm("email", args[4] or getConfig("user.email"))
do
local path = pathJoin(home, ".ssh", "id_rsa")
if fs.access(path, "r") then
config.privateKey = path
end
confirm("privateKey")
end
core.authUser()
if dirty then config.save() end
|
Fix paths in auth
|
Fix paths in auth
|
Lua
|
apache-2.0
|
squeek502/lit,1yvT0s/lit,luvit/lit,zhaozg/lit,james2doyle/lit
|
0a48ff4e828dba66fa80ce177af63977c3eb430d
|
lua/wire/UpdateCheck.lua
|
lua/wire/UpdateCheck.lua
|
-- $Rev: 1621 $
-- $LastChangedDate: 2009-09-03 15:24:56 -0700 (Thu, 03 Sep 2009) $
-- $LastChangedBy: TomyLobo $
local rss_url = "http://www.wiremod.com:8060/changelog/~rss,feedmax=1/Wiremod/wire/rss.xml"
WireVersion = "1910" --manual revision, change this value to the revision-to-be once changes are committed
WireVersion = WireVersion .. " (exported)" -- leave this alone, it's to differentiate SVN checkouts from SVN Exported or downloaded versions of wire when a player types "wire_PrintVersion"
if file.Exists("../lua/wire/.svn/entries") then
WireVersion = tonumber(string.Explode("\n", file.Read( "../lua/wire/.svn/entries"))[4]) --get svn revision, stolen from ULX
SVNver = WireVersion -- this is for the sv_tags changing function at the bottom of WireLib.lua
end
WireLib.Version = WireVersion
if SERVER then
local function initplayer(pl)
umsg.Start("wire_rev", pl)
umsg.Short(WireVersion)
umsg.End()
end
hook.Add( "PlayerInitialSpawn", "WirePlayerInitSpawn", initplayer )
local function PrintWireVersion(pl,cmd,args)
if (pl and pl:IsValid()) then
pl:PrintMessage(HUD_PRINTTALK, "Wire revision: "..WireVersion)
else
print("Wire revision: "..WireVersion)
end
end
concommand.Add( "Wire_PrintVersion", PrintWireVersion )
MsgN("================================\n=== Wire "..WireVersion.." Installed ===\n================================")
end
if CLIENT then
WireVersionLocal = WireVersion
local function initplayer(um)
WIRE_SERVER_INSTALLED = true
WireVersion = um:ReadShort()
MsgN("================================\n=== Wire revision: "..WireVersion.." ===\n=== Local Wire revision:"..WireVersion.." ===\n================================")
end
usermessage.Hook( "wire_rev", initplayer )
end
--[[ Doesn't work, and nobody seems to know how to fix. Also, do not enable without uncommenting administration menu option in wiremenus.lua!
local update_check_lbl
-- http.Get Callback
local function CheckForUpdateCallback(contents, size)
local rev = string.match(contents, "http://www%.wiremod%.com:8060/changelog/Wiremod%?cs=(%d+)&csize=1")
if rev then
if tonumber(rev) > WireVersion then
update_check_lbl:SetText("There's a newer rev of wire!\nYou have: "..WireVersion.."\n"..rev.." is current.")
else
update_check_lbl:SetText("You have: "..WireVersion.."\nYour Wire is up to date!")
end
else
update_check_lbl:SetText("Unable to contact SVN server.\nD:")
end
update_check_lbl:GetParent():PerformLayout()
end
local function CheckForUpdateCP(Panel)
local update_check_btn = vgui.Create("DButton")
update_check_btn:SetText("Check for Update")
update_check_btn.DoClick = function(button)
http.Get(rss_url, "", CheckForUpdateCallback)
button:SetDisabled(true)
button:SetText("Checking....")
end
Panel:AddItem(update_check_btn)
update_check_lbl = vgui.Create("DLabel")
update_check_lbl:SetText("")
update_check_lbl:SetAutoStretchVertical(true)
Panel:AddItem(update_check_lbl)
end
hook.Add("PopulateToolMenu", "AddWireAdminUpdateCheck", function()
spawnmenu.AddToolMenuOption("Wire", "Administration", "WireAdminUpdateCheck", "Check For Update", "", "", CheckForUpdateCP, {})
end)
]]
|
-- $Rev: 1621 $
-- $LastChangedDate: 2009-09-03 15:24:56 -0700 (Thu, 03 Sep 2009) $
-- $LastChangedBy: TomyLobo $
local rss_url = "http://www.wiremod.com:8060/changelog/~rss,feedmax=1/Wiremod/wire/rss.xml"
WireVersion = "2114" --manual revision, change this value to the revision-to-be once changes are committed
WireVersion = WireVersion .. " (exported)" -- leave this alone, it's to differentiate SVN checkouts from SVN Exported or downloaded versions of wire when a player types "wire_PrintVersion"
// This function is broken, as gmod now prevents file.Read for .svn file type
-- if file.Exists("../lua/wire/.svn/entries") then
-- WireVersion = tonumber(string.Explode("\n", file.Read( "../lua/wire/.svn/entries"))[4]) --get svn revision, stolen from ULX
-- SVNver = WireVersion -- this is for the sv_tags changing function at the bottom of WireLib.lua
-- end
WireLib.Version = WireVersion
if SERVER then
local function initplayer(pl)
umsg.Start("wire_rev", pl)
umsg.Short(WireVersion)
umsg.End()
end
hook.Add( "PlayerInitialSpawn", "WirePlayerInitSpawn", initplayer )
local function PrintWireVersion(pl,cmd,args)
if (pl and pl:IsValid()) then
pl:PrintMessage(HUD_PRINTTALK, "Wire revision: "..WireVersion)
else
print("Wire revision: "..WireVersion)
end
end
concommand.Add( "Wire_PrintVersion", PrintWireVersion )
MsgN("================================\n=== Wire "..WireVersion.." Installed ===\n================================")
end
if CLIENT then
WireVersionLocal = WireVersion
local function initplayer(um)
WIRE_SERVER_INSTALLED = true
WireVersion = um:ReadShort()
MsgN("================================\n=== Wire revision: "..WireVersion.." ===\n=== Local Wire revision:"..WireVersion.." ===\n================================")
end
usermessage.Hook( "wire_rev", initplayer )
end
--[[ Doesn't work, and nobody seems to know how to fix. Also, do not enable without uncommenting administration menu option in wiremenus.lua!
local update_check_lbl
-- http.Get Callback
local function CheckForUpdateCallback(contents, size)
local rev = string.match(contents, "http://www%.wiremod%.com:8060/changelog/Wiremod%?cs=(%d+)&csize=1")
if rev then
if tonumber(rev) > WireVersion then
update_check_lbl:SetText("There's a newer rev of wire!\nYou have: "..WireVersion.."\n"..rev.." is current.")
else
update_check_lbl:SetText("You have: "..WireVersion.."\nYour Wire is up to date!")
end
else
update_check_lbl:SetText("Unable to contact SVN server.\nD:")
end
update_check_lbl:GetParent():PerformLayout()
end
local function CheckForUpdateCP(Panel)
local update_check_btn = vgui.Create("DButton")
update_check_btn:SetText("Check for Update")
update_check_btn.DoClick = function(button)
http.Get(rss_url, "", CheckForUpdateCallback)
button:SetDisabled(true)
button:SetText("Checking....")
end
Panel:AddItem(update_check_btn)
update_check_lbl = vgui.Create("DLabel")
update_check_lbl:SetText("")
update_check_lbl:SetAutoStretchVertical(true)
Panel:AddItem(update_check_lbl)
end
hook.Add("PopulateToolMenu", "AddWireAdminUpdateCheck", function()
spawnmenu.AddToolMenuOption("Wire", "Administration", "WireAdminUpdateCheck", "Check For Update", "", "", CheckForUpdateCP, {})
end)
]]
|
UpdateCheck.lua: Fixed keyboard being broken since last update, wire svn version detection no longer works
|
UpdateCheck.lua: Fixed keyboard being broken since last update, wire svn version detection no longer works
|
Lua
|
apache-2.0
|
immibis/wiremod,bigdogmat/wire,NezzKryptic/Wire,garrysmodlua/wire,CaptainPRICE/wire,notcake/wire,mms92/wire,Python1320/wire,dvdvideo1234/wire,rafradek/wire,wiremod/wire,thegrb93/wire,sammyt291/wire,mitterdoo/wire,Grocel/wire,plinkopenguin/wiremod
|
77374bc194d3dab72da4e6e395eeeba995b2b642
|
Modules/Shared/String/String.lua
|
Modules/Shared/String/String.lua
|
--- This module provides utility functions for strings
-- @module String
local String = {}
function String.trim(str, pattern)
pattern = pattern or "%s";
-- %S is whitespaces
-- When we find the first non space character defined by ^%s
-- we yank out anything in between that and the end of the string
-- Everything else is replaced with %1 which is essentially nothing
return str:gsub("^"..pattern.."*(.-)"..pattern.."*$", "%1")
end
--- Sets it to UpperCamelCase
function String.toCamelCase(str)
str = str:lower()
str = str:gsub("[ _](%a)", string.upper)
str = str:gsub("^%a", string.upper)
str = str:gsub("%p", "")
return str
end
function String.uppercaseFirstLetter(str)
return str:gsub("^%a", string.upper)
end
function String.toLowerCamelCase(str)
str = str:lower()
str = str:gsub("[ _](%a)", string.upper)
str = str:gsub("^%a", string.lower)
str = str:gsub("%p", "")
return str
end
function String.toPrivateCase(str)
return "_" .. str:sub(1, 1):lower() .. str:sub(2, #str)
end
-- Only trims the front of the string...
function String.trimFront(str, pattern)
pattern = pattern or "%s";
return (str:gsub("^"..pattern.."*(.-)"..pattern.."*", "%1"))
end
function String.checkNumOfCharacterInString(str, char)
local count = 0
for _ in string.gmatch(str, char) do
count = count + 1
end
return count
end
--- Checks if a string is empty or nil
function String.isEmptyOrWhitespaceOrNil(str)
return type(str) ~= "string" or str == "" or String.isWhitespace(str)
end
--- Returns whether or not text is whitespace
function String.isWhitespace(str)
return string.match(str, "[%s]+") == str
end
--- Converts text to have a ... after it if it's too long.
function String.elipseLimit(str, characterLimit)
if #str > characterLimit then
str = str:sub(1, characterLimit-3).."..."
end
return str
end
function String.addCommas(number)
if type(number) == "number" then
number = tostring(number)
end
local index = -1
while index ~= 0 do
number, index = string.gsub(number, "^(-?%d+)(%d%d%d)", '%1,%2')
end
return number
end
return String
|
--- This module provides utility functions for strings
-- @module String
local String = {}
function String.trim(str, pattern)
if not pattern then
return str:match("^%s*(.-)%s*$")
else
-- When we find the first non space character defined by ^%s
-- we yank out anything in between that and the end of the string
-- Everything else is replaced with %1 which is essentially nothing
return str:match("^"..pattern.."*(.-)"..pattern.."*$")
end
end
--- Sets it to UpperCamelCase
function String.toCamelCase(str)
str = str:lower()
str = str:gsub("[ _](%a)", string.upper)
str = str:gsub("^%a", string.upper)
str = str:gsub("%p", "")
return str
end
function String.uppercaseFirstLetter(str)
return str:gsub("^%a", string.upper)
end
function String.toLowerCamelCase(str)
str = str:lower()
str = str:gsub("[ _](%a)", string.upper)
str = str:gsub("^%a", string.lower)
str = str:gsub("%p", "")
return str
end
function String.toPrivateCase(str)
return "_" .. str:sub(1, 1):lower() .. str:sub(2, #str)
end
-- Only trims the front of the string...
function String.trimFront(str, pattern)
pattern = pattern or "%s";
return (str:gsub("^"..pattern.."*(.-)"..pattern.."*", "%1"))
end
function String.checkNumOfCharacterInString(str, char)
local count = 0
for _ in string.gmatch(str, char) do
count = count + 1
end
return count
end
--- Checks if a string is empty or nil
function String.isEmptyOrWhitespaceOrNil(str)
return type(str) ~= "string" or str == "" or String.isWhitespace(str)
end
--- Returns whether or not text is whitespace
function String.isWhitespace(str)
return string.match(str, "[%s]+") == str
end
--- Converts text to have a ... after it if it's too long.
function String.elipseLimit(str, characterLimit)
if #str > characterLimit then
str = str:sub(1, characterLimit-3).."..."
end
return str
end
function String.addCommas(number)
if type(number) == "number" then
number = tostring(number)
end
local index = -1
while index ~= 0 do
number, index = string.gsub(number, "^(-?%d+)(%d%d%d)", '%1,%2')
end
return number
end
return String
|
Fix trim so it doesn't leak args/for performance
|
Fix trim so it doesn't leak args/for performance
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
0efbd6f731715711436644524331a138bd771c93
|
MMOCoreORB/bin/scripts/screenplays/village/convos/elder_conv_handler.lua
|
MMOCoreORB/bin/scripts/screenplays/village/convos/elder_conv_handler.lua
|
local ObjectManager = require("managers.object.object_manager")
local CRYSTAL_OBJECT = "object/tangible/loot/quest/force_sensitive/force_crystal.iff"
villageElderConvoHandler = Object:new {}
function villageElderConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
function villageElderConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local state = CreatureObject(pPlayer):getScreenPlayState("VillageElderScreenPlay")
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
if (state == 1) then
return convoTemplate:getScreen("intro")
else
return convoTemplate:getScreen("greetings")
end
end
function villageElderConvoHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNpc, selectedOption, pConversationScreen)
local screen = LuaConversationScreen(pConversationScreen)
local screenID = screen:getScreenID()
if (screenID == "intro") then
local conversationScreen = screen:cloneScreen()
local clonedConversation = LuaConversationScreen(conversationScreen)
local pInventory = CreatureObject(pConversingPlayer):getSlottedObject("inventory")
if (pInventory ~= nil) then
local pInvItem = getContainerObjectByTemplate(pInventory, CRYSTAL_OBJECT, true)
if (pInvItem ~= nil) then
clonedConversation:addOption("@conversation/village_elder_1:s_9dc8bf5d", "already_have_crystal")
else
clonedConversation:addOption("@conversation/village_elder_1:s_9dc8bf5d", "give_new_crystal")
end
end
return conversationScreen
elseif (screenID == "give_new_crystal") then
local pInventory = CreatureObject(pConversingPlayer):getSlottedObject("inventory")
if (pInventory ~= nil) then
local pItem = getContainerObjectByTemplate(pInventory, CRYSTAL_OBJECT, true)
if (pItem == nil) then
if (SceneObject(pInventory):isContainerFullRecursive()) then
CreatureObject(pConversingPlayer):sendSystemMessage("@error_message:inv_full")
else
pItem = giveItem(pInventory, CRYSTAL_OBJECT, -1)
if (pItem == nil) then
CreatureObject(pConversingPlayer):sendSystemMessage("Error: Unable to generate item.")
end
end
end
end
elseif (screenID == "yes_you_might") then
CreatureObject(pConversingPlayer):setScreenPlayState(1, "VillageElderScreenPlay")
local pGhost = CreatureObject(pConversingPlayer):getPlayerObject()
PlayerObject(pGhost):setJediState(1)
awardSkill(pConversingPlayer, "force_title_jedi_novice")
end
return pConversationScreen
end
|
local ObjectManager = require("managers.object.object_manager")
local CRYSTAL_OBJECT = "object/tangible/loot/quest/force_sensitive/force_crystal.iff"
villageElderConvoHandler = Object:new {}
function villageElderConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
function villageElderConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local state = CreatureObject(pPlayer):getScreenPlayState("VillageElderScreenPlay")
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
if (state == 1) then
return convoTemplate:getScreen("intro")
else
return convoTemplate:getScreen("greetings")
end
end
function villageElderConvoHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNpc, selectedOption, pConversationScreen)
local screen = LuaConversationScreen(pConversationScreen)
local screenID = screen:getScreenID()
if (screenID == "intro") then
local conversationScreen = screen:cloneScreen()
local clonedConversation = LuaConversationScreen(conversationScreen)
local pInventory = CreatureObject(pConversingPlayer):getSlottedObject("inventory")
if (pInventory ~= nil) then
local pInvItem = getContainerObjectByTemplate(pInventory, CRYSTAL_OBJECT, true)
if (pInvItem ~= nil) then
clonedConversation:addOption("@conversation/village_elder_1:s_9dc8bf5d", "already_have_crystal")
else
clonedConversation:addOption("@conversation/village_elder_1:s_9dc8bf5d", "give_new_crystal")
end
end
return conversationScreen
elseif (screenID == "give_new_crystal") then
local pInventory = CreatureObject(pConversingPlayer):getSlottedObject("inventory")
if (pInventory ~= nil) then
local pItem = getContainerObjectByTemplate(pInventory, CRYSTAL_OBJECT, true)
if (pItem == nil) then
if (SceneObject(pInventory):isContainerFullRecursive()) then
CreatureObject(pConversingPlayer):sendSystemMessage("@error_message:inv_full")
else
pItem = giveItem(pInventory, CRYSTAL_OBJECT, -1)
if (pItem == nil) then
CreatureObject(pConversingPlayer):sendSystemMessage("Error: Unable to generate item.")
end
end
end
end
elseif (screenID == "yes_you_might") then
CreatureObject(pConversingPlayer):setScreenPlayState(1, "VillageElderScreenPlay")
local pGhost = CreatureObject(pConversingPlayer):getPlayerObject()
if (not PlayerObject(pGhost):isJedi()) then
PlayerObject(pGhost):setJediState(1)
end
awardSkill(pConversingPlayer, "force_title_jedi_novice")
end
return pConversationScreen
end
|
[fixed] Jedi going down in jedistate when talking to Rohak (Mantis #6545 part deux)
|
[fixed] Jedi going down in jedistate when talking to Rohak (Mantis #6545
part deux)
Change-Id: I337ade7158dc65064f99862689b752106784b879
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
50f815281fabbf0c01c3c946c43c46cd954d90d3
|
Wikilib-forms.lua
|
Wikilib-forms.lua
|
--[[
Funzioni di libreria per la gestione
delle forme alternative
--]]
local mw = require('mw')
local f = {}
local tab = require('Wikilib-tables') -- luacheck: no unused
local genUtil = require('Wikilib-gens')
local alt = require("AltForms-data")
--[[
Unisce le tabelle AltForms/data e UselessForms/data
gestendo anche la presenza di Pokémon in entrambi.
Restituisce la tabella così creata
--]]
f.allFormsData = function()
local all = table.cloneLoadData(alt)
local useless = require('UselessForms-data')
--[[
No need for ipairs because integer keys
are used only to index Pokémon by ndex
--]]
for k, v in pairs(useless) do
if all[k] then
--[[
This Pokémon is in both useless and altForms
Right now only Pikachu
--]]
all[k] = table.recursiveMerge(all[k], v)
--[[
gamesOrder is a pain in the neck
right now, with Pikachu, it is possible to
simply concatenate the two tables and remove
the second 'base'
--]]
all[k].gamesOrder = table.noDuplicates(table.merge(
all[k].gamesOrder,
v.gamesOrder
))
else
all[k] = v
end
end
return all
end
f.allformsdata, f.all_forms_data = f.allFormsData, f.allFormsData
--[[
Se merge è false usa come modulo dati
per le forme alternative UselessForms/data,
se è true li usa entrambi.
Gestisce anche Pikachu, unico Pokémon presente
in entrambi i moduli dati.
--]]
f.loadUseless = function(merge)
if merge then
alt = f.allFormsData()
else
alt = require("UselessForms-data")
end
end
f.loaduseless, f.load_useless = f.loadUseless, f.loadUseless
--[[
Estrae la sigla della forma alternativa dal
nome del Pokémon così come è negli indici
delle tabelle dati o negli ndex dei Mini
Sprite, oppure a partire dal nome del Pokémon
e quello esteso della forma alternativa. In
caso di fallimento, ritorna la stringa vuota.
--]]
f.getabbr = function(name, extform)
if alt[tonumber(name) or name:lower()] then
extform = string.lower(extform or '')
name = tonumber(name) or name:lower()
return alt[name].ext[extform] or 'base'
end
return name:match('(%u+%a*)$') or 'base'
end
f.getAbbr, f.get_abbr = f.getabbr, f.getabbr
--[[
Estrae nome e sigla della forma alternativa
dal nome del Pokémon così come è negli indici
delle tabelle dati o negli ndex dei Mini Sprite.
In caso di fallimento, ritorna la stringa vuota.
--]]
f.getnameabbr = function(name, extform)
if alt[tonumber(name) or name:lower()] then
extform = string.lower(extform or '')
name = tonumber(name) or name:lower()
return name, alt[name].ext[extform] or 'base'
end
local poke, abbr = name:match("^([%lé%-♂♀'%s%.&#;%d]+)(%u*%a*)$")
return tonumber(poke) or poke or '', abbr or 'base'
end
f.getNameAbbr, f.get_name_abbr = f.getnameabbr, f.getnameabbr
--[[
Il parametro black è un booleano, mentre ext
deve essere minuscolo. Recupera il link per
le forme alternative a partire dal nome del
Pokémon comprensivo di sigla, oppure dal nome
del Pokémon e quello esteso della forma alternativa.
--]]
f.getlink = function(poke, black, extform)
black = black and 'black' or ''
poke, extform = f.getnameabbr(poke, extform)
if extform == '' or extform == 'base' then
return ''
end
return alt[poke] and alt[poke][black .. 'links'][extform] or ''
end
f.getLink, f.get_link = f.getlink, f.getlink
--[[
Dato il nome di un Pokémon con forma alternativa,
ne determina il numero di dex nazionale senza passare
per il modulo Poké/data. Ritorna 0 in caso di errore.
--]]
f.getNdexForm = function(poke)
poke = string.lower(poke or '')
if not alt[poke] then
return 0
end
for k, tab in pairs(alt) do
if type(k) == 'number' and tab == alt[poke] then
return k
end
end
end
f.getndexform, f.get_ndex_form = f.getNdexForm, f.getNdexForm
-- Converte la sigla vuota in 'base'
f.toBase = function(abbr)
return abbr == '' and 'base' or abbr
end
f.tobase, f.to_base = f.toBase, f.toBase
-- Converte la sigla 'base' nella sigla vuota
f.toEmptyAbbr = function(abbr)
return abbr == 'base' and '' or abbr
end
f.toemptyabbr, f.to_empty_abbr = f.toEmptyAbbr, f.toEmptyAbbr
--[[
Ritorna un valore convertibile a true se
il Pokémon passato, solo come nome, ha una
megaevoluzione o archeorisveglio, uno equiparabile
a false altrimenti
--]]
f.hasMega = function(poke)
poke = string.lower(poke or '')
if alt.mega then
return table.search(alt.mega, poke)
or table.search(alt.megaxy, poke)
or table.search(alt.archeo, poke)
end
return false
end
f.has_mega, f.hasmega = f.hasMega, f.hasMega
--[[
Ritorna un valore convertibile a true se il
Pokémon passato, solo come nome, ha una forma
di alola, uno equiparabile a false altrimenti.
--]]
f.hasAlola = function(poke)
poke = string.lower(poke or '')
if alt.alola then
return table.search(alt.alola, poke)
end
return false
end
f.has_alola, f.hasalola = f.hasAlola, f.hasAlola
--[[
Returns the first and last game a form is
available.
--]]
f.formSpan = function(poke, abbr)
return alt[poke].since[abbr],
alt[poke]['until']
and alt[poke]['until'][abbr]
or genUtil.latest.game
end
f.formspan, f.form_span = f.formSpan, f.formSpan
--[[
Parse an argument that should be a Pokémon name or ndex followed by a form
abbreviation so that it can be used to index a data module.
If name is a Pokémon name (not an ndex) it should be lowercase but the first
letter, that can be both upper or lower case.
--]]
f.nameToDataindex = function(name)
local trueName, extform = f.getnameabbr(string.fl(string.trim(name)))
-- If the Pokémon isn't in altForms/data, should return the plain name
-- The return when extform == 'base' settles problems with number and concat
if extform == 'base' or not alt[tonumber(trueName) or trueName] then
return trueName
end
return trueName .. f.toEmptyAbbr(extform)
end
return f
|
--[[
Funzioni di libreria per la gestione
delle forme alternative
--]]
local mw = require('mw')
local f = {}
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local genUtil = require('Wikilib-gens')
local alt = require("AltForms-data")
--[[
Unisce le tabelle AltForms/data e UselessForms/data
gestendo anche la presenza di Pokémon in entrambi.
Restituisce la tabella così creata
--]]
f.allFormsData = function()
local all = table.cloneLoadData(alt)
local useless = require('UselessForms-data')
--[[
No need for ipairs because integer keys
are used only to index Pokémon by ndex
--]]
for k, v in pairs(useless) do
if all[k] then
--[[
This Pokémon is in both useless and altForms
Right now only Pikachu
--]]
all[k] = table.recursiveMerge(all[k], v)
--[[
gamesOrder is a pain in the neck
right now, with Pikachu, it is possible to
simply concatenate the two tables and remove
the second 'base'
--]]
all[k].gamesOrder = table.noDuplicates(table.merge(
all[k].gamesOrder,
v.gamesOrder
))
else
all[k] = v
end
end
return all
end
f.allformsdata, f.all_forms_data = f.allFormsData, f.allFormsData
--[[
Se merge è false usa come modulo dati
per le forme alternative UselessForms/data,
se è true li usa entrambi.
Gestisce anche Pikachu, unico Pokémon presente
in entrambi i moduli dati.
--]]
f.loadUseless = function(merge)
if merge then
alt = f.allFormsData()
else
alt = require("UselessForms-data")
end
end
f.loaduseless, f.load_useless = f.loadUseless, f.loadUseless
--[[
Estrae la sigla della forma alternativa dal
nome del Pokémon così come è negli indici
delle tabelle dati o negli ndex dei Mini
Sprite, oppure a partire dal nome del Pokémon
e quello esteso della forma alternativa. In
caso di fallimento, ritorna la stringa vuota.
--]]
f.getabbr = function(name, extform)
if alt[tonumber(name) or name:lower()] then
extform = string.lower(extform or '')
name = tonumber(name) or name:lower()
return alt[name].ext[extform] or 'base'
end
return name:match('(%u+%a*)$') or 'base'
end
f.getAbbr, f.get_abbr = f.getabbr, f.getabbr
--[[
Estrae nome e sigla della forma alternativa
dal nome del Pokémon così come è negli indici
delle tabelle dati o negli ndex dei Mini Sprite.
In caso di fallimento, ritorna la stringa vuota.
--]]
f.getnameabbr = function(name, extform)
if alt[tonumber(name) or name:lower()] then
extform = string.lower(extform or '')
name = tonumber(name) or name:lower()
return name, alt[name].ext[extform] or 'base'
end
local poke, abbr = name:match("^([%lé%-♂♀'%s%.&#;%d]+)(%u*%a*)$")
return tonumber(poke) or poke or '', abbr or 'base'
end
f.getNameAbbr, f.get_name_abbr = f.getnameabbr, f.getnameabbr
--[[
Il parametro black è un booleano, mentre ext
deve essere minuscolo. Recupera il link per
le forme alternative a partire dal nome del
Pokémon comprensivo di sigla, oppure dal nome
del Pokémon e quello esteso della forma alternativa.
--]]
f.getlink = function(poke, black, extform)
black = black and 'black' or ''
poke, extform = f.getnameabbr(poke, extform)
if extform == '' or extform == 'base' then
return ''
end
return alt[poke] and alt[poke][black .. 'links'][extform] or ''
end
f.getLink, f.get_link = f.getlink, f.getlink
--[[
Dato il nome di un Pokémon con forma alternativa,
ne determina il numero di dex nazionale senza passare
per il modulo Poké/data. Ritorna 0 in caso di errore.
--]]
f.getNdexForm = function(poke)
poke = string.lower(poke or '')
if not alt[poke] then
return 0
end
for k, tab in pairs(alt) do
if type(k) == 'number' and tab == alt[poke] then
return k
end
end
end
f.getndexform, f.get_ndex_form = f.getNdexForm, f.getNdexForm
-- Converte la sigla vuota in 'base'
f.toBase = function(abbr)
return abbr == '' and 'base' or abbr
end
f.tobase, f.to_base = f.toBase, f.toBase
-- Converte la sigla 'base' nella sigla vuota
f.toEmptyAbbr = function(abbr)
return abbr == 'base' and '' or abbr
end
f.toemptyabbr, f.to_empty_abbr = f.toEmptyAbbr, f.toEmptyAbbr
--[[
Ritorna un valore convertibile a true se
il Pokémon passato, solo come nome, ha una
megaevoluzione o archeorisveglio, uno equiparabile
a false altrimenti
--]]
f.hasMega = function(poke)
poke = string.lower(poke or '')
if alt.mega then
return table.search(alt.mega, poke)
or table.search(alt.megaxy, poke)
or table.search(alt.archeo, poke)
end
return false
end
f.has_mega, f.hasmega = f.hasMega, f.hasMega
--[[
Ritorna un valore convertibile a true se il
Pokémon passato, solo come nome, ha una forma
di alola, uno equiparabile a false altrimenti.
--]]
f.hasAlola = function(poke)
poke = string.lower(poke or '')
if alt.alola then
return table.search(alt.alola, poke)
end
return false
end
f.has_alola, f.hasalola = f.hasAlola, f.hasAlola
--[[
Returns the first and last game a form is
available.
--]]
f.formSpan = function(poke, abbr)
return alt[poke].since[abbr],
alt[poke]['until']
and alt[poke]['until'][abbr]
or genUtil.latest.game
end
f.formspan, f.form_span = f.formSpan, f.formSpan
--[[
Parse an argument that should be a Pokémon name or ndex followed by a form
abbreviation so that it can be used to index a data module.
If name is a Pokémon name (not an ndex) it should be lowercase but the first
letter, that can be both upper or lower case.
--]]
f.nameToDataindex = function(name)
local trueName, extform = f.getnameabbr(string.fl(string.trim(name)))
-- If the Pokémon isn't in altForms/data, should return the plain name
-- The return when extform == 'base' settles problems with number and concat
if extform == 'base' or not alt[tonumber(trueName) or trueName] then
return trueName
end
trueName = type(trueName) == 'number' and string.tf(trueName) or trueName
return trueName .. f.toEmptyAbbr(extform)
end
return f
|
Fast bugfix
|
Fast bugfix
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
9dc1ef7d94f7fba65e376c8416fa48a9412d5d73
|
fbcunn/TemporalConvolutionFB.lua
|
fbcunn/TemporalConvolutionFB.lua
|
-- Copyright 2004-present Facebook. All Rights Reserved.
require 'nn'
local TemporalConvolutionFB, parent =
torch.class('nn.TemporalConvolutionFB', 'nn.Module')
function TemporalConvolutionFB:__init(inputFrameSize, outputFrameSize, kW, dW)
parent.__init(self)
dW = dW or 1
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
self.kW = kW
self.dW = dW
self.weight = torch.Tensor(outputFrameSize, kW, inputFrameSize)
self.bias = torch.Tensor(outputFrameSize)
self.gradWeight = torch.Tensor(outputFrameSize, kW, inputFrameSize)
self.gradBias = torch.Tensor(outputFrameSize)
self:reset()
end
function TemporalConvolutionFB:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.inputFrameSize)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
function TemporalConvolutionFB:updateOutput(input)
input.nn.TemporalConvolutionFB_updateOutput(self, input)
return self.output
end
function TemporalConvolutionFB:updateGradInput(input, gradOutput)
if self.gradInput then
return input.nn.TemporalConvolutionFB_updateGradInput(
self, input, gradOutput)
end
end
function TemporalConvolutionFB:accGradParameters(input, gradOutput, scale)
scale = scale or 1
input.nn.TemporalConvolutionFB_accGradParameters(
self, input, gradOutput, scale)
end
-- we do not need to accumulate parameters when sharing
TemporalConvolutionFB.sharedAccUpdateGradParameters =
TemporalConvolutionFB.accUpdateGradParameters
|
-- Copyright 2004-present Facebook. All Rights Reserved.
require 'nn'
local TemporalConvolutionFB, parent =
torch.class('nn.TemporalConvolutionFB', 'nn.Module')
function TemporalConvolutionFB:__init(inputFrameSize, outputFrameSize, kW, dW)
parent.__init(self)
dW = dW or 1
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
self.kW = kW
self.dW = dW
self.weight = torch.Tensor(outputFrameSize, kW, inputFrameSize)
self.bias = torch.Tensor(outputFrameSize)
self.gradWeight = torch.Tensor(outputFrameSize, kW, inputFrameSize)
self.gradBias = torch.Tensor(outputFrameSize)
self:reset()
end
function TemporalConvolutionFB:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.inputFrameSize)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
function TemporalConvolutionFB:updateOutput(input)
input.nn.TemporalConvolutionFB_updateOutput(self, input)
return self.output
end
function TemporalConvolutionFB:updateGradInput(input, gradOutput)
if self.gradInput then
return input.nn.TemporalConvolutionFB_updateGradInput(
self, input, gradOutput)
end
end
function TemporalConvolutionFB:accGradParameters(input, gradOutput, scale)
scale = scale or 1
input.nn.TemporalConvolutionFB_accGradParameters(
self, input, gradOutput, scale)
end
function TemporalConvolutionFB:sharedAccUpdateGradParameters(input, gradOutput, lr)
-- we do not need to accumulate parameters when sharing:
self:defaultAccUpdateGradParameters(input, gradOutput, lr)
end
|
Update nn to 5989f82800a640ed0f5613c8ef3e417c4502661d and cunn to 64224a65eff88d1bfe5bc47d26a901ed8c0b4705.
|
Update nn to 5989f82800a640ed0f5613c8ef3e417c4502661d and cunn to 64224a65eff88d1bfe5bc47d26a901ed8c0b4705.
Summary:
Update nn and cunn.
Also added NN_HEAD and CUNN_HEAD for tracking upstream sync points; I wrote some scripts to do this sync automatically,
but didn't commit them yet because they probably need some resume functionality for the cases where there are merge conflicts.
This required some reworking of how THCUNN is defined in TARGETS, i.e. the non-generic .cu files are the source files,
everything else is a header file. And need to pass -I to the preprocessor for our macro definitions to work correctly.
Finally, needed to implement the equivalent of "Fix shared function override for specific modules" from nn in fbcunn,
otherwise some tests would fail with stack overflows.
Reviewed By: soumith
Differential Revision: D4438135
fbshipit-source-id: 06ea19bd5208d545087e3702044155116fbd83a2
|
Lua
|
bsd-3-clause
|
facebook/fbcunn,facebook/fbcunn,facebook/fbcunn
|
bc9ec2c6851065f3bab179307239fe744adb8e48
|
lua/entities/gmod_starfall/init.lua
|
lua/entities/gmod_starfall/init.lua
|
--[[
SF Entity
{
Inputs
Outputs
context
player
}
]]
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
self:SetOverlayText("Starfall")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:OnRestore()
end
function ENT:Compile(code)
if self.context and not self.error then
SF_Compiler.RunInternalHook("deinit",self.context,false)
end
self.error = false
self.context = nil
local ok, context = SF_Compiler.Compile(code,self.player,self)
if not ok then
self:Error(context)
return
end
self.context = context
context.data.inputs = {}
context.data.outputs = {}
SF_Compiler.RunInternalHook("init",context)
SF_Compiler.RunInternalHook("preexec",self.context,nil)
local ok, msg = SF_Compiler.RunStarfallFunction(self.context, self.context.func)
SF_Compiler.RunInternalHook("postexec",self.context,nil)
if not ok then
self:Error(msg)
return
end
end
function ENT:SendCode(ply, code)
if ply ~= self.player then return end
self:Compile(code)
end
function ENT:Think()
self.BaseClass.Think(self)
self:NextThink(CurTime())
self:RunHook("Think")
return true
end
function ENT:Error(msg)
self.error = true
if self.context then
SF_Compiler.RunInternalHook("deinit",self.context,true,msg)
end
ErrorNoHalt(msg.." (from processor of "..self.player:Nick()..")\n")
WireLib.ClientError(msg, self.player)
end
function ENT:OnRemove()
if not self.error or not self.context then
SF_Compiler.RunInternalHook("deinit",self.context,false)
end
self.error = true
self.context = nil
end
function ENT:RunHook(name, ...)
if not self.context or self.error then return end
SF_Compiler.RunInternalHook("preexec",self.context,name)
local ok, msg = SF_Compiler.CallHook(name, self.context, ...)
SF_Compiler.RunInternalHook("postexec",self.context,name)
if ok == false then
self:Error(msg)
end
return msg
end
function ENT:TriggerInput(key, value)
SF_Compiler.RunInternalHook("WireInputChanged",self,key,value)
end
function ENT:ReadCell(address)
local ret = self:RunHook("ReadCell",address)
if type(ret) ~= "number" then
self:Error("Returned "..type(ret).." to hook ReadCell (expected number)")
return 0
end
return ret
end
function ENT:WriteCell(address, data)
self:RunHook("WriteCell",address,data)
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID, GetConstByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID, GetConstByID)
end
|
--[[
SF Entity
{
Inputs
Outputs
context
player
}
]]
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
self:SetOverlayText("Starfall")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:OnRestore()
end
function ENT:Compile(code)
if self.context and not self.error then
SF_Compiler.RunInternalHook("deinit",self.context,false)
end
self.error = false
self.context = nil
local ok, context = SF_Compiler.Compile(code,self.player,self)
if not ok then
self:Error(context)
return
end
self.context = context
context.data.inputs = {}
context.data.outputs = {}
SF_Compiler.RunInternalHook("init",context)
SF_Compiler.RunInternalHook("preexec",self.context,nil)
local ok, msg = SF_Compiler.RunStarfallFunction(self.context, self.context.func)
SF_Compiler.RunInternalHook("postexec",self.context,nil)
if not ok then
self:Error(msg)
return
end
end
function ENT:SendCode(ply, code)
if ply ~= self.player then return end
self:Compile(code)
end
function ENT:Think()
self.BaseClass.Think(self)
self:NextThink(CurTime())
self:RunHook("Think")
return true
end
function ENT:Error(msg)
self.error = true
if self.context then
SF_Compiler.RunInternalHook("deinit",self.context,true,msg)
end
ErrorNoHalt(msg.." (from processor of "..self.player:Nick()..")\n")
WireLib.ClientError(msg, self.player)
end
function ENT:OnRemove()
if not self.error or not self.context then
SF_Compiler.RunInternalHook("deinit",self.context,false)
end
self.error = true
self.context = nil
end
function ENT:RunHook(name, ...)
if not self.context or self.error then return end
SF_Compiler.RunInternalHook("preexec",self.context,name)
local ok, msg = SF_Compiler.CallHook(name, self.context, ...)
SF_Compiler.RunInternalHook("postexec",self.context,name)
if ok == false then
self:Error(msg)
end
return msg
end
function ENT:TriggerInput(key, value)
SF_Compiler.RunInternalHook("WireInputChanged",self,key,value)
end
function ENT:ReadCell(address)
if self.error or not self.context then return 0 end
local ret = self:RunHook("ReadCell",address)
if type(ret) ~= "number" then
self:Error("Returned "..type(ret).." to hook ReadCell (expected number)")
return 0
end
return ret
end
function ENT:WriteCell(address, data)
self:RunHook("WriteCell",address,data)
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID, GetConstByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID, GetConstByID)
end
|
[SF] Quick fix for ReadCell. If the chip is errored, ReadCell returns 0.
|
[SF] Quick fix for ReadCell. If the chip is errored, ReadCell returns 0.
|
Lua
|
bsd-3-clause
|
Xandaros/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall
|
8260f71a583de82212a2b5c5a446d93eca40a679
|
docs/ntp/init-cool.lua
|
docs/ntp/init-cool.lua
|
uart.setup(1, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.write(1, "nodemcu loaded\n")
station_cfg = {}
station_cfg.ssid = "RON_G" -- SSID of your WiFi network
station_cfg.pwd = "xxxxxxxxxxxxxx" -- password of your WiFi network
station_cfg.auto = false
station_cfg.save = true
DHCP = 1
-- set your static network parameters here if DHCP == 0
net_ip = "10.10.10.110"
net_mask = "255.255.255.0"
net_gate = "10.10.10.1"
ntp_server = "pool.ntp.org"
uarttimestring = 0
rtcGood = 0
-- UTCTZ = 5 -- your timezone (unix TZ) offset
sync_att = 0
local function check_int(n)
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to use bitwise operation on non-integer!")
end
end
local function to_bits(n)
check_int(n)
if (n < 0) then
-- negative
return to_bits(bit.bnot(math.abs(n)) + 1)
end
-- to bits table
local tbl = {}
local cnt = 1
while (n > 0) do
local last = n % 2
if (last == 1) then
tbl[cnt] = 1
else
tbl[cnt] = 0
end
n = (n-last)/2
cnt = cnt + 1
end
return tbl
end
local function tbl_to_number(tbl)
local n = table.getn(tbl)
local rslt = 0
local power = 1
for i = 1, n do
rslt = rslt + tbl[i]*power
power = power*2
end
return rslt
end
local function expand(tbl_m, tbl_n)
local big = {}
local small = {}
if (table.getn(tbl_m) > table.getn(tbl_n)) then
big = tbl_m
small = tbl_n
else
big = tbl_n
small = tbl_m
end
-- expand small
for i = table.getn(small) + 1, table.getn(big) do
small[i] = 0
end
end
local function bit_xor(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
for i = 1, rslt do
if (tbl_m[i] ~= tbl_n[i]) then
tbl[i] = 1
else
tbl[i] = 0
end
end
--table.foreach(tbl, print)
return tbl_to_number(tbl)
end
local function to_hex(n)
if (type(n) ~= "number") then
error("non-number type passed in.")
end
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to apply bitwise operation on non-integer!")
end
if (n < 0) then
-- negative
n = bit.tobits(bit.bnot(math.abs(n)) + 1)
n = bit.tonumb(n)
end
hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'}
hex_str = ""
while (n ~= 0) do
last = n % 16
if (last < 10) then
hex_str = tostring(last) .. hex_str
else
hex_str = hex_tbl[last-10+1] .. hex_str
end
n = math.floor(n/16)
end
if (hex_str == "") then
hex_str = "0"
end
if (string.len(hex_str) < 2) then
return "0"..hex_str
else
return hex_str
end
end
function UpdateRtc()
local sec, usec = rtctime.get()
if (sec ~= 0) then
while (sec == rtctime.get()) do end
end
-- tm = rtctime.epoch2cal((rtctime.get()+1)+UTCTZ*3600)
tm = rtctime.epoch2cal(rtctime.get())
if (tm["year"] >= 2000) then
tm["year"] = tm["year"] - 2000;
else
tm["year"] = 0;
end
uarttimestring = string.format("$GPRMC,%02d%02d%02d.00,A,,,,,,,%02d%02d%02d,,,*",
tm["hour"], tm["min"], tm["sec"], tm["day"], tm["mon"], tm["year"]);
local crc = 0
for i=2,string.len(uarttimestring)-1 do
crc = bit_xor(crc, string.byte(uarttimestring,i));
end
uarttimestring = uarttimestring..to_hex(crc).."\r\n"
if (rtcGood == 1) then
print(uarttimestring)
else
print("ntp not synced")
end
end
function PrintUart()
print("ESP8266 wifi : " .. wifi.sta.getip())
UpdateRtc()
if (rtcGood == 1) then
uart.write(1, uarttimestring)
print("uart sync sent")
sync_att = sync_att + 1
if (sync_att >= 2) then
print("going to deep sleep mode")
for i=1,1000000 do end
rtctime.dsleep(1800000000); -- 1/2 hrs
end
end
end
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
if DHCP == 0 then
wifi.sta.setip({ip=net_ip,netmask=net_mask,gateway=net_gate})
end
function ntpSyncGood(sec, usec, server, info)
print('ntp synced', sec, usec, server)
offset_s = info.offset_s or 0
offset_us = info.offset_us or 0
delay_us = info.delay_us or 0
stratum = info.stratum or 0
leap = info.leap or 0
print("offset_s " .. offset_s)
print("offset_us " .. offset_us)
print("delay_us " .. delay_us )
print("stratum " .. stratum )
print("leap " .. leap)
rtcGood = 1
end
function ntpSyncFail()
print('failed!')
rtcGood = 0
end
function wifi_connected()
print("starting sync")
sntp.sync(ntp_server, ntpSyncGood, ntpSyncFail, 1 )
end
wifi.sta.connect(wifi_connected)
-- sync time / repeat after 1000 sec
uartTimer = tmr.create()
uartTimer:register(10000, tmr.ALARM_AUTO, PrintUart)
uartTimer:interval(10000) -- Maximum value is 6870947 (1:54:30.947).
uartTimer:start()
|
uart.setup(1, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.write(1, "nodemcu loaded\n")
station_cfg = {}
station_cfg.ssid = "RON_G" -- SSID of your WiFi network
station_cfg.pwd = "xxxxxxxxxxxxxx" -- password of your WiFi network
station_cfg.auto = false
station_cfg.save = true
DHCP = 1
-- set your static network parameters here if DHCP == 0
net_ip = "10.10.10.110"
net_mask = "255.255.255.0"
net_gate = "10.10.10.1"
ntp_server = "pool.ntp.org"
uarttimestring = 0
rtcGood = 0
-- UTCTZ = 5 -- your timezone (unix TZ) offset
sync_att = 0
local function check_int(n)
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to use bitwise operation on non-integer!")
end
end
local function to_bits(n)
check_int(n)
if (n < 0) then
-- negative
return to_bits(bit.bnot(math.abs(n)) + 1)
end
-- to bits table
local tbl = {}
local cnt = 1
while (n > 0) do
local last = n % 2
if (last == 1) then
tbl[cnt] = 1
else
tbl[cnt] = 0
end
n = (n-last)/2
cnt = cnt + 1
end
return tbl
end
local function tbl_to_number(tbl)
local n = table.getn(tbl)
local rslt = 0
local power = 1
for i = 1, n do
rslt = rslt + tbl[i]*power
power = power*2
end
return rslt
end
local function expand(tbl_m, tbl_n)
local big = {}
local small = {}
if (table.getn(tbl_m) > table.getn(tbl_n)) then
big = tbl_m
small = tbl_n
else
big = tbl_n
small = tbl_m
end
-- expand small
for i = table.getn(small) + 1, table.getn(big) do
small[i] = 0
end
end
local function bit_xor(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
for i = 1, rslt do
if (tbl_m[i] ~= tbl_n[i]) then
tbl[i] = 1
else
tbl[i] = 0
end
end
--table.foreach(tbl, print)
return tbl_to_number(tbl)
end
local function to_hex(n)
if (type(n) ~= "number") then
error("non-number type passed in.")
end
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to apply bitwise operation on non-integer!")
end
if (n < 0) then
-- negative
n = bit.tobits(bit.bnot(math.abs(n)) + 1)
n = bit.tonumb(n)
end
hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'}
hex_str = ""
while (n ~= 0) do
last = n % 16
if (last < 10) then
hex_str = tostring(last) .. hex_str
else
hex_str = hex_tbl[last-10+1] .. hex_str
end
n = math.floor(n/16)
end
if (hex_str == "") then
hex_str = "0"
end
if (string.len(hex_str) < 2) then
return "0"..hex_str
else
return hex_str
end
end
function UpdateRtc()
local sec, usec = rtctime.get()
if (sec ~= 0) then
while (sec == rtctime.get()) do end
end
-- tm = rtctime.epoch2cal((rtctime.get()+1)+UTCTZ*3600)
tm = rtctime.epoch2cal(rtctime.get())
if (tm["year"] >= 2000) then
tm["year"] = tm["year"] - 2000;
else
tm["year"] = 0;
end
uarttimestring = string.format("$GPRMC,%02d%02d%02d.00,A,,,,,,,%02d%02d%02d,,,*",
tm["hour"], tm["min"], tm["sec"], tm["day"], tm["mon"], tm["year"]);
local crc = 0
for i=2,string.len(uarttimestring)-1 do
crc = bit_xor(crc, string.byte(uarttimestring,i));
end
uarttimestring = uarttimestring..to_hex(crc).."\r\n"
if (rtcGood == 1) then
print(uarttimestring)
else
print("ntp not synced")
end
end
function PrintUart()
print("ESP8266 wifi : " .. wifi.sta.getip())
UpdateRtc()
if (rtcGood == 1) then
uart.write(1, uarttimestring)
print("uart sync sent")
sync_att = sync_att + 1
if (sync_att >= 2) then
print("going to deep sleep mode")
rtctime.dsleep(1800000000); -- 1/2 hrs
end
end
end
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
if DHCP == 0 then
wifi.sta.setip({ip=net_ip,netmask=net_mask,gateway=net_gate})
end
function ntpSyncGood(sec, usec, server, info)
print('ntp synced', sec, usec, server)
offset_s = info.offset_s or 0
offset_us = info.offset_us or 0
delay_us = info.delay_us or 0
stratum = info.stratum or 0
leap = info.leap or 0
print("offset_s " .. offset_s)
print("offset_us " .. offset_us)
print("delay_us " .. delay_us )
print("stratum " .. stratum )
print("leap " .. leap)
rtcGood = 1
end
function ntpSyncFail()
print('failed!')
rtcGood = 0
end
function wifi_connected()
print("starting sync")
sntp.sync(ntp_server, ntpSyncGood, ntpSyncFail, 1 )
end
wifi.sta.connect(wifi_connected)
-- sync time / repeat after 1000 sec
uartTimer = tmr.create()
uartTimer:register(10000, tmr.ALARM_AUTO, PrintUart)
uartTimer:interval(10000) -- Maximum value is 6870947 (1:54:30.947).
uartTimer:start()
|
ESP8266/NTP deep sleep script fix
|
ESP8266/NTP deep sleep script fix
|
Lua
|
mit
|
zerog2k/stc_diyclock,zerog2k/stc_diyclock,zerog2k/stc_diyclock
|
a865e486e646f72ad1f82fb8a8e7416f5d2cc420
|
spec/assertions_spec.lua
|
spec/assertions_spec.lua
|
describe("Test Assertions", function()
it("Checks to see if tables 1 and 2 are the same", function()
local table1 = { derp = false}
local table2 = { derp = false}
assert.same(table1, table2)
end)
it("Checks to see if tables 1 and 2 are equal", function()
local table1 = { derp = false}
local table2 = table1
assert.equals(table1, table2)
end)
it("Checks to see if table1 only contains unique elements", function()
local table2 = { derp = false}
local table3 = { derp = true }
local table1 = {table2,table3}
local tablenotunique = {table2,table2}
assert.is.unique(table1)
assert.is_not.unique(tablenotunique)
end)
it("Ensures the is operator doesn't change the behavior of equals", function()
assert.is.equals(true, true)
end)
it("Ensures the not operator does change the behavior of equals", function()
assert.is_not.equals(true, false)
end)
it("Ensures that error only throws an error when the first argument function does not throw an error", function()
local test_function = function() error("test") end
assert.has.error(test_function)
assert.has.error(test_function, "test")
assert.has_no.errors(test_function, "derp")
end)
it("Checks to see if var is truthy", function()
assert.is_not.truthy(nil)
assert.is.truthy(true)
assert.is.truthy({})
assert.is.truthy(function() end)
assert.is.truthy("")
assert.is_not.truthy(false)
assert.error(function() assert.truthy(false) end)
end)
it("Checks to see if var is falsy", function()
assert.is.falsy(nil)
assert.is_not.falsy(true)
assert.is_not.falsy({})
assert.is_not.falsy(function() end)
assert.is_not.falsy("")
assert.is.falsy(false)
end)
end)
|
describe("Test Assertions", function()
it("Checks to see if tables 1 and 2 are the same", function()
local table1 = { derp = false}
local table2 = { derp = false}
assert.same(table1, table2)
end)
it("Checks same() assertion to handle nils properly", function()
assert.same(nil, nil)
assert.is_not.same("a string", nil)
assert.is_not.same(nil, "a string")
end)
it("Checks to see if tables 1 and 2 are equal", function()
local table1 = { derp = false}
local table2 = table1
assert.equals(table1, table2)
end)
it("Checks equals() assertion to handle nils properly", function()
assert.equals(nil, nil)
assert.is_not.equals("a string", nil)
assert.is_not.equals(nil, "a string")
end)
it("Checks to see if table1 only contains unique elements", function()
local table2 = { derp = false}
local table3 = { derp = true }
local table1 = {table2,table3}
local tablenotunique = {table2,table2}
assert.is.unique(table1)
assert.is_not.unique(tablenotunique)
end)
it("Ensures the is operator doesn't change the behavior of equals", function()
assert.is.equals(true, true)
end)
it("Ensures the not operator does change the behavior of equals", function()
assert.is_not.equals(true, false)
end)
it("Ensures that error only throws an error when the first argument function does not throw an error", function()
local test_function = function() error("test") end
assert.has.error(test_function)
assert.has.error(test_function, "test")
assert.has_no.errors(test_function, "derp")
end)
it("Checks to see if var is truthy", function()
assert.is_not.truthy(nil)
assert.is.truthy(true)
assert.is.truthy({})
assert.is.truthy(function() end)
assert.is.truthy("")
assert.is_not.truthy(false)
assert.error(function() assert.truthy(false) end)
end)
it("Checks to see if var is falsy", function()
assert.is.falsy(nil)
assert.is_not.falsy(true)
assert.is_not.falsy({})
assert.is_not.falsy(function() end)
assert.is_not.falsy("")
assert.is.falsy(false)
end)
end)
|
Added test to highlight a bug in comparing nils in the equals() and same() assertions
|
Added test to highlight a bug in comparing nils in the equals() and same() assertions
|
Lua
|
mit
|
mpeterv/luassert,tst2005/lua-luassert,o-lim/luassert,ZyX-I/luassert
|
60b0095e56c44969f87cf308b3130068ce917103
|
lualib/sys/dns.lua
|
lualib/sys/dns.lua
|
local core = require "sys.core"
local socket = require "sys.socket"
local assert = assert
local sub = string.sub
local concat = table.concat
local pack = string.pack
local unpack = string.unpack
local format = string.format
local match = string.match
local gmatch = string.gmatch
local dns = {}
local A = 1
local CNAME = 5
local AAAA = 28
local name_cache = {}
local wait_coroutine = {}
local weakmt = {__mode = "kv"}
local session = 0
local dns_server
local connectfd
setmetatable(name_cache, weakmt)
local timenow = core.monotonicsec
--[[
ID:16
QR:1 0 -> request 1-> acknowledge
OPCODE:4 0 -> QUERY 1 -> IQUERY 2 -> STATUS
AA:1 authoriative Answer
TC:1 trun cation
RD:1 recursion desiered
RA:1 rescursion availavle
Z:3 0
RCODE:4 0 -> ok 1 -> FormatError 2 -> Server Failure 3 -> NameError
4 -> NotEmplemented 5 -> Refresued
QDCOUNT:16 quest descriptor count
ANCOUNT:16 anser RRs
NSCOUNT:16 authority RRs
ARCOUNT:16 Additional RRs
QNAME:z question name
QTYPE:16 0x01 -> IP... 0x05 -> CNAME
QCLASS:16 0x01 -> IN
]]--
local parseformat = ">I2I2I2I2I2I2zI2I2"
local headerformat = ">I2I2I2I2I2I2"
local function QNAME(name, n)
local i = #n
for k in gmatch(name, "([^%.]+)") do
i = i + 1
n[i] = pack(">I1", #k)
i = i + 1
n[i] = k
end
i = i + 1
n[i] = '\0'
end
local function question(name, typ)
if typ == "AAAA" then
typ = AAAA
else
typ = A
end
session = session + 1
local ID = session
--[[ FLAG
QR = 0,
OPCODE = 0, (4bit)
AA = 0,
TC = 0,
RD = 1,
RA = 0,
--3 bit zero
RCCODE = 0,
]]--
local FLAG = 0x0100
local QDCOUNT = 1
local ANCOUNT = 0
local NSCOUNT = 0
local ARCOUNT = 0
local QTYPE = typ
local QCLASS = 1
local dat = {
pack(headerformat,
ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT)
}
QNAME(name, dat)
dat[#dat + 1] = pack(">I2I2", QTYPE, QCLASS)
return ID, concat(dat)
end
local function readptr(init, dat, pos)
local n, pos = unpack(">I1", dat, pos)
if n >= 0xc0 then
n = n & 0x3f
local l, pos = unpack(">I1", dat, pos)
n = n << 8 | l
return readptr(init, dat, n + 1)
elseif n > 0 then
local nxt = pos + n
init[#init + 1] = sub(dat, pos, nxt - 1)
init[#init + 1] = "."
return readptr(init, dat, nxt)
else
return
end
end
local function readname(dat, i)
local tbl = {}
while true do --first
local n, j = unpack(">I1", dat, i)
if n >= 0xc0 then
readptr(tbl, dat, i)
i = i + 2
break
elseif n == 0 then
i = j
break
end
tbl[#tbl + 1] = sub(dat, j, i + n)
tbl[#tbl + 1] = "."
i = j + n
end
tbl[#tbl] = nil
return concat(tbl), i
end
local function answer(dat, pos, n)
for i = 1, n do
local src, pos = readname(dat, pos)
local qtype, qclass, ttl, rdlen, pos
= unpack(">I2I2I4I2", dat, pos)
if qtype == A then
local d1, d2, d3, d4 =
unpack(">I1I1I1I1", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "A",
A = format("%d.%d.%d.%d", d1, d2, d3, d4),
}
elseif qtype == CNAME then
local cname = readname(dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "CNAME",
CNAME = cname,
}
elseif qtype == AAAA then
local x1, x2, x3, x4, x5, x6, x7, x8 =
unpack(">I2I2I2I2I2I2I2I2", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "AAAA",
AAAA = format("%x:%x:%x:%x:%x%x:%x:%x",
x1, x2, x3, x4, x5, x6, x7, x8),
}
end
end
end
local function callback(msg, _)
local pos
if msg then
local ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT,
QNAME,
QTYPE, QCLASS, pos = unpack(parseformat, msg)
answer(msg, pos, ANCOUNT)
local co = wait_coroutine[ID]
if not co then --already timeout
return
end
wait_coroutine[ID] = nil
core.wakeup(co, ANCOUNT > 0)
else --udp closed
for k, co in pairs(wait_coroutine) do
core.wakeup(co, false)
wait_coroutine[k] = nil
end
connectfd = nil
end
end
local function suspend(session, timeout)
local co = core.running()
wait_coroutine[session] = co
core.fork(function()
core.sleep(timeout)
local co = wait_coroutine[session]
if not co then
return
end
wait_coroutine[session] = nil
core.wakeup(co, false)
end)
return core.wait(co)
end
local function connectserver()
if not dns_server then
local f = io.open("/etc/resolv.conf", "r")
for l in f:lines() do
dns_server = l:match("^%s*nameserver%s+([^%s]+)")
if dns_server then
if dns_server:find(':') then
dns_server = '[' .. dns_server .. ']'
end
dns_server = format("%s:53", dns_server)
break
end
end
end
assert(dns_server)
return socket.udp(dns_server, callback)
end
local function query(name, typ, timeout)
if not connectfd then
connectfd = connectserver()
end
assert(connectfd > 0)
local retry = 1
local s, r = question(name, typ)
--RFC 1123 #page-76, the default timeout
--should be less than 5 seconds
timeout = timeout or 5000
while true do
local ok = socket.udpwrite(connectfd, r)
if not ok then
return false
end
local ok = suspend(s, timeout)
if ok then
return ok
end
retry = retry + 1
if retry > 3 then
return false
end
core.sleep(timeout * retry)
end
end
local function lookup(name)
local d
local now = timenow()
for i = 1, 100 do
d = name_cache[name]
if not d then
return nil, name
end
if d.TTL < now then
name_cache[name] = nil
return nil, name
end
if d.TYPE == "CNAME" then
name = d.CNAME
else
return d
end
end
return nil, name
end
local function isname(name)
local right = name:match("([%x])", #name)
if right then
return false
end
return true
end
function dns.resolve(name, typ, timeout)
if not isname(name) then
return name
end
local d , cname = lookup(name)
if not d then
for i = 1, 100 do
local res = query(cname, typ, timeout)
if not res then
return
end
d, cname = lookup(cname)
if not cname then
goto FIND
end
end
return
end
::FIND::
if typ then
return d[typ], typ
else
return d.A or d.AAAA, d.TYPE
end
end
function dns.server(ip)
dns_server = ip
end
dns.isname = isname
return dns
|
local core = require "sys.core"
local socket = require "sys.socket"
local assert = assert
local sub = string.sub
local concat = table.concat
local pack = string.pack
local unpack = string.unpack
local format = string.format
local match = string.match
local gmatch = string.gmatch
local dns = {}
local A = 1
local CNAME = 5
local AAAA = 28
local name_cache = {}
local wait_coroutine = {}
local weakmt = {__mode = "kv"}
local session = 0
local dns_server
local connectfd
local timenow = core.monotonicsec
--[[
ID:16
QR:1 0 -> request 1-> acknowledge
OPCODE:4 0 -> QUERY 1 -> IQUERY 2 -> STATUS
AA:1 authoriative Answer
TC:1 trun cation
RD:1 recursion desiered
RA:1 rescursion availavle
Z:3 0
RCODE:4 0 -> ok 1 -> FormatError 2 -> Server Failure 3 -> NameError
4 -> NotEmplemented 5 -> Refresued
QDCOUNT:16 quest descriptor count
ANCOUNT:16 anser RRs
NSCOUNT:16 authority RRs
ARCOUNT:16 Additional RRs
QNAME:z question name
QTYPE:16 0x01 -> IP... 0x05 -> CNAME
QCLASS:16 0x01 -> IN
]]--
local parseformat = ">I2I2I2I2I2I2zI2I2"
local headerformat = ">I2I2I2I2I2I2"
local function QNAME(name, n)
local i = #n
for k in gmatch(name, "([^%.]+)") do
i = i + 1
n[i] = pack(">I1", #k)
i = i + 1
n[i] = k
end
i = i + 1
n[i] = '\0'
end
local function question(name, typ)
if typ == "AAAA" then
typ = AAAA
else
typ = A
end
session = session + 1
local ID = session
--[[ FLAG
QR = 0,
OPCODE = 0, (4bit)
AA = 0,
TC = 0,
RD = 1,
RA = 0,
--3 bit zero
RCCODE = 0,
]]--
local FLAG = 0x0100
local QDCOUNT = 1
local ANCOUNT = 0
local NSCOUNT = 0
local ARCOUNT = 0
local QTYPE = typ
local QCLASS = 1
local dat = {
pack(headerformat,
ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT)
}
QNAME(name, dat)
dat[#dat + 1] = pack(">I2I2", QTYPE, QCLASS)
return ID, concat(dat)
end
local function readptr(init, dat, pos)
local n, pos = unpack(">I1", dat, pos)
if n >= 0xc0 then
n = n & 0x3f
local l, pos = unpack(">I1", dat, pos)
n = n << 8 | l
return readptr(init, dat, n + 1)
elseif n > 0 then
local nxt = pos + n
init[#init + 1] = sub(dat, pos, nxt - 1)
init[#init + 1] = "."
return readptr(init, dat, nxt)
else
return
end
end
local function readname(dat, i)
local tbl = {}
while true do --first
local n, j = unpack(">I1", dat, i)
if n >= 0xc0 then
readptr(tbl, dat, i)
i = i + 2
break
elseif n == 0 then
i = j
break
end
tbl[#tbl + 1] = sub(dat, j, i + n)
tbl[#tbl + 1] = "."
i = j + n
end
tbl[#tbl] = nil
return concat(tbl), i
end
local function answer(dat, pos, n)
for i = 1, n do
local src, pos = readname(dat, pos)
local qtype, qclass, ttl, rdlen, pos
= unpack(">I2I2I4I2", dat, pos)
if qtype == A then
local d1, d2, d3, d4 =
unpack(">I1I1I1I1", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "A",
A = format("%d.%d.%d.%d", d1, d2, d3, d4),
}
elseif qtype == CNAME then
local cname = readname(dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "CNAME",
CNAME = cname,
}
elseif qtype == AAAA then
local x1, x2, x3, x4, x5, x6, x7, x8 =
unpack(">I2I2I2I2I2I2I2I2", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "AAAA",
AAAA = format("%x:%x:%x:%x:%x%x:%x:%x",
x1, x2, x3, x4, x5, x6, x7, x8),
}
end
end
end
local function callback(msg, _)
local pos
if msg then
local ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT,
QNAME,
QTYPE, QCLASS, pos = unpack(parseformat, msg)
answer(msg, pos, ANCOUNT)
local co = wait_coroutine[ID]
if not co then --already timeout
return
end
wait_coroutine[ID] = nil
core.wakeup(co, ANCOUNT > 0)
else --udp closed
for k, co in pairs(wait_coroutine) do
core.wakeup(co, false)
wait_coroutine[k] = nil
end
connectfd = nil
end
end
local function suspend(session, timeout)
local co = core.running()
wait_coroutine[session] = co
core.fork(function()
core.sleep(timeout)
local co = wait_coroutine[session]
if not co then
return
end
wait_coroutine[session] = nil
core.wakeup(co, false)
end)
return core.wait(co)
end
local function connectserver()
if not dns_server then
local f = io.open("/etc/resolv.conf", "r")
for l in f:lines() do
dns_server = l:match("^%s*nameserver%s+([^%s]+)")
if dns_server then
if dns_server:find(':') then
dns_server = '[' .. dns_server .. ']'
end
dns_server = format("%s:53", dns_server)
break
end
end
end
assert(dns_server)
return socket.udp(dns_server, callback)
end
local function query(name, typ, timeout)
if not connectfd then
connectfd = connectserver()
end
assert(connectfd > 0)
local retry = 1
local s, r = question(name, typ)
--RFC 1123 #page-76, the default timeout
--should be less than 5 seconds
timeout = timeout or 5000
while true do
local ok = socket.udpwrite(connectfd, r)
if not ok then
return false
end
local ok = suspend(s, timeout)
if ok then
return ok
end
retry = retry + 1
if retry > 3 then
return false
end
core.sleep(timeout * retry)
end
end
local function lookup(name)
local d
local now = timenow()
for i = 1, 100 do
d = name_cache[name]
if not d then
return nil, name
end
if d.TTL < now then
name_cache[name] = nil
return nil, name
end
if d.TYPE == "CNAME" then
name = d.CNAME
else
return d
end
end
return nil, name
end
local function isname(name)
local right = name:match("([%x])", #name)
if right then
return false
end
return true
end
function dns.resolve(name, typ, timeout)
if not isname(name) then
return name
end
local d , cname = lookup(name)
if not d then
for i = 1, 100 do
local res = query(cname, typ, timeout)
if not res then
return
end
d, cname = lookup(cname)
if not cname then
goto FIND
end
end
return
end
::FIND::
if typ then
return d[typ], typ
else
return d.A or d.AAAA, d.TYPE
end
end
function dns.server(ip)
dns_server = ip
end
dns.isname = isname
return dns
|
dns fix incorrect weaktable
|
dns fix incorrect weaktable
|
Lua
|
mit
|
findstr/silly
|
043311e654999c6eeff6ad3dbdc074acbfd4c50a
|
lualib/mqueue.lua
|
lualib/mqueue.lua
|
local skynet = require "skynet"
local c = require "skynet.c"
local mqueue = {}
local init_once
local thread_id
local message_queue = {}
skynet.register_protocol {
name = "queue",
-- please read skynet.h for magic number 8
id = 8,
pack = skynet.pack,
unpack = skynet.unpack,
dispatch = function(session, from, ...)
table.insert(message_queue, {session = session, addr = from, ... })
if thread_id then
skynet.wakeup(thread_id)
thread_id = nil
end
end
}
local function do_func(f, msg)
return pcall(f, table.unpack(msg))
end
local function message_dispatch(f)
while true do
if #message_queue==0 then
thread_id = coroutine.running()
skynet.wait()
else
local msg = table.remove(message_queue,1)
local session = msg.session
if session == 0 then
local ok, msg = do_func(f, msg)
if ok then
if msg then
skynet.fork(message_dispatch,f)
error(string.format("[:%x] send a message to [:%x] return something", msg.addr, skynet.self()))
end
else
error(string.format("[:%x] send a message to [:%x] throw an error : %s", msg.addr, skynet.self(),msg))
end
else
local data, size = skynet.pack(do_func(f,msg))
-- 1 means response
c.send(msg.addr, 1, session, data, size)
end
end
end
end
function mqueue.register(f)
assert(init_once == nil)
init_once = true
skynet.fork(message_dispatch,f)
end
local function catch(succ, ...)
if succ then
return ...
else
error(...)
end
end
function mqueue.call(addr, ...)
return catch(skynet.call(addr, "queue", ...))
end
function mqueue.send(addr, ...)
return skynet.send(addr, "queue", ...)
end
function mqueue.size()
return #message_queue
end
return mqueue
|
local skynet = require "skynet"
local c = require "skynet.c"
local mqueue = {}
local init_once
local thread_id
local message_queue = {}
skynet.register_protocol {
name = "queue",
-- please read skynet.h for magic number 8
id = 8,
pack = skynet.pack,
unpack = skynet.unpack,
dispatch = function(session, from, ...)
table.insert(message_queue, {session = session, addr = from, ... })
if thread_id then
skynet.wakeup(thread_id)
thread_id = nil
end
end
}
local function do_func(f, msg)
return pcall(f, table.unpack(msg))
end
local function message_dispatch(f)
while true do
if #message_queue==0 then
thread_id = coroutine.running()
skynet.wait()
else
local msg = table.remove(message_queue,1)
local session = msg.session
if session == 0 then
local ok, msg = do_func(f, msg)
if ok then
if msg then
skynet.fork(message_dispatch,f)
error(string.format("[:%x] send a message to [:%x] return something", msg.addr, skynet.self()))
end
else
skynet.fork(message_dispatch,f)
error(string.format("[:%x] send a message to [:%x] throw an error : %s", msg.addr, skynet.self(),msg))
end
else
local data, size = skynet.pack(do_func(f,msg))
-- 1 means response
c.send(msg.addr, 1, session, data, size)
end
end
end
end
function mqueue.register(f)
assert(init_once == nil)
init_once = true
skynet.fork(message_dispatch,f)
end
local function catch(succ, ...)
if succ then
return ...
else
error(...)
end
end
function mqueue.call(addr, ...)
return catch(skynet.call(addr, "queue", ...))
end
function mqueue.send(addr, ...)
return skynet.send(addr, "queue", ...)
end
function mqueue.size()
return #message_queue
end
return mqueue
|
bugfix: fork a new thread when message dispatch error
|
bugfix: fork a new thread when message dispatch error
|
Lua
|
mit
|
zhaijialong/skynet,enulex/skynet,jiuaiwo1314/skynet,codingabc/skynet,ilylia/skynet,xinjuncoding/skynet,Zirpon/skynet,asanosoyokaze/skynet,xjdrew/skynet,longmian/skynet,JiessieDawn/skynet,microcai/skynet,cuit-zhaxin/skynet,your-gatsby/skynet,Zirpon/skynet,microcai/skynet,lawnight/skynet,plsytj/skynet,great90/skynet,yunGit/skynet,czlc/skynet,bttscut/skynet,lynx-seu/skynet,harryzeng/skynet,JiessieDawn/skynet,zhoukk/skynet,liuxuezhan/skynet,felixdae/skynet,ypengju/skynet_comment,lc412/skynet,wangyi0226/skynet,bingo235/skynet,yinjun322/skynet,ruleless/skynet,togolwb/skynet,togolwb/skynet,kebo/skynet,LuffyPan/skynet,chenjiansnail/skynet,yinjun322/skynet,wangjunwei01/skynet,icetoggle/skynet,leezhongshan/skynet,Zirpon/skynet,great90/skynet,matinJ/skynet,fhaoquan/skynet,MetSystem/skynet,KAndQ/skynet,javachengwc/skynet,boyuegame/skynet,gitfancode/skynet,Ding8222/skynet,catinred2/skynet,xinmingyao/skynet,codingabc/skynet,zhangshiqian1214/skynet,yunGit/skynet,xjdrew/skynet,boyuegame/skynet,chuenlungwang/skynet,cmingjian/skynet,rainfiel/skynet,helling34/skynet,lynx-seu/skynet,cmingjian/skynet,LuffyPan/skynet,harryzeng/skynet,chenjiansnail/skynet,firedtoad/skynet,liuxuezhan/skynet,bttscut/skynet,LuffyPan/skynet,javachengwc/skynet,helling34/skynet,puXiaoyi/skynet,ludi1991/skynet,felixdae/skynet,wangyi0226/skynet,nightcj/mmo,wangyi0226/skynet,sundream/skynet,wangjunwei01/skynet,MetSystem/skynet,yinjun322/skynet,korialuo/skynet,ludi1991/skynet,bttscut/skynet,codingabc/skynet,zhoukk/skynet,MoZhonghua/skynet,samael65535/skynet,KAndQ/skynet,cdd990/skynet,ludi1991/skynet,zhangshiqian1214/skynet,chuenlungwang/skynet,letmefly/skynet,kebo/skynet,u20024804/skynet,cuit-zhaxin/skynet,LiangMa/skynet,KittyCookie/skynet,lynx-seu/skynet,QuiQiJingFeng/skynet,LiangMa/skynet,javachengwc/skynet,fztcjjl/skynet,zhaijialong/skynet,u20024804/skynet,yunGit/skynet,zzh442856860/skynet,bingo235/skynet,zzh442856860/skynet-Note,longmian/skynet,asanosoyokaze/skynet,ludi1991/skynet,Ding8222/skynet,xinmingyao/skynet,sdgdsffdsfff/skynet,pichina/skynet,helling34/skynet,sanikoyes/skynet,longmian/skynet,bingo235/skynet,winglsh/skynet,qyli/test,togolwb/skynet,lawnight/skynet,letmefly/skynet,firedtoad/skynet,ilylia/skynet,zzh442856860/skynet,zzh442856860/skynet-Note,MetSystem/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,korialuo/skynet,your-gatsby/skynet,peimin/skynet,zhaijialong/skynet,lawnight/skynet,pigparadise/skynet,enulex/skynet,hongling0/skynet,vizewang/skynet,catinred2/skynet,QuiQiJingFeng/skynet,sdgdsffdsfff/skynet,MRunFoss/skynet,lawnight/skynet,catinred2/skynet,MRunFoss/skynet,zhouxiaoxiaoxujian/skynet,dymx101/skynet,vizewang/skynet,cpascal/skynet,dymx101/skynet,hongling0/skynet,peimin/skynet,zhoukk/skynet,Markal128/skynet,ypengju/skynet_comment,cuit-zhaxin/skynet,cloudwu/skynet,wangjunwei01/skynet,iskygame/skynet,fhaoquan/skynet,MRunFoss/skynet,icetoggle/skynet,iskygame/skynet,fztcjjl/skynet,KAndQ/skynet,jxlczjp77/skynet,cdd990/skynet,czlc/skynet,microcai/skynet,gitfancode/skynet,puXiaoyi/skynet,MoZhonghua/skynet,qyli/test,your-gatsby/skynet,leezhongshan/skynet,iskygame/skynet,harryzeng/skynet,chenjiansnail/skynet,leezhongshan/skynet,cloudwu/skynet,bigrpg/skynet,zhangshiqian1214/skynet,KittyCookie/skynet,QuiQiJingFeng/skynet,winglsh/skynet,sundream/skynet,xubigshu/skynet,pichina/skynet,cpascal/skynet,pichina/skynet,rainfiel/skynet,qyli/test,MoZhonghua/skynet,zhouxiaoxiaoxujian/skynet,rainfiel/skynet,korialuo/skynet,cmingjian/skynet,fztcjjl/skynet,jiuaiwo1314/skynet,chfg007/skynet,matinJ/skynet,xinjuncoding/skynet,plsytj/skynet,jxlczjp77/skynet,sundream/skynet,ag6ag/skynet,xcjmine/skynet,zhouxiaoxiaoxujian/skynet,samael65535/skynet,ilylia/skynet,enulex/skynet,plsytj/skynet,nightcj/mmo,felixdae/skynet,winglsh/skynet,samael65535/skynet,cloudwu/skynet,jiuaiwo1314/skynet,peimin/skynet_v0.1_with_notes,xinjuncoding/skynet,xjdrew/skynet,gitfancode/skynet,ag6ag/skynet,liuxuezhan/skynet,chuenlungwang/skynet,matinJ/skynet,xcjmine/skynet,ruleless/skynet,dymx101/skynet,zhangshiqian1214/skynet,zzh442856860/skynet-Note,sdgdsffdsfff/skynet,Markal128/skynet,kyle-wang/skynet,kyle-wang/skynet,letmefly/skynet,pigparadise/skynet,lc412/skynet,sanikoyes/skynet,u20024804/skynet,vizewang/skynet,ypengju/skynet_comment,sanikoyes/skynet,jxlczjp77/skynet,LiangMa/skynet,bigrpg/skynet,ruleless/skynet,chfg007/skynet,qyli/test,xubigshu/skynet,zzh442856860/skynet-Note,lc412/skynet,czlc/skynet,great90/skynet,xcjmine/skynet,KittyCookie/skynet,letmefly/skynet,zzh442856860/skynet,nightcj/mmo,fhaoquan/skynet,hongling0/skynet,pigparadise/skynet,Ding8222/skynet,boyuegame/skynet,asanosoyokaze/skynet,kyle-wang/skynet,chfg007/skynet,cpascal/skynet,liuxuezhan/skynet,cdd990/skynet,JiessieDawn/skynet,ag6ag/skynet,Markal128/skynet,bigrpg/skynet,peimin/skynet_v0.1_with_notes,kebo/skynet,icetoggle/skynet,firedtoad/skynet,puXiaoyi/skynet
|
bb7e2ae7dc0166ad6ab7fc04da5ea5756fa93d96
|
GuemUICastingBarFrame.lua
|
GuemUICastingBarFrame.lua
|
local AddonName, AddonTable = ...
local LSM = LibStub("LibSharedMedia-3.0")
_G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName)
local Addon = _G[AddonName]
local assert = assert
local type = type
local getmetatable = getmetatable
local CreateFrame = CreateFrame
local UIParent = UIParent
function Addon:CreateClass(Class, Name, Parent)
Name = Name or nil
Parent = Parent or UIParent
local obj = CreateFrame(Class, Name, Parent)
local base = getmetatable(obj).__index
obj.callbacks = {}
--Wrapping RegisterUnitEvent method
function obj:RegisterUnitEvent(event, unit, callback)
assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback")
self.callbacks[event] = callback
base.RegisterUnitEvent(self, event, unit)
end
--Wrapping UnregisterAllEvent method
function obj:UnregisterAllEvents()
self.callbacks = {}
base.UnregisterAllEvents()
end
--Wrapping UnregisterEvent method
function obj:UnregisterEvent(event)
assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)")
self.callbacks[event] = nil
base.UnregisterEvent(self, event)
end
--SetScript will call self.callbacks[event] on "OnEvent" fired
obj:SetScript("OnEvent", function(self, event, ...)
self.callbacks[event](self, event, ...)
end)
return obj
end
function Addon:CreateCastingBarFrame(Unit)
local f = self:CreateClass("StatusBar")
f:Hide()
f:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid")
f:SetStatusBarColor(0, 0.7, 1.0)
f:SetSize(220, 24)
f:SetPoint("BOTTOM", 0, 170)
f:SetFillStyle("STANDARD")
f:SetMinMaxValues(0.0, 1.0)
local t = f:CreateTexture()
t:SetColorTexture(0, 0, 0)
t:SetAllPoints(f)
f.fadein = f:CreateAnimationGroup()
f.fadein:SetLooping("NONE")
local alpha = f.fadein:CreateAnimation("Alpha")
alpha:SetDuration(0.2)
alpha:SetFromAlpha(0.0)
alpha:SetToAlpha(1.0)
f.fadeout = f:CreateAnimationGroup()
f.fadeout:SetLooping("NONE")
local alpha = f.fadeout:CreateAnimation("Alpha")
alpha:SetDuration(0.5)
alpha:SetFromAlpha(1.0)
alpha:SetToAlpha(0.0)
f:RegisterUnitEvent("UNIT_SPELLCAST_START", "player", function(self, event, unit, name, ...)
self:Show()
self.fadeout:Stop()
self.fadein:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", "player", function(self, event, unit, name, ...)
self.fadeout:Play()
end)
f.fadeout:SetScript("OnFinished", function(self, ...)
f:Hide()
end)
f:SetScript('OnUpdate', function(self, rate)
local _, _, _, _, startTime, endTime = UnitCastingInfo("player")
if startTime and endTime then
f:SetValue((GetTime()*1000 - startTime) / (endTime-startTime))
end
end)
return f
end
|
local AddonName, AddonTable = ...
local LSM = LibStub("LibSharedMedia-3.0")
_G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName)
local Addon = _G[AddonName]
local assert = assert
local type = type
local getmetatable = getmetatable
local CreateFrame = CreateFrame
local UIParent = UIParent
function Addon:CreateClass(Class, Name, Parent)
Name = Name or nil
Parent = Parent or UIParent
local obj = CreateFrame(Class, Name, Parent)
local base = getmetatable(obj).__index
obj.callbacks = {}
--Wrapping RegisterUnitEvent method
function obj:RegisterUnitEvent(event, unit, callback)
assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback")
self.callbacks[event] = callback
base.RegisterUnitEvent(self, event, unit)
end
--Wrapping UnregisterAllEvent method
function obj:UnregisterAllEvents()
self.callbacks = {}
base.UnregisterAllEvents()
end
--Wrapping UnregisterEvent method
function obj:UnregisterEvent(event)
assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)")
self.callbacks[event] = nil
base.UnregisterEvent(self, event)
end
--SetScript will call self.callbacks[event] on "OnEvent" fired
obj:SetScript("OnEvent", function(self, event, ...)
self.callbacks[event](self, event, ...)
end)
return obj
end
function Addon:CreateCastingBarFrame(Unit)
assert(type(Unit) == "string", "Usage : CreateCastingBarFrame(string Unit)")
local f = self:CreateClass("Frame", AddonName..Unit)
local s = self:CreateClass("StatusBar", nil, f)
f:Hide()
f:SetSize(220, 24)
f:SetPoint("BOTTOM", 0, 170)
local t = f:CreateTexture()
t:SetColorTexture(0, 0, 0)
t:SetAllPoints(f)
s:SetAllPoints(f)
s:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid")
s:SetStatusBarColor(0, 0.7, 1.0)
s:SetFillStyle("STANDARD")
s:SetMinMaxValues(0.0, 1.0)
f.fadein = f:CreateAnimationGroup()
f.fadein:SetLooping("NONE")
local alpha = f.fadein:CreateAnimation("Alpha")
alpha:SetDuration(0.2)
alpha:SetFromAlpha(0.0)
alpha:SetToAlpha(1.0)
f.fadeout = f:CreateAnimationGroup()
f.fadeout:SetLooping("NONE")
local alpha = f.fadeout:CreateAnimation("Alpha")
alpha:SetDuration(0.5)
alpha:SetFromAlpha(1.0)
alpha:SetToAlpha(0.0)
f:RegisterUnitEvent("UNIT_SPELLCAST_START", "player", function(self, event, unit, name, ...)
self:Show()
self.fadeout:Stop()
self.fadein:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", "player", function(self, event, unit, name, ...)
self.fadeout:Play()
end)
f.fadeout:SetScript("OnFinished", function(self, ...)
f:Hide()
end)
f:SetScript('OnUpdate', function(self, rate)
local _, _, _, _, startTime, endTime = UnitCastingInfo("player")
if startTime and endTime then
s:SetValue((GetTime()*1000 - startTime) / (endTime-startTime))
end
end)
return f
end
|
fixed a bug making castbar randomly not show correctly
|
fixed a bug making castbar randomly not show correctly
|
Lua
|
unlicense
|
Guema/gCastBars,Guema/GuemUICastBars
|
f1d1551f39ee459f288d137eccea26eef19c7a75
|
src/gui/ButtonAnimations.lua
|
src/gui/ButtonAnimations.lua
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local PropertyUtils = require("util.PropertyUtils")
local UIEvent = require("gui.UIEvent")
local ButtonAnimations = {}
local AnimationBase = class()
---
--
--
function AnimationBase:init(params)
if params then
PropertyUtils.setProperties(self, params, false)
end
end
function AnimationBase:setButton(button)
if self.button then
self:removeButton(button)
end
if not button then return end
local addEventListener = function(event, callback)
if self[callback] then
button:addEventListener(event, self[callback], self)
end
end
self.button = button
addEventListener ( UIEvent.DOWN, "downAnimation" )
addEventListener ( UIEvent.UP, "upAnimation" )
addEventListener ( UIEvent.CANCEL, "cancelAnimation" )
addEventListener ( UIEvent.CLICK, "clickAnimation" )
addEventListener ( UIEvent.ENABLE, "enabledAnimation" )
addEventListener ( UIEvent.DISABLE, "disabledAnimation" )
end
function AnimationBase:removeButton(button)
if not self.button then return end
button:removeEventListener ( UIEvent.DOWN, "downAnimation", self )
button:removeEventListener ( UIEvent.UP, "upAnimation", self )
button:removeEventListener ( UIEvent.CANCEL, "cancelAnimation", self )
button:removeEventListener ( UIEvent.CLICK, "clickAnimation", self )
button:removeEventListener ( UIEvent.ENABLE, "enabledAnimation", self )
button:removeEventListener ( UIEvent.DISABLE, "disabledAnimation", self )
self.button = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Change = class(AnimationBase)
local Color = class(AnimationBase)
local Scale = class(AnimationBase)
local ToggleFlip = class(AnimationBase)
---
-- Toggle between normal, active and disabled images
--
function Change:downAnimation(event)
local button = event.target
if button.activeSprite then
button.activeSprite:setVisible(true)
button.normalSprite:setVisible(false)
if button.disabledSprite then
button.disabledSprite:setVisible(false)
end
end
end
function Change:upAnimation(event)
local button = event.target
local showSprite = button.enabled and button.normalSprite or button.disabledSprite
local hideSprite = button.enabled and button.disabledSprite or button.normalSprite
if showSprite then
showSprite:setVisible(true)
end
if button.activeSprite then
button.activeSprite:setVisible(false)
end
if hideSprite then
hideSprite:setVisible(false)
end
end
function Change:disabledAnimation(event)
local button = event.target
if button.disabledSprite then
button.disabledSprite:setVisible(true)
button.normalSprite:setVisible(false)
if button.activeSprite then
button.activeSprite:setVisible(false)
end
end
end
function Change:enabledAnimation(event)
self:upAnimation(event)
end
function Change:cancelAnimation(event)
self:upAnimation(event)
end
---
-- Scale animation
--
-- Scale {
-- duration = 0.5,
-- activeEaseType = MOAIEaseType.BOUNCE_IN,
-- normalEaseType = MOAIEaseType.BOUNCE_OUT,
-- activeScale = 1.2,
-- normalDuration = 0.2,
-- }
Scale.defaultActiveScale = 1.2
Scale.defaultNormalScale = 1
Scale.defaultDuration = 0.3
function Scale:downAnimation(event)
local target = event.target
if self.upAction then
self.upAction:stop()
self.upAction = nil
target:setScl(self.normalScale or self.defaultNormalScale)
end
local scl = self.activeScale or self.defaultActiveScale
local dur = self.activeDuration or self.duration or self.defaultDuration
self.downAction = target:seekScl(scl, scl, 1, dur, self.activeEaseType or self.easeType)
end
function Scale:upAnimation(event)
local target = event.target
if self.downAction then
self.downAction:stop()
self.downAction = nil
target:setScl(self.activeScale or self.defaultActiveScale)
end
local scl = self.normalScale or self.defaultNormalScale
local dur = self.normalDuration or self.duration or self.defaultDuration
self.upAction = target:seekScl(scl, scl, 1, dur, self.normalEaseType or self.easeType)
end
function Scale:cancelAnimation(event)
self:upAnimation(event)
end
---
-- Color animation
--
-- Color.normalSpriteColor = {1, 1, 1, 1}
-- Color.activeSpriteColor = {1, 1, 1, 1}
-- Color.disabledSpriteColor = {1, 1, 1, 1}
-- Color.normalTextColor = {0, 0, 0, 1}
-- Color.activeTextColor = {0, 0, 0, 1}
-- Color.disabledTextColor = {0, 0, 0, 1}
function Color:downAnimation(event)
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
ButtonAnimations.Change = Change
ButtonAnimations.Bounce = Bounce
ButtonAnimations.Scale = Scale
return ButtonAnimations
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local PropertyUtils = require("util.PropertyUtils")
local UIEvent = require("gui.UIEvent")
local ButtonAnimations = {}
local AnimationBase = class()
---
--
--
function AnimationBase:init(params)
if params then
PropertyUtils.setProperties(self, params, false)
end
end
function AnimationBase:setButton(button)
if self.button then
self:removeButton(button)
end
if not button then return end
local addEventListener = function(event, callback)
if self[callback] then
button:addEventListener(event, self[callback], self)
end
end
self.button = button
addEventListener ( UIEvent.DOWN, "downAnimation" )
addEventListener ( UIEvent.UP, "upAnimation" )
addEventListener ( UIEvent.CANCEL, "cancelAnimation" )
addEventListener ( UIEvent.CLICK, "clickAnimation" )
addEventListener ( UIEvent.ENABLE, "enabledAnimation" )
addEventListener ( UIEvent.DISABLE, "disabledAnimation" )
end
function AnimationBase:removeButton(button)
if not self.button then return end
button:removeEventListener ( UIEvent.DOWN, "downAnimation", self )
button:removeEventListener ( UIEvent.UP, "upAnimation", self )
button:removeEventListener ( UIEvent.CANCEL, "cancelAnimation", self )
button:removeEventListener ( UIEvent.CLICK, "clickAnimation", self )
button:removeEventListener ( UIEvent.ENABLE, "enabledAnimation", self )
button:removeEventListener ( UIEvent.DISABLE, "disabledAnimation", self )
self.button = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Change = class(AnimationBase)
local Color = class(AnimationBase)
local Scale = class(AnimationBase)
local ToggleFlip = class(AnimationBase)
---
-- Toggle between normal, active and disabled images
--
function Change:downAnimation(event)
local button = event.target
if button.activeSprite then
button.activeSprite:setVisible(true)
button.normalSprite:setVisible(false)
if button.disabledSprite then
button.disabledSprite:setVisible(false)
end
end
end
function Change:upAnimation(event)
local button = event.target
local showSprite, hideSprite
if button.enabled then
showSprite = button.normalSprite
hideSprite = button.disabledSprite
else
showSprite = button.disabledSprite
hideSprite = button.normalSprite
end
if showSprite then
showSprite:setVisible(true)
end
if button.activeSprite then
button.activeSprite:setVisible(false)
end
if hideSprite then
hideSprite:setVisible(false)
end
end
function Change:disabledAnimation(event)
local button = event.target
if button.disabledSprite then
button.disabledSprite:setVisible(true)
button.normalSprite:setVisible(false)
if button.activeSprite then
button.activeSprite:setVisible(false)
end
end
end
function Change:enabledAnimation(event)
self:upAnimation(event)
end
function Change:cancelAnimation(event)
self:upAnimation(event)
end
---
-- Scale animation
--
-- Scale {
-- duration = 0.5,
-- activeEaseType = MOAIEaseType.BOUNCE_IN,
-- normalEaseType = MOAIEaseType.BOUNCE_OUT,
-- activeScale = 1.2,
-- normalDuration = 0.2,
-- }
Scale.defaultActiveScale = 1.2
Scale.defaultNormalScale = 1
Scale.defaultDuration = 0.3
function Scale:downAnimation(event)
local target = event.target
if self.upAction then
self.upAction:stop()
self.upAction = nil
target:setScl(self.normalScale or self.defaultNormalScale)
end
local scl = self.activeScale or self.defaultActiveScale
local dur = self.activeDuration or self.duration or self.defaultDuration
self.downAction = target:seekScl(scl, scl, 1, dur, self.activeEaseType or self.easeType)
end
function Scale:upAnimation(event)
local target = event.target
if self.downAction then
self.downAction:stop()
self.downAction = nil
target:setScl(self.activeScale or self.defaultActiveScale)
end
local scl = self.normalScale or self.defaultNormalScale
local dur = self.normalDuration or self.duration or self.defaultDuration
self.upAction = target:seekScl(scl, scl, 1, dur, self.normalEaseType or self.easeType)
end
function Scale:cancelAnimation(event)
self:upAnimation(event)
end
---
-- Color animation
--
-- Color.normalSpriteColor = {1, 1, 1, 1}
-- Color.activeSpriteColor = {1, 1, 1, 1}
-- Color.disabledSpriteColor = {1, 1, 1, 1}
-- Color.normalTextColor = {0, 0, 0, 1}
-- Color.activeTextColor = {0, 0, 0, 1}
-- Color.disabledTextColor = {0, 0, 0, 1}
function Color:downAnimation(event)
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
ButtonAnimations.Change = Change
ButtonAnimations.Bounce = Bounce
ButtonAnimations.Scale = Scale
return ButtonAnimations
|
fix toggle button animation 2
|
fix toggle button animation 2
|
Lua
|
mit
|
Vavius/moai-framework,Vavius/moai-framework
|
26f6dd6fef1d0dbfa8207a1214894812f351dc57
|
pkg/torch/argtypes.lua
|
pkg/torch/argtypes.lua
|
torch.argtypes = {}
torch.argtypes["numbers"] = {
vararg = true,
check = function(self)
local idx = self.luaname:match('select%((%d+), %.%.%.%)')
if idx then -- ordered arguments
return string.format([[
(function(...)
%s = {}
for i=%d,narg do
local z = select(i, ...)
if type() ~= 'number' then
%s = nil
return false
end
table.insert(%s, z)
end
return true
end)() ]], self.name, idx, self.name, self.name)
else -- named arguments
return string.format(
[[
(function(...)
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
return false
end
end
return true
end)() ]], self.luaname)
end
end,
read = function(self)
end
}
torch.argtypes["number"] = {
check = function(self)
return string.format("type(%s) == 'number'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["boolean"] = {
check = function(self)
return string.format("type(%s) == 'boolean'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["string"] = {
check = function(self)
assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name))
return string.format("type(%s) == 'string'", self.luaname)
end,
initdefault = function(self)
return string.format('"%s"', self.default)
end
}
for _,Tensor in ipairs{'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.LongTensor',
'torch.FloatTensor',
'torch.DoubleTensor'} do
torch.argtypes[Tensor] = {
check = function(self)
if self.dim then
return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim)
else
return string.format("type(%s) == '" .. Tensor .. "'", self.luaname)
end
end,
initdefault = function(self)
return Tensor .. "()"
end
}
end
|
torch.argtypes = {}
torch.argtypes["numbers"] = {
vararg = true, -- if needed, one can override it to false
check = function(self)
local idx = self.luaname:match('select%((%d+), %.%.%.%)')
if idx then -- ordered arguments
if self.vararg then -- can be (1, 2, 3) or {1, 2, 3}
return string.format([[
(function(...)
if %d == narg and type(select(%d, ...)) == 'table' then
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
else
%s = {}
for i=%d,narg do
local z = select(i, ...)
if type(z) ~= 'number' then
%s = nil
return false
end
table.insert(%s, z)
end
end
return true
end)(...) ]], idx, idx, self.name, idx, self.name, self.name, self.name, self.name, self.name, idx, self.name, self.name)
else -- can only be {1, 2, 3}
return string.format([[
(function(...)
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
return true
end)(...) ]], self.name, idx, self.name, self.name, self.name, self.name)
end
else -- named arguments
return string.format(
[[
(function(...)
if not %s then
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
return false
end
end
return true
end)(...) ]], self.luaname, self.luaname)
end
end,
read = function(self)
end
}
torch.argtypes["number"] = {
check = function(self)
return string.format("type(%s) == 'number'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["boolean"] = {
check = function(self)
return string.format("type(%s) == 'boolean'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["string"] = {
check = function(self)
assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name))
return string.format("type(%s) == 'string'", self.luaname)
end,
initdefault = function(self)
return string.format('"%s"', self.default)
end
}
for _,Tensor in ipairs{'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.LongTensor',
'torch.FloatTensor',
'torch.DoubleTensor'} do
torch.argtypes[Tensor] = {
check = function(self)
if self.dim then
return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim)
else
return string.format("type(%s) == '" .. Tensor .. "'", self.luaname)
end
end,
initdefault = function(self)
return Tensor .. "()"
end
}
end
|
argtypes: fixed and added functionalities for the "type" "numbers"
|
argtypes: fixed and added functionalities for the "type" "numbers"
|
Lua
|
bsd-3-clause
|
torch/argcheck
|
006b14b7558ff469daa3ff5e260efe606805ddf0
|
tests/sample/security-rules.lua
|
tests/sample/security-rules.lua
|
------------------------------------
-- Loading disscetors
------------------------------------
require("ipv4")
require("tcp")
require("http")
------------------------------------
-- Function definition
------------------------------------
local function getpayload(data)
payload = ''
for i = 1, #data do
payload = payload .. string.char(data[i])
end
return payload
end
local function contains(table, elem)
return table[elem] ~= nil
end
local function dict(table)
local ret = {}
for _, v in pairs(table) do
ret[v] = true
end
return ret
end
------------------------------------
-- IP compliance
------------------------------------
haka.rule {
hooks = { "ipv4-up" },
eval = function (self, pkt)
-- bad IP checksum
if not pkt:verify_checksum() then
haka.log.error("filter", "Bad IP checksum")
pkt:drop()
end
end
}
------------------------------------
-- IP attacks
------------------------------------
haka.rule {
hooks = { "ipv4-up" },
eval = function (self, pkt)
if pkt.src == pkt.dst then
haka.log.error("filter", "Land attack detected")
pkt:drop()
end
end
}
------------------------------------
-- TCP attacks
------------------------------------
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
--Xmas scan, as made by nmap -sX <IP>
if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then
haka.log.error("filter", "Xmas attack detected !!!")
pkt:drop()
end
end
}
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" ..
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" ..
"\x80\xe8\xdc\xff\xff\xff/bin/sh"
if #pkt.payload > 0 then
-- reconstruct payload
payload = getpayload(pkt.payload)
-- test if shellcode is present in data
if string.find(payload, bindshell) then
haka.log.error("filter", "/bin/sh shellcode detected !!!")
pkt:drop()
end
end
end
}
------------------------------------
-- HTTP compliance
------------------------------------
-- check http method value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local http_methods = dict({ 'get', 'post', 'head', 'put', 'trace', 'delete', 'options' })
local method = http.request.method:lower()
if not contains(http_methods, method) then
haka.log.error("filter", "non authorized http method '%s'", method)
http:drop()
end
end
}
-- check http version value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local http_versions = dict({ '0.9', '1.0', '1.1' })
local protocol = http.request.version:sub(1,4)
local version = http.request.version:sub(6)
if not protocol == "HTTP" or not contains(http_versions, version) then
haka.log.error("filter", "unsupported http version '%s/%s'", protocol, version)
http:drop()
end
end
}
-- check content length value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local content_length = http.request.headers["Content-Length"]
if content_length then
content_length = tonumber(content_length)
if content_length == nil or content_length < 0 then
haka.log.error("filter", "corrupted content-length header value")
http:drop()
end
end
end
}
------------------------------------
-- HTTP Policy
------------------------------------
-- add custom user-agent
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
http.request.headers["User-Agent"] = "Haka User-Agent"
end
}
-- allow only get and post methods
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local method = http.request.method:lower()
if method ~= 'get' and method ~= 'post' then
haka.log.warning("filter", "forbidden http method '%s'", method)
end
end
}
------------------------------------
-- HTTP Attacks
------------------------------------
-- detect malicious web scanners
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
--user-agent patterns of known web scanners
local http_useragent = {
nikto = '.+%(Nikto%/.+%)%s%(Evasions:.+%)%s%(Test:.+%)',
nessus = '^Nessus.*',
w3af = '*.%s;w3af.sf.net%)',
sqlmap = '^sqlmap%/.*%s%(http:%/%/sqlmap.*%)',
fimap = '^fimap%.googlecode%.%com.*',
grabber = '^Grabber.*'
}
if (http.request.headers['User-Agent']) then
local user_agent = http.request.headers['User-Agent']
for scanner, pattern in pairs(http_useragent) do
if user_agent:match(pattern) then
haka.log.error("filter", "'%s' scan detected !!!", scanner)
http:drop()
end
end
end
end
}
------------------------------------
-- Firewall rules
------------------------------------
akpf = haka.rule_group {
name = "akpf",
init = function (self, pkt)
haka.log.debug("filter", "entering packet filetring rules : %d --> %d", pkt.tcp.srcport, pkt.tcp.dstport)
end,
fini = function (self, pkt)
haka.log.error("filter", "packet dropped : drop by default")
pkt:drop()
end,
continue = function (self, ret)
return not ret
end
}
akpf:rule {
hooks = {"tcp-connection-new"},
eval = function (self, pkt)
local netsrc = ipv4.network("10.2.96.0/22")
local netdst = ipv4.network("10.2.104.0/22")
local tcp = pkt.tcp
if netsrc:contains(tcp.ip.src) and
netdst:contains(tcp.ip.dst) and
tcp.dstport == 80 then
haka.log.warning("filter", "authorizing http traffic")
pkt.next_dissector = "http"
return true
end
end
}
akpf:rule {
hooks = {"tcp-connection-new"},
eval = function (self, pkt)
local netsrc = ipv4.network("10.2.96.0/22")
local netdst = ipv4.network("10.2.104.0/22")
local tcp = pkt.tcp
if netsrc:contains(tcp.ip.src) and
netdst:contains(tcp.ip.dst) and
tcp.dstport == 22 then
haka.log.warning("filter", "authorizing ssh traffic")
haka.log.warning("filter", "no available dissector for ssh")
return true
end
end
}
|
------------------------------------
-- Loading disscetors
------------------------------------
require("ipv4")
require("tcp")
require("http")
------------------------------------
-- Function definition
------------------------------------
local function getpayload(data)
payload = ''
for i = 1, #data do
payload = payload .. string.char(data[i])
end
return payload
end
local function contains(table, elem)
return table[elem] ~= nil
end
local function dict(table)
local ret = {}
for _, v in pairs(table) do
ret[v] = true
end
return ret
end
------------------------------------
-- IP compliance
------------------------------------
haka.rule {
hooks = { "ipv4-up" },
eval = function (self, pkt)
-- bad IP checksum
if not pkt:verify_checksum() then
haka.log.error("filter", "Bad IP checksum")
pkt:drop()
end
end
}
------------------------------------
-- IP attacks
------------------------------------
haka.rule {
hooks = { "ipv4-up" },
eval = function (self, pkt)
if pkt.src == pkt.dst then
haka.log.error("filter", "Land attack detected")
pkt:drop()
end
end
}
------------------------------------
-- TCP attacks
------------------------------------
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
--Xmas scan, as made by nmap -sX <IP>
if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then
haka.log.error("filter", "Xmas attack detected !!!")
pkt:drop()
end
end
}
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" ..
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" ..
"\x80\xe8\xdc\xff\xff\xff/bin/sh"
if #pkt.payload > 0 then
-- reconstruct payload
payload = getpayload(pkt.payload)
-- test if shellcode is present in data
if string.find(payload, bindshell) then
haka.log.error("filter", "/bin/sh shellcode detected !!!")
pkt:drop()
end
end
end
}
------------------------------------
-- HTTP compliance
------------------------------------
-- check http method value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local http_methods = dict({ 'get', 'post', 'head', 'put', 'trace', 'delete', 'options' })
local method = http.request.method:lower()
if not contains(http_methods, method) then
haka.log.error("filter", "non authorized http method '%s'", method)
http:drop()
end
end
}
-- check http version value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local http_versions = dict({ '0.9', '1.0', '1.1' })
local protocol = http.request.version:sub(1,4)
local version = http.request.version:sub(6)
if not protocol == "HTTP" or not contains(http_versions, version) then
haka.log.error("filter", "unsupported http version '%s/%s'", protocol, version)
http:drop()
end
end
}
-- check content length value
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local content_length = http.request.headers["Content-Length"]
if content_length then
content_length = tonumber(content_length)
if content_length == nil or content_length < 0 then
haka.log.error("filter", "corrupted content-length header value")
http:drop()
end
end
end
}
------------------------------------
-- HTTP Attacks
------------------------------------
-- detect malicious web scanners
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
--user-agent patterns of known web scanners
local http_useragent = {
nikto = '.+%(Nikto%/.+%)%s%(Evasions:.+%)%s%(Test:.+%)',
nessus = '^Nessus.*',
w3af = '*.%s;w3af.sf.net%)',
sqlmap = '^sqlmap%/.*%s%(http:%/%/sqlmap.*%)',
fimap = '^fimap%.googlecode%.%com.*',
grabber = '^Grabber.*'
}
if (http.request.headers['User-Agent']) then
local user_agent = http.request.headers['User-Agent']
for scanner, pattern in pairs(http_useragent) do
if user_agent:match(pattern) then
haka.log.error("filter", "'%s' scan detected !!!", scanner)
http:drop()
end
end
end
end
}
------------------------------------
-- HTTP Policy
------------------------------------
-- add custom user-agent
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
http.request.headers["User-Agent"] = "Haka User-Agent"
end
}
-- allow only get and post methods
haka.rule {
hooks = {"http-request"},
eval = function (self, http)
local method = http.request.method:lower()
if method ~= 'get' and method ~= 'post' then
haka.log.warning("filter", "forbidden http method '%s'", method)
end
end
}
------------------------------------
-- Firewall rules
------------------------------------
akpf = haka.rule_group {
name = "akpf",
init = function (self, pkt)
haka.log.debug("filter", "entering packet filetring rules : %d --> %d", pkt.tcp.srcport, pkt.tcp.dstport)
end,
fini = function (self, pkt)
haka.log.error("filter", "packet dropped : drop by default")
pkt:drop()
end,
continue = function (self, ret)
return not ret
end
}
akpf:rule {
hooks = {"tcp-connection-new"},
eval = function (self, pkt)
local netsrc = ipv4.network("10.2.96.0/22")
local netdst = ipv4.network("10.2.104.0/22")
local tcp = pkt.tcp
if netsrc:contains(tcp.ip.src) and
netdst:contains(tcp.ip.dst) and
tcp.dstport == 80 then
haka.log.warning("filter", "authorizing http traffic")
pkt.next_dissector = "http"
return true
end
end
}
akpf:rule {
hooks = {"tcp-connection-new"},
eval = function (self, pkt)
local netsrc = ipv4.network("10.2.96.0/22")
local netdst = ipv4.network("10.2.104.0/22")
local tcp = pkt.tcp
if netsrc:contains(tcp.ip.src) and
netdst:contains(tcp.ip.dst) and
tcp.dstport == 22 then
haka.log.warning("filter", "authorizing ssh traffic")
haka.log.warning("filter", "no available dissector for ssh")
return true
end
end
}
|
Fix security rule configuration sample
|
Fix security rule configuration sample
|
Lua
|
mpl-2.0
|
lcheylus/haka,LubyRuffy/haka,lcheylus/haka,nabilbendafi/haka,Wingless-Archangel/haka,nabilbendafi/haka,haka-security/haka,haka-security/haka,haka-security/haka,Wingless-Archangel/haka,nabilbendafi/haka,lcheylus/haka,LubyRuffy/haka
|
784b294223cc347b52daae45bdad949a997dc6d6
|
orange/plugins/rate_limiting_for_every_value/handler.lua
|
orange/plugins/rate_limiting_for_every_value/handler.lua
|
local ipairs = ipairs
local type = type
local tostring = tostring
local utils = require("orange.utils.utils")
local orange_db = require("orange.store.orange_db")
local judge_util = require("orange.utils.judge")
local BasePlugin = require("orange.plugins.base_handler")
local plugin_config = require("orange.plugins.rate_limiting_for_every_value.plugin")
local counter = require(plugin_config.require_prefix .. "counter")
local function get_current_stat(limit_key)
return counter.get(limit_key)
end
local function incr_stat(limit_key, limit_type)
counter.incr(limit_key, 1, limit_type)
end
local function get_limit_type(period)
if not period then return nil end
if period == 1 then
return "Second"
elseif period == 60 then
return "Minute"
elseif period == 3600 then
return "Hour"
elseif period == 86400 then
return "Day"
else
return nil
end
end
local function filter_rules(sid, plugin, ngx_var_uri)
local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules")
if not rules or type(rules) ~= "table" or #rules <= 0 then
return false
end
local get_rate_limite_key = function(condition_type,condition)
local real
if condition_type == "URI" then
real = ngx.var.uri
elseif condition_type == "Query" then
local query = ngx.req.get_uri_args()
real = query[condition.name]
elseif condition_type == "Header" then
local headers = ngx.req.get_headers()
real = headers[condition.name]
elseif condition_type == "IP" then
real = ngx.var.remote_addr
elseif condition_type == "UserAgent" then
real = ngx.var.http_user_agent
elseif condition_type == "PostParams" then
local headers = ngx.req.get_headers()
local header = headers['Content-Type']
if header then
local is_multipart = string_find(header, "multipart")
if is_multipart and is_multipart > 0 then
return false
end
end
ngx.req.read_body()
local post_params, err = ngx.req.get_post_args()
if not post_params or err then
ngx.log(ngx.ERR, "[Condition Judge]failed to get post args: ", err)
return false
end
real = post_params[condition.name]
elseif condition_type == "Referer" then
real = ngx.var.http_referer
elseif condition_type == "Host" then
real = ngx.var.host
end
return real
end
for i, rule in ipairs(rules) do
if rule.enable == true then
-- judge阶段
local condition = rule.judge.conditions[0];
local real_value = get_rate_limite_key(condition.type,condition)
local pass = real_value and true or false;
-- handle阶段
local handle = rule.handle
if pass then
local limit_type = get_limit_type(handle.period)
-- only work for valid limit type(1 second/minute/hour/day)
if limit_type then
local current_timetable = utils.current_timetable()
local time_key = current_timetable[limit_type]
local limit_key = rule.id .. "#" .. time_key .. "#" .. real_value
local current_stat = get_current_stat(limit_key) or 0
ngx.header[plugin_config.plug_reponse_header_prefix .. limit_type] = handle.count
if current_stat >= handle.count then
if handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting-Forbidden-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat, " remaining:", 0)
end
ngx.header[plugin_config.plug_reponse_header_prefix ..limit_type] = 0
ngx.exit(429)
return true
else
ngx.header[plugin_config.plug_reponse_header_prefix ..limit_type] = handle.count - current_stat - 1
incr_stat(limit_key, limit_type)
-- only for test, comment it in production
-- if handle.log == true then
-- ngx.log(ngx.INFO, "[RateLimiting-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat + 1)
-- end
end
end
end -- end `pass`
end -- end `enable`
end -- end for
return false
end
local RateLimitingHandler = BasePlugin:extend()
RateLimitingHandler.PRIORITY = 1000
function RateLimitingHandler:new(store)
-- RateLimitingHandler.super.new(self, "rate-limiting-plugin")
RateLimitingHandler.super.new(self, plugin_config.name)
self.store = store
end
function RateLimitingHandler:access(conf)
RateLimitingHandler.super.access(self)
local enable = orange_db.get(plugin_config.table_name..".enable")
local meta = orange_db.get_json(plugin_config.table_name..".meta")
local selectors = orange_db.get_json(plugin_config.table_name..".selectors")
local ordered_selectors = meta and meta.selectors
if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then
return
end
local ngx_var_uri = ngx.var.uri
for i, sid in ipairs(ordered_selectors) do
ngx.log(ngx.INFO, "==[RateLimiting][PASS THROUGH SELECTOR:", sid, "]")
local selector = selectors[sid]
if selector and selector.enable == true then
local selector_pass
if selector.type == 0 then -- 全流量选择器
selector_pass = true
else
selector_pass = judge_util.judge_selector(selector,plugin_config.table_name)-- selector judge
end
if selector_pass then
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting][PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
local stop = filter_rules(sid, plugin_config.table_name, ngx_var_uri)
if stop then -- 不再执行此插件其他逻辑
return
end
else
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
end
-- if continue or break the loop
if selector.handle and selector.handle.continue == true then
-- continue next selector
else
break
end
end
end
end
return RateLimitingHandler
|
local ipairs = ipairs
local type = type
local tostring = tostring
local utils = require("orange.utils.utils")
local orange_db = require("orange.store.orange_db")
local judge_util = require("orange.utils.judge")
local BasePlugin = require("orange.plugins.base_handler")
local plugin_config = require("orange.plugins.rate_limiting_for_every_value.plugin")
local counter = require("orange.plugins.rate_limiting_for_every_value.counter")
local function get_current_stat(limit_key)
return counter.get(limit_key)
end
local function incr_stat(limit_key, limit_type)
counter.incr(limit_key, 1, limit_type)
end
local function get_limit_type(period)
if not period then return nil end
if period == 1 then
return "Second"
elseif period == 60 then
return "Minute"
elseif period == 3600 then
return "Hour"
elseif period == 86400 then
return "Day"
else
return nil
end
end
local function filter_rules(sid, plugin, ngx_var_uri)
local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules")
if not rules or type(rules) ~= "table" or #rules <= 0 then
return false
end
local get_rate_limite_key = function(condition_type,condition)
local real
if condition_type == "URI" then
real = ngx.var.uri
elseif condition_type == "Query" then
local query = ngx.req.get_uri_args()
real = query[condition.name]
elseif condition_type == "Header" then
local headers = ngx.req.get_headers()
real = headers[condition.name]
elseif condition_type == "IP" then
real = ngx.var.remote_addr
elseif condition_type == "UserAgent" then
real = ngx.var.http_user_agent
elseif condition_type == "PostParams" then
local headers = ngx.req.get_headers()
local header = headers['Content-Type']
if header then
local is_multipart = string_find(header, "multipart")
if is_multipart and is_multipart > 0 then
return false
end
end
ngx.req.read_body()
local post_params, err = ngx.req.get_post_args()
if not post_params or err then
ngx.log(ngx.ERR, "[Condition Judge]failed to get post args: ", err)
return false
end
real = post_params[condition.name]
elseif condition_type == "Referer" then
real = ngx.var.http_referer
elseif condition_type == "Host" then
real = ngx.var.host
end
return real
end
for i, rule in ipairs(rules) do
if rule.enable == true then
-- judge阶段
local condition = rule.judge.conditions[1];
local real_value = get_rate_limite_key(condition.type,condition)
local pass = real_value and true or false;
-- handle阶段
local handle = rule.handle
if pass then
local limit_type = get_limit_type(handle.period)
-- only work for valid limit type(1 second/minute/hour/day)
if limit_type then
local current_timetable = utils.current_timetable()
local time_key = current_timetable[limit_type]
local limit_key = rule.id .. "#" .. time_key .. "#" .. real_value
local current_stat = get_current_stat(limit_key) or 0
ngx.header[plugin_config.plug_reponse_header_prefix .. limit_type] = handle.count
if current_stat >= handle.count then
if handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting-Forbidden-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat, " remaining:", 0)
end
ngx.header[plugin_config.plug_reponse_header_prefix ..limit_type] = 0
ngx.exit(429)
return true
else
ngx.header[plugin_config.plug_reponse_header_prefix ..limit_type] = handle.count - current_stat - 1
incr_stat(limit_key, limit_type)
-- only for test, comment it in production
-- if handle.log == true then
-- ngx.log(ngx.INFO, "[RateLimiting-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat + 1)
-- end
end
end
end -- end `pass`
end -- end `enable`
end -- end for
return false
end
local RateLimitingHandler = BasePlugin:extend()
RateLimitingHandler.PRIORITY = 1000
function RateLimitingHandler:new(store)
-- RateLimitingHandler.super.new(self, "rate-limiting-plugin")
RateLimitingHandler.super.new(self, plugin_config.name)
self.store = store
end
function RateLimitingHandler:access(conf)
RateLimitingHandler.super.access(self)
local enable = orange_db.get(plugin_config.table_name..".enable")
local meta = orange_db.get_json(plugin_config.table_name..".meta")
local selectors = orange_db.get_json(plugin_config.table_name..".selectors")
local ordered_selectors = meta and meta.selectors
if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then
return
end
local ngx_var_uri = ngx.var.uri
for i, sid in ipairs(ordered_selectors) do
ngx.log(ngx.INFO, "==[RateLimiting][PASS THROUGH SELECTOR:", sid, "]")
local selector = selectors[sid]
if selector and selector.enable == true then
local selector_pass
if selector.type == 0 then -- 全流量选择器
selector_pass = true
else
selector_pass = judge_util.judge_selector(selector,plugin_config.table_name)-- selector judge
end
if selector_pass then
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting][PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
local stop = filter_rules(sid, plugin_config.table_name, ngx_var_uri)
if stop then -- 不再执行此插件其他逻辑
return
end
else
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[RateLimiting][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
end
-- if continue or break the loop
if selector.handle and selector.handle.continue == true then
-- continue next selector
else
break
end
end
end
end
return RateLimitingHandler
|
fix bug lua 数组下表 从1开始
|
fix bug lua 数组下表 从1开始
|
Lua
|
mit
|
wuhuatianbao007/orange,jxskiss/orange,jxskiss/orange,sumory/orange,wuhuatianbao007/orange,wuhuatianbao007/orange,thisverygoodhhhh/orange,sumory/orange,sumory/orange,thisverygoodhhhh/orange,jxskiss/orange,thisverygoodhhhh/orange
|
1920d700fd3b1a421e50f775b91715838267c5df
|
game/scripts/vscripts/items/item_urn_of_demons.lua
|
game/scripts/vscripts/items/item_urn_of_demons.lua
|
function modifier_item_urn_of_demons_aura_on_death(keys)
local urn_with_least_charges
for i = 0, 5 do
local current_item = keys.caster:GetItemInSlot(i)
if current_item then
local item_name = current_item:GetName()
if item_name == keys.ability:GetName() then
if not urn_with_least_charges then
urn_with_least_charges = current_item
elseif current_item:GetCurrentCharges() < urn_with_least_charges:GetCurrentCharges() then
urn_with_least_charges = current_item
end
end
end
end
if urn_with_least_charges then
if urn_with_least_charges:GetCurrentCharges() == 0 then
urn_with_least_charges:SetCurrentCharges(2)
else
urn_with_least_charges:SetCurrentCharges(urn_with_least_charges:GetCurrentCharges() + 1)
end
end
end
function modifier_item_urn_of_demons_damage_on_interval_think(keys)
local ability = keys.ability
local target = keys.target
local damage_to_deal = keys.TotalHealthPct * 0.01 * target:GetMaxHealth() / keys.TotalDuration * keys.Interval
local mana_to_burn = keys.TotalManaPct * 0.01 * target:GetMaxMana() / keys.TotalDuration * keys.Interval
ApplyDamage({victim = target, attacker = keys.caster, damage = damage_to_deal, damage_type = ability:GetAbilityDamageType(), ability = ability})
target:SetMana(target:GetMana() - mana_to_burn)
end
function modifier_item_urn_of_demons_heal_on_interval_think(keys)
local target = keys.target
local amount_to_heal = keys.TotalHealthPct * 0.01 * target:GetMaxHealth() / keys.TotalDuration * keys.Interval
local mana_to_heal = keys.TotalManaPct * 0.01 * target:GetMaxMana() / keys.TotalDuration * keys.Interval
SafeHeal(target, mana_to_heal)
target:GiveMana(mana_to_heal)
end
function item_urn_of_demons_on_spell_start(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
target:EmitSound("DOTA_Item.UrnOfShadows.Activate")
if caster:GetTeam() == target:GetTeam() then
ability:ApplyDataDrivenModifier(caster, target, "modifier_item_urn_of_demons_ally", nil)
else
ability:ApplyDataDrivenModifier(caster, target, "modifier_item_urn_of_demons_enemy", nil)
end
ability:SetCurrentCharges(ability:GetCurrentCharges() - 1)
end
|
function modifier_item_urn_of_demons_aura_on_death(keys)
local urn_with_least_charges
for i = 0, 5 do
local current_item = keys.caster:GetItemInSlot(i)
if current_item then
local item_name = current_item:GetName()
if item_name == keys.ability:GetName() then
if not urn_with_least_charges then
urn_with_least_charges = current_item
elseif current_item:GetCurrentCharges() < urn_with_least_charges:GetCurrentCharges() then
urn_with_least_charges = current_item
end
end
end
end
if urn_with_least_charges then
if urn_with_least_charges:GetCurrentCharges() == 0 then
urn_with_least_charges:SetCurrentCharges(2)
else
urn_with_least_charges:SetCurrentCharges(urn_with_least_charges:GetCurrentCharges() + 1)
end
end
end
function modifier_item_urn_of_demons_damage_on_interval_think(keys)
local ability = keys.ability
local target = keys.target
local damage_to_deal = keys.TotalHealthPct * 0.01 * target:GetMaxHealth() / keys.TotalDuration * keys.Interval
local mana_to_burn = keys.TotalManaPct * 0.01 * target:GetMaxMana() / keys.TotalDuration * keys.Interval
ApplyDamage({
victim = target,
attacker = keys.caster,
damage = damage_to_deal,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = ability
})
target:SetMana(target:GetMana() - mana_to_burn)
end
function modifier_item_urn_of_demons_heal_on_interval_think(keys)
local target = keys.target
local amount_to_heal = keys.TotalHealthPct * 0.01 * target:GetMaxHealth() / keys.TotalDuration * keys.Interval
local mana_to_heal = keys.TotalManaPct * 0.01 * target:GetMaxMana() / keys.TotalDuration * keys.Interval
SafeHeal(target, mana_to_heal)
target:GiveMana(mana_to_heal)
end
function item_urn_of_demons_on_spell_start(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
target:EmitSound("DOTA_Item.UrnOfShadows.Activate")
if caster:GetTeam() == target:GetTeam() then
ability:ApplyDataDrivenModifier(caster, target, "modifier_item_urn_of_demons_ally", nil)
else
ability:ApplyDataDrivenModifier(caster, target, "modifier_item_urn_of_demons_enemy", nil)
end
ability:SetCurrentCharges(ability:GetCurrentCharges() - 1)
end
|
fix(items): Urn of Demons damage is affected by spell amplification
|
fix(items): Urn of Demons damage is affected by spell amplification
Fixes #91
|
Lua
|
mit
|
ark120202/aabs
|
2ccc3e8e47527948fb1e786a4f28d8010ca87775
|
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
|
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
|
#!/usr/bin/lua
local config = require("lime.config")
local network = require("lime.network")
local utils = require("lime.utils")
local libuci = require("uci")
local fs = require("nixio.fs")
local iwinfo = require("iwinfo")
wireless = {}
wireless.limeIfNamePrefix="lm_"
wireless.wifiModeSeparator="-"
function wireless.get_phy_mac(phy)
local path = "/sys/class/ieee80211/"..phy.."/macaddress"
local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","")
return utils.split(mac, ":")
end
function wireless.clean()
print("Clearing wireless config...")
local uci = libuci:cursor()
uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end)
uci:save("wireless")
end
function wireless.scandevices()
local devices = {}
local uci = libuci:cursor()
uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end)
return devices
end
function wireless.is5Ghz(radio)
local devModes = iwinfo.nl80211.hwmodelist(radio)
return devModes.a or devModes.ac
end
wireless.availableModes = { adhoc=true, ap=true, apname=true, ieee80211s=true }
function wireless.isMode(m)
return wireless.availableModes[m]
end
function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras)
--! checks("table", "string", "?string", "?table")
--! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks
nameSuffix = nameSuffix or ""
local radioName = radio[".name"]
local phyIndex = radioName:match("%d+")
local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix
--! sanitize generated ifname for constructing uci section name
--! because only alphanumeric and underscores are allowed
local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName
local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_")
local uci = libuci:cursor()
uci:set("wireless", wirelessInterfaceName, "wifi-iface")
uci:set("wireless", wirelessInterfaceName, "mode", mode)
uci:set("wireless", wirelessInterfaceName, "device", radioName)
uci:set("wireless", wirelessInterfaceName, "ifname", ifname)
uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName)
if extras then
for key, value in pairs(extras) do
uci:set("wireless", wirelessInterfaceName, key, value)
end
end
uci:save("wireless")
return uci:get_all("wireless", wirelessInterfaceName)
end
function wireless.configure()
local specificRadios = {}
config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end)
local allRadios = wireless.scandevices()
for _,radio in pairs(allRadios) do
local radioName = radio[".name"]
local specRadio = specificRadios[radioName]
local modes = config.get("wifi", "modes")
local options = config.get_all("wifi")
if specRadio then
modes = specRadio["modes"]
options = specRadio
end
--! If manual mode is used toghether with other modes it results in an
--! unpredictable behaviour
local distance
if modes[1] ~= "manual" then
if wireless.is5Ghz(radioName) then
freqSuffix = "_5ghz"
ignoredSuffix = "_2ghz"
distance = options["distance"..freqSuffix] or options["distance"] or 1000
else
local freqSuffix = "_2ghz"
local ignoredSuffix = "_5ghz"
distance = options["distance"..freqSuffix] or options["distance"] or 100
end
local htmode = options["htmode"..freqSuffix] or options["htmode"]
local channel = options["channel"..freqSuffix] or options["channel"]
local uci = libuci:cursor()
uci:set("wireless", radioName, "disabled", 0)
uci:set("wireless", radioName, "distance", distance)
uci:set("wireless", radioName, "noscan", 1)
uci:set("wireless", radioName, "channel", channel)
if options["country"] then uci:set("wireless", radioName, "country", options["country"]) end
if htmode then uci:set("wireless", radioName, "htmode", htmode) end
uci:save("wireless")
for _,modeName in pairs(modes) do
local args = {}
local mode = require("lime.mode."..modeName)
for key,value in pairs(options) do
local keyPrefix = utils.split(key, "_")[1]
local isGoodOption = ( (key ~= "modes")
and (not key:match("^%."))
and (not key:match("channel"))
and (not key:match("country"))
and (not key:match("htmode"))
and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName))
and (not key:match(ignoredSuffix)) )
if isGoodOption then
local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "")
if nk == "ssid" then
value = utils.applyHostnameTemplate(value)
value = utils.applyMacTemplate16(value, network.primary_mac())
value = string.sub(value, 1, 32)
end
args[nk] = value
end
end
mode.setup_radio(radio, args)
end
end
end
end
return wireless
|
#!/usr/bin/lua
local config = require("lime.config")
local network = require("lime.network")
local utils = require("lime.utils")
local libuci = require("uci")
local fs = require("nixio.fs")
local iwinfo = require("iwinfo")
wireless = {}
wireless.limeIfNamePrefix="lm_"
wireless.wifiModeSeparator="-"
function wireless.get_phy_mac(phy)
local path = "/sys/class/ieee80211/"..phy.."/macaddress"
local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","")
return utils.split(mac, ":")
end
function wireless.clean()
print("Clearing wireless config...")
local uci = libuci:cursor()
uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end)
uci:save("wireless")
end
function wireless.scandevices()
local devices = {}
local uci = libuci:cursor()
uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end)
return devices
end
function wireless.is5Ghz(radio)
local devModes = iwinfo.nl80211.hwmodelist(radio)
return devModes.a or devModes.ac
end
wireless.availableModes = { adhoc=true, ap=true, apname=true, ieee80211s=true }
function wireless.isMode(m)
return wireless.availableModes[m]
end
function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras)
--! checks("table", "string", "?string", "?table")
--! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks
nameSuffix = nameSuffix or ""
local radioName = radio[".name"]
local phyIndex = radioName:match("%d+")
local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix
--! sanitize generated ifname for constructing uci section name
--! because only alphanumeric and underscores are allowed
local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName
local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_")
local uci = libuci:cursor()
uci:set("wireless", wirelessInterfaceName, "wifi-iface")
uci:set("wireless", wirelessInterfaceName, "mode", mode)
uci:set("wireless", wirelessInterfaceName, "device", radioName)
uci:set("wireless", wirelessInterfaceName, "ifname", ifname)
uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName)
if extras then
for key, value in pairs(extras) do
uci:set("wireless", wirelessInterfaceName, key, value)
end
end
uci:save("wireless")
return uci:get_all("wireless", wirelessInterfaceName)
end
function wireless.configure()
local specificRadios = {}
config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end)
local allRadios = wireless.scandevices()
for _,radio in pairs(allRadios) do
local radioName = radio[".name"]
local specRadio = specificRadios[radioName]
local modes = config.get("wifi", "modes")
local options = config.get_all("wifi")
if specRadio then
modes = specRadio["modes"]
options = specRadio
end
--! If manual mode is used toghether with other modes it results in an
--! unpredictable behaviour
local freqSuffix
local ignoredSuffix
local distance
local htmode
if modes[1] ~= "manual" then
if wireless.is5Ghz(radioName) then
freqSuffix = "_5ghz"
ignoredSuffix = "_2ghz"
distance = options["distance"..freqSuffix] or options["distance"] or 1000
htmode = options["htmode"..freqSuffix] or options["htmode"] or "HT40"
else
freqSuffix = "_2ghz"
ignoredSuffix = "_5ghz"
distance = options["distance"..freqSuffix] or options["distance"] or 100
htmode = options["htmode"..freqSuffix] or options["htmode"] or "HT20"
end
local channel = options["channel"..freqSuffix] or options["channel"]
local uci = libuci:cursor()
uci:set("wireless", radioName, "disabled", 0)
uci:set("wireless", radioName, "distance", distance)
uci:set("wireless", radioName, "noscan", 1)
uci:set("wireless", radioName, "channel", channel)
if options["country"] then uci:set("wireless", radioName, "country", options["country"]) end
if htmode then uci:set("wireless", radioName, "htmode", htmode) end
uci:save("wireless")
for _,modeName in pairs(modes) do
local args = {}
local mode = require("lime.mode."..modeName)
for key,value in pairs(options) do
local keyPrefix = utils.split(key, "_")[1]
local isGoodOption = ( (key ~= "modes")
and (not key:match("^%."))
and (not key:match("channel"))
and (not key:match("country"))
and (not key:match("htmode"))
and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName))
and (not key:match(ignoredSuffix)) )
if isGoodOption then
local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "")
if nk == "ssid" then
value = utils.applyHostnameTemplate(value)
value = utils.applyMacTemplate16(value, network.primary_mac())
value = string.sub(value, 1, 32)
end
args[nk] = value
end
end
mode.setup_radio(radio, args)
end
end
end
end
return wireless
|
wireless: fix ignored freqs + default htmode
|
wireless: fix ignored freqs + default htmode
fix error due to local ignored freqs if 2.4ghz
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
358451800937a901eba6790861a48680037c8d73
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/t4/spi_loop_back.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/t4/spi_loop_back.lua
|
--This is an SPI example for the T4. It tests SPI functionality using the
--standard loop-back methidology where a user must connect the MISO and MOSI
--data lines together.
print ("T4 SPI Loop-Back Example")
SPI_Utils={}
function SPI_Utils.configure(self, cs, clk, miso, mosi, mode, speed, options, debug)
self.cs=cs
self.clk=clk
self.miso=miso
self.mosi=mosi
self.mode=mode
self.speed=speed
self.options=options
self.debug=debug
MB.W(5000, 0, cs) --CS
MB.W(5001, 0, clk) --CLK
MB.W(5002, 0, miso) --MISO
MB.W(5003, 0, mosi) --MOSI
MB.W(5004, 0, mode) --Mode
MB.W(5005, 0, speed) --Speed
MB.W(5006, 0, options) --Options, enable CS
end
function SPI_Utils.transfer(self, txData)
local numBytes = table.getn(txData)
--Configure num bytes to read/write
MB.W(5009, 0, numBytes) --Num Bytes to Tx/Rx
local errorVal = MB.WA(5010, 99, numBytes, txData) --SPI_DATA_TX
MB.W(5007, 0, 1) --SPI_GO
local rxData = MB.RA(5050, 99, numBytes) --SPI_DATA_RX
return rxData
end
function SPI_Utils.transferString(self, txString)
local numBytes = string.len(txString)
local txData={}
for i=1,numBytes do
txData[i]=string.byte(txString,i)
end
--Append a null character
-- numBytes += 1
-- txData[numBytes]=0
--Configure num bytes to read/write
MB.W(5009, 0, numBytes) --Num Bytes to Tx/Rx
local errorVal = MB.WA(5010, 99, numBytes, txData) --SPI_DATA_TX
MB.W(5007, 0, 1) --SPI_GO
local rxData = MB.RA(5050, 99, numBytes) --SPI_DATA_RX
local rxString = ""
for i=1,numBytes do
rxString = rxString..string.char(rxData[i])
end
return rxString
end
function SPI_Utils.calc_options(self, autoCSDisable)
autoCSDisableVal = autoCSDisable and 1 or 0
return autoCSDisableVal*1
end
function SPI_Utils.calc_mode(self, cpol, cpha)
cpolVal = cpol and 1 or 0
cphaVal = cpha and 1 or 0
return cpolVal*2 + cphaVal*1
end
spi = SPI_Utils
--Define DIO Numbers
spiCS=8
spiCLK=9
spiMISO=6
spiMOSI=7
--Define SPI Options
spiMode = spi.calc_mode(spi, false, false)
spiSpeed = 0
spiOptions = spi.calc_options(spi, false)
--Configure SPI bus
spi.configure(spi, spiCS, spiCLK, spiMISO, spiMOSI, spiMode, spiSpeed, spiOptions, false)
txString = "Hello_world"
print("Transfered String: "..txString)
rxString = spi.transferString(spi, txString)
print("Received String: "..rxString)
--Stop the Lua Script
MB.W(6000, 1, 0)
|
--[[
Name: spi_loop_back.lua
Desc: This is an SPI example for the T4. It tests SPI functionality using
the standard loop-back methodology where a user must connect the MISO
and MOSI data lines together.
Note: See our T-Series SPI page for more detailed info on SPI settings:
https://labjack.com/support/datasheets/t-series/digital-io/spi
--]]
print ("T4 SPI Loop-Back Example")
spiutils={}
function spiutils.configure(self, cs, clk, miso, mosi, mode, speed, options, debug)
self.cs=cs
self.clk=clk
self.miso=miso
self.mosi=mosi
self.mode=mode
self.speed=speed
self.options=options
self.debug=debug
-- Write the DIO register number for chip select to SPI_CS_DIONUM
MB.W(5000, 0, cs)
-- Write the DIO register number for clock to SPI_CLK_DIONUM
MB.W(5001, 0, clk)
-- Write the DIO register number for MISO to SPI_MISO_DIONUM
MB.W(5002, 0, miso)
-- Write the DIO register number for MOSI to SPI_MOSI_DIONUM
MB.W(5003, 0, mosi)
-- Write the desired SPI mode to SPI_MODE
MB.W(5004, 0, mode)
-- Write the desired clock speed to SPI_SPEED_THROTTLE
MB.W(5005, 0, speed)
-- Write the desired SPI_OPTIONS
MB.W(5006, 0, options)
end
function spiutils.transfer(self, txdata)
local numbytes = table.getn(txdata)
-- Configure the number of bytes to read/write (write to SPI_NUM_BYTES)
MB.W(5009, 0, numbytes)
-- SPI_DATA_TX is a buffer for data to send to slave devices
local errorval = MB.WA(5010, 99, numbytes, txdata)
-- Write 1 to SPI_GO to begin the SPI transaction
MB.W(5007, 0, 1)
-- Read SPI_DATA_RX to capture data sent back from the slave device
local rxdata = MB.RA(5050, 99, numbytes)
return rxdata
end
function spiutils.stringtransfer(self, txstring)
local numbytes = string.len(txstring)
-- Convert the transfer string to bytes
local txdata={}
for i=1,numbytes do
txdata[i]=string.byte(txstring,i)
end
-- Append a null character
-- numbytes += 1
-- txdata[numbytes]=0
-- Get return data from the slave device
local rxdata = self.transfer(self, txdata)
-- Convert the data to a string
local rxString = ""
for i=1,numbytes do
rxString = rxString..string.char(rxdata[i])
end
return rxString
end
function spiutils.calculateoptions(self, autodisable)
local autodisableval = autodisable and 1 or 0
return autodisableval*1
end
function spiutils.calculatemode(self, cpol, cpha)
local cpolval = cpol and 1 or 0
local cphaval = cpha and 1 or 0
return cpolval*2 + cphaval*1
end
local spi = spiutils
-- Use DIO8 for chip select
local cs=8
-- Use DIO9 for clock
local clk=9
-- Use DIO6 for MISO
local miso=6
-- Use DIO7 for MOSI
local mosi=7
-- Set the mode such that the clock idles at 0 with polarity 0
local mode = spi.calculatemode(spi, false, false)
-- Set the clock at default speed (~800KHz)
local speed = 0
-- Set the options such that there are no special operation (such as disabling CS)
local options = spi.calculateoptions(spi, false)
-- Configure the SPI bus
spi.configure(spi, cs, clk, miso, mosi, mode, speed, options, false)
local txstring = "Hello_world"
print("Transfered String: "..txstring)
local rxString = spi.stringtransfer(spi, txstring)
print("Received String: "..rxString)
-- Write 0 to LUA_RUN to stop the script
MB.W(6000, 1, 0)
|
Fixed up the formatting of the T4 SPI example
|
Fixed up the formatting of the T4 SPI example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
ca7c4fdfe0f736dbd6c3a5830258a9682d2df684
|
plugins/database.lua
|
plugins/database.lua
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
save_data(_config.database.db, database)
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
fix database
|
fix database
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
fb7f444d0286dd2a901aae2703d169b3963c6da4
|
agents/monitoring/tests/net/init.lua
|
agents/monitoring/tests/net/init.lua
|
local table = require('table')
local async = require('async')
local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream
local misc = require('monitoring/default/util/misc')
local helper = require('../helper')
local timer = require('timer')
local fixtures = require('../fixtures')
local constants = require('constants')
local consts = require('../../default/util/constants')
local Endpoint = require('../../default/endpoint').Endpoint
local path = require('path')
local exports = {}
local child
exports['test_reconnects'] = function(test, asserts)
local options = {
datacenter = 'test',
stateDirectory = './tests',
host = "127.0.0.1",
port = 50061,
tls = { rejectUnauthorized = false }
}
local client = ConnectionStream:new('id', 'token', 'guid', options)
local clientEnd = 0
local reconnect = 0
client:on('client_end', function(err)
clientEnd = clientEnd + 1
end)
client:on('reconnect', function(err)
reconnect = reconnect + 1
end)
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client:on('handshake_success', misc.nCallbacks(callback, 3))
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
client:createConnections(endpoints, function() end)
end,
function(callback)
helper.stop_server(child)
client:on('reconnect', counterTrigger(3, callback))
end,
function(callback)
child = helper.start_server(function()
client:on('handshake_success', counterTrigger(3, callback))
end)
end,
}, function()
helper.stop_server(child)
asserts.ok(clientEnd > 0)
asserts.ok(reconnect > 0)
test.done()
end)
end
exports['test_upgrades'] = function(test, asserts)
local options, client, endpoints
-- Override the default download path
consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp')
options = {
datacenter = 'test',
stateDirectory = './tests',
host = "127.0.0.1",
port = 50061,
tls = { rejectUnauthorized = false }
}
endpoints = get_endpoints()
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client = ConnectionStream:new('id', 'token', 'guid', options)
client:on('handshake_success', misc.nCallbacks(callback, 3))
client:createConnections(endpoints, function() end)
end,
function(callback)
callback = misc.nCallbacks(callback, 4)
client:on('binary_upgrade.found', callback)
client:on('bundle_upgrade.found', callback)
client:on('bundle_upgrade.error', callback)
client:on('binary_upgrade.error', callback)
client:getUpgrade():forceUpgradeCheck()
end
}, function()
helper.stop_server(child)
client:done()
test.done()
end)
end
return exports
|
local table = require('table')
local async = require('async')
local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream
local misc = require('monitoring/default/util/misc')
local helper = require('../helper')
local timer = require('timer')
local fixtures = require('../fixtures')
local constants = require('constants')
local consts = require('../../default/util/constants')
local Endpoint = require('../../default/endpoint').Endpoint
local path = require('path')
local exports = {}
local child
function counterTrigger(trigger, callback)
local counter = 0
return function()
counter = counter + 1
if counter == trigger then
callback()
end
end
end
exports['test_reconnects'] = function(test, asserts)
local options = {
datacenter = 'test',
stateDirectory = './tests',
host = "127.0.0.1",
port = 50061,
tls = { rejectUnauthorized = false }
}
local client = ConnectionStream:new('id', 'token', 'guid', options)
local clientEnd = 0
local reconnect = 0
client:on('client_end', function(err)
clientEnd = clientEnd + 1
end)
client:on('reconnect', function(err)
reconnect = reconnect + 1
end)
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client:on('handshake_success', misc.nCallbacks(callback, 3))
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
client:createConnections(endpoints, function() end)
end,
function(callback)
helper.stop_server(child)
client:on('reconnect', counterTrigger(3, callback))
end,
function(callback)
child = helper.start_server(function()
client:on('handshake_success', counterTrigger(3, callback))
end)
end,
}, function()
helper.stop_server(child)
asserts.ok(clientEnd > 0)
asserts.ok(reconnect > 0)
test.done()
end)
end
exports['test_upgrades'] = function(test, asserts)
local options, client, endpoints
-- Override the default download path
consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp')
options = {
datacenter = 'test',
stateDirectory = './tests',
host = "127.0.0.1",
port = 50061,
tls = { rejectUnauthorized = false }
}
endpoints = get_endpoints()
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client = ConnectionStream:new('id', 'token', 'guid', options)
client:on('handshake_success', misc.nCallbacks(callback, 3))
client:createConnections(endpoints, function() end)
end,
function(callback)
callback = misc.nCallbacks(callback, 4)
client:on('binary_upgrade.found', callback)
client:on('bundle_upgrade.found', callback)
client:on('bundle_upgrade.error', callback)
client:on('binary_upgrade.error', callback)
client:getUpgrade():forceUpgradeCheck()
end
}, function()
helper.stop_server(child)
client:done()
test.done()
end)
end
return exports
|
fix merge on counterTrigger
|
fix merge on counterTrigger
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
a6e8d783cb0dcecf8d029e8e1b33c07adba24add
|
missions/daredevil.lua
|
missions/daredevil.lua
|
return {
id='daredevil',
name='Daredevil: living on the edge',
commissionedby='spacecorp',
description = [[
Hello!
Are you interested in doing something dangerous and XTREME? Are you interested in doing that for shiploads of money?
Seek no further! SpaceCorp has a new reality show, in which contestants have to fly within the danger-zone of the black hole.
Accept this mission for the ride of your life! (SpaceCorp is not responsable for injuries or death.)]],
debrief = [[
Oh, you actually flew this close to the black hole?
I'm sorry we forgot to tell you, but the show's not going through. Something about breaking the law.
Anyway, here is your money.]],
canrefuse=true,
available = function()
return player.rank < 4
end,
accept = function()
--
end,
refuse = function()
end,
checkcompleted = function()
if math.sqrt((player.x-map.objects.blackhole.x)^2+(player.y-map.objects.blackhole.y)^2) < map.objects.blackhole.radius then
return true
end
end,
completed = false,
}
|
return {
id='daredevil',
name='Daredevil: living on the edge',
commissionedby='spacecorp',
description = [[
Hello!
Are you interested in doing something dangerous and XTREME? Are you interested in doing that for shiploads of money?
Seek no further! SpaceCorp has a new reality show, in which contestants have to fly within the danger-zone of the black hole.
Accept this mission for the ride of your life! (SpaceCorp is not responsible for injuries or death.)]],
debrief = [[
Oh, you actually flew this close to the black hole?
I'm sorry we forgot to tell you, but the show's been cancelled. Something about being illegal. Can you imagine?
Anyway, here is your money.]],
canrefuse=true,
available = function()
return player.rank < 4
end,
accept = function()
--
end,
refuse = function()
end,
checkcompleted = function()
if math.sqrt((player.x-map.objects.blackhole.x)^2+(player.y-map.objects.blackhole.y)^2) < map.objects.blackhole.radius then
return true
end
end,
completed = false,
}
|
Grammatical fixes in daredevil mission (thanks bartbes, for reporting)
|
Grammatical fixes in daredevil mission (thanks bartbes, for reporting)
|
Lua
|
mit
|
gvx/space,gvx/space
|
c8845e8d446071080d7f79e292e176f893b27340
|
mods/farming/nodes.lua
|
mods/farming/nodes.lua
|
minetest.override_item("default:dirt", {
groups = {crumbly=3,soil=1},
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.override_item("default:dirt_with_grass", {
groups = {crumbly=3,soil=1},
soil = {
base = "default:dirt_with_grass",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.register_node("farming:soil", {
description = "Soil",
tiles = {"farming_soil.png", "default_dirt.png"},
drop = "default:dirt",
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory=1, soil=2, grassland = 1},
sounds = default.node_sound_dirt_defaults(),
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.register_node("farming:soil_wet", {
description = "Wet Soil",
tiles = {"farming_soil_wet.png", "farming_soil_wet_side.png"},
drop = "default:dirt",
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory=1, soil=3, wet = 1, grassland = 1},
sounds = default.node_sound_dirt_defaults(),
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.override_item("default:desert_sand", {
groups = {crumbly=3, falling_node=1, sand=1, soil = 1},
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_node("farming:desert_sand_soil", {
description = "Desert Sand",
tiles = {"farming_desert_sand_soil.png", "default_desert_sand.png"},
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory = 1, falling_node=1, sand=1, soil = 2, desert = 1},
sounds = default.node_sound_sand_defaults(),
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_node("farming:desert_sand_soil_wet", {
description = "Desert Sand",
drop = "default:desert_sand",
tiles = {"farming_desert_sand_soil_wet.png", "farming_desert_sand_soil_wet_side.png"},
is_ground_content = true,
groups = {crumbly=3, falling_node=1, sand=1, not_in_creative_inventory=1, soil=3, wet = 1, desert = 1},
sounds = default.node_sound_sand_defaults(),
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_abm({
nodenames = {"group:soil", "group:wet"},
interval = 5,
chance = 10,
action = function(pos, node)
pos.y = pos.y+1
local nn = minetest.get_node(pos).name
node = minetest.registered_nodes[node.name]
pos.y = pos.y-1
if node.soil == nil or node.soil.wet == nil or node.soil.base == nil or node.soil.dry == nil then
return
end
if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].walkable and minetest.get_item_group(nn, "plant") == 0 and node.name ~= node.soil.base then
minetest.set_node(pos, {name = node.soil.base})
end
-- check if there is water nearby
if minetest.find_node_near(pos, 3, {"group:water"}) then
-- if it is dry soil and not base node, turn it into wet soil
if node.name ~= node.soil.base and minetest.get_item_group(node.name, "wet") == 0 then
minetest.set_node(pos, {name = node.soil.wet})
end
else
-- turn it back into base if it is already dry
if minetest.get_item_group(node.name, "wet") == 0 then
-- only turn it back if there is no plant/seed on top of it
if minetest.get_item_group(nn, "plant") == 0 and minetest.get_item_group(nn, "seed") == 0 then
minetest.set_node(pos, {name = node.soil.base})
end
-- if its wet turn it back into dry soil
elseif minetest.get_item_group(node.name, "wet") == 1 then
minetest.set_node(pos, {name = node.soil.dry})
end
end
end,
})
for i = 1, 5 do
minetest.override_item("default:grass_"..i, {drop = {
max_items = 1,
items = {
{items = {'farming:seed_wheat'},rarity = 5},
{items = {'default:grass_1'}},
}
}})
end
minetest.override_item("default:junglegrass", {drop = {
max_items = 1,
items = {
{items = {'farming:seed_cotton'},rarity = 8},
{items = {'default:junglegrass'}},
}
}})
|
minetest.override_item("default:dirt", {
groups = {crumbly=3,soil=1},
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.override_item("default:dirt_with_grass", {
groups = {crumbly=3,soil=1},
soil = {
base = "default:dirt_with_grass",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.register_node("farming:soil", {
description = "Soil",
tiles = {"farming_soil.png", "default_dirt.png"},
drop = "default:dirt",
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory=1, soil=2, grassland = 1},
sounds = default.node_sound_dirt_defaults(),
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.register_node("farming:soil_wet", {
description = "Wet Soil",
tiles = {"farming_soil_wet.png", "farming_soil_wet_side.png"},
drop = "default:dirt",
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory=1, soil=3, wet = 1, grassland = 1},
sounds = default.node_sound_dirt_defaults(),
soil = {
base = "default:dirt",
dry = "farming:soil",
wet = "farming:soil_wet"
}
})
minetest.override_item("default:desert_sand", {
groups = {crumbly=3, falling_node=1, sand=1, soil = 1},
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_node("farming:desert_sand_soil", {
description = "Desert Sand Soil",
drop = "default:desert_sand",
tiles = {"farming_desert_sand_soil.png", "default_desert_sand.png"},
is_ground_content = true,
groups = {crumbly=3, not_in_creative_inventory = 1, falling_node=1, sand=1, soil = 2, desert = 1},
sounds = default.node_sound_sand_defaults(),
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_node("farming:desert_sand_soil_wet", {
description = "Wet Desert Sand Soil",
drop = "default:desert_sand",
tiles = {"farming_desert_sand_soil_wet.png", "farming_desert_sand_soil_wet_side.png"},
is_ground_content = true,
groups = {crumbly=3, falling_node=1, sand=1, not_in_creative_inventory=1, soil=3, wet = 1, desert = 1},
sounds = default.node_sound_sand_defaults(),
soil = {
base = "default:desert_sand",
dry = "farming:desert_sand_soil",
wet = "farming:desert_sand_soil_wet"
}
})
minetest.register_abm({
nodenames = {"group:soil", "group:wet"},
interval = 5,
chance = 10,
action = function(pos, node)
pos.y = pos.y+1
local nn = minetest.get_node(pos).name
node = minetest.registered_nodes[node.name]
pos.y = pos.y-1
if node.soil == nil or node.soil.wet == nil or node.soil.base == nil or node.soil.dry == nil then
return
end
if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].walkable and minetest.get_item_group(nn, "plant") == 0 and node.name ~= node.soil.base then
minetest.set_node(pos, {name = node.soil.base})
end
-- check if there is water nearby
if minetest.find_node_near(pos, 3, {"group:water"}) then
-- if it is dry soil and not base node, turn it into wet soil
if node.name ~= node.soil.base and minetest.get_item_group(node.name, "wet") == 0 then
minetest.set_node(pos, {name = node.soil.wet})
end
else
-- turn it back into base if it is already dry
if minetest.get_item_group(node.name, "wet") == 0 then
-- only turn it back if there is no plant/seed on top of it
if minetest.get_item_group(nn, "plant") == 0 and minetest.get_item_group(nn, "seed") == 0 then
minetest.set_node(pos, {name = node.soil.base})
end
-- if its wet turn it back into dry soil
elseif minetest.get_item_group(node.name, "wet") == 1 then
minetest.set_node(pos, {name = node.soil.dry})
end
end
end,
})
for i = 1, 5 do
minetest.override_item("default:grass_"..i, {drop = {
max_items = 1,
items = {
{items = {'farming:seed_wheat'},rarity = 5},
{items = {'default:grass_1'}},
}
}})
end
minetest.override_item("default:junglegrass", {drop = {
max_items = 1,
items = {
{items = {'farming:seed_cotton'},rarity = 8},
{items = {'default:junglegrass'}},
}
}})
|
Fix desert_sand_soil dropping itself, and changed the descriptions
|
Fix desert_sand_soil dropping itself, and changed the descriptions
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
7d3f355c8e06f6411943ed32d9d51c55c0567a19
|
packages/pullquote.lua
|
packages/pullquote.lua
|
SILE.require("packages/color")
SILE.require("packages/raiselower")
SILE.require("packages/rebox")
SILE.registerCommand("pullquote:font", function (_, _)
end, "The font chosen for the pullquote environment")
SILE.registerCommand("pullquote:author-font", function (_, _)
SILE.settings.set("font.style", "italic")
end, "The font style with which to typeset the author attribution.")
SILE.registerCommand("pullquote:mark-font", function (_, _)
SILE.settings.set("font.family", "Libertinus Serif")
end, "The font from which to pull the quotation marks.")
local typesetMark = function (open, setback, scale, color, mark)
SILE.settings.temporarily(function ()
SILE.call("pullquote:mark-font")
local setwidth = SU.cast("length", setback)
SILE.typesetter:pushGlue({ width = open and -setwidth or setwidth })
SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function ()
SILE.settings.set("font.size", SILE.settings.get("font.size")*scale)
SILE.call("color", { color = color }, function ()
SILE.call("rebox", { width = 0, height = 0 }, { mark })
end)
end)
SILE.typesetter:pushGlue({width = open and setwidth or -setwidth })
end)
end
SILE.registerCommand("pullquote", function (options, content)
local author = options.author or nil
local setback = options.setback or "2em"
local scale = options.scale or 3
local color = options.color or "#999999"
SILE.settings.temporarily(function ()
SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback))
SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback))
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.glue())
SILE.settings.set("current.parindent", SILE.nodefactory.glue())
SILE.call("pullquote:font")
typesetMark(true, setback, scale, color, "“")
SILE.process(content)
SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue())
typesetMark(false, setback, scale, color, "”")
if author then
SILE.settings.temporarily(function ()
SILE.typesetter:leaveHmode()
SILE.call("pullquote:author-font")
SILE.call("raggedleft", {}, function ()
SILE.typesetter:typeset("— " .. author)
end)
end)
else
SILE.call("par")
end
end)
end, "Typesets its contents in a formatted blockquote with decorative quotation\
marks in the margins.")
return { documentation = [[\begin{document}
The \code{pullquote} command formats longer quotations in an indented
blockquote block with decorative quotation marks in the margins.
Here is some text set in a pullquote environment:
\begin[author=Anatole France]{pullquote}
An education is not how much you have committed to memory, or even how much you
know. It is being able to differentiate between what you do know and what you
do not know.
\end{pullquote}
Optional values are available for:
\listitem \code{author} to add an attribution line
\listitem \code{setback} to set the bilateral margins around the block
\listitem \code{color} to change the color of the quote marks
\listitem \code{scale} to change the relative size of the quote marks
If you want to specify what font the pullquote environment should use, you
can redefine the \code{pullquote:font} command. By default it will be the same
as the surrounding document. The font style used for the attribution line
can likewise be set using \code{pullquote:author-font} and the font used for
the quote marks can be set using \code{pullquote:mark-font}.
\end{document}]] }
|
SILE.require("packages/color")
SILE.require("packages/raiselower")
SILE.require("packages/rebox")
SILE.registerCommand("pullquote:font", function (_, _)
end, "The font chosen for the pullquote environment")
SILE.registerCommand("pullquote:author-font", function (_, _)
SILE.settings.set("font.style", "italic")
end, "The font style with which to typeset the author attribution.")
SILE.registerCommand("pullquote:mark-font", function (_, _)
SILE.settings.set("font.family", "Libertinus Serif")
end, "The font from which to pull the quotation marks.")
local typesetMark = function (open, setback, scale, color, mark)
SILE.settings.temporarily(function ()
SILE.call("pullquote:mark-font")
local setwidth = SU.cast("length", setback)
SILE.typesetter:pushGlue({ width = open and -setwidth or setwidth })
SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function ()
SILE.settings.set("font.size", SILE.settings.get("font.size")*scale)
SILE.call("color", { color = color }, function ()
SILE.call("rebox", { width = 0, height = 0 }, { mark })
end)
end)
SILE.typesetter:pushGlue({width = open and setwidth or -setwidth })
end)
end
SILE.registerCommand("pullquote", function (options, content)
local author = options.author or nil
local setback = options.setback or "2em"
local scale = options.scale or 3
local color = options.color or "#999999"
SILE.settings.temporarily(function ()
SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback))
SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback))
SILE.settings.set("current.parindent", SILE.nodefactory.glue())
SILE.call("pullquote:font")
typesetMark(true, setback, scale, color, "“")
SILE.process(content)
SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue())
typesetMark(false, setback, scale, color, "”")
if author then
SILE.settings.temporarily(function ()
SILE.typesetter:leaveHmode()
SILE.call("pullquote:author-font")
SILE.call("raggedleft", {}, function ()
SILE.typesetter:typeset("— " .. author)
end)
end)
else
SILE.call("par")
end
end)
end, "Typesets its contents in a formatted blockquote with decorative quotation\
marks in the margins.")
return { documentation = [[\begin{document}
The \code{pullquote} command formats longer quotations in an indented
blockquote block with decorative quotation marks in the margins.
Here is some text set in a pullquote environment:
\begin[author=Anatole France]{pullquote}
An education is not how much you have committed to memory, or even how much you
know. It is being able to differentiate between what you do know and what you
do not know.
\end{pullquote}
Optional values are available for:
\listitem \code{author} to add an attribution line
\listitem \code{setback} to set the bilateral margins around the block
\listitem \code{color} to change the color of the quote marks
\listitem \code{scale} to change the relative size of the quote marks
If you want to specify what font the pullquote environment should use, you
can redefine the \code{pullquote:font} command. By default it will be the same
as the surrounding document. The font style used for the attribution line
can likewise be set using \code{pullquote:author-font} and the font used for
the quote marks can be set using \code{pullquote:mark-font}.
\end{document}]] }
|
fix(packages): Improve multi-paragraph pullquotes
|
fix(packages): Improve multi-paragraph pullquotes
This removes the stretched lines at the end of every paragraph but the
last, when a `pullquote` (from the `pullquote` package) contains several
paragraphs. It does not fix the bug mentioned in #865.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
b5f916a02f5215ff65d3dcc8f430309ef57044bd
|
argcheck.lua
|
argcheck.lua
|
local env = require 'argcheck.env' -- retrieve argcheck environement
env.istype = function(obj, typename)
if (typename == "Dataframe") then
return torch.isTypeOf(obj, Dataframe)
end
-- Either a number or string
if (typename == "number|string") then
return torch.type(obj) == "number" or
torch.type(obj) == "string"
end
-- Either a number or boolean
if (typename == "number|boolean") then
return torch.type(obj) == "number" or
torch.type(obj) == "boolean"
end
-- Either a boolean or string
if (typename == "string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string"
end
if (typename == "number|string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number"
end
if (typename == "number|string|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number" or
isnan(obj)
end
-- Either a Df_Dict or boolean
if (typename == "Df_Dict|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "Df_Dict"
end
-- Either a Df_Dict or string
if (typename == "Df_Dict|string") then
return torch.type(obj) == "string" or
torch.type(obj) == "Df_Dict"
end
-- Only numerical tensors count
if (typename == "torch.*Tensor") then
-- regular expressions don't work therefore this
return torch.type(obj) == "torch.IntTensor" or
torch.type(obj) == "torch.FloatTensor" or
torch.type(obj) == "torch.DoubleTensor"
end
return torch.type(obj) == typename
end
|
local env = require 'argcheck.env' -- retrieve argcheck environement
env.istype = function(obj, typename)
if (typename == "Dataframe") then
return torch.isTypeOf(obj, Dataframe)
end
-- Either a number or string
if (typename == "number|string") then
return torch.type(obj) == "number" or
torch.type(obj) == "string"
end
-- Either a number or boolean
if (typename == "number|boolean") then
return torch.type(obj) == "number" or
torch.type(obj) == "boolean"
end
-- Either a boolean or string
if (typename == "string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string"
end
if (typename == "number|string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number"
end
if (typename == "number|string|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number" or
isnan(obj)
end
-- Either a Df_Dict or boolean
if (typename == "Df_Dict|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "Df_Dict"
end
-- Either a Df_Dict or string
if (typename == "Df_Dict|string") then
return torch.type(obj) == "string" or
torch.type(obj) == "Df_Dict"
end
-- Only numerical tensors count
if (typename == "torch.*Tensor") then
-- regular expressions don't work therefore this
return torch.type(obj) == "torch.IntTensor" or
torch.type(obj) == "torch.FloatTensor" or
torch.type(obj) == "torch.DoubleTensor"
end
return torch.type(obj) == typename
end
|
Indentation fix for argcheck
|
Indentation fix for argcheck
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
c8a46da97c9a669b18d78ca0e24879c1e480de5d
|
vi_mode_search.lua
|
vi_mode_search.lua
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0x00FFFF
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
-- Hack - need the old FIND_POSIX|FIND_REGEXP, but one's gone.
local search_flags = (_SCINTILLA.constants.FIND_REGEXP + _SCINTILLA.constants.FIND_REGEXP/2)
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer.search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer.goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
keys.vi_search_command = {
['\n'] = function ()
local exit = state.exitfunc
state.exitfunc = nil
return ui_ce.finish_mode(function(text)
if string.len(text) == 0 then
text = state.pattern
end
handle_search_command(text)
exit()
end)
end,
cv = {
['\t'] = function()
local text = ui_ce.entry_text
ui_ce.enter_mode(nil)
ui_ce.entry_text = text .. "\t"
ui_ce.enter_mode("vi_search_command")
end,
},
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.MODE = "vi_command"
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry.entry_text = ""
ui.command_entry.enter_mode('vi_search_command')
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
state.pattern = '\\<' .. word .. '\\>'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0x00FFFF
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
local search_flags = _SCINTILLA.constants.FIND_REGEXP
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer.search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer.goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
keys.vi_search_command = {
['\n'] = function ()
local exit = state.exitfunc
state.exitfunc = nil
return ui_ce.finish_mode(function(text)
if string.len(text) == 0 then
text = state.pattern
end
handle_search_command(text)
exit()
end)
end,
cv = {
['\t'] = function()
local text = ui_ce.entry_text
ui_ce.enter_mode(nil)
ui_ce.entry_text = text .. "\t"
ui_ce.enter_mode("vi_search_command")
end,
},
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.MODE = "vi_command"
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry.entry_text = ""
ui.command_entry.enter_mode('vi_search_command')
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
state.pattern = '\\<' .. word .. '\\>'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
Remove a hacky workaround for 7.0 beta regex search problem, which was causing different problems (setting the WORD_START flag) now that the textadept issue is fixed.
|
Remove a hacky workaround for 7.0 beta regex search problem, which was
causing different problems (setting the WORD_START flag) now that the
textadept issue is fixed.
|
Lua
|
mit
|
jugglerchris/textadept-vi,jugglerchris/textadept-vi,erig0/textadept-vi
|
74bf8c2957820039d8e830e1f3ac584804f6d7ec
|
plugins/mod_roster.lua
|
plugins/mod_roster.lua
|
local st = require "util.stanza"
local send = require "core.sessionmanager".send_to_session
local jid_split = require "util.jid".split;
local t_concat = table.concat;
local rm_remove_from_roster = require "core.rostermanager".remove_from_roster;
local rm_add_to_roster = require "core.rostermanager".add_to_roster;
local rm_roster_push = require "core.rostermanager".roster_push;
add_iq_handler("c2s", "jabber:iq:roster",
function (session, stanza)
if stanza.tags[1].name == "query" then
if stanza.attr.type == "get" then
local roster = st.reply(stanza)
:query("jabber:iq:roster");
for jid in pairs(session.roster) do
if jid ~= "pending" then
roster:tag("item", {
jid = jid,
subscription = session.roster[jid].subscription,
ask = session.roster[jid].ask,
name = session.roster[jid].name,
});
for group in pairs(session.roster[jid].groups) do
roster:tag("group"):text(group):up();
end
roster:up(); -- move out from item
end
end
send(session, roster);
session.interested = true; -- resource is interested in roster updates
return true;
elseif stanza.attr.type == "set" then
local query = stanza.tags[1];
if #query.tags == 1 and query.tags[1].name == "item"
and query.tags[1].attr.xmlns == "jabber:iq:roster" and query.tags[1].attr.jid
and query.tags[1].attr.jid ~= "pending" then
local item = query.tags[1];
local from_node, from_host = jid_split(stanza.attr.from);
local node, host, resource = jid_split(item.attr.jid);
if not resource then
if item.attr.jid ~= from_node.."@"..from_host then
if item.attr.subscription == "remove" then
if session.roster[item.attr.jid] then
local success, err_type, err_cond, err_msg = rm_remove_from_roster(session, item.attr.jid);
if success then
send(session, st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
else
send(session, st.error_reply(stanza, err_type, err_cond, err_msg));
end
else
send(session, st.error_reply(stanza, "modify", "item-not-found"));
end
else
local r_item = {name = item.attr.name, groups = {}};
if r_item.name == "" then r_item.name = nil; end
if session.roster[item.attr.jid] then
r_item.subscription = session.roster[item.attr.jid].subscription;
r_item.ask = session.roster[item.attr.jid].ask;
else
r_item.subscription = "none";
end
for _, child in ipairs(item) do
if child.name == "group" then
local text = t_concat(child);
if text and text ~= "" then
r_item.groups[text] = true;
end
end
end
local success, err_type, err_cond, err_msg = rm_add_to_roster(session, item.attr.jid, r_item);
if success then
send(session, st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
else
send(session, st.error_reply(stanza, err_type, err_cond, err_msg));
end
end
else
send(session, st.error_reply(stanza, "cancel", "not-allowed"));
end
else
send(session, st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error?
end
else
send(session, st.error_reply(stanza, "modify", "bad-request"));
end
return true;
end
end
end);
|
local st = require "util.stanza"
local jid_split = require "util.jid".split;
local t_concat = table.concat;
local rm_remove_from_roster = require "core.rostermanager".remove_from_roster;
local rm_add_to_roster = require "core.rostermanager".add_to_roster;
local rm_roster_push = require "core.rostermanager".roster_push;
add_iq_handler("c2s", "jabber:iq:roster",
function (session, stanza)
if stanza.tags[1].name == "query" then
if stanza.attr.type == "get" then
local roster = st.reply(stanza)
:query("jabber:iq:roster");
for jid in pairs(session.roster) do
if jid ~= "pending" then
roster:tag("item", {
jid = jid,
subscription = session.roster[jid].subscription,
ask = session.roster[jid].ask,
name = session.roster[jid].name,
});
for group in pairs(session.roster[jid].groups) do
roster:tag("group"):text(group):up();
end
roster:up(); -- move out from item
end
end
session.send(roster);
session.interested = true; -- resource is interested in roster updates
return true;
elseif stanza.attr.type == "set" then
local query = stanza.tags[1];
if #query.tags == 1 and query.tags[1].name == "item"
and query.tags[1].attr.xmlns == "jabber:iq:roster" and query.tags[1].attr.jid
and query.tags[1].attr.jid ~= "pending" then
local item = query.tags[1];
local from_node, from_host = jid_split(stanza.attr.from);
local node, host, resource = jid_split(item.attr.jid);
if not resource then
if item.attr.jid ~= from_node.."@"..from_host then
if item.attr.subscription == "remove" then
if session.roster[item.attr.jid] then
local success, err_type, err_cond, err_msg = rm_remove_from_roster(session, item.attr.jid);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
else
session.send(st.error_reply(stanza, "modify", "item-not-found"));
end
else
local r_item = {name = item.attr.name, groups = {}};
if r_item.name == "" then r_item.name = nil; end
if session.roster[item.attr.jid] then
r_item.subscription = session.roster[item.attr.jid].subscription;
r_item.ask = session.roster[item.attr.jid].ask;
else
r_item.subscription = "none";
end
for _, child in ipairs(item) do
if child.name == "group" then
local text = t_concat(child);
if text and text ~= "" then
r_item.groups[text] = true;
end
end
end
local success, err_type, err_cond, err_msg = rm_add_to_roster(session, item.attr.jid, r_item);
if success then
session.send(st.reply(stanza));
rm_roster_push(from_node, from_host, item.attr.jid);
else
session.send(st.error_reply(stanza, err_type, err_cond, err_msg));
end
end
else
session.send(st.error_reply(stanza, "cancel", "not-allowed"));
end
else
session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error?
end
else
session.send(st.error_reply(stanza, "modify", "bad-request"));
end
return true;
end
end
end);
|
Fix mod_roster to use session.send for sending stanzas
|
Fix mod_roster to use session.send for sending stanzas
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
d1ec976464886f8e63b7440abbf1c74d8d8b8553
|
site/api/compose.lua
|
site/api/compose.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is compose.lua - a script for sending replies or new topics to lists
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local user = require 'lib/user'
local config = require 'lib/config'
local smtp = require 'socket.smtp'
local cross = require 'lib/cross'
function handle(r)
local account = user.get(r)
cross.contentType(r, "application/json")
-- make sure the user is logged in
if account and account.cid then
-- parse response, up to 1MB of it. if >1MB, we're gonna pretend we never saw anything ;)
local post = r:parsebody(1024*1024)
-- check that recipient, subject and body exists
if post.to and post.subject and post.body then
-- validate recipient
local to = ("<%s>"):format(post.to)
local fp, lp = post.to:match("([^@]+)@([^@]+)")
local domainIsOkay = false
-- check that recipient is whitelisted in config.lua
if type(config.accepted_domains) == "string" then
if r.strcmp_match(lp, config.accepted_domains) or config.accepted_domains == "*" then
domainIsOkay = true
end
elseif type(config.accepted_domains) == "table" then
for k, ad in pairs(config.accepted_domains) do
if r.strcmp_match(lp, ad) or ad == "*" then
domainIsOkay = true
break
end
end
end
-- if we can send, then...
if domainIsOkay then
-- find user's full name
local fname = nil
if account.preferences then
fname = account.preferences.fullname
end
-- construct sender name+address
local fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, account.credentials.email)
-- Using alt email??
if account.credentials.altemail and post.alt then
for k, v in pairs(account.credentials.altemail) do
if v.email == post.alt then
fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, v.email)
break
end
end
end
-- standard headers + headers we need ourselves for parsing in the archiver (notifications etc)
local headers = {
['Content-Type'] = 'text/plain; charset=utf-8',
['X-PonyMail-Sender'] = r:sha1(account.cid),
['X-PonyMail-Agent'] = "PonyMail Composer/0.2",
['message-id'] = ("<pony-%s-%s@%s>"):format(r:sha1(account.cid), r:sha1(r:clock() .. os.time() .. r.useragent_ip), post.to:gsub("@", ".")),
to = to,
subject = post.subject,
from = fr,
}
-- set references and IRT if need be
if post['references'] then
headers['references'] = post['references']
end
if post['in-reply-to'] then
headers['in-reply-to'] = post['in-reply-to']
end
local msgbody = post.body
-- set an email footer if specified in config.lua
if config.email_footer then
local subs = {
list = to:gsub("[<>]", ""),
domain = r.hostname,
port = r.port,
msgid = headers['message-id']
}
msgbody = msgbody .. "\n" .. config.email_footer:gsub("$([a-z]+)", function(a) return subs[a] or a end)
end
-- construct the smtp object
local source = smtp.message{
headers = headers,
body = msgbody
}
-- send email!
local rv, er = smtp.send{
from = fr,
rcpt = to,
source = source,
server = config.mailserver
}
-- let the user know what happened
r:puts(JSON.encode{
result = rv,
error = er,
src = headers
})
else
r:puts(JSON.encode{
error = "Invalid recipient specified."
})
end
else
r:puts(JSON.encode{
error = "Invalid or missing headers",
headers = post
})
end
else
r:puts[[{"error": "You need to be logged in before you can send emails"}]]
end
return cross.OK
end
cross.start(handle)
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is compose.lua - a script for sending replies or new topics to lists
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local user = require 'lib/user'
local config = require 'lib/config'
local smtp = require 'socket.smtp'
local cross = require 'lib/cross'
function handle(r)
local account = user.get(r)
cross.contentType(r, "application/json")
-- make sure the user is logged in
if account and account.cid then
-- parse response, up to 1MB of it. if >1MB, we're gonna pretend we never saw anything ;)
local post = r:parsebody(1024*1024)
-- check that recipient, subject and body exists
if post.to and post.subject and post.body then
-- validate recipient
local to = ("<%s>"):format(post.to)
local fp, lp = post.to:match("([^@]+)@([^@]+)")
local domainIsOkay = false
-- check that recipient is whitelisted in config.lua
if type(config.accepted_domains) == "string" then
if r.strcmp_match(lp, config.accepted_domains) or config.accepted_domains == "*" then
domainIsOkay = true
end
elseif type(config.accepted_domains) == "table" then
for k, ad in pairs(config.accepted_domains) do
if r.strcmp_match(lp, ad) or ad == "*" then
domainIsOkay = true
break
end
end
end
-- if we can send, then...
if domainIsOkay then
-- find user's full name
local fname = nil
if account.preferences then
fname = account.preferences.fullname
end
-- construct sender name+address
local fr = ([[%s<%s>]]):format(fname or account.credentials.fullname, account.credentials.email)
-- Using alt email??
if account.credentials.altemail and post.alt then
for k, v in pairs(account.credentials.altemail) do
if v.email == post.alt then
fr = ([[%s<%s>]]):format(fname or account.credentials.fullname, v.email)
break
end
end
end
-- standard headers + headers we need ourselves for parsing in the archiver (notifications etc)
local headers = {
['Content-Type'] = 'text/plain; charset=utf-8',
['X-PonyMail-Sender'] = r:sha1(account.cid),
['X-PonyMail-Agent'] = "PonyMail Composer/0.2",
['message-id'] = ("<pony-%s-%s@%s>"):format(r:sha1(account.cid), r:sha1(r:clock() .. os.time() .. r.useragent_ip), post.to:gsub("@", ".")),
to = to,
subject = post.subject,
from = fr,
}
-- set references and IRT if need be
if post['references'] then
headers['references'] = post['references']
end
if post['in-reply-to'] then
headers['in-reply-to'] = post['in-reply-to']
end
local msgbody = post.body
-- set an email footer if specified in config.lua
if config.email_footer then
local subs = {
list = to:gsub("[<>]", ""),
domain = r.hostname,
port = r.port,
msgid = headers['message-id']
}
msgbody = msgbody .. "\n" .. config.email_footer:gsub("$([a-z]+)", function(a) return subs[a] or a end)
end
-- construct the smtp object
local source = smtp.message{
headers = headers,
body = msgbody
}
-- send email!
local rv, er = smtp.send{
from = fr:gsub(".-<", "<"), -- MTAs only need the email address in MAIL FROM, cut out the name.
rcpt = to,
source = source,
server = config.mailserver
}
-- let the user know what happened
r:puts(JSON.encode{
result = rv,
error = er,
src = headers
})
else
r:puts(JSON.encode{
error = "Invalid recipient specified."
})
end
else
r:puts(JSON.encode{
error = "Invalid or missing headers",
headers = post
})
end
else
r:puts[[{"error": "You need to be logged in before you can send emails"}]]
end
return cross.OK
end
cross.start(handle)
|
Fix FROM header and MTA command so emails will get through.
|
Fix FROM header and MTA command so emails will get through.
This fixes #496.
|
Lua
|
apache-2.0
|
jimjag/ponymail,jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,jimjag/ponymail,jimjag/ponymail
|
62766910f70c487c42ded97b324b2fac20349037
|
src_trunk/resources/irc/s_irc.lua
|
src_trunk/resources/irc/s_irc.lua
|
server = "irc.gtanet.com"
port = 6667
username = "ValhallaGaming"
username2 = "ValhallaGaming2"
channel = "#vgmta.admins"
pubchannel = "#mta"
password = "adminmtavg"
conn = nil
conn2 = nil
timer = nil
useSecond = false
function initIRC()
ircInit()
conn = ircOpen(server, port, username, channel, password)
sendMessage("Server Started.")
conn2 = ircOpen(server, port, username2, channel, password)
displayStatus()
timer = setTimer(displayStatus, 300000, 0)
ircJoin(conn, pubchannel)
ircJoin(conn2, pubchannel)
end
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), initIRC)
function stopIRC()
sendMessage("Server Stopped.")
ircPart(conn, channel)
ircDisconnect(conn)
killTimer(timer)
timer = nil
conn = nil
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), stopIRC)
function sendMessage(message)
local time = getRealTime()
local hour = time.hour
local mins = time.minute
hour = hour + 8
if (hour==24) then
hour = 0
elseif (hour>24) then
hour = hour - 24
end
-- Fix time
if (hour<10) then
hour = 0 .. tostring(hour)
end
if (mins<10) then
mins = 0 .. tostring(mins)
end
outputDebugString(tostring(message))
if not (useSecond) then
useSecond = true
ircMessage(conn, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message))
else
useSecond = false
ircMessage(conn2, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message))
end
end
function displayStatus()
local playerCount = getPlayerCount()
local maxPlayers = getMaxPlayers()
local servername = getServerName()
local ip = "67.210.235.106:22003"
local totalping = 0
local averageping = 0
for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do
totalping = totalping + getPlayerPing(value)
end
if (playerCount>0) then
averageping = math.floor(totalping / playerCount)
end
local output = servername .. " - " .. playerCount .. "/" .. maxPlayers .. "(" .. math.ceil((playerCount/maxPlayers)*100) .. "%) - " .. ip .. " - GameMode: Roleplay - Average Ping: " .. averageping .. "."
if not (useSecond) then
useSecond = true
ircMessage(conn, channel, output)
else
useSecond = false
ircMessage(conn2, channel, output)
end
end
|
server = "irc.multitheftauto.com"
port = 6667
username = "ValhallaGaming"
username2 = "ValhallaGaming2"
channel = "#Valhalla.echo"
channeladmins = "#Valhalla.admins"
pubchannel = "#mta"
password = "adminmtavg"
conn = nil
conn2 = nil
timer = nil
useSecond = false
function initIRC()
ircInit()
conn = ircOpen(server, port, username, channel, password)
sendMessage("Server Started.")
conn2 = ircOpen(server, port, username2, channel, password)
displayStatus()
timer = setTimer(displayStatus, 600000, 0)
ircJoin(conn, pubchannel)
ircJoin(conn2, pubchannel)
end
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), initIRC)
function stopIRC()
sendMessage("Server Stopped.")
ircPart(conn, channel)
ircDisconnect(conn)
killTimer(timer)
timer = nil
conn = nil
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), stopIRC)
function sendMessage(message)
local time = getRealTime()
local hour = time.hour
local mins = time.minute
hour = hour + 8
if (hour==24) then
hour = 0
elseif (hour>24) then
hour = hour - 24
end
-- Fix time
if (hour<10) then
hour = 0 .. tostring(hour)
end
if (mins<10) then
mins = 0 .. tostring(mins)
end
outputDebugString(tostring(message))
if not (useSecond) then
useSecond = true
ircMessage(conn, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message))
else
useSecond = false
ircMessage(conn2, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message))
end
end
function displayStatus()
local playerCount = getPlayerCount()
local maxPlayers = getMaxPlayers()
local servername = getServerName()
local ip = "67.210.235.106:22003"
local totalping = 0
local averageping = 0
for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do
totalping = totalping + getPlayerPing(value)
end
if (playerCount>0) then
averageping = math.floor(totalping / playerCount)
end
local output = servername .. " - " .. playerCount .. "/" .. maxPlayers .. "(" .. math.ceil((playerCount/maxPlayers)*100) .. "%) - " .. ip .. " - GameMode: Roleplay - Average Ping: " .. averageping .. "."
if not (useSecond) then
useSecond = true
ircMessage(conn, channel, output)
ircMessage(conn, channeladmins, output)
else
useSecond = false
ircMessage(conn2, channel, output)
ircMessage(conn, channeladmins, output)
end
end
|
Fixed irc
|
Fixed irc
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@543 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
738cc1b0f49bcc3c100f134196d875a7d9d615e4
|
nvim/lua/plugins.lua
|
nvim/lua/plugins.lua
|
-- ensure packer.nvim is installed
local fn = vim.fn
local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path })
vim.cmd("packadd packer.nvim")
end
-- use plugins
require("packer").startup(function(use)
-- packer itself
use("wbthomason/packer.nvim")
-- Load only when require
use({ "nvim-lua/plenary.nvim", module = "plenary" })
use({ "kyazdani42/nvim-web-devicons", module = "nvim-web-devicons" })
-- UI
use({
{
"nvim-treesitter/nvim-treesitter",
event = "BufReadPre",
run = ":TSUpdate",
config = function()
require("nvim-treesitter.configs").setup({
ensure_installed = {
"bash",
"css",
"go",
"gomod",
"hcl",
"html",
"json",
"java",
"javascript",
"lua",
"python",
"typescript",
"vim",
"yaml",
},
highlight = {
enable = true,
},
indent = {
enable = false,
},
autotag = {
enable = true,
},
rainbow = {
enable = true,
extended_mode = true, -- Also highlight non-bracket delimiters like html tags, boolean or table: lang -> boolean
max_file_lines = nil, -- Do not enable for files with more than n lines, int
-- colors = {}, -- table of hex strings
-- termcolors = {} -- table of colour name strings
},
})
end,
},
{ "windwp/nvim-ts-autotag", after = "nvim-treesitter" },
{ "p00f/nvim-ts-rainbow", after = "nvim-treesitter" },
})
use({
"EdenEast/nightfox.nvim",
config = function()
require("nightfox").setup({
options = {
styles = {
comments = "italic",
keywords = "italic",
},
},
})
vim.cmd("colorscheme nordfox")
end,
})
use({
"nvim-lualine/lualine.nvim",
event = "VimEnter",
requires = { "kyazdani42/nvim-web-devicons", opt = true },
config = function()
require("lualine").setup({
tabline = {
lualine_a = { "buffers" },
lualine_b = {},
lualine_c = {},
lualine_x = {},
lualine_y = {},
lualine_z = {},
},
})
end,
})
-- LSP, completion
use({
{
"williamboman/mason.nvim",
event = "VimEnter",
config = function()
require("mason").setup()
end,
},
{
"williamboman/mason-lspconfig.nvim",
config = function()
require("mason-lspconfig").setup({
ensure_installed = {
-- 'gopls',
"pyright",
"sumneko_lua",
-- 'terraformls',
"tsserver",
},
})
end,
-- mason-lspconfig requires nvim-lspconfig, so we have to load it first
after = "nvim-lspconfig",
},
{
"neovim/nvim-lspconfig",
event = "BufReadPre",
config = function()
require("plugins.lsp")
end,
},
{
"glepnir/lspsaga.nvim",
branch = "main",
config = function()
require("lspsaga").init_lsp_saga({
code_action_icon = "",
})
end,
after = "nvim-lspconfig",
},
})
use({
"jose-elias-alvarez/null-ls.nvim",
event = "BufRead",
config = function()
require("plugins.null-ls")
end,
})
use({
{
"hrsh7th/nvim-cmp",
event = "InsertEnter",
config = function()
require("plugins.cmp")
end,
requires = {
{
"L3MON4D3/LuaSnip",
event = "InsertEnter",
config = function()
require("plugins.luasnip")
end,
requires = {
{
"rafamadriz/friendly-snippets",
event = "InsertEnter",
},
},
},
},
},
{
"zbirenbaum/copilot-cmp",
event = "VimEnter",
requires = {
{
"zbirenbaum/copilot.lua",
event = "VimEnter",
config = function()
vim.defer_fn(function()
require("copilot").setup()
end, 100)
end,
},
},
},
{ "tzachar/cmp-tabnine", after = "nvim-cmp", run = "./install.sh" },
{ "saadparwaiz1/cmp_luasnip", after = "nvim-cmp" },
{ "hrsh7th/cmp-path", after = "nvim-cmp" },
{ "hrsh7th/cmp-buffer", after = "nvim-cmp" },
{ "hrsh7th/cmp-nvim-lsp", after = "nvim-cmp" },
})
use({
"github/copilot.vim",
-- copilot.lua needs it for the authentication, at least for now
cond = false,
config = function()
vim.g.copilot_filetypes = {
markdown = true,
yaml = true,
}
end,
})
-- utils
use({
"norcalli/nvim-colorizer.lua",
event = "BufRead",
config = function()
require("colorizer").setup()
end,
})
use({
"lewis6991/gitsigns.nvim",
event = "BufRead",
requires = { "nvim-lua/plenary.nvim" },
config = function()
require("plugins.gitsigns")
end,
})
use({
"lukas-reineke/indent-blankline.nvim",
event = "BufRead",
config = function()
require("indent_blankline").setup({
show_end_of_line = true,
})
end,
})
use({
"ggandor/lightspeed.nvim",
event = "BufRead",
})
use({
{
"nvim-telescope/telescope.nvim",
event = "VimEnter",
requires = { { "nvim-lua/plenary.nvim" } },
config = function()
require("plugins.telescope")
end,
},
{
"nvim-telescope/telescope-fzf-native.nvim",
after = "telescope.nvim",
run = "make",
config = function()
---@diagnostic disable-next-line: different-requires
require("telescope").load_extension("fzf")
end,
},
})
use({
"windwp/nvim-autopairs",
event = "InsertCharPre",
-- load after nvim-cmp to ensure <CR> works correctly
after = "nvim-cmp",
config = function()
require("nvim-autopairs").setup()
-- integration with nvim-cmp
---@diagnostic disable-next-line: different-requires
require("cmp").event:on("confirm_done", require("nvim-autopairs.completion.cmp").on_confirm_done())
end,
})
use({
"b3nj5m1n/kommentary",
event = "BufRead",
})
use({
"ntpeters/vim-better-whitespace",
event = "BufRead",
})
use({
"tpope/vim-surround",
event = "BufRead",
requires = {
{
"tpope/vim-repeat",
event = "BufRead",
},
},
})
use({
"tpope/vim-abolish",
event = "BufRead",
})
end)
|
-- ensure packer.nvim is installed
local fn = vim.fn
local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path })
vim.cmd("packadd packer.nvim")
end
-- use plugins
require("packer").startup(function(use)
-- packer itself
use("wbthomason/packer.nvim")
-- Load only when require
use({ "nvim-lua/plenary.nvim", module = "plenary" })
use({ "kyazdani42/nvim-web-devicons", module = "nvim-web-devicons" })
-- UI
use({
{
"nvim-treesitter/nvim-treesitter",
event = "BufReadPre",
run = ":TSUpdate",
config = function()
require("nvim-treesitter.configs").setup({
ensure_installed = {
"bash",
"css",
"go",
"gomod",
"hcl",
"html",
"json",
"java",
"javascript",
"lua",
"python",
"typescript",
"vim",
"yaml",
},
highlight = {
enable = true,
},
indent = {
enable = false,
},
autotag = {
enable = true,
},
rainbow = {
enable = true,
extended_mode = true, -- Also highlight non-bracket delimiters like html tags, boolean or table: lang -> boolean
max_file_lines = nil, -- Do not enable for files with more than n lines, int
-- colors = {}, -- table of hex strings
-- termcolors = {} -- table of colour name strings
},
})
end,
},
{ "windwp/nvim-ts-autotag", after = "nvim-treesitter" },
{ "p00f/nvim-ts-rainbow", after = "nvim-treesitter" },
})
use({
"EdenEast/nightfox.nvim",
config = function()
require("nightfox").setup({
options = {
styles = {
comments = "italic",
keywords = "italic",
},
},
})
vim.cmd("colorscheme nordfox")
end,
})
use({
"nvim-lualine/lualine.nvim",
event = "VimEnter",
requires = { "kyazdani42/nvim-web-devicons", opt = true },
config = function()
require("lualine").setup({
tabline = {
lualine_a = { "buffers" },
lualine_b = {},
lualine_c = {},
lualine_x = {},
lualine_y = {},
lualine_z = {},
},
})
end,
})
-- LSP, completion
use({
{
"williamboman/mason.nvim",
event = "VimEnter",
config = function()
require("mason").setup()
end,
},
{
"williamboman/mason-lspconfig.nvim",
config = function()
require("mason-lspconfig").setup({
ensure_installed = {
-- 'gopls',
"pyright",
"sumneko_lua",
-- 'terraformls',
"tsserver",
},
})
end,
-- mason-lspconfig requires nvim-lspconfig, so we have to load it first
after = { "nvim-lspconfig", "mason.nvim" },
},
{
"neovim/nvim-lspconfig",
event = "BufReadPre",
config = function()
require("plugins.lsp")
end,
requires = {
-- cmp-nvim-lsp is needed to update lsp client capabilities
{ "hrsh7th/cmp-nvim-lsp", module = "cmp_nvim_lsp" },
},
},
{
"glepnir/lspsaga.nvim",
branch = "main",
config = function()
require("lspsaga").init_lsp_saga({
code_action_icon = "",
})
end,
after = "nvim-lspconfig",
},
})
use({
"jose-elias-alvarez/null-ls.nvim",
event = "BufRead",
config = function()
require("plugins.null-ls")
end,
})
use({
{
"hrsh7th/nvim-cmp",
event = "InsertEnter",
config = function()
require("plugins.cmp")
end,
requires = {
{
"L3MON4D3/LuaSnip",
event = "InsertEnter",
config = function()
require("plugins.luasnip")
end,
requires = {
{
"rafamadriz/friendly-snippets",
event = "InsertEnter",
},
},
},
},
},
{
"zbirenbaum/copilot-cmp",
event = "VimEnter",
requires = {
{
"zbirenbaum/copilot.lua",
event = "VimEnter",
config = function()
vim.defer_fn(function()
require("copilot").setup()
end, 100)
end,
},
},
},
{ "tzachar/cmp-tabnine", after = "nvim-cmp", run = "./install.sh" },
{ "saadparwaiz1/cmp_luasnip", after = "nvim-cmp" },
{ "hrsh7th/cmp-path", after = "nvim-cmp" },
{ "hrsh7th/cmp-buffer", after = "nvim-cmp" },
})
use({
"github/copilot.vim",
-- copilot.lua needs it for the authentication, at least for now
cond = false,
config = function()
vim.g.copilot_filetypes = {
markdown = true,
yaml = true,
}
end,
})
-- utils
use({
"norcalli/nvim-colorizer.lua",
event = "BufRead",
config = function()
require("colorizer").setup()
end,
})
use({
"lewis6991/gitsigns.nvim",
event = "BufRead",
requires = { "nvim-lua/plenary.nvim" },
config = function()
require("plugins.gitsigns")
end,
})
use({
"lukas-reineke/indent-blankline.nvim",
event = "BufRead",
config = function()
require("indent_blankline").setup({
show_end_of_line = true,
})
end,
})
use({
"ggandor/lightspeed.nvim",
event = "BufRead",
})
use({
{
"nvim-telescope/telescope.nvim",
event = "VimEnter",
requires = { { "nvim-lua/plenary.nvim" } },
config = function()
require("plugins.telescope")
end,
},
{
"nvim-telescope/telescope-fzf-native.nvim",
after = "telescope.nvim",
run = "make",
config = function()
---@diagnostic disable-next-line: different-requires
require("telescope").load_extension("fzf")
end,
},
})
use({
"windwp/nvim-autopairs",
event = "InsertCharPre",
-- load after nvim-cmp to ensure <CR> works correctly
after = "nvim-cmp",
config = function()
require("nvim-autopairs").setup()
-- integration with nvim-cmp
---@diagnostic disable-next-line: different-requires
require("cmp").event:on("confirm_done", require("nvim-autopairs.completion.cmp").on_confirm_done())
end,
})
use({
"b3nj5m1n/kommentary",
event = "BufRead",
})
use({
"ntpeters/vim-better-whitespace",
event = "BufRead",
})
use({
"tpope/vim-surround",
event = "BufRead",
requires = {
{
"tpope/vim-repeat",
event = "BufRead",
},
},
})
use({
"tpope/vim-abolish",
event = "BufRead",
})
end)
|
fix plugin loading order
|
fix plugin loading order
|
Lua
|
mit
|
zhyu/dotfiles
|
2a3410d735876a1ade47eaf3a1f8a32c997f11c2
|
Skins/ModernGadgets/@Resources/Scripts/LoadSkin.lua
|
Skins/ModernGadgets/@Resources/Scripts/LoadSkin.lua
|
--[[
--------------------------------------------------
LOADSKIN.LUA
raiguard
v3.0.1
--------------------------------------------------
Release Notes:
v3.0.1 - 2018-10-28
- Fixed script crashing if called through inline LUA
v3.0.0 - 2018-10-28
- Redesigned script to simplify the required inputs
- Improved documentation
v2.0.0 - 2018-6-22
- Updated to use the new ConfigActive plugin rather than WebParser
v1.3.0 - 2018-6-21
- The script now gets the input from a WebParser measure, rather than directly parsing
Rainmeter.ini (for Rainmeter 4.2+ compatibility)
v1.2.0 - 2017-12-27
- Added ability to specifically load or unload skins, rather than always toggling them
v1.1.0 - 2017-12-7
- Consolidated LoadConfig() into LoadSkin()
v1.0.0 - 2017-10-2
- Initial release
--------------------------------------------------
This script loads / unlaods the specified skin or config, and sets parameters for toggle
buttons related to those skins.
INSTRUCTIONS FOR USE:
Copy this file and paste it into your own suite. First, you will need to create a
ConfigActive plugin measure:
[MeasureConfigActive]
Measure=Plugin
Plugin=ConfigActive
That's all you need to add to this measure, the script will handle the rest. Speaking of
the script, that is the next measure you need to create:
[MeasureLoadSkinScript]
Measure=Script
ScriptFile=#@#Scripts\LoadSkin.lua
ToggleOn=#@#Images\toggle-on.png
ToggleOff=#@#Images\toggle-off.png
ToggleGroup=ToggleButtons
MeasureName=MeasureConfigActive
The 'ToggleOn' and 'ToggleOff' parameters are for the toggle buttons. If you are using
images, these will be the image paths for the buttons' respective on and off states. If
you are using strings, these will be the 'on' and 'off' strings that will show on the
buttons. If you do not include these parameters, the script will default to 'Enabled'
and 'Disabled' respectively.
There are also optional 'RadioOn' and 'RadioOff' options for the script measure. This
allows you to specify a different set of images or strings for 'radio buttons', usually
to have buttons that will load different variants of a config. These options are
optional, and if left unspecified, will be defined as what you set in 'ToggleOn' and
'ToggleOff' respectively.
The 'ToggleGroup' parameter specifies the group that the toggle button meters belong to.
If you do not include this option, it will default to 'SkinToggles'.
Last but not least, the 'MeasureName' option is simply the name of the ConfigActive
measure that you created before. If unspecified, it will default to 'MeasureConfigActive'.
A toggle button meter should look something like this:
[MeterToggleSystem]
Meter=Image
ImageName=[&MeasureLoadSkinScript:GetIcon('illustro\\System')]
X=5
Y=5
W=31
H=20
LeftMouseUpAction=[!CommandMeasure MeasureLoadSkinScript "ToggleSkin('illustro\\System')"]
DynamicVariables=1
Group=SkinToggles
The toggle buttons get their parameters via inline LUA, which requires that
'DynamicVariables=1' must be set on all the buttons. The buttons must also belong to the
group specified in the script measure.
Obviously, if you are using strings as your buttons, the inline LUA will be contained in
the 'Text' option, rather than 'ImageName'.
--------------------------------------------------
]]--
function Initialize()
toggleOn = SELF:GetOption('ToggleOn', SKIN:GetVariable('toggleOn'))
toggleOff = SELF:GetOption('ToggleOff', SKIN:GetVariable('toggleOff'))
radioOn = SELF:GetOption('RadioOn', toggleOn)
radioOff = SELF:GetOption('RadioOff', toggleOff)
toggleGroup = SELF:GetOption('ToggleGroup', 'SkinToggles')
caMeasureName = SELF:GetOption('MeasureName', 'MeasureConfigActive')
measureCA = SKIN:GetMeasure(caMeasureName)
end
function Update() end
-- toggles or sets the specified skin or config
function ToggleSkin(configName, iniName, toState)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
configName: the name of the config you wish to toggle (e.g. 'illustro\\Disk')
iniName (optional): the name of the skin INI you wish to toggle (e.g. '1 Disk.ini')
toState (optional): the state you wish to set the skin to (1 for active, -1 for inactive)
]]--
local configState, activeIni = GetConfigState(configName)
local toState = toState or iniName and (iniName == activeIni and -1 or 1) or configState * -1
if toState == 1 then
if iniName == nil then
SKIN:Bang('!ActivateConfig', configName)
elseif iniName ~= activeIni then
SKIN:Bang('!ActivateConfig', configName, iniName)
end
elseif configState == 1 then
SKIN:Bang('!DeactivateConfig', configName)
end
SKIN:Bang('!UpdateMeterGroup', toggleGroup)
SKIN:Bang('!Redraw')
return ''
end
-- returns the corresponding button state
function GetIcon(configName, iniName, radio)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
configName: the name of the relevant config (e.g. 'illustro\\Disk')
iniName (optional): the name of the relevant INI file (e.g. '1 Disk.ini')
radio: if set to true, the function will return the 'radioOn' and 'radioOff' options,
instead of 'toggleOn' and 'toggleOff'
]]--
local configState, activeIni = GetConfigState(configName)
-- determine which icon to provide
if iniName then
if configState == 1 and activeIni == iniName then return radio and radioOn or toggleOn
else return radio and radioOff or toggleOff end
else
if configState == 1 then return radio and radioOn or toggleOn
else return radio and radioOff or toggleOff end
end
end
-- retrieves config state and active INI
function GetConfigState(configName)
SKIN:Bang('!SetOption', caMeasureName, 'ConfigName', configName)
SKIN:Bang('!UpdateMeasure', caMeasureName)
return measureCA:GetValue(), -- active state of the config (1 or -1)
measureCA:GetStringValue() -- name of the currently active INI (if inactive, returns -1)
end
|
--[[
--------------------------------------------------
LOADSKIN.LUA
raiguard
v3.0.1
--------------------------------------------------
Release Notes:
v3.0.1 - 2018-10-28
- Changed default toggle values back to the #toggleOn# and #toggleOff# variables
- Fixed script crashing if called through inline LUA
v3.0.0 - 2018-10-28
- Redesigned script to simplify the required inputs
- Improved documentation
v2.0.0 - 2018-6-22
- Updated to use the new ConfigActive plugin rather than WebParser
v1.3.0 - 2018-6-21
- The script now gets the input from a WebParser measure, rather than directly parsing
Rainmeter.ini (for Rainmeter 4.2+ compatibility)
v1.2.0 - 2017-12-27
- Added ability to specifically load or unload skins, rather than always toggling them
v1.1.0 - 2017-12-7
- Consolidated LoadConfig() into LoadSkin()
v1.0.0 - 2017-10-2
- Initial release
--------------------------------------------------
This script loads / unlaods the specified skin or config, and sets parameters for toggle
buttons related to those skins.
INSTRUCTIONS FOR USE:
Copy this file and paste it into your own suite. First, you will need to create a
ConfigActive plugin measure:
[MeasureConfigActive]
Measure=Plugin
Plugin=ConfigActive
That's all you need to add to this measure, the script will handle the rest. Speaking of
the script, that is the next measure you need to create:
[MeasureLoadSkinScript]
Measure=Script
ScriptFile=#@#Scripts\LoadSkin.lua
ToggleOn=#@#Images\toggle-on.png
ToggleOff=#@#Images\toggle-off.png
ToggleGroup=ToggleButtons
MeasureName=MeasureConfigActive
The 'ToggleOn' and 'ToggleOff' parameters are for the toggle buttons. If you are using
images, these will be the image paths for the buttons' respective on and off states. If
you are using strings, these will be the 'on' and 'off' strings that will show on the
buttons. If you do not include these parameters, the script will default to 'Enabled'
and 'Disabled' respectively.
There are also optional 'RadioOn' and 'RadioOff' options for the script measure. This
allows you to specify a different set of images or strings for 'radio buttons', usually
to have buttons that will load different variants of a config. These options are
optional, and if left unspecified, will be defined as what you set in 'ToggleOn' and
'ToggleOff' respectively.
The 'ToggleGroup' parameter specifies the group that the toggle button meters belong to.
If you do not include this option, it will default to 'SkinToggles'.
Last but not least, the 'MeasureName' option is simply the name of the ConfigActive
measure that you created before. If unspecified, it will default to 'MeasureConfigActive'.
A toggle button meter should look something like this:
[MeterToggleSystem]
Meter=Image
ImageName=[&MeasureLoadSkinScript:GetIcon('illustro\\System')]
X=5
Y=5
W=31
H=20
LeftMouseUpAction=[!CommandMeasure MeasureLoadSkinScript "ToggleSkin('illustro\\System')"]
DynamicVariables=1
Group=SkinToggles
The toggle buttons get their parameters via inline LUA, which requires that
'DynamicVariables=1' must be set on all the buttons. The buttons must also belong to the
group specified in the script measure.
Obviously, if you are using strings as your buttons, the inline LUA will be contained in
the 'Text' option, rather than 'ImageName'.
--------------------------------------------------
]]--
function Initialize()
toggleOn = SELF:GetOption('ToggleOn', SKIN:GetVariable('toggleOn'))
toggleOff = SELF:GetOption('ToggleOff', SKIN:GetVariable('toggleOff'))
radioOn = SELF:GetOption('RadioOn', toggleOn)
radioOff = SELF:GetOption('RadioOff', toggleOff)
toggleGroup = SELF:GetOption('ToggleGroup', 'SkinToggles')
caMeasureName = SELF:GetOption('MeasureName', 'MeasureConfigActive')
measureCA = SKIN:GetMeasure(caMeasureName)
end
function Update() end
-- toggles or sets the specified skin or config
function ToggleSkin(configName, iniName, toState)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
configName: the name of the config you wish to toggle (e.g. 'illustro\\Disk')
iniName (optional): the name of the skin INI you wish to toggle (e.g. '1 Disk.ini')
toState (optional): the state you wish to set the skin to (1 for active, -1 for inactive)
]]--
local configState, activeIni = GetConfigState(configName)
local toState = toState or iniName and (iniName == activeIni and -1 or 1) or configState * -1
if toState == 1 then
if iniName == nil then
SKIN:Bang('!ActivateConfig', configName)
elseif iniName ~= activeIni then
SKIN:Bang('!ActivateConfig', configName, iniName)
end
elseif configState == 1 then
SKIN:Bang('!DeactivateConfig', configName)
end
SKIN:Bang('!UpdateMeterGroup', toggleGroup)
SKIN:Bang('!Redraw')
return ''
end
-- returns the corresponding button state
function GetIcon(configName, iniName, radio)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
configName: the name of the relevant config (e.g. 'illustro\\Disk')
iniName (optional): the name of the relevant INI file (e.g. '1 Disk.ini')
radio: if set to true, the function will return the 'radioOn' and 'radioOff' options,
instead of 'toggleOn' and 'toggleOff'
]]--
local configState, activeIni = GetConfigState(configName)
-- determine which icon to provide
if iniName then
if configState == 1 and activeIni == iniName then return radio and radioOn or toggleOn
else return radio and radioOff or toggleOff end
else
if configState == 1 then return radio and radioOn or toggleOn
else return radio and radioOff or toggleOff end
end
end
-- retrieves config state and active INI
function GetConfigState(configName)
SKIN:Bang('!SetOption', caMeasureName, 'ConfigName', configName)
SKIN:Bang('!UpdateMeasure', caMeasureName)
return measureCA:GetValue(), -- active state of the config (1 or -1)
measureCA:GetStringValue() -- name of the currently active INI (if inactive, returns -1)
end
|
Fix loadskin changelog
|
Fix loadskin changelog
|
Lua
|
mit
|
raiguard/ModernGadgets,raiguard/ModernGadgets,iamanai/ModernGadgets,raiguard/ModernGadgets,iamanai/ModernGadgets
|
325485e3cff4adea35c3c6e5db7964c3b78b59a0
|
net/xmppclient_listener.lua
|
net/xmppclient_listener.lua
|
local logger = require "logger";
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local sm_new_session = require "core.sessionmanager".new_session;
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session; --import("core.sessionmanager", "new_session", "destroy_session");
local sm_streamopened = sessionmanager.streamopened;
local st = stanza;
local sessions = {};
local xmppclient = { default_port = 5222 };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, sm_streamopened), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
parser:parse(data);
end
return true;
end
-- End of session methods --
function xmppclient.listener(conn, data)
local session = sessions[conn];
if not session then
session = sm_new_session(conn);
sessions[conn] = session;
-- Logging functions --
local mainlog, log = log;
do
local conn_name = tostring(conn):match("[a-f0-9]+$");
log = logger.init(conn_name);
end
local print = function (...) log("info", t_concatall({...}, "\t")); end
session.log = log;
print("Client connected");
session.reset_stream = session_reset_stream;
session_reset_stream(session); -- Initialise, ready for use
-- TODO: Below function should be session,stanza - and xmlhandlers should use :method() notation to call,
-- this will avoid the useless indirection we have atm
-- (I'm on a mission, no time to fix now)
-- Debug version --
local function handleerr(err) print("Traceback:", err, debug.traceback()); end
session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
-- session.stanza_dispatch = function (stanza) return core_process_stanza(session, stanza); end
end
if data then
session.data(conn, data);
end
end
function xmppclient.disconnect(conn)
local session = sessions[conn];
if session then
if session.last_presence and session.last_presence.attr.type ~= "unavailable" then
local pres = st.presence{ type = "unavailable" };
if err == "closed" then err = "connection closed"; end --FIXME where did err come from?
pres:tag("status"):text("Disconnected: "..err);
session.stanza_dispatch(pres);
end
sm_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
connlisteners_register("xmppclient", xmppclient);
|
local logger = require "logger";
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local sm_new_session = require "core.sessionmanager".new_session;
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session; --import("core.sessionmanager", "new_session", "destroy_session");
local sm_streamopened = sessionmanager.streamopened;
local st = stanza;
local sessions = {};
local xmppclient = { default_port = 5222 };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, sm_streamopened), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
parser:parse(data);
end
return true;
end
-- End of session methods --
function xmppclient.listener(conn, data)
local session = sessions[conn];
if not session then
session = sm_new_session(conn);
sessions[conn] = session;
-- Logging functions --
local mainlog, log = log;
do
local conn_name = tostring(conn):match("[a-f0-9]+$");
log = logger.init(conn_name);
end
local print = function (...) log("info", t_concatall({...}, "\t")); end
session.log = log;
print("Client connected");
session.reset_stream = session_reset_stream;
session_reset_stream(session); -- Initialise, ready for use
-- TODO: Below function should be session,stanza - and xmlhandlers should use :method() notation to call,
-- this will avoid the useless indirection we have atm
-- (I'm on a mission, no time to fix now)
-- Debug version --
local function handleerr(err) print("Traceback:", err, debug.traceback()); end
session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
-- session.stanza_dispatch = function (stanza) return core_process_stanza(session, stanza); end
end
if data then
session.data(conn, data);
end
end
function xmppclient.disconnect(conn, err)
local session = sessions[conn];
if session then
if session.presence and session.presence.attr.type ~= "unavailable" then
local pres = st.presence{ type = "unavailable" };
if err == "closed" then err = "connection closed"; end
pres:tag("status"):text("Disconnected: "..err);
session.stanza_dispatch(pres);
end
session.log("info", "Client disconnected: %s", err);
sm_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
connlisteners_register("xmppclient", xmppclient);
|
Fix logging of disconnect reason, and also sending of unavailable presence on disconnect
|
Fix logging of disconnect reason, and also sending of unavailable presence on disconnect
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
c635aa3aca47dcf7116784d3dd2e433e6fe743b4
|
src/main/resources/std/table.lua
|
src/main/resources/std/table.lua
|
-- Copyright (c) 2018. tangzx([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- 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.
---@class table
table = {}
---
--- Given a list where all elements are strings or numbers, returns the string
--- `list[i]..sep..list[i+1] ... sep..list[j]`. The default value for
--- `sep` is the empty string, the default for `i` is 1, and the default for
--- `j` is #list. If `i` is greater than `j`, returns the empty string.
---@overload fun(t:table, sep:string):string
---@param list table
---@param optional sep string
---@param optional i number
---@param optional j number
---@return string
function table.concat(list, sep, i, j) end
---
--- Inserts element `value` at position `pos` in `list`, shifting up the
--- elements to `list[pos]`, `list[pos+1]`, `···`, `list[#list]`. The default
--- value for `pos` is ``#list+1`, so that a call `table.insert(t,x)`` inserts
--- `x` at the end of list `t`.
---@overload fun(t:table, value:any):void
---@param list table
---@param optional pos number
---@param value any
function table.insert(list, pos, value) end
---
--- Returns the largest positive numerical index of the given table, or
--- zero if the table has no positive numerical indices. (To do its job this
--- function does a linear traversal of the whole table.)
---@param t table
---@return string
function table.maxn(t) return 0 end
---
--- Removes from `table` the element at position `pos`, shifting down other
--- elements to close the space, if necessary. Returns the value of the removed
--- element. The default value for `pos` is `n`, where `n` is the length of the
--- table, so that a call `table.remove(t)` removes the last element of table
--- `t`.
---@overload fun(t:table):void
---@param t table
---@param pos number
function table.remove(t, pos) end
---
--- Sorts table elements in a given order,
--- *in-place*, from `table[1]` to `table[n]`, where `n` is the length of the
--- table. If `comp` is given, then it must be a function that receives two
--- table elements, and returns true when the first is less than the second
--- (so that `not comp(a[i+1],a[i])` will be true after the sort). If `comp`
--- is not given, then the '<' operator will be used.
---@param t table
---@param comp fun(a:any, b:any):number
function table.sort(t, comp) end
return table
|
-- Copyright (c) 2018. tangzx([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- 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.
table = {}
---
--- Given a list where all elements are strings or numbers, returns the string
--- `list[i]..sep..list[i+1] ... sep..list[j]`. The default value for
--- `sep` is the empty string, the default for `i` is 1, and the default for
--- `j` is #list. If `i` is greater than `j`, returns the empty string.
---@overload fun(t:table, sep:string):string
---@param list table
---@param optional sep string
---@param optional i number
---@param optional j number
---@return string
function table.concat(list, sep, i, j) end
---
--- Inserts element `value` at position `pos` in `list`, shifting up the
--- elements to `list[pos]`, `list[pos+1]`, `···`, `list[#list]`. The default
--- value for `pos` is ``#list+1`, so that a call `table.insert(t,x)`` inserts
--- `x` at the end of list `t`.
---@overload fun(t:table, pos:number, value:any):number
---@param list table
---@param optional pos number
---@param value any
---@return number
function table.insert(list, pos, value) end
---
--- Moves elements from table a1 to table `a2`, performing the equivalent to
--- the following multiple assignment: `a2[t]`,`··· = a1[f]`,`···,a1[e]`. The
--- default for `a2` is `a1`. The destination range can overlap with the source
--- range. The number of elements to be moved must fit in a Lua integer.
---
--- Returns the destination table `a2`.
---@param a1 table
---@param f number
---@param e number
---@param t number
---@param optional a2 table
---@return table
function table.move(a1, f, e, t, a2) end
---
--- Returns a new table with all arguments stored into keys 1, 2, etc. and
--- with a field "`n`" with the total number of arguments. Note that the
--- resulting table may not be a sequence, if some arguments are **nil**.
---@return table
function table.pack(···) end
---
--- Removes from `table` the element at position `pos`, shifting down other
--- elements to close the space, if necessary. Returns the value of the removed
--- element. The default value for `pos` is `n`, where `n` is the length of the
--- table, so that a call `table.remove(t)` removes the last element of table
--- `t`.
---@overload fun(t:table, pos:number):any
---@param t table
---@param optional pos number
---@return any
function table.remove(t, pos) end
---
--- Sorts table elements in a given order, *in-place*, from `table[1]` to
--- `table[n]`, where `n` is the length of the table. If `comp` is given,
--- then it must be a function that receives two table elements, and returns
--- true when the first is less than the second in the final order (so that,
--- after the `sort`, `i < j` implies `not comp(a[i+1], a[i])`. If comp is
--- not given, then the standard Lua operator `<` is used instead.
---
--- Note that the comp function must define a strict partial order over the
--- elements in the list; that is, it must be asymmetric and transitive.
--- Otherwise, no valid sort may be possible.
---
--- The sort algorithm is not stable: elements considered equal by the given
--- order may have their relative positions changed by the sort.
---@param t table
---@param optional comp fun(a:any, b:any):number
---@return number
function table.sort(t, comp) end
return table
|
fix params, return types and doc
|
fix params, return types and doc
Check params and return types for rightness.
|
Lua
|
apache-2.0
|
tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
|
b85c830564ac6417650ba23f24b63150003283cd
|
rbm.lua
|
rbm.lua
|
require('nn')
require('pl')
require('torch')
require('rbm-util')
require('rbm-regularization')
require('rbm-grads')
require ('socket') -- for timing
function rbmtrain(rbm,x_train,y_train,x_val,y_val,x_semisup)
-- train RBM
-- Reset gradient accums
-- Print rbm
--print(x_train)
--print(y_train)
--print(x_val)
--print(y_val)
--print(x_semisup)
printRBM(rbm,x_train,x_val,x_semisup)
rbm.time = {}
local x_tr,y_tr,x_semi, total_time, epoch_time,acc_train
local best_val_err = 1/0
local patience = rbm.patience
total_time = socket.gettime()
for epoch = 1, rbm.numepochs do
epoch_time = socket.gettime()
rbm.cur_err = torch.zeros(1)
for i = 1, x_train:size(1) do -- iter over samples
x_tr,y_tr,x_semi = getsamples(rbm,x_train,y_train,x_semisup,i)
regularization.applydropoutordropconnect(rbm) -- cp org weights, drops weights if enabled
grads.calculategrads(rbm,x_tr,y_tr,x_semi) -- calculates dW, dU, db, dc and dd
regularization.applyregularization(rbm) -- regularizes dW, dU, db, dc and dd
updategradsandmomentum(rbm)
-- update vW, vU, vb, vc and vd, formulae: vx = vX*mom + dX
restoreorgweights(rbm) -- restore weights from before dropping
updateweights(rbm) -- updates W,U,b,c and d, formulae: X = X + vX
if (i % 5000) == 0 then
io.write(".")
io.flush()
end
if (i % 100) == 0 then
collectgarbage()
end
end -- samples loop
epoch_time = socket.gettime() - epoch_time
rbm.err_recon_train[epoch] = rbm.cur_err:div(rbm.n_samples)
--timer = torch.Timer()
err_train = 1-accuracy(rbm,x_train,y_train)
rbm.err_train[epoch] = err_train
--print(timer:time().real)
if x_val and y_val then
err_val = 1-accuracy(rbm,x_val,y_val)
rbm.err_val[epoch] = err_val
if err_val < best_val_err then
best_val_err = err_val
patience = rbm.patience
saverbm(rbm.tempfile,rbm) -- save current best
best_rbm = cprbm(rbm) -- save best weights
best = '***'
else
patience = patience - 1
end
end
print(string.format("%i/%i -LR: %f, MOM %f - Recon err: %4.1f err TR: %f err VAL: %f time: %f Patience %i %s", epoch, rbm.numepochs, rbm.learningrate,rbm.momentum, rbm.cur_err[1],err_train,err_val or 1/0,epoch_time, patience,best or ''))
if patience < 0 then -- Stop training
-- Cp weights from best_rbm
rbm.W = best_rbm.W:clone()
rbm.U = best_rbm.U:clone()
rbm.b = best_rbm.b:clone()
rbm.c = best_rbm.c:clone()
rbm.d = best_rbm.d:clone()
break
end
end
total_time = socket.gettime() - total_time
print("Mean epoch time:", total_time / rbm.numepochs)
return(rbm)
end
function getsamples(rbm,x_train,y_train,x_semisup,i_tr)
local x_tr, y_tr
x_tr = x_train[i_tr]:resize(1,x_train:size(2))
y_tr = y_train[i_tr]:resize(1,y_train:size(2))
if rbm.beta > 0 then
i_semi = (i_tr-1) % x_semisup:size(1) +1;
x_semi = x_semisup[i_tr]:resize(1,x_semisup:size(2))
end
return x_tr,y_tr,x_semi
end
function updategradsandmomentum(rbm)
-- multiply updates by learningrate
rbm.dW:mul(rbm.learningrate)
rbm.dU:mul(rbm.learningrate)
rbm.db:mul(rbm.learningrate)
rbm.dc:mul(rbm.learningrate)
rbm.dd:mul(rbm.learningrate)
-- If momentum is zero this will be zero
--if momentum > 0 then
if rbm.momentum > 0 then
rbm.vW:mul(rbm.momentum)
rbm.vU:mul(rbm.momentum)
rbm.vb:mul(rbm.momentum)
rbm.vc:mul(rbm.momentum)
rbm.vd:mul(rbm.momentum)
else
rbm.vW:fill(0)
rbm.vU:fill(0)
rbm.vb:fill(0)
rbm.vc:fill(0)
rbm.vd:fill(0)
end
-- Add current update to momentum
rbm.vW:add(rbm.dW)
rbm.vU:add(rbm.dU)
rbm.vb:add(rbm.db)
rbm.vc:add(rbm.dc)
rbm.vd:add(rbm.dd)
--end
end
function updateweights(rbm)
-- update gradients
rbm.W:add(rbm.vW)
rbm.U:add(rbm.vU)
rbm.b:add(rbm.vb)
rbm.c:add(rbm.vc)
rbm.d:add(rbm.vd)
end
function restoreorgweights(rbm)
if rbm.dropout > 0 or rbm.dropconnect > 0 then
-- TODO: not sure if i need to clone here
rbm.W = rbm.W_org:clone();
rbm.U = rbm.U_org:clone();
rbm.c = rbm.c_org:clone();
end
end
function cprbm(rbm)
newrbm = {}
newrbm.W =rbm.W:clone()
newrbm.U =rbm.U:clone()
newrbm.b = rbm.b:clone()
newrbm.c = rbm.c:clone()
newrbm.d = rbm.d:clone()
return(newrbm)
end
|
require('nn')
require('pl')
require('torch')
require('rbm-util')
require('rbm-regularization')
require('rbm-grads')
require ('socket') -- for timing
function rbmtrain(rbm,x_train,y_train,x_val,y_val,x_semisup)
-- train RBM
-- Reset gradient accums
-- Print rbm
--print(x_train)
--print(y_train)
--print(x_val)
--print(y_val)
--print(x_semisup)
printRBM(rbm,x_train,x_val,x_semisup)
rbm.time = {}
local x_tr,y_tr,x_semi, total_time, epoch_time,acc_train
local best_val_err = 1/0
local patience = rbm.patience
total_time = socket.gettime()
for epoch = 1, rbm.numepochs do
epoch_time = socket.gettime()
rbm.cur_err = torch.zeros(1)
for i = 1, x_train:size(1) do -- iter over samples
x_tr,y_tr,x_semi = getsamples(rbm,x_train,y_train,x_semisup,i)
regularization.applydropoutordropconnect(rbm) -- cp org weights, drops weights if enabled
grads.calculategrads(rbm,x_tr,y_tr,x_semi) -- calculates dW, dU, db, dc and dd
regularization.applyregularization(rbm) -- regularizes dW, dU, db, dc and dd
updategradsandmomentum(rbm)
-- update vW, vU, vb, vc and vd, formulae: vx = vX*mom + dX
restoreorgweights(rbm) -- restore weights from before dropping
updateweights(rbm) -- updates W,U,b,c and d, formulae: X = X + vX
if (i % 5000) == 0 then
io.write(".")
io.flush()
end
-- Force garbagecollector to collect. Reduces memory with atleast factor of 3.
if (i % 100) == 0 then
collectgarbage()
end
end -- samples loop
epoch_time = socket.gettime() - epoch_time
rbm.err_recon_train[epoch] = rbm.cur_err:div(rbm.n_samples)
--timer = torch.Timer()
err_train = 1-accuracy(rbm,x_train,y_train)
rbm.err_train[epoch] = err_train
--print(timer:time().real)
if x_val and y_val then
err_val = 1-accuracy(rbm,x_val,y_val)
rbm.err_val[epoch] = err_val
if err_val < best_val_err then
best_val_err = err_val
patience = rbm.patience
saverbm(rbm.tempfile,rbm) -- save current best
best_rbm = cprbm(rbm) -- save best weights
best = '***'
else
patience = patience - 1
best = ''
end
end
print(string.format("%i/%i -LR: %f, MOM %f - Recon err: %4.1f err TR: %f err VAL: %f time: %f Patience %i %s", epoch, rbm.numepochs, rbm.learningrate,rbm.momentum, rbm.cur_err[1],err_train,err_val or 1/0,epoch_time, patience,best))
if patience < 0 then -- Stop training
-- Cp weights from best_rbm
rbm.W = best_rbm.W:clone()
rbm.U = best_rbm.U:clone()
rbm.b = best_rbm.b:clone()
rbm.c = best_rbm.c:clone()
rbm.d = best_rbm.d:clone()
break
end
end
total_time = socket.gettime() - total_time
print("Mean epoch time:", total_time / rbm.numepochs)
return(rbm)
end
function getsamples(rbm,x_train,y_train,x_semisup,i_tr)
local x_tr, y_tr
x_tr = x_train[i_tr]:resize(1,x_train:size(2))
y_tr = y_train[i_tr]:resize(1,y_train:size(2))
if rbm.beta > 0 then
i_semi = (i_tr-1) % x_semisup:size(1) +1;
x_semi = x_semisup[i_tr]:resize(1,x_semisup:size(2))
end
return x_tr,y_tr,x_semi
end
function updategradsandmomentum(rbm)
-- multiply updates by learningrate
rbm.dW:mul(rbm.learningrate)
rbm.dU:mul(rbm.learningrate)
rbm.db:mul(rbm.learningrate)
rbm.dc:mul(rbm.learningrate)
rbm.dd:mul(rbm.learningrate)
-- If momentum is zero this will be zero
--if momentum > 0 then
if rbm.momentum > 0 then
rbm.vW:mul(rbm.momentum)
rbm.vU:mul(rbm.momentum)
rbm.vb:mul(rbm.momentum)
rbm.vc:mul(rbm.momentum)
rbm.vd:mul(rbm.momentum)
else
rbm.vW:fill(0)
rbm.vU:fill(0)
rbm.vb:fill(0)
rbm.vc:fill(0)
rbm.vd:fill(0)
end
-- Add current update to momentum
rbm.vW:add(rbm.dW)
rbm.vU:add(rbm.dU)
rbm.vb:add(rbm.db)
rbm.vc:add(rbm.dc)
rbm.vd:add(rbm.dd)
--end
end
function updateweights(rbm)
-- update gradients
rbm.W:add(rbm.vW)
rbm.U:add(rbm.vU)
rbm.b:add(rbm.vb)
rbm.c:add(rbm.vc)
rbm.d:add(rbm.vd)
end
function restoreorgweights(rbm)
if rbm.dropout > 0 or rbm.dropconnect > 0 then
-- TODO: not sure if i need to clone here
rbm.W = rbm.W_org:clone();
rbm.U = rbm.U_org:clone();
rbm.c = rbm.c_org:clone();
end
end
function cprbm(rbm)
newrbm = {}
newrbm.W =rbm.W:clone()
newrbm.U =rbm.U:clone()
newrbm.b = rbm.b:clone()
newrbm.c = rbm.c:clone()
newrbm.d = rbm.d:clone()
return(newrbm)
end
|
fix best rbm printing
|
fix best rbm printing
|
Lua
|
bsd-3-clause
|
skaae/rbm_toolbox_lua,elezar/rbm_toolbox_lua
|
737ddb8935135e2c1f6e7762f2a06998c59469ac
|
src/websocket/sync.lua
|
src/websocket/sync.lua
|
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tools = require'websocket.tools'
local tinsert = table.insert
local tconcat = table.concat
local receive = function(self)
if self.state ~= 'OPEN' and not self.is_closing then
return nil,'wrong state'
end
local first_opcode
local frames
local bytes = 3
local encoded = ''
local clean = function(was_clean,code,reason)
self.state = 'CLOSED'
self:sock_close()
if self.on_close then
self:on_close()
end
return nil,was_clean,code,reason or 'closed'
end
while true do
local chunk,err = self:sock_receive(bytes)
if err then
return clean(err)
end
encoded = encoded..chunk
local decoded,fin,opcode,_,masked = frame.decode(encoded)
if not self.is_server and masked then
return clean(false,1006,'Websocket receive failed: frame was not masked')
end
if decoded then
if opcode == frame.CLOSE then
if not self.is_closing then
local code,reason = frame.decode_close(decoded)
-- echo code
local msg = frame.encode_close(code)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
if n == #encoded then
return clean(true,code,reason)
else
return clean(false,code,err)
end
else
return decoded,opcode
end
end
if not first_opcode then
first_opcode = opcode
end
if not fin then
if not frames then
frames = {}
elseif opcode ~= frame.CONTINUATION then
return clean(false,1002,'protocol error')
end
bytes = 3
encoded = ''
tinsert(frames,decoded)
elseif not frames then
return decoded,first_opcode
else
tinsert(frames,decoded)
return tconcat(frames),first_opcode
end
else
assert(type(fin) == 'number' and fin > 0)
bytes = fin
end
end
end
local send = function(self,data,opcode)
if self.state ~= 'OPEN' then
return nil,'wrong state'
end
local encoded = frame.encode(data,opcode or frame.TEXT,not self.is_server)
local n,err = self:sock_send(encoded)
if n ~= #encoded then
return self:close(1006,err)
end
return true
end
local close = function(self,code,reason)
if self.state ~= 'OPEN' then
return nil,'wrong state'
end
local msg = frame.encode_close(code or 1000,reason)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
local was_clean = false
local code = 1006
local reason = ''
if n == #encoded then
self.is_closing = true
local rmsg,opcode = self:receive()
if rmsg and opcode == frame.CLOSE then
code,reason = frame.decode_close(rmsg)
was_clean = true
end
end
self:sock_close()
if self.on_close then
self:on_close()
end
self.state = 'CLOSED'
return was_clean,code,reason or ''
end
local connect = function(self,ws_url,ws_protocol)
if self.state ~= 'CLOSED' then
return nil,'wrong state'
end
local protocol,host,port,uri = tools.parse_url(ws_url)
if protocol ~= 'ws' then
return nil,'bad protocol'
end
local _,err = self:sock_connect(host,port)
if err then
return nil,err
end
local key = tools.generate_key()
local req = handshake.upgrade_request
{
key = key,
host = host,
port = port,
protocols = {ws_protocol or ''},
origin = origin,
uri = uri
}
local n,err = self:sock_send(req)
if n ~= #req then
return nil,err
end
local resp = {}
repeat
local line,err = self:sock_receive('*l')
resp[#resp+1] = line
if err then
return nil,err
end
until line == ''
local response = table.concat(resp,'\r\n')
local headers = handshake.http_headers(response)
local expected_accept = handshake.sec_websocket_accept(key)
if headers['sec-websocket-accept'] ~= expected_accept then
local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)'
return nil,msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil')
end
self.state = 'OPEN'
return true
end
local extend = function(obj)
assert(obj.sock_send)
assert(obj.sock_receive)
assert(obj.sock_close)
obj.receive = receive
obj.send = send
obj.close = close
obj.connect = connect
return obj
end
return {
extend = extend
}
|
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tools = require'websocket.tools'
local tinsert = table.insert
local tconcat = table.concat
local receive = function(self)
if self.state ~= 'OPEN' and not self.is_closing then
return nil,'wrong state'
end
local first_opcode
local frames
local bytes = 3
local encoded = ''
local clean = function(was_clean,code,reason)
self.state = 'CLOSED'
self:sock_close()
if self.on_close then
self:on_close()
end
return nil,was_clean,code,reason or 'closed'
end
while true do
local chunk,err = self:sock_receive(bytes)
if err then
return clean(false,1006,err)
end
encoded = encoded..chunk
local decoded,fin,opcode,_,masked = frame.decode(encoded)
if not self.is_server and masked then
return clean(false,1006,'Websocket receive failed: frame was not masked')
end
if decoded then
if opcode == frame.CLOSE then
if not self.is_closing then
local code,reason = frame.decode_close(decoded)
-- echo code
local msg = frame.encode_close(code)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
if n == #encoded then
return clean(true,code,reason)
else
return clean(false,code,err)
end
else
return decoded,opcode
end
end
if not first_opcode then
first_opcode = opcode
end
if not fin then
if not frames then
frames = {}
elseif opcode ~= frame.CONTINUATION then
return clean(false,1002,'protocol error')
end
bytes = 3
encoded = ''
tinsert(frames,decoded)
elseif not frames then
return decoded,first_opcode
else
tinsert(frames,decoded)
return tconcat(frames),first_opcode
end
else
assert(type(fin) == 'number' and fin > 0)
bytes = fin
end
end
end
local send = function(self,data,opcode)
if self.state ~= 'OPEN' then
return nil,'wrong state'
end
local encoded = frame.encode(data,opcode or frame.TEXT,not self.is_server)
local n,err = self:sock_send(encoded)
if n ~= #encoded then
return self:close(1006,err)
end
return true
end
local close = function(self,code,reason)
if self.state ~= 'OPEN' then
return nil,'wrong state'
end
if self.state == 'CLOSED' then
return nil,'wrong state'
end
local msg = frame.encode_close(code or 1000,reason)
local encoded = frame.encode(msg,frame.CLOSE,not self.is_server)
local n,err = self:sock_send(encoded)
local was_clean = false
local code = 1006
local reason = ''
if n == #encoded then
self.is_closing = true
local rmsg,opcode = self:receive()
if rmsg and opcode == frame.CLOSE then
code,reason = frame.decode_close(rmsg)
was_clean = true
end
end
self:sock_close()
if self.on_close then
self:on_close()
end
self.state = 'CLOSED'
return was_clean,code,reason or ''
end
local connect = function(self,ws_url,ws_protocol)
if self.state ~= 'CLOSED' then
return nil,'wrong state'
end
local protocol,host,port,uri = tools.parse_url(ws_url)
if protocol ~= 'ws' then
return nil,'bad protocol'
end
local _,err = self:sock_connect(host,port)
if err then
return nil,err
end
local key = tools.generate_key()
local req = handshake.upgrade_request
{
key = key,
host = host,
port = port,
protocols = {ws_protocol or ''},
origin = origin,
uri = uri
}
local n,err = self:sock_send(req)
if n ~= #req then
return nil,err
end
local resp = {}
repeat
local line,err = self:sock_receive('*l')
resp[#resp+1] = line
if err then
return nil,err
end
until line == ''
local response = table.concat(resp,'\r\n')
local headers = handshake.http_headers(response)
local expected_accept = handshake.sec_websocket_accept(key)
if headers['sec-websocket-accept'] ~= expected_accept then
local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)'
return nil,msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil')
end
self.state = 'OPEN'
return true
end
local extend = function(obj)
assert(obj.sock_send)
assert(obj.sock_receive)
assert(obj.sock_close)
obj.receive = receive
obj.send = send
obj.close = close
obj.connect = connect
return obj
end
return {
extend = extend
}
|
fix receive return codes on sock err, don't close again on multiple call to close
|
fix receive return codes on sock err, don't close again on multiple call to close
|
Lua
|
mit
|
KSDaemon/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets
|
935fe615aa8747c82039017fd03faff629a49bb7
|
lib/px/block/pxtemplate.lua
|
lib/px/block/pxtemplate.lua
|
---------------------------------------------
-- PerimeterX(www.perimeterx.com) Nginx plugin
----------------------------------------------
local M = {}
function M.load(px_config)
local _M = {}
local lustache = require "lustache"
local px_constants = require "px.utils.pxconstants"
local px_logger = require("px.utils.pxlogger").load(px_config)
local function get_props(px_config, uuid, vid, action)
local logo_css_style = 'visible'
if (px_config.custom_logo == nil) then
logo_css_style = 'hidden'
end
local is_mobile = ngx.ctx.px_cookie_origin == 'header'
local js_client_src = string.format('//client.perimeterx.net/%s/main.min.js', px_config.px_appId)
local collectorUrl = '//' .. px_config.collector_host
local captcha_url_prefix = 'https://' .. px_config.captcha_script_host
-- in case we are in first party mode (not relevant for mobile), change the base paths to use first party
if px_config.first_party_enabled and not is_mobile then
local reverse_prefix = string.sub(px_config.px_appId, 3, string.len(px_config.px_appId))
js_client_src = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_VENDOR_PATH)
collectorUrl = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_XHR_PATH)
captcha_url_prefix = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_CAPTCHA_PATH)
end
local captcha_src = ''
if action ~= 'r' then
captcha_src = captcha_url_prefix .. string.format('/' .. px_config.px_appId .. '/captcha.js?a=%s&m=%s&u=%s&v=%s', action, (is_mobile and '1' or '0'), uuid, vid)
end
return {
refId = uuid,
vid = vid,
appId = px_config.px_appId,
uuid = uuid,
customLogo = px_config.custom_logo,
cssRef = px_config.css_ref,
jsRef = px_config.js_ref,
logoVisibility = logo_css_style,
hostUrl = collectorUrl,
jsClientSrc = js_client_src,
firstPartyEnabled = px_config.first_party_enabled,
blockScript = captcha_src
}
end
local function get_path()
return string.sub(debug.getinfo(1).source, 2, string.len("/pxtemplate.lua") * -1)
end
local function get_content(action)
local __dirname = get_path()
local path = 'block_template'
if action == 'r' then
path = 'ratelimit'
end
local template_path = string.format("%stemplates/%s.mustache", __dirname, path)
px_logger.debug("fetching template from: " .. template_path)
local file = io.open(template_path, "r")
if (file == nil) then
px_logger.debug("the template " .. string.format("%s.mustache", template_path) .. " was not found")
end
local content = file:read("*all")
file:close()
return content
end
function _M.get_template(action, uuid, vid)
local props = get_props(px_config, uuid, vid, action)
local templateStr = get_content(action)
return lustache:render(templateStr, props)
end
return _M
end
return M
|
---------------------------------------------
-- PerimeterX(www.perimeterx.com) Nginx plugin
----------------------------------------------
local M = {}
function M.load(px_config)
local _M = {}
local lustache = require "lustache"
local px_constants = require "px.utils.pxconstants"
local px_logger = require("px.utils.pxlogger").load(px_config)
local function get_props(px_config, uuid, vid, action)
local logo_css_style = 'visible'
if (px_config.custom_logo == nil) then
logo_css_style = 'hidden'
end
local is_mobile = ngx.ctx.px_cookie_origin == 'header'
local js_client_src = string.format('//client.perimeterx.net/%s/main.min.js', px_config.px_appId)
local collectorUrl = '//' .. px_config.collector_host
local captcha_url_prefix = 'https://' .. px_config.captcha_script_host
local first_party_enabled = false
-- in case we are in first party mode (not relevant for mobile), change the base paths to use first party
if px_config.first_party_enabled and not is_mobile then
local reverse_prefix = string.sub(px_config.px_appId, 3, string.len(px_config.px_appId))
js_client_src = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_VENDOR_PATH)
collectorUrl = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_XHR_PATH)
captcha_url_prefix = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_CAPTCHA_PATH)
first_party_enabled = true
end
local captcha_src = ''
if action ~= 'r' then
captcha_src = captcha_url_prefix .. string.format('/' .. px_config.px_appId .. '/captcha.js?a=%s&m=%s&u=%s&v=%s', action, (is_mobile and '1' or '0'), uuid, vid)
end
return {
refId = uuid,
vid = vid,
appId = px_config.px_appId,
uuid = uuid,
customLogo = px_config.custom_logo,
cssRef = px_config.css_ref,
jsRef = px_config.js_ref,
logoVisibility = logo_css_style,
hostUrl = collectorUrl,
jsClientSrc = js_client_src,
firstPartyEnabled = first_party_enabled,
blockScript = captcha_src
}
end
local function get_path()
return string.sub(debug.getinfo(1).source, 2, string.len("/pxtemplate.lua") * -1)
end
local function get_content(action)
local __dirname = get_path()
local path = 'block_template'
if action == 'r' then
path = 'ratelimit'
end
local template_path = string.format("%stemplates/%s.mustache", __dirname, path)
px_logger.debug("fetching template from: " .. template_path)
local file = io.open(template_path, "r")
if (file == nil) then
px_logger.debug("the template " .. string.format("%s.mustache", template_path) .. " was not found")
end
local content = file:read("*all")
file:close()
return content
end
function _M.get_template(action, uuid, vid)
local props = get_props(px_config, uuid, vid, action)
local templateStr = get_content(action)
return lustache:render(templateStr, props)
end
return _M
end
return M
|
fixed config for fp in block template
|
fixed config for fp in block template
|
Lua
|
mit
|
PerimeterX/perimeterx-nginx-plugin
|
1ae79d6088bc8541d821afbcc7cf868429f5d3db
|
stdlib/misc/config.lua
|
stdlib/misc/config.lua
|
--- For working with mod configurations.
-- @module Misc.Config
-- @usage require('__stdlib__/stdlib/config/config')
---
-- @tfield function new
-- @tfield function get
-- @tfield function set
-- @tfield function delete
-- @tfield function is_set
-- @table Config
local M = {
__class = 'Config',
__index = require('__stdlib__/stdlib/core')
}
setmetatable(M, M)
local table = require('__stdlib__/stdlib/utils/table')
-----------------------------------------------------------------------
--Setup repeated code for use in sub functions here
-----------------------------------------------------------------------
local reservedCharacters = [[`~!@#$%^&*+=|;:/\\\'",?()[]{}<>]]
local testReservedCharacters = function(path)
local reserved = reservedCharacters
for c in reserved:gmatch('.') do
if path:find(c, 1, true) then
return c
end
end
return nil
end
--- Creates a new Config object to ease the management of a config table.
-- @tparam table config_table the config table to manage
-- @treturn Config the Config object to manage the config table
--
-- @usage --[Use a global table for config that persists across game save/loads]
-- CONFIG = Config.new(global.testtable)
--
-- @usage --[You can also create a temporary scratch pad config]
-- CONFIG = Config.new({}) -- Temporary scratch pad
--
-- @usage --[Setting data in Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.set("your.path.here", "myvalue")
--
-- @usage --[Getting data out of Config]
-- CONFIG = Config.new(global.testtable)
-- my_data = CONFIG.get("your.path.here")
--
-- @usage --[Getting data out of Config with a default to use if path is not found in Config]
-- CONFIG = Config.new(global.testtable)
-- my_data = CONFIG.get("your.path.here", "Your Default here")
--
-- @usage --[Deleting a path from Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.delete("your.path.here")
--
-- @usage --[Checking if a path exists in Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.is_set("your.path.here")
function M.new(config_table)
if not config_table then
error('config_table is a required parameter.', 2)
elseif type(config_table) ~= 'table' then
error('config_table must be a table. Was given [' .. type(config_table) .. ']', 2)
elseif type(config_table.get) == 'function' then
error("Config can't manage another Config object", 2)
end
-----------------------------------------------------------------------
--Setup the Config object
-----------------------------------------------------------------------
local Config = {}
--- Get a stored config value.
-- @tparam string path the variable to retrieve
-- @tparam[opt] Mixed default value to be used if path is nil
-- @treturn Mixed value at path or nil if not found and no default given
function Config.get(path, default)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path '" .. path .. "' contains the reserved character '" .. c .. "'", 2)
end
local pathParts = string.split(path, '.')
local part = config
local value = nil
for key = 1, #pathParts, 1 do
local partKey = pathParts[key]
if (type(part) ~= 'table') then
value = nil
break
end
value = part[partKey]
part = part[partKey]
end
if (type(value) == 'table') then
--Force break references.
return table.deepcopy(value)
elseif (value ~= nil) then
return value
else
return default
end
end
--- Set a stored config value.
-- @tparam string path the config path to set
-- @tparam ?|nil|Mixed data the value to set the path to. If *nil*, it behaves identical to @{delete|Config.delete()}
-- @treturn uint 0 on failure or the number of affected paths on success
function Config.set(path, data)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path contains the reserved character '" .. c .. "'", 2)
end
local pathParts = string.split(path, '.')
local part = config
for key = 1, #pathParts - 1, 1 do
local partKey = pathParts[key]
if (type(part[partKey]) ~= 'table') then
part[partKey] = {}
end
part = part[partKey]
end
part[pathParts[#pathParts]] = data
return 1
end
--- Delete a stored config value.
-- @tparam string path the config path to delete
-- @treturn uint 0 on failure or the number of affected paths on success
function Config.delete(path)
if type(path) ~= 'string' or string == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path contains the reserved character '" .. c .. "'", 2)
end
local pathParts = path:split('.')
local part = config
for key = 1, #pathParts - 1, 1 do
local partKey = pathParts[key]
if (type(part[partKey]) ~= 'table') then
return 0
end
part = part[partKey]
end
if part[pathParts[#pathParts]] == nil then
return 0
else
part[pathParts[#pathParts]] = nil
return 1
end
end
--- Test the existence of a stored config value.
-- @tparam string path the config path to test
-- @treturn boolean true if the value exists, false otherwise
function Config.is_set(path)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
return Config.get(path) ~= nil
end
return Config
end
return M
|
--- For working with mod configurations.
-- @module Misc.Config
-- @usage require('__stdlib__/stdlib/config/config')
---
-- @tfield function new
-- @tfield function get
-- @tfield function set
-- @tfield function delete
-- @tfield function is_set
-- @table Config
local M = {
__class = 'Config',
__index = require('__stdlib__/stdlib/core')
}
setmetatable(M, M)
local table = require('__stdlib__/stdlib/utils/table')
local string = require('__stdlib__/stdlib/utils/string')
-----------------------------------------------------------------------
--Setup repeated code for use in sub functions here
-----------------------------------------------------------------------
local reservedCharacters = [[`~!@#$%^&*+=|;:/\\\'",?()[]{}<>]]
local testReservedCharacters = function(path)
local reserved = reservedCharacters
for c in reserved:gmatch('.') do
if path:find(c, 1, true) then
return c
end
end
return nil
end
--- Creates a new Config object to ease the management of a config table.
-- @tparam table config_table the config table to manage
-- @treturn Config the Config object to manage the config table
--
-- @usage --[Use a global table for config that persists across game save/loads]
-- CONFIG = Config.new(global.testtable)
--
-- @usage --[You can also create a temporary scratch pad config]
-- CONFIG = Config.new({}) -- Temporary scratch pad
--
-- @usage --[Setting data in Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.set("your.path.here", "myvalue")
--
-- @usage --[Getting data out of Config]
-- CONFIG = Config.new(global.testtable)
-- my_data = CONFIG.get("your.path.here")
--
-- @usage --[Getting data out of Config with a default to use if path is not found in Config]
-- CONFIG = Config.new(global.testtable)
-- my_data = CONFIG.get("your.path.here", "Your Default here")
--
-- @usage --[Deleting a path from Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.delete("your.path.here")
--
-- @usage --[Checking if a path exists in Config]
-- CONFIG = Config.new(global.testtable)
-- CONFIG.is_set("your.path.here")
function M.new(config_table)
if not config_table then
error('config_table is a required parameter.', 2)
elseif type(config_table) ~= 'table' then
error('config_table must be a table. Was given [' .. type(config_table) .. ']', 2)
elseif type(config_table.get) == 'function' then
error("Config can't manage another Config object", 2)
end
-----------------------------------------------------------------------
--Setup the Config object
-----------------------------------------------------------------------
local Config = {}
--- Get a stored config value.
-- @tparam string path the variable to retrieve
-- @tparam[opt] Mixed default value to be used if path is nil
-- @treturn Mixed value at path or nil if not found and no default given
function Config.get(path, default)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path '" .. path .. "' contains the reserved character '" .. c .. "'", 2)
end
local pathParts = string.split(path, '.')
local part = config
local value = nil
for key = 1, #pathParts, 1 do
local partKey = pathParts[key]
if (type(part) ~= 'table') then
value = nil
break
end
value = part[partKey]
part = part[partKey]
end
if (type(value) == 'table') then
--Force break references.
return table.deepcopy(value)
elseif (value ~= nil) then
return value
else
return default
end
end
--- Set a stored config value.
-- @tparam string path the config path to set
-- @tparam ?|nil|Mixed data the value to set the path to. If *nil*, it behaves identical to @{delete|Config.delete()}
-- @treturn uint 0 on failure or the number of affected paths on success
function Config.set(path, data)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path contains the reserved character '" .. c .. "'", 2)
end
local pathParts = string.split(path, '.')
local part = config
for key = 1, #pathParts - 1, 1 do
local partKey = pathParts[key]
if (type(part[partKey]) ~= 'table') then
part[partKey] = {}
end
part = part[partKey]
end
part[pathParts[#pathParts]] = data
return 1
end
--- Delete a stored config value.
-- @tparam string path the config path to delete
-- @treturn uint 0 on failure or the number of affected paths on success
function Config.delete(path)
if type(path) ~= 'string' or string == '' then
error('path is invalid', 2)
end
local config = config_table
local c = testReservedCharacters(path)
if c ~= nil then
error("path contains the reserved character '" .. c .. "'", 2)
end
local pathParts = string.split(path, '.')
local part = config
for key = 1, #pathParts - 1, 1 do
local partKey = pathParts[key]
if (type(part[partKey]) ~= 'table') then
return 0
end
part = part[partKey]
end
if part[pathParts[#pathParts]] == nil then
return 0
else
part[pathParts[#pathParts]] = nil
return 1
end
end
--- Test the existence of a stored config value.
-- @tparam string path the config path to test
-- @treturn boolean true if the value exists, false otherwise
function Config.is_set(path)
if type(path) ~= 'string' or path == '' then
error('path is invalid', 2)
end
return Config.get(path) ~= nil
end
return Config
end
return M
|
Fixes
|
Fixes
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
8451c9a064fd14a521546eefbcc1a67854884d5e
|
mods/ITEMS/walls/init.lua
|
mods/ITEMS/walls/init.lua
|
--[[
Walls
--]]
walls = {}
walls.register = function(wall_name, wall_desc, wall_texture, wall_mat, wall_sounds)
-- inventory node, and pole-type wall start item
minetest.register_node(wall_name, {
description = wall_desc,
drawtype = "nodebox",
node_box = {
type = "connected",
fixed = {{-1/4, -1/2, -1/4, 1/4, 1/2, 1/4}},
-- connect_bottom =
connect_front = {{-3/16, -1/2, -1/2, 3/16, 3/8, -1/4}},
connect_left = {{-1/2, -1/2, -3/16, -1/4, 3/8, 3/16}},
connect_back = {{-3/16, -1/2, 1/4, 3/16, 3/8, 1/2}},
connect_right = {{ 1/4, -1/2, -3/16, 1/2, 3/8, 3/16}},
},
connects_to = { "group:wall", "group:stone" },
paramtype = "light",
is_ground_content = false,
tiles = { wall_texture, },
walkable = true,
groups = { cracky = 3, wall = 1, stone = 2 },
sounds = wall_sounds,
})
-- crafting recipe
minetest.register_craft({
output = wall_name .. " 6",
recipe = {
{ '', '', '' },
{ wall_mat, wall_mat, wall_mat},
{ wall_mat, wall_mat, wall_mat},
}
})
end
walls.register("walls:cobble", "Cobblestone Wall", "base_cobble.png",
"base:cobble", base.node_sound_stone_defaults())
walls.register("walls:mossycobble", "Mossy Cobblestone Wall", "base_mossycobble.png",
"base:mossycobble", base.node_sound_stone_defaults())
walls.register("walls:desertcobble", "Desert Cobblestone Wall", "base_desert_cobble.png",
"base:desert_cobble", base.node_sound_stone_defaults())
walls.register("walls:bluestone", "Bluestone Cobble Wall", "aus_bluestone_cobble.png",
"australia:bluestone_cobble", base.node_sound_stone_defaults())
walls.register("walls:bluestone_cobble", "Bluestone Wall", "aus_bluestone.png",
"australia:bluestone", base.node_sound_stone_defaults())
walls.register("walls:bluestone_brick", "Bluestone Brick Wall", "aus_bluestone_brick.png",
"australia:bluestone_brick", base.node_sound_stone_defaults())
walls.register("walls:brick", "Brick Wall", "base_brick.png",
"base:brick", base.node_sound_stone_defaults())
walls.register("walls:desert_stone", "Desert Stone Wall", "base_desert_stone.png",
"base:desert_stone", base.node_sound_stone_defaults())
walls.register("walls:desert_stonebrick", "Desert Stone Brick Wall", "base_desert_stone_brick.png",
"base:desert_stonebrick", base.node_sound_stone_defaults())
walls.register("walls:red_stone", "Red Cobblestone Wall", "aus_red_cobble.png",
"australia:red_cobble", base.node_sound_stone_defaults())
walls.register("walls:red_cobble", "Red Stone Wall", "aus_red_stone.png",
"australia:red_stone", base.node_sound_stone_defaults())
walls.register("walls:red_stonebrick", "Red Stone Brick Wall", "aus_red_stonebrick.png",
"australia:red_stonebrick", base.node_sound_stone_defaults())
walls.register("walls:sandstone", "Sandstone Wall", "base_sandstone.png",
"base:sandstone", base.node_sound_stone_defaults())
walls.register("walls:sandstone_brick", "Sandstone Brick Wall", "base_sandstone_brick.png",
"base:sandstonebrick", base.node_sound_stone_defaults())
walls.register("walls:sandstone_cobble", "Sandstone Cobble Wall", "aus_sandstone_cobble.png",
"australia:sandstone_cobble", base.node_sound_stone_defaults())
walls.register("walls:stone", "Stone Wall", "base_stone.png",
"base:stone", base.node_sound_stone_defaults())
walls.register("walls:stone_brick", "Stone Brick Wall", "base_stone_brick.png",
"base:stonebrick", base.node_sound_stone_defaults())
|
--[[
Walls
--]]
walls = {}
walls.register = function(wall_name, wall_desc, wall_texture, wall_mat, wall_sounds)
-- inventory node, and pole-type wall start item
minetest.register_node(wall_name, {
description = wall_desc,
drawtype = "nodebox",
node_box = {
type = "connected",
fixed = {{-1/4, -1/2, -1/4, 1/4, 1/2, 1/4}},
-- connect_bottom =
connect_front = {{-3/16, -1/2, -1/2, 3/16, 3/8, -1/4}},
connect_left = {{-1/2, -1/2, -3/16, -1/4, 3/8, 3/16}},
connect_back = {{-3/16, -1/2, 1/4, 3/16, 3/8, 1/2}},
connect_right = {{ 1/4, -1/2, -3/16, 1/2, 3/8, 3/16}},
},
connects_to = { "group:wall", "group:stone" },
paramtype = "light",
is_ground_content = false,
tiles = { wall_texture, },
walkable = true,
groups = { cracky = 3, wall = 1, stone = 2 },
sounds = wall_sounds,
})
-- crafting recipe
minetest.register_craft({
output = wall_name .. " 6",
recipe = {
{ '', '', '' },
{ wall_mat, wall_mat, wall_mat},
{ wall_mat, wall_mat, wall_mat},
}
})
end
walls.register("walls:cobble", "Cobblestone Wall", "base_cobble.png",
"base:cobble", base.node_sound_stone_defaults())
walls.register("walls:mossycobble", "Mossy Cobblestone Wall", "base_mossycobble.png",
"base:mossycobble", base.node_sound_stone_defaults())
walls.register("walls:desertcobble", "Desert Cobblestone Wall", "base_desert_cobble.png",
"base:desert_cobble", base.node_sound_stone_defaults())
walls.register("walls:bluestone", "Bluestone Cobble Wall", "base_bluestone_cobble.png",
"base:bluestone_cobble", base.node_sound_stone_defaults())
walls.register("walls:bluestone_cobble", "Bluestone Wall", "base_bluestone.png",
"base:bluestone", base.node_sound_stone_defaults())
walls.register("walls:bluestone_brick", "Bluestone Brick Wall", "base_bluestone_brick.png",
"base:bluestone_brick", base.node_sound_stone_defaults())
walls.register("walls:brick", "Brick Wall", "base_brick.png",
"base:brick", base.node_sound_stone_defaults())
walls.register("walls:desert_stone", "Desert Stone Wall", "base_desert_stone.png",
"base:desert_stone", base.node_sound_stone_defaults())
walls.register("walls:desert_stonebrick", "Desert Stone Brick Wall", "base_desert_stone_brick.png",
"base:desert_stonebrick", base.node_sound_stone_defaults())
walls.register("walls:red_stone", "Red Cobblestone Wall", "base_red_cobble.png",
"base:red_cobble", base.node_sound_stone_defaults())
walls.register("walls:red_cobble", "Red Stone Wall", "base_red_stone.png",
"base:red_stone", base.node_sound_stone_defaults())
walls.register("walls:red_stonebrick", "Red Stone Brick Wall", "base_red_stonebrick.png",
"base:red_stonebrick", base.node_sound_stone_defaults())
walls.register("walls:sandstone", "Sandstone Wall", "base_sandstone.png",
"base:sandstone", base.node_sound_stone_defaults())
walls.register("walls:sandstone_brick", "Sandstone Brick Wall", "base_sandstone_brick.png",
"base:sandstonebrick", base.node_sound_stone_defaults())
walls.register("walls:sandstone_cobble", "Sandstone Cobble Wall", "base_sandstone_cobble.png",
"base:sandstone_cobble", base.node_sound_stone_defaults())
walls.register("walls:stone", "Stone Wall", "base_stone.png",
"base:stone", base.node_sound_stone_defaults())
walls.register("walls:stone_brick", "Stone Brick Wall", "base_stone_brick.png",
"base:stonebrick", base.node_sound_stone_defaults())
|
Fix walls registration
|
Fix walls registration
|
Lua
|
lgpl-2.1
|
vlapsley/outback,vlapsley/outback
|
95898598e99f87ff0e6c029f30f3e454a42edd61
|
src/nodes/platform.lua
|
src/nodes/platform.lua
|
local Timer = require 'vendor/timer'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide(player, dt, mtv_x, mtv_y)
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
player:impactDamage()
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 4 ) + mtv_y
updatePlayer()
end
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if player.state ~= 'crouch' or player.jumping then
self.hasdropped = false
if self.dropdelay then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
end
return Platform
|
local Timer = require 'vendor/timer'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide(player, dt, mtv_x, mtv_y)
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
player:impactDamage()
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 4 ) + mtv_y
updatePlayer()
end
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if player.state ~= 'crouch' or player.jumping then
self.hasdropped = false
if self.dropdelay then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
end
return Platform
|
Fix line endings
|
Fix line endings
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
77c45f1828f327ed29dda76d63f5df1b9cb6bc00
|
character/TrackEffect.lua
|
character/TrackEffect.lua
|
module 'character'
local function fixpath(p)
p=string.gsub(p,'\\','/')
return p
end
local function stripExt(p)
return string.gsub( p, '%..*$', '' )
end
local function stripDir(p)
p=fixpath(p)
return string.match(p, "[^\\/]+$")
end
--------------------------------------------------------------------
CLASS: EventEffect ( CharacterActionEvent )
:MODEL{
Field 'effect' :asset( 'effect' );
Field 'loop' :boolean();
'----';
Field 'spineSlot' :string() :selection( 'getSpineSlotList' );
Field 'followSlot' :boolean();
'----';
Field 'loc' :type('vec3') :getset('Loc');
Field 'rot' :type('vec3') :getset('Rot');
Field 'scl' :type('vec3') :getset('Scl');
'----';
Field 'stopWithEvent' :boolean();
}
function EventEffect:__init()
self.name = 'effect'
self.loop = false
self.effect = false
self.followSlot = false
self.spineSlot = false
self.transform = MOAITransform.new()
self.stopWithEvent = true
end
function EventEffect:getSpineSlotList()
local result = {
{ '<none>', false }
}
local config = self:getRootConfig()
local spinePath = config:getSpine()
local spineData = mock.loadAsset( spinePath )
if not spineData then return nil end
for k,i in pairs( spineData._slotTable ) do
table.insert( result, { k, k } )
end
return result
end
function EventEffect:setLoc( x,y,z )
return self.transform:setLoc( x,y,z )
end
function EventEffect:getLoc()
return self.transform:getLoc()
end
function EventEffect:setRot( x,y,z )
return self.transform:setRot( x,y,z )
end
function EventEffect:getRot()
return self.transform:getRot()
end
function EventEffect:setScl( x,y,z )
return self.transform:setScl( x,y,z )
end
function EventEffect:getScl()
return self.transform:getScl()
end
function EventEffect:isResizable()
return true
end
function EventEffect:start( state, pos )
local effect = self.effect
if effect == '' then effect = nil end
if not self.effect then return end
local target = state.target
local emEnt = target:getEntity()
local em = mock.EffectEmitter()
emEnt:attachInternal( em )
local transform = self.transform
em:setEffect( self.effect )
local x,y,z = transform:getLoc()
local rx,ry,rz = transform:getRot()
local sx,sy,sz = transform:getScl()
local kx = target.mirrorX and -1 or 1
local ky = target.mirrorY and -1 or 1
sx = sx * kx
sy = sy * ky
x = x * kx
y = y * ky
if kx * ky == -1 then
rz = - rz
end
em.prop:setLoc( x,y,z )
em.prop:setRot( rx,ry,rz )
em.prop:setScl( sx,sy,sz )
em:start()
local length = self.length/1000
em:setDuration( length )
if self.stopWithEvent then
em:setActionOnStop( 'detach' )
else
em:setActionOnStop( 'none' )
end
state.effectEmitters[ self.parent ][ em ] = true
end
function EventEffect:toString()
if not self.effect then return '<nil>' end
local name = stripExt( stripDir( self.effect ) )
return self.loop and '<loop>'..name or name
end
--
function EventEffect:onBuildGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
linkLoc( giz:getProp(), self.transform )
linkRot( giz:getProp(), self.transform )
linkScl( giz:getProp(), self.transform )
return giz
end
function EventEffect:drawBounds()
MOAIDraw.drawEmitter( 0,0 )
end
--------------------------------------------------------------------
CLASS: TrackEffect ( CharacterActionTrack )
:MODEL{
Field 'layer' :type('layer') :no_nil();
}
function TrackEffect:__init()
self.name = 'fx'
self.layer = false
end
function TrackEffect:getType()
return 'effect'
end
function TrackEffect:createEvent()
return EventEffect()
end
function TrackEffect:toString()
return '<fx>' .. tostring( self.name )
end
function TrackEffect:start( state )
--build MOAISpineAnimationTrack
local target = state.target
local effectEmitters = state.effectEmitters
if not effectEmitters then
effectEmitters = {}
state.effectEmitters = effectEmitters
end
effectEmitters[ self ] = {}
end
function TrackEffect:stop( state )
local emitterList = state.effectEmitters
if not emitterList then return end
local emitters = emitterList[ self ]
local ent = state.target:getEntity()
for em in pairs( emitters ) do
if em._entity then
ent:detach( em )
end
end
state.effectEmitters[ self ] = nil
end
--------------------------------------------------------------------
registerCharacterActionTrackType( 'Effect', TrackEffect )
|
module 'character'
local function fixpath(p)
p=string.gsub(p,'\\','/')
return p
end
local function stripExt(p)
return string.gsub( p, '%..*$', '' )
end
local function stripDir(p)
p=fixpath(p)
return string.match(p, "[^\\/]+$")
end
--------------------------------------------------------------------
CLASS: EventEffect ( CharacterActionEvent )
:MODEL{
Field 'effect' :asset( 'effect' );
Field 'loop' :boolean();
'----';
Field 'spineSlot' :string() :selection( 'getSpineSlotList' );
Field 'followSlot' :boolean();
'----';
Field 'loc' :type('vec3') :getset('Loc');
Field 'rot' :type('vec3') :getset('Rot');
Field 'scl' :type('vec3') :getset('Scl');
'----';
Field 'stopWithEvent' :boolean();
}
function EventEffect:__init()
self.name = 'effect'
self.loop = false
self.effect = false
self.followSlot = false
self.spineSlot = false
self.transform = MOAITransform.new()
self.stopWithEvent = true
end
function EventEffect:getSpineSlotList()
local result = {
{ '<none>', false }
}
local config = self:getRootConfig()
local spinePath = config:getSpine()
local spineData = mock.loadAsset( spinePath )
if not spineData then return nil end
for k,i in pairs( spineData._slotTable ) do
table.insert( result, { k, k } )
end
return result
end
function EventEffect:setLoc( x,y,z )
return self.transform:setLoc( x,y,z )
end
function EventEffect:getLoc()
return self.transform:getLoc()
end
function EventEffect:setRot( x,y,z )
return self.transform:setRot( x,y,z )
end
function EventEffect:getRot()
return self.transform:getRot()
end
function EventEffect:setScl( x,y,z )
return self.transform:setScl( x,y,z )
end
function EventEffect:getScl()
return self.transform:getScl()
end
function EventEffect:isResizable()
return true
end
function EventEffect:start( state, pos )
local effect = self.effect
if effect == '' then effect = nil end
if not self.effect then return end
local target = state.target
local emEnt = target:getEntity()
local em = mock.EffectEmitter()
emEnt:attachInternal( em )
local transform = self.transform
em:setEffect( self.effect )
local x,y,z = transform:getLoc()
local rx,ry,rz = transform:getRot()
local sx,sy,sz = transform:getScl()
local kx = target.mirrorX and -1 or 1
local ky = target.mirrorY and -1 or 1
sx = sx * kx
sy = sy * ky
x = x * kx
y = y * ky
if kx * ky == -1 then
rz = - rz
end
em.prop:setLoc( x,y,z )
em.prop:setRot( rx,ry,rz )
em.prop:setScl( sx,sy,sz )
em:start()
local length = self.length/1000
em:setDuration( length )
if self.stopWithEvent then
em:setActionOnStop( 'detach' )
else
em:setActionOnStop( 'none' )
end
state.effectEmitters[ self.parent ][ em ] = true
end
function EventEffect:toString()
if not self.effect then return '<nil>' end
local name = stripExt( stripDir( self.effect ) )
return self.loop and '<loop>'..name or name
end
--
function EventEffect:onBuildGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
linkLoc( giz:getProp(), self.transform )
linkRot( giz:getProp(), self.transform )
linkScl( giz:getProp(), self.transform )
return giz
end
function EventEffect:drawBounds()
MOAIDraw.drawEmitter( 0,0 )
end
--------------------------------------------------------------------
CLASS: TrackEffect ( CharacterActionTrack )
:MODEL{
Field 'layer' :type('layer') :no_nil();
}
function TrackEffect:__init()
self.name = 'fx'
self.layer = false
end
function TrackEffect:getType()
return 'effect'
end
function TrackEffect:createEvent()
return EventEffect()
end
function TrackEffect:toString()
return '<fx>' .. tostring( self.name )
end
function TrackEffect:start( state )
--build MOAISpineAnimationTrack
local target = state.target
local effectEmitters = state.effectEmitters
if not effectEmitters then
effectEmitters = {}
state.effectEmitters = effectEmitters
end
effectEmitters[ self ] = {}
end
function TrackEffect:stop( state )
local emitterList = state.effectEmitters
if not emitterList then return end
local emitters = emitterList[ self ]
if not emitters then return end
local ent = state.target:getEntity()
for em in pairs( emitters ) do
if em._entity then
ent:detach( em )
end
end
state.effectEmitters[ self ] = nil
end
--------------------------------------------------------------------
registerCharacterActionTrackType( 'Effect', TrackEffect )
|
[yaka]fix enemy creature may start attack action in hurt state; tweak hero defense sensitivity
|
[yaka]fix enemy creature may start attack action in hurt state; tweak hero defense sensitivity
|
Lua
|
mit
|
tommo/mock
|
21dcbb68baf960be2eeb267d4531fffac8257681
|
nyagos.d/box.lua
|
nyagos.d/box.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
nyagos.key.C_o = function(this)
local word,pos = this:lastword()
word = string.gsub(word,'"','')
local wildcard = word.."*"
local list = nyagos.glob(wildcard)
if #list == 1 and list[1] == wildcard then
return
end
local dict = {}
local array = {}
for _,path in ipairs(list) do
local index=string.find(path,"[^\\]+$")
local fname
if index then
fname=string.sub(path,index)
else
fname=path
end
array[1+#array] = fname
dict[fname] = path
end
nyagos.write("\n")
local result=nyagos.box(array)
if result then
result = dict[result]
if not result then
result = word
end
else
result = word
end
this:call("REPAINT_ON_NEWLINE")
if string.find(result," ",1,true) then
if string.find(result,"^~[\\/]") then
result = '~"'..string.sub(result,2)..'"'
else
result = '"'..result..'"'
end
end
assert( this:replacefrom(pos,result) )
end
share.__dump_history = function()
local uniq={}
local result={}
for i=nyagos.gethistory()-1,1,-1 do
local line = nyagos.gethistory(i)
if line ~= "" and not uniq[line] then
result[ #result+1 ] = line
uniq[line] = true
end
end
return result
end
nyagos.key.C_x = function(this)
nyagos.write("\nC-x: [r]:command-history, [h]:cd-history, [g]:git-revision\n")
local ch = nyagos.getkey()
local c = string.lower(string.char(ch))
local result
if c == 'r' or ch == bit32.band(string.byte('r'),0x1F) then
result = nyagos.box(share.__dump_history())
elseif c == 'h' or ch == bit32.band(string.byte('h') , 0x1F) then
result = nyagos.eval('cd --history | box')
if string.find(result,' ') then
result = '"'..result..'"'
end
elseif c == 'g' or ch == bit32.band(string.byte('g'),0x1F) then
result = nyagos.eval('git log --pretty="format:%h %s" | box')
result = string.match(result,"^%S+") or ""
end
this:call("REPAINT_ON_NEWLINE")
return result
end
nyagos.key.M_r = function(this)
nyagos.write("\n")
local result = nyagos.box(share.__dump_history())
this:call("REPAINT_ON_NEWLINE")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end
nyagos.key.M_h = function(this)
nyagos.write("\n")
local result = nyagos.eval('cd --history | box')
this:call("REPAINT_ON_NEWLINE")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end
nyagos.key.M_g = function(this)
nyagos.write("\n")
local result = nyagos.eval('git log --pretty="format:%h %s" | box')
this:call("REPAINT_ON_NEWLINE")
return string.match(result,"^%S+") or ""
end
nyagos.key["M-o"] = function(this)
local spacecut = false
if string.match(this.text," $") then
this:call("BACKWARD_DELETE_CHAR")
spacecut = true
end
local path,pos = this:lastword()
if not string.match(path,"%.[Ll][Nn][Kk]$") then
return
end
path = string.gsub(path,'"','')
path = string.gsub(path,"/","\\")
path = string.gsub(path,"^~",os.getenv("USERPROFILE"))
local wsh,err = nyagos.create_object("WScript.Shell")
if wsh then
local shortcut = wsh:CreateShortCut(path)
if shortcut then
local newpath = shortcut:_get("TargetPath")
if newpath then
local isDir = false
local fso = nyagos.create_object("Scripting.FileSystemObject")
if fso then
if fso:FolderExists(newpath) then
isDir = true
end
fso:_release()
end
if string.find(newpath," ") then
if isDir then
newpath = '"'..newpath..'\\'
else
newpath = '"'..newpath..'"'
if spacecut then
newpath = newpath .. ' '
end
end
elseif isDir then
newpath = newpath .. '\\'
elseif spacecut then
newpath = newpath .. ' '
end
if string.len(newpath) > 0 then
this:replacefrom(pos,newpath)
end
end
shortcut:_release()
end
wsh:_release()
end
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
nyagos.key.C_o = function(this)
local word,pos = this:lastword()
word = string.gsub(word,'"','')
local wildcard = word.."*"
local list = nyagos.glob(wildcard)
if #list == 1 and list[1] == wildcard then
return
end
local dict = {}
local array = {}
for _,path in ipairs(list) do
local index=string.find(path,"[^\\]+$")
local fname
if index then
fname=string.sub(path,index)
else
fname=path
end
array[1+#array] = fname
dict[fname] = path
end
nyagos.write("\n")
local result=nyagos.box(array)
if result then
result = dict[result]
if not result then
result = word
end
else
result = word
end
this:call("REPAINT_ON_NEWLINE")
if string.find(result," ",1,true) then
if string.find(result,"^~[\\/]") then
result = '~"'..string.sub(result,2)..'"'
else
result = '"'..result..'"'
end
end
assert( this:replacefrom(pos,result) )
end
share.__dump_history = function()
local uniq={}
local result={}
for i=nyagos.gethistory()-1,1,-1 do
local line = nyagos.gethistory(i)
if line ~= "" and not uniq[line] then
result[ #result+1 ] = line
uniq[line] = true
end
end
return result
end
nyagos.key.C_x = function(this)
nyagos.write("\nC-x: [r]:command-history, [h]:cd-history, [g]:git-revision\n")
local ch = nyagos.getkey()
local c = string.lower(string.char(ch))
local result
if c == 'r' or ch == bit32.band(string.byte('r'),0x1F) then
result = nyagos.box(share.__dump_history())
elseif c == 'h' or ch == bit32.band(string.byte('h') , 0x1F) then
result = nyagos.eval('cd --history | box')
if string.find(result,' ') then
result = '"'..result..'"'
end
elseif c == 'g' or ch == bit32.band(string.byte('g'),0x1F) then
result = nyagos.eval('git log --pretty="format:%h %s" | box')
result = string.match(result,"^%S+") or ""
end
this:call("REPAINT_ON_NEWLINE")
return result
end
nyagos.key.M_r = function(this)
nyagos.write("\n")
local result = nyagos.box(share.__dump_history())
this:call("REPAINT_ON_NEWLINE")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end
nyagos.key.M_h = function(this)
nyagos.write("\n")
local result = nyagos.eval('cd --history | box')
this:call("REPAINT_ON_NEWLINE")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end
nyagos.key.M_g = function(this)
nyagos.write("\n")
local result = nyagos.eval('git log --pretty="format:%h %s" | box')
this:call("REPAINT_ON_NEWLINE")
return string.match(result,"^%S+") or ""
end
nyagos.key["M-o"] = function(this)
local spacecut = false
if string.match(this.text," $") then
this:call("BACKWARD_DELETE_CHAR")
spacecut = true
end
local path,pos = this:lastword()
if not string.match(path,"%.[Ll][Nn][Kk]$") then
if spacecut then
return " "
end
return
end
path = string.gsub(path,'"','')
path = string.gsub(path,"/","\\")
path = string.gsub(path,"^~",os.getenv("USERPROFILE"))
local wsh,err = nyagos.create_object("WScript.Shell")
if wsh then
local shortcut = wsh:CreateShortCut(path)
if shortcut then
local newpath = shortcut:_get("TargetPath")
if newpath then
local isDir = false
local fso = nyagos.create_object("Scripting.FileSystemObject")
if fso then
if fso:FolderExists(newpath) then
isDir = true
end
fso:_release()
end
if string.find(newpath," ") then
if isDir then
newpath = '"'..newpath..'\\'
else
newpath = '"'..newpath..'"'
if spacecut then
newpath = newpath .. ' '
end
end
elseif isDir then
newpath = newpath .. '\\'
elseif spacecut then
newpath = newpath .. ' '
end
if string.len(newpath) > 0 then
this:replacefrom(pos,newpath)
end
end
shortcut:_release()
end
wsh:_release()
end
end
|
box.lua: fix: space on tail was cut, when shortcut expansion failed
|
box.lua: fix: space on tail was cut, when shortcut expansion failed
|
Lua
|
bsd-3-clause
|
nocd5/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos
|
a1c8c13a822bf0d4c15675f196166da505886d3d
|
src/tools/gcc.lua
|
src/tools/gcc.lua
|
--
-- gcc.lua
-- Provides GCC-specific configuration strings.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
premake.tools.gcc = {}
local gcc = premake.tools.gcc
local project = premake.project
local config = premake.config
--
-- Returns list of C preprocessor flags for a configuration.
--
gcc.cppflags = {
system = {
haiku = "-MMD",
wii = { "-MMD", "-MP", "-I$(LIBOGC_INC)", "$(MACHDEP)" },
_ = { "-MMD", "-MP" }
}
}
function gcc.getcppflags(cfg)
local flags = config.mapFlags(cfg, gcc.cppflags)
return flags
end
--
-- Returns list of C compiler flags for a configuration.
--
gcc.cflags = {
architecture = {
x32 = "-m32",
x64 = "-m64",
},
flags = {
FatalCompileWarnings = "-Werror",
NoFramePointer = "-fomit-frame-pointer",
ShadowedVariables = "-Wshadow",
Symbols = "-g",
UndefinedIdentifiers = "-Wundef",
},
floatingpoint = {
Fast = "-ffast-math",
Strict = "-ffloat-store",
},
kind = {
SharedLib = function(cfg)
if cfg.system ~= premake.WINDOWS then return "-fPIC" end
end,
},
strictaliasing = {
Off = "-fno-strict-aliasing",
Level1 = { "-fstrict-aliasing", "-Wstrict-aliasing=1" },
Level2 = { "-fstrict-aliasing", "-Wstrict-aliasing=2" },
Level3 = { "-fstrict-aliasing", "-Wstrict-aliasing=3" },
},
optimize = {
Off = "-O0",
On = "-O2",
Debug = "-Og",
Full = "-O3",
Size = "-Os",
Speed = "-O3",
},
vectorextensions = {
AVX = "-mavx",
SSE = "-msse",
SSE2 = "-msse2",
},
warnings = {
Extra = "-Wall -Wextra",
Off = "-w",
}
}
function gcc.getcflags(cfg)
local flags = config.mapFlags(cfg, gcc.cflags)
return flags
end
--
-- Returns list of C++ compiler flags for a configuration.
--
gcc.cxxflags = {
flags = {
NoExceptions = "-fno-exceptions",
NoRTTI = "-fno-rtti",
NoBufferSecurityCheck = "-fno-stack-protector"
}
}
function gcc.getcxxflags(cfg)
local flags = config.mapFlags(cfg, gcc.cxxflags)
return flags
end
--
-- Decorate defines for the GCC command line.
--
function gcc.getdefines(defines)
local result = {}
for _, define in ipairs(defines) do
table.insert(result, '-D' .. define)
end
return result
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function gcc.getforceincludes(cfg)
local result = {}
table.foreachi(cfg.forceincludes, function(value)
local fn = project.getrelative(cfg.project, value)
table.insert(result, string.format('-include %s', premake.quoted(fn)))
end)
return result
end
--
-- Decorate include file search paths for the GCC command line.
--
function gcc.getincludedirs(cfg, dirs)
local result = {}
for _, dir in ipairs(dirs) do
dir = project.getrelative(cfg.project, dir)
table.insert(result, '-I' .. premake.quoted(dir))
end
return result
end
--
-- Return a list of LDFLAGS for a specific configuration.
--
gcc.ldflags = {
architecture = {
x32 = "-m32",
x64 = "-m64",
},
flags = {
_Symbols = function(cfg)
-- OS X has a bug, see http://lists.apple.com/archives/Darwin-dev/2006/Sep/msg00084.html
return iif(cfg.system == premake.MACOSX, "-Wl,-x", "-s")
end,
},
kind = {
SharedLib = function(cfg)
local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") }
if cfg.system == "windows" and not cfg.flags.NoImportLib then
table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"')
end
return r
end,
WindowedApp = function(cfg)
if cfg.system == premake.WINDOWS then return "-mwindows" end
end,
},
system = {
wii = "$(MACHDEP)",
}
}
function gcc.getldflags(cfg)
local flags = config.mapFlags(cfg, gcc.ldflags)
return flags
end
--
-- Return a list of decorated additional libraries directories.
--
gcc.libraryDirectories = {
architecture = {
x32 = "-L/usr/lib32",
x64 = "-L/usr/lib64",
},
system = {
wii = "-L$(LIBOGC_LIB)",
}
}
function gcc.getLibraryDirectories(cfg)
local flags = config.mapFlags(cfg, gcc.libraryDirectories)
-- Scan the list of linked libraries. If any are referenced with
-- paths, add those to the list of library search paths
for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do
table.insert(flags, '-L' .. project.getrelative(cfg.project, dir))
end
return flags
end
--
-- Return the list of libraries to link, decorated with flags as needed.
--
function gcc.getlinks(cfg, systemonly)
local result = {}
-- Don't use the -l form for sibling libraries, since they may have
-- custom prefixes or extensions that will confuse the linker. Instead
-- just list out the full relative path to the library.
if not systemonly then
result = config.getlinks(cfg, "siblings", "fullpath")
end
-- The "-l" flag is fine for system libraries
local links = config.getlinks(cfg, "system", "fullpath")
for _, link in ipairs(links) do
if path.isframework(link) then
table.insert(result, "-framework " .. path.getbasename(link))
elseif path.isobjectfile(link) then
table.insert(result, link)
else
table.insert(result, "-l" .. path.getname(link))
end
end
return result
end
--
-- Returns makefile-specific configuration rules.
--
gcc.makesettings = {
system = {
wii = [[
ifeq ($(strip $(DEVKITPPC)),)
$(error "DEVKITPPC environment variable is not set")'
endif
include $(DEVKITPPC)/wii_rules']]
}
}
function gcc.getmakesettings(cfg)
local settings = config.mapFlags(cfg, gcc.makesettings)
return table.concat(settings)
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
gcc.tools = {
ps3 = {
cc = "ppu-lv2-g++",
cxx = "ppu-lv2-g++",
ar = "ppu-lv2-ar",
},
}
function gcc.gettoolname(cfg, tool)
local names = gcc.tools[cfg.architecture] or gcc.tools[cfg.system] or {}
local name = names[tool]
if tool == "rc" then
name = name or "windres"
end
return name
end
|
--
-- gcc.lua
-- Provides GCC-specific configuration strings.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
premake.tools.gcc = {}
local gcc = premake.tools.gcc
local project = premake.project
local config = premake.config
--
-- Returns list of C preprocessor flags for a configuration.
--
gcc.cppflags = {
system = {
haiku = "-MMD",
wii = { "-MMD", "-MP", "-I$(LIBOGC_INC)", "$(MACHDEP)" },
_ = { "-MMD", "-MP" }
}
}
function gcc.getcppflags(cfg)
local flags = config.mapFlags(cfg, gcc.cppflags)
return flags
end
--
-- Returns list of C compiler flags for a configuration.
--
gcc.cflags = {
architecture = {
x32 = "-m32",
x64 = "-m64",
},
flags = {
FatalCompileWarnings = "-Werror",
NoFramePointer = "-fomit-frame-pointer",
ShadowedVariables = "-Wshadow",
Symbols = "-g",
UndefinedIdentifiers = "-Wundef",
},
floatingpoint = {
Fast = "-ffast-math",
Strict = "-ffloat-store",
},
kind = {
SharedLib = function(cfg)
if cfg.system ~= premake.WINDOWS then return "-fPIC" end
end,
},
strictaliasing = {
Off = "-fno-strict-aliasing",
Level1 = { "-fstrict-aliasing", "-Wstrict-aliasing=1" },
Level2 = { "-fstrict-aliasing", "-Wstrict-aliasing=2" },
Level3 = { "-fstrict-aliasing", "-Wstrict-aliasing=3" },
},
optimize = {
Off = "-O0",
On = "-O2",
Debug = "-Og",
Full = "-O3",
Size = "-Os",
Speed = "-O3",
},
vectorextensions = {
AVX = "-mavx",
SSE = "-msse",
SSE2 = "-msse2",
},
warnings = {
Extra = "-Wall -Wextra",
Off = "-w",
}
}
function gcc.getcflags(cfg)
local flags = config.mapFlags(cfg, gcc.cflags)
return flags
end
--
-- Returns list of C++ compiler flags for a configuration.
--
gcc.cxxflags = {
flags = {
NoExceptions = "-fno-exceptions",
NoRTTI = "-fno-rtti",
NoBufferSecurityCheck = "-fno-stack-protector"
}
}
function gcc.getcxxflags(cfg)
local flags = config.mapFlags(cfg, gcc.cxxflags)
return flags
end
--
-- Decorate defines for the GCC command line.
--
function gcc.getdefines(defines)
local result = {}
for _, define in ipairs(defines) do
table.insert(result, '-D' .. define)
end
return result
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function gcc.getforceincludes(cfg)
local result = {}
table.foreachi(cfg.forceincludes, function(value)
local fn = project.getrelative(cfg.project, value)
table.insert(result, string.format('-include %s', premake.quoted(fn)))
end)
return result
end
--
-- Decorate include file search paths for the GCC command line.
--
function gcc.getincludedirs(cfg, dirs)
local result = {}
for _, dir in ipairs(dirs) do
dir = project.getrelative(cfg.project, dir)
table.insert(result, '-I' .. premake.quoted(dir))
end
return result
end
--
-- Return a list of LDFLAGS for a specific configuration.
--
gcc.ldflags = {
architecture = {
x32 = "-m32",
x64 = "-m64",
},
flags = {
_Symbols = function(cfg)
-- OS X has a bug, see http://lists.apple.com/archives/Darwin-dev/2006/Sep/msg00084.html
return iif(cfg.system == premake.MACOSX, "-Wl,-x", "-s")
end,
},
kind = {
SharedLib = function(cfg)
local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") }
if cfg.system == "windows" and not cfg.flags.NoImportLib then
table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"')
end
return r
end,
WindowedApp = function(cfg)
if cfg.system == premake.WINDOWS then return "-mwindows" end
end,
},
system = {
wii = "$(MACHDEP)",
}
}
function gcc.getldflags(cfg)
local flags = config.mapFlags(cfg, gcc.ldflags)
return flags
end
--
-- Return a list of decorated additional libraries directories.
--
gcc.libraryDirectories = {
architecture = {
x32 = "-L/usr/lib32",
x64 = "-L/usr/lib64",
},
system = {
wii = "-L$(LIBOGC_LIB)",
}
}
function gcc.getLibraryDirectories(cfg)
local flags = config.mapFlags(cfg, gcc.libraryDirectories)
-- Scan the list of linked libraries. If any are referenced with
-- paths, add those to the list of library search paths
for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do
table.insert(flags, '-L' .. project.getrelative(cfg.project, dir))
end
return flags
end
--
-- Return the list of libraries to link, decorated with flags as needed.
--
function gcc.getlinks(cfg, systemonly)
local result = {}
-- Don't use the -l form for sibling libraries, since they may have
-- custom prefixes or extensions that will confuse the linker. Instead
-- just list out the full relative path to the library.
if not systemonly then
result = config.getlinks(cfg, "siblings", "fullpath")
end
-- The "-l" flag is fine for system libraries
local links = config.getlinks(cfg, "system", "fullpath")
for _, link in ipairs(links) do
if path.isframework(link) then
table.insert(result, "-framework " .. path.getbasename(link))
elseif path.isobjectfile(link) then
table.insert(result, link)
else
table.insert(result, "-l" .. path.getname(link))
end
end
return result
end
--
-- Returns makefile-specific configuration rules.
--
gcc.makesettings = {
system = {
wii = [[
ifeq ($(strip $(DEVKITPPC)),)
$(error "DEVKITPPC environment variable is not set")'
endif
include $(DEVKITPPC)/wii_rules']]
}
}
function gcc.getmakesettings(cfg)
local settings = config.mapFlags(cfg, gcc.makesettings)
return table.concat(settings)
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
gcc.tools = {
ps3 = {
cc = "ppu-lv2-g++",
cxx = "ppu-lv2-g++",
ar = "ppu-lv2-ar",
},
}
function gcc.gettoolname(cfg, tool)
local names = gcc.tools[cfg.architecture] or gcc.tools[cfg.system] or {}
local name = names[tool]
if tool == "rc" then
name = name or "windres"
end
return name
end
|
Fix incorrect whitespace
|
Fix incorrect whitespace
|
Lua
|
bsd-3-clause
|
annulen/premake,annulen/premake,annulen/premake,annulen/premake
|
cd431fdf314c6f2130b14b51ac659ea9691a2421
|
amd_tressfx_sample/src/SushiToLuaParseHook.lua
|
amd_tressfx_sample/src/SushiToLuaParseHook.lua
|
--=================================================================================================
--
-- Author: Josh Barczak
-- 3D Application Research Group
-- ATI Research, Inc.
--
-- tolua++ parser hook which is used to work around things that the tolua parser screws up on.
--
--
--=================================================================================================
-- $Id: //depot/3darg/Demos/Effects/TressFXRelease/amd_tressfx_sample/src/SushiToLuaParseHook.lua#1 $
--
-- Last check-in: $DateTime: 2017/03/28 18:02:41 $
-- Last edited by: $Author: khillesl $
--=================================================================================================
-- (C) ATI Research, Inc. All rights reserved.
--=================================================================================================
-- called right after processing the $[ichl]file directives,
-- right before processing anything else
-- takes the package object as the parameter
function preprocess_hook(p)
-- p.code has all the input code from the pkg
-- tolua screws up on our SU_DLL symbol (it thinks its a type), so strip it out
p.code = string.gsub( p.code, "SU_DLL", "" )
end
-- called for every $ifile directive
-- takes a table with a string called 'code' inside, the filename, and any extra arguments
-- passed to $ifile. no return value
function include_file_hook(t, filename, ...)
end
-- called after processing anything that's not code (like '$renaming', comments, etc)
-- and right before parsing the actual code.
-- takes the Package object with all the code on the 'code' key. no return value
function preparse_hook(package)
_basic['SuString'] = 'sushistring'
_basic_ctype.sushistring = 'const char*'
end
-- called after writing all the output.
-- takes the Package object
function post_output_hook(package)
end
-- called at the beginning of the main parser function, with the code being parsed as a parameter
-- it can return nil if nothing was foind, or the contents of 'code', modified by the function
-- Usually a parser hook will search the beginning of the string for a token, and if it finds
-- anything, return the string without that token (after doing whatever it has to do with the token).
function parser_hook(code)
return nil
end
|
--=================================================================================================
--
-- Author: Josh Barczak
-- 3D Application Research Group
-- ATI Research, Inc.
--
-- tolua++ parser hook which is used to work around things that the tolua parser screws up on.
--
--
--=================================================================================================
-- $Id: //depot/3darg/Demos/Effects/TressFXRelease/amd_tressfx_sample/src/SushiToLuaParseHook.lua#1 $
--
-- Last check-in: $DateTime: 2017/03/28 18:02:41 $
-- Last edited by: $Author: khillesl $
--=================================================================================================
-- (C) ATI Research, Inc. All rights reserved.
--=================================================================================================
-- called right after processing the $[ichl]file directives,
-- right before processing anything else
-- takes the package object as the parameter
function preprocess_hook(p)
-- p.code has all the input code from the pkg
-- tolua screws up on our SU_DLL symbol (it thinks its a type), so strip it out
p.code = string.gsub( p.code, "SU_DLL", "" )
end
-- called for every $ifile directive
-- takes a table with a string called 'code' inside, the filename, and any extra arguments
-- passed to $ifile. no return value
function include_file_hook(t, filename, ...)
end
-- called after processing anything that's not code (like '$renaming', comments, etc)
-- and right before parsing the actual code.
-- takes the Package object with all the code on the 'code' key. no return value
function preparse_hook(package)
_basic['SuString'] = 'sushistring'
_basic_ctype.sushistring = 'const char*'
end
-- called after writing all the output.
-- takes the Package object
function post_output_hook(package)
end
-- called at the beginning of the main parser function, with the code being parsed as a parameter
-- it can return nil if nothing was foind, or the contents of 'code', modified by the function
-- Usually a parser hook will search the beginning of the string for a token, and if it finds
-- anything, return the string without that token (after doing whatever it has to do with the token).
function parser_hook(code)
return nil
end
|
Fix up line endings in this one lua file
|
Fix up line endings in this one lua file
|
Lua
|
mit
|
GPUOpen-Effects/TressFX,GPUOpen-Effects/TressFX,GPUOpen-Effects/TressFX
|
9abf02a9e6df5f54c7221d1d4cec4e26ba00c1bd
|
catalog.d/ezoe.lua
|
catalog.d/ezoe.lua
|
nyagos.on_command_not_found = function(args)
nyagos.writerr(args[0]..": コマンドではない。\n")
return true
end
local fsObj = nyagos.ole.create_object_utf8("Scripting.FileSystemObject")
local cd = nyagos.alias.cd
nyagos.alias.cd = function(args)
local success=true
for i=1,#args do
local dir=args[i]
if dir:sub(1,1) ~= "-" and not dir:match("%.[lL][nN][kK]$") then
local stat = nyagos.stat(dir)
if not stat or not stat.isdir then
nyagos.writerr(dir..": ディレクトリではない。\n")
success = false
end
end
end
if success then
if cd then
cd(args)
else
args[0] = "__cd__"
nyagos.exec(args)
end
end
end
-- vim:set fenc=utf8 --
|
nyagos.on_command_not_found = function(args)
nyagos.writerr(args[0]..": コマンドではない。\n")
return true
end
local cd = nyagos.alias.cd
nyagos.alias.cd = function(args)
local success=true
for i=1,#args do
local dir=args[i]
if dir:sub(1,1) ~= "-" and not dir:match("%.[lL][nN][kK]$") then
local stat = nyagos.stat(dir)
if not stat or not stat.isdir then
nyagos.writerr(dir..": ディレクトリではない。\n")
success = false
end
end
end
if success then
if cd then
cd(args)
else
args[0] = "__cd__"
nyagos.exec(args)
end
end
end
-- vim:set fenc=utf8 --
|
Fixed ezoe.lua loaded unused Scripting.FileSystemObject
|
Fixed ezoe.lua loaded unused Scripting.FileSystemObject
|
Lua
|
bsd-3-clause
|
hattya/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos,hattya/nyagos,tyochiai/nyagos,kissthink/nyagos,nocd5/nyagos,kissthink/nyagos,hattya/nyagos
|
cc3b441240cf86a4a5c1307126bf27e4324f56c5
|
boss.lua
|
boss.lua
|
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0")
local Debug = LibStub("LibDebug-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local BOSSES = {
-- The Obsidian Sanctum
[28860] = "Sartharion",
-- Eye of Eternity
[28859] = "Malygos",
-- Naxxramas
[15956] = "Anub'Rekhan",
[15953] = "Grand Widow Faerlina",
[15952] = "Maexxna",
[16028] = "Patchwerk",
[15931] = "Grobbulus",
[15932] = "Gluth",
[15928] = "Thaddius",
[16061] = "Instructor Razuvious",
[16060] = "Gothik the Harvester",
-- TODO(alkis): Add Four Horsemen
[15954] = "Noth the Plaguebringer",
[15936] = "Heigan the Unclean",
[16011] = "Loatheb",
[15989] = "Sapphiron",
[15990] = "Kel'Thuzad",
-- Vault of Archavon
[31125] = "Archavon the Stone Watcher",
[33993] = "Emalon the Storm Watcher",
-- Ulduar
[33113] = "Flame Leviathan",
[33118] = "Ignis the Furnace Master",
[33186] = "Razorscale",
[33293] = "XT-002 Deconstructor",
-- TODO(alkis): Add Assembly of Iron
[32930] = "Kologarn",
[33515] = "Auriaya",
[33412] = "Mimiron",
[32845] = "Hodir",
[32865] = "Thorim",
[32906] = "Freya",
[33271] = "General Vezax",
[33288] = "Yogg-Saron",
-- TODO(alkis): Add Algalon the Observer
}
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name,
timestamp, event,
source, source_name, source_flags,
dest, dest_name, dest_flags,
...)
-- bitlib does not support 64 bit integers so we are going to do some
-- string hacking to get what we want. For an NPC:
-- guid & 0x00F0000000000000 == 3
-- and the NPC id is:
-- (guid & 0x0000FFFFFF000000) >> 24
if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then
local npc_id = tonumber(string.sub(dest, -12, -7), 16)
if BOSSES[npc_id] then
self:SendMessage("BossKilled", dest_name, "kill")
end
end
end
local in_combat = false
local award_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopAwardQueue(event_name)
if in_combat then return end
if #award_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
if StaticPopup_Visible("EPGP_BOSS_DEAD") or StaticPopup_Visible("EPGP_BOSS_ATTEMPT") then
return
end
local boss_name = table.remove(award_queue, 1)
local dialog
if event_name == "kill" then
dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name)
else
dialog = StaticPopup_Show("EPGP_BOSS_ATTEMPT", boss_name)
end
if dialog then
dialog.reason = boss_name
end
end
local function BossAttempt(event_name, boss_name)
Debug("Boss attempt: %s (%s)", boss_name, event_name)
-- Temporary fix since we cannot unregister DBM callbacks
if not mod:IsEnabled() then return end
if CanEditOfficerNote() and IsRLorML() then
tinsert(award_queue, boss_name)
if not timer then
timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 0.1, event_name)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:DebugTest()
BossKilled("BossKilled", "Sapphiron")
end
mod.dbDefaults = {
profile = {
enabled = false,
wipedetection = false,
},
}
mod.optionsName = L["Boss"]
mod.optionsDesc = L["Automatic boss tracking"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."]
},
wipedetection = {
type = "toggle",
name = L["Wipe awards"],
desc = L["Awards for wipes on bosses. Requires Deadly Boss Mods"],
order = 2,
disabled = function(v) return not DBM end,
},
}
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
if DBM then
EPGP:Print(L["Using DBM for boss kill tracking"])
DBM:RegisterCallback("kill",
function (mod)
BossAttempt("kill", mod.combatInfo.name)
end)
DBM:RegisterCallback("wipe",
function (mod)
BossAttempt("wipe", mod.combatInfo.name)
end)
else
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
self:RegisterMessage("BossKilled", BossAttempt)
end
end
|
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0")
local Debug = LibStub("LibDebug-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local BOSSES = {
-- The Obsidian Sanctum
[28860] = "Sartharion",
-- Eye of Eternity
[28859] = "Malygos",
-- Naxxramas
[15956] = "Anub'Rekhan",
[15953] = "Grand Widow Faerlina",
[15952] = "Maexxna",
[16028] = "Patchwerk",
[15931] = "Grobbulus",
[15932] = "Gluth",
[15928] = "Thaddius",
[16061] = "Instructor Razuvious",
[16060] = "Gothik the Harvester",
-- TODO(alkis): Add Four Horsemen
[15954] = "Noth the Plaguebringer",
[15936] = "Heigan the Unclean",
[16011] = "Loatheb",
[15989] = "Sapphiron",
[15990] = "Kel'Thuzad",
-- Vault of Archavon
[31125] = "Archavon the Stone Watcher",
[33993] = "Emalon the Storm Watcher",
-- Ulduar
[33113] = "Flame Leviathan",
[33118] = "Ignis the Furnace Master",
[33186] = "Razorscale",
[33293] = "XT-002 Deconstructor",
-- TODO(alkis): Add Assembly of Iron
[32930] = "Kologarn",
[33515] = "Auriaya",
[33412] = "Mimiron",
[32845] = "Hodir",
[32865] = "Thorim",
[32906] = "Freya",
[33271] = "General Vezax",
[33288] = "Yogg-Saron",
-- TODO(alkis): Add Algalon the Observer
}
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name,
timestamp, event,
source, source_name, source_flags,
dest, dest_name, dest_flags,
...)
-- bitlib does not support 64 bit integers so we are going to do some
-- string hacking to get what we want. For an NPC:
-- guid & 0x00F0000000000000 == 3
-- and the NPC id is:
-- (guid & 0x0000FFFFFF000000) >> 24
if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then
local npc_id = tonumber(string.sub(dest, -12, -7), 16)
if BOSSES[npc_id] then
self:SendMessage("BossKilled", dest_name, "kill")
end
end
end
local in_combat = false
local award_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopAwardQueue(event_name)
if in_combat then return end
if #award_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
if StaticPopup_Visible("EPGP_BOSS_DEAD") or StaticPopup_Visible("EPGP_BOSS_ATTEMPT") then
return
end
local boss_name = table.remove(award_queue, 1)
local dialog
if event_name == "kill" then
dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name)
elseif event_name == "wipe" and mod.db.profile.wipedetection then
dialog = StaticPopup_Show("EPGP_BOSS_ATTEMPT", boss_name)
end
if dialog then
dialog.reason = boss_name
end
end
local function BossAttempt(event_name, boss_name)
Debug("Boss attempt: %s (%s)", boss_name, event_name)
-- Temporary fix since we cannot unregister DBM callbacks
if not mod:IsEnabled() then return end
if CanEditOfficerNote() and IsRLorML() then
tinsert(award_queue, boss_name)
if not timer then
timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 0.1, event_name)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:DebugTest()
BossKilled("BossKilled", "Sapphiron")
end
mod.dbDefaults = {
profile = {
enabled = false,
wipedetection = false,
},
}
mod.optionsName = L["Boss"]
mod.optionsDesc = L["Automatic boss tracking"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."]
},
wipedetection = {
type = "toggle",
name = L["Wipe awards"],
desc = L["Awards for wipes on bosses. Requires Deadly Boss Mods"],
order = 2,
disabled = function(v) return not DBM end,
},
}
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
if DBM then
EPGP:Print(L["Using DBM for boss kill tracking"])
DBM:RegisterCallback("kill",
function (mod)
BossAttempt("kill", mod.combatInfo.name)
end)
DBM:RegisterCallback("wipe",
function (mod)
BossAttempt("wipe", mod.combatInfo.name)
end)
else
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
self:RegisterMessage("BossKilled", BossAttempt)
end
end
|
Make wipe detection respect a disabled setting.
|
Make wipe detection respect a disabled setting.
This fixes issue 473.
|
Lua
|
bsd-3-clause
|
protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp
|
f05a1a964f14634dbe5b3e623230131b22df1a75
|
boss.lua
|
boss.lua
|
local mod = EPGP:NewModule("EPGP_Boss", "AceEvent-3.0", "AceTimer-3.0")
local BOSSES = {
-- The Obsidian Sanctum
[28860] = "Sartharion",
-- Eye of Eternity
[28859] = "Malygos",
-- Naxxramas
[15956] = "Anub'Rekhan",
[15953] = "Grand Widow Faerlina",
[15952] = "Maexxna",
[16028] = "Patchwerk",
[15931] = "Grobbulus",
[15932] = "Gluth",
[15928] = "Thaddius",
[16061] = "Instructor Razuvious",
[16060] = "Gothik the Harvester",
-- TODO(alkis): Add Four Horsemen
[15954] = "Noth the Plaguebringer",
[15936] = "Heigan the Unclean",
[16011] = "Loatheb",
[15989] = "Sapphiron",
[15990] = "Kel'Thuzad",
}
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
local monitoring = false
function mod:RAID_ROSTER_UPDATE()
if EPGP.db.profile.auto_boss and IsRLorML() then
if not monitoring then
monitoring = true
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
else
if monitoring then
monitoring = false
self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
end
end
function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name,
timestamp, event,
source, source_name, source_flags,
dest, dest_name, dest_flags,
...)
-- bitlib does not support 64 bit integers so we are going to do some
-- string hacking to get what we want. For an NPC:
-- guid & 0x00F0000000000000 == 3
-- and the NPC id is:
-- (guid & 0x0000FFFFFF000000) >> 24
if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then
local npc_id = tonumber(string.sub(dest, -12, -7), 16)
if BOSSES[npc_id] then
self:SendMessage("BossKilled", dest_name)
end
end
end
local in_combat = false
local award_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopAwardQueue()
if in_combat then return end
if #award_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
if StaticPopup_Visible("EPGP_BOSS_DEAD") then
return
end
local boss_name = table.remove(award_queue, 1)
local dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name)
if dialog then
dialog.reason = boss_name
end
end
local function BossKilled(event_name, boss_name)
if CanEditOfficerNote() then
tinsert(award_queue, boss_name)
if not timer then
timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 1)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:Debug()
BossKilled("BossKilled", "Sapphiron")
end
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterEvent("RAID_ROSTER_UPDATE")
self:RegisterMessage("BossKilled", BossKilled)
end
|
local mod = EPGP:NewModule("EPGP_Boss", "AceEvent-3.0", "AceTimer-3.0")
local BOSSES = {
-- The Obsidian Sanctum
[28860] = "Sartharion",
-- Eye of Eternity
[28859] = "Malygos",
-- Naxxramas
[15956] = "Anub'Rekhan",
[15953] = "Grand Widow Faerlina",
[15952] = "Maexxna",
[16028] = "Patchwerk",
[15931] = "Grobbulus",
[15932] = "Gluth",
[15928] = "Thaddius",
[16061] = "Instructor Razuvious",
[16060] = "Gothik the Harvester",
-- TODO(alkis): Add Four Horsemen
[15954] = "Noth the Plaguebringer",
[15936] = "Heigan the Unclean",
[16011] = "Loatheb",
[15989] = "Sapphiron",
[15990] = "Kel'Thuzad",
-- Vault of Archavon
[31125] = "Archavon the Stone Watcher",
}
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
local monitoring = false
function mod:RAID_ROSTER_UPDATE()
if EPGP.db.profile.auto_boss and IsRLorML() then
if not monitoring then
monitoring = true
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
else
if monitoring then
monitoring = false
self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
end
end
function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name,
timestamp, event,
source, source_name, source_flags,
dest, dest_name, dest_flags,
...)
-- bitlib does not support 64 bit integers so we are going to do some
-- string hacking to get what we want. For an NPC:
-- guid & 0x00F0000000000000 == 3
-- and the NPC id is:
-- (guid & 0x0000FFFFFF000000) >> 24
if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then
local npc_id = tonumber(string.sub(dest, -12, -7), 16)
if BOSSES[npc_id] then
self:SendMessage("BossKilled", dest_name)
end
end
end
local in_combat = false
local award_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopAwardQueue()
if in_combat then return end
if #award_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
if StaticPopup_Visible("EPGP_BOSS_DEAD") then
return
end
local boss_name = table.remove(award_queue, 1)
local dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name)
if dialog then
dialog.reason = boss_name
end
end
local function BossKilled(event_name, boss_name)
if CanEditOfficerNote() then
tinsert(award_queue, boss_name)
if not timer then
timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 1)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:Debug()
BossKilled("BossKilled", "Sapphiron")
end
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterEvent("RAID_ROSTER_UPDATE")
self:RegisterMessage("BossKilled", BossKilled)
end
|
Add Archavon. This fixes issue 303.
|
Add Archavon. This fixes issue 303.
|
Lua
|
bsd-3-clause
|
protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,sheldon/epgp
|
c7aa1e494a4bc5ceccac7b3b3eb48d3fa70eb860
|
plugins/unban.lua
|
plugins/unban.lua
|
--[[
Copyright 2017 Matthew Hesketh <[email protected]>
This code is licensed under the MIT. See LICENSE for details.
]]
local unban = {}
local mattata = require('mattata')
local redis = require('mattata-redis')
function unban:init()
unban.commands = mattata.commands(
self.info.username
):command('unban').table
unban.help = '/unban [user] - Unbans a user from the current chat. This command can only be used by moderators and administrators of a supergroup.'
end
function unban:on_message(message, configuration, language)
if message.chat.type ~= 'supergroup'
then
return mattata.send_reply(
message,
language['errors']['supergroup']
)
elseif not mattata.is_group_admin(
message.chat.id,
message.from.id
)
then
return mattata.send_reply(
message,
language['errors']['admin']
)
end
local reason = false
local user = false
local input = mattata.input(message.text)
-- Check the message object for any users this command
-- is intended to be executed on.
if message.reply
then
user = message.reply.from.id
if input
then
reason = input
end
elseif input
and input:match(' ')
then
user, reason = input:match('^(.-) (.-)$')
elseif input
then
user = input
end
if not user then
local success = mattata.send_force_reply(
message,
'Which user would you like me to unban? You can specify this user by their @username or numerical ID.'
)
if success then
redis:set(
string.format(
'action:%s:%s',
message.chat.id,
success.result.message_id
),
'/unban'
)
end
return
elseif not message.reply then
if input:match('^.- .-$')
then
reason = input:match(' (.-)$')
input = input:match('^(.-) ')
end
elseif mattata.input(message.text) then
reason = mattata.input(message.text)
end
if tonumber(input) == nil
and not input:match('^%@')
then
input = '@' .. input
end
local user = mattata.get_user(input) -- Resolve the username/ID to a user object.
if not user
then
return mattata.send_reply(
message,
language['errors']['unknown']
)
elseif user.result.id == self.info.id
then
return
end
user = user.result
local status = mattata.get_chat_member(
message.chat.id,
user.id
)
if not status
then
return mattata.send_reply(
message,
language['errors']['generic']
)
elseif status.result.status == 'creator'
or status.result.status == 'administrator'
then -- We won't try and unban administrators.
return mattata.send_reply(
message,
'I cannot unban this user because they are a moderator or an administrator in this chat.'
)
elseif status.result.status == 'member'
then -- Check if the user is in the group or not.
return mattata.send_reply(
message,
'I cannot unban this user because they are still in this chat.'
)
end
local success = mattata.unban_chat_member( -- Attempt to unban the user from the group.
message.chat.id,
user.id
)
if not success
then -- Since we've ruled everything else out, it's safe to say if it wasn't a success then the bot isn't an administrator in the group.
return mattata.send_reply(
message,
'I need to have administrative permissions in order to unban this user. Please amend this issue, and try again.'
)
end
redis:hincrby(
string.format(
'chat:%s:%s',
message.chat.id,
user.id
),
'unbans',
1
)
if mattata.get_setting(
message.chat.id,
'log administrative actions'
)
then
mattata.send_message(
mattata.get_log_chat(message.chat.id),
string.format(
'<pre>%s%s [%s] has unbanned %s%s [%s] from %s%s [%s]%s.</pre>',
message.from.username and '@' or '',
message.from.username or mattata.escape_html(message.from.first_name),
message.from.id,
user.username and '@' or '',
user.username or mattata.escape_html(user.first_name),
user.id,
message.chat.username and '@' or '',
message.chat.username or mattata.escape_html(message.chat.title),
message.chat.id,
reason and ', for ' .. reason or ''
),
'html'
)
end
if message.reply
and mattata.get_setting(
message.chat.id,
'delete reply on action'
)
then
mattata.delete_message(
message.chat.id,
message.reply.message_id
)
end
return mattata.send_message(
message.chat.id,
string.format(
'<pre>%s%s has unbanned %s%s%s.</pre>',
message.from.username and '@' or '',
message.from.username or mattata.escape_html(message.from.first_name),
user.username and '@' or '',
user.username or mattata.escape_html(user.first_name),
reason and ', for ' .. reason or ''
),
'html'
)
end
return unban
|
--[[
Copyright 2017 Matthew Hesketh <[email protected]>
This code is licensed under the MIT. See LICENSE for details.
]]
local unban = {}
local mattata = require('mattata')
local redis = require('mattata-redis')
function unban:init()
unban.commands = mattata.commands(
self.info.username
):command('unban').table
unban.help = '/unban [user] - Unbans a user from the current chat. This command can only be used by moderators and administrators of a supergroup.'
end
function unban:on_message(message, configuration, language)
if message.chat.type ~= 'supergroup'
then
return mattata.send_reply(
message,
language['errors']['supergroup']
)
elseif not mattata.is_group_admin(
message.chat.id,
message.from.id
)
then
return mattata.send_reply(
message,
language['errors']['admin']
)
end
local reason = false
local user = false
local input = mattata.input(message.text)
-- Check the message object for any users this command
-- is intended to be executed on.
if message.reply
then
user = message.reply.from.id
if input
then
reason = input
end
elseif input
and input:match(' ')
then
user, reason = input:match('^(.-) (.-)$')
elseif input
then
user = input
end
if not user then
local success = mattata.send_force_reply(
message,
'Which user would you like me to unban? You can specify this user by their @username or numerical ID.'
)
if success then
redis:set(
string.format(
'action:%s:%s',
message.chat.id,
success.result.message_id
),
'/unban'
)
end
return
end
if tonumber(user) == nil
and not user:match('^%@')
then
user = '@' .. user
end
user = mattata.get_user(user)
or mattata.get_chat(user) -- Resolve the username/ID to a user object.
if not user
then
return mattata.send_reply(
message,
language['errors']['unknown']
)
elseif user.result.id == self.info.id
then
return
end
user = user.result
local status = mattata.get_chat_member(
message.chat.id,
user.id
)
if not status
then
return mattata.send_reply(
message,
language['errors']['generic']
)
elseif status.result.status == 'creator'
or status.result.status == 'administrator'
then -- We won't try and unban administrators.
return mattata.send_reply(
message,
'I cannot unban this user because they are a moderator or an administrator in this chat.'
)
elseif status.result.status == 'member'
then -- Check if the user is in the group or not.
return mattata.send_reply(
message,
'I cannot unban this user because they are still in this chat.'
)
end
local success = mattata.unban_chat_member( -- Attempt to unban the user from the group.
message.chat.id,
user.id
)
if not success
then -- Since we've ruled everything else out, it's safe to say if it wasn't a success then the bot isn't an administrator in the group.
return mattata.send_reply(
message,
'I need to have administrative permissions in order to unban this user. Please amend this issue, and try again.'
)
end
redis:hincrby(
string.format(
'chat:%s:%s',
message.chat.id,
user.id
),
'unbans',
1
)
if mattata.get_setting(
message.chat.id,
'log administrative actions'
)
then
mattata.send_message(
mattata.get_log_chat(message.chat.id),
string.format(
'<pre>%s%s [%s] has unbanned %s%s [%s] from %s%s [%s]%s.</pre>',
message.from.username and '@' or '',
message.from.username or mattata.escape_html(message.from.first_name),
message.from.id,
user.username and '@' or '',
user.username or mattata.escape_html(user.first_name),
user.id,
message.chat.username and '@' or '',
message.chat.username or mattata.escape_html(message.chat.title),
message.chat.id,
reason and ', for ' .. reason or ''
),
'html'
)
end
if message.reply
and mattata.get_setting(
message.chat.id,
'delete reply on action'
)
then
mattata.delete_message(
message.chat.id,
message.reply.message_id
)
end
return mattata.send_message(
message.chat.id,
string.format(
'<pre>%s%s has unbanned %s%s%s.</pre>',
message.from.username and '@' or '',
message.from.username or mattata.escape_html(message.from.first_name),
user.username and '@' or '',
user.username or mattata.escape_html(user.first_name),
reason and ', for ' .. reason or ''
),
'html'
)
end
return unban
|
I think this fixes it??
|
I think this fixes it??
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
a4571c297ed2a6d5f421dd6c472d8281fc41a20d
|
frontend/apps/reader/modules/readertypeset.lua
|
frontend/apps/reader/modules/readertypeset.lua
|
local InputContainer = require("ui/widget/container/inputcontainer")
local ConfirmBox = require("ui/widget/confirmbox")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local Event = require("ui/event")
local DEBUG = require("dbg")
local T = require("ffi/util").template
local _ = require("gettext")
local ReaderTypeset = InputContainer:new{
css_menu_title = _("Set render style"),
css = nil,
internal_css = true,
}
function ReaderTypeset:init()
self.ui.menu:registerToMainMenu(self)
end
function ReaderTypeset:onReadSettings(config)
self.css = config:readSetting("css")
if self.css and self.css ~= "" then
self.ui.document:setStyleSheet(self.css)
else
self.ui.document:setStyleSheet(self.ui.document.default_css)
self.css = self.ui.document.default_css
end
-- default to enable embedded css
self.embedded_css = config:readSetting("embedded_css")
if self.embedded_css == nil then self.embedded_css = true end
self.ui.document:setEmbeddedStyleSheet(self.embedded_css and 1 or 0)
-- set page margins
self:onSetPageMargins(config:readSetting("copt_page_margins") or DCREREADER_CONFIG_MARGIN_SIZES_MEDIUM)
-- default to enable floating punctuation
-- the floating punctuation should not be boolean value for the following
-- expression otherwise a false value will never be returned but numerical
-- values will survive this expression
self.floating_punctuation = config:readSetting("floating_punctuation") or
G_reader_settings:readSetting("floating_punctuation") or 1
self:toggleFloatingPunctuation(self.floating_punctuation)
end
function ReaderTypeset:onSaveSettings()
self.ui.doc_settings:saveSetting("css", self.css)
self.ui.doc_settings:saveSetting("embedded_css", self.embedded_css)
self.ui.doc_settings:saveSetting("floating_punctuation", self.floating_punctuation)
end
function ReaderTypeset:onToggleEmbeddedStyleSheet(toggle)
self:toggleEmbeddedStyleSheet(toggle)
return true
end
function ReaderTypeset:genStyleSheetMenu()
local file_list = {
{
text = _("clear all external styles"),
callback = function()
self:setStyleSheet(nil)
end
},
{
text = _("Auto"),
callback = function()
self:setStyleSheet(self.ui.document.default_css)
end
},
}
for f in lfs.dir("./data") do
if lfs.attributes("./data/"..f, "mode") == "file" and string.match(f, "%.css$") then
table.insert(file_list, {
text = f,
callback = function()
self:setStyleSheet("./data/"..f)
end
})
end
end
return file_list
end
function ReaderTypeset:setStyleSheet(new_css)
if new_css ~= self.css then
--DEBUG("setting css to ", new_css)
self.css = new_css
if new_css == nil then
new_css = ""
end
self.ui.document:setStyleSheet(new_css)
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:setEmbededStyleSheetOnly()
if self.css ~= nil then
-- clear applied css
self.ui.document:setStyleSheet("")
self.ui.document:setEmbeddedStyleSheet(1)
self.css = nil
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:toggleEmbeddedStyleSheet(toggle)
if not toggle then
self.embedded_css = false
self:setStyleSheet(self.ui.document.default_css)
self.ui.document:setEmbeddedStyleSheet(0)
else
self.embedded_css = true
--self:setStyleSheet(self.ui.document.default_css)
self.ui.document:setEmbeddedStyleSheet(1)
end
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:toggleFloatingPunctuation(toggle)
-- for some reason the toggle value read from history files may stay boolean
-- and there seems no more elegant way to convert boolean values to numbers
if toggle == true then
toggle = 1
elseif toggle == false then
toggle = 0
end
self.ui.document:setFloatingPunctuation(toggle)
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:addToMainMenu(tab_item_table)
-- insert table to main reader menu
table.insert(tab_item_table.typeset, {
text = self.css_menu_title,
sub_item_table = self:genStyleSheetMenu(),
})
table.insert(tab_item_table.typeset, {
text = _("Floating punctuation"),
checked_func = function() return self.floating_punctuation == 1 end,
callback = function()
self.floating_punctuation = self.floating_punctuation == 1 and 0 or 1
self:toggleFloatingPunctuation(self.floating_punctuation)
end,
hold_callback = function() self:makeDefaultFloatingPunctuation() end,
})
end
function ReaderTypeset:makeDefaultFloatingPunctuation()
local toggler = self.floating_punctuation == 1 and _("On") or _("Off")
UIManager:show(ConfirmBox:new{
text = T(
_("Set default floating punctuation to %1?"),
toggler
),
ok_callback = function()
G_reader_settings:saveSetting("floating_punctuation", self.floating_punctuation)
end,
})
end
function ReaderTypeset:onSetPageMargins(margins)
local left = Screen:scaleBySize(margins[1])
local top = Screen:scaleBySize(margins[2])
local right = Screen:scaleBySize(margins[3])
local bottom = Screen:scaleBySize(margins[4])
self.ui.document:setPageMargins(left, top, right, bottom)
self.ui:handleEvent(Event:new("UpdatePos"))
return true
end
return ReaderTypeset
|
local InputContainer = require("ui/widget/container/inputcontainer")
local ConfirmBox = require("ui/widget/confirmbox")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local Event = require("ui/event")
local DEBUG = require("dbg")
local T = require("ffi/util").template
local _ = require("gettext")
local ReaderTypeset = InputContainer:new{
css_menu_title = _("Set render style"),
css = nil,
internal_css = true,
}
function ReaderTypeset:init()
self.ui.menu:registerToMainMenu(self)
end
function ReaderTypeset:onReadSettings(config)
self.css = config:readSetting("css")
if self.css and self.css ~= "" then
self.ui.document:setStyleSheet(self.css)
else
self.ui.document:setStyleSheet(self.ui.document.default_css)
self.css = self.ui.document.default_css
end
self.embedded_css = config:readSetting("embedded_css")
if self.embedded_css == nil then
-- default to enable embedded css
-- note that it's a bit confusing here:
-- global settins store 0/1, while document settings store false/true
-- we leave it that way for now to maintain backwards compatibility
local global = G_reader_settings:readSetting("copt_embedded_css")
self.embedded_css = (global == nil or global == 1) and true or false
end
self.ui.document:setEmbeddedStyleSheet(self.embedded_css and 1 or 0)
-- set page margins
self:onSetPageMargins(config:readSetting("copt_page_margins") or DCREREADER_CONFIG_MARGIN_SIZES_MEDIUM)
-- default to enable floating punctuation
-- the floating punctuation should not be boolean value for the following
-- expression otherwise a false value will never be returned but numerical
-- values will survive this expression
self.floating_punctuation = config:readSetting("floating_punctuation") or
G_reader_settings:readSetting("floating_punctuation") or 1
self:toggleFloatingPunctuation(self.floating_punctuation)
end
function ReaderTypeset:onSaveSettings()
self.ui.doc_settings:saveSetting("css", self.css)
self.ui.doc_settings:saveSetting("embedded_css", self.embedded_css)
self.ui.doc_settings:saveSetting("floating_punctuation", self.floating_punctuation)
end
function ReaderTypeset:onToggleEmbeddedStyleSheet(toggle)
self:toggleEmbeddedStyleSheet(toggle)
return true
end
function ReaderTypeset:genStyleSheetMenu()
local file_list = {
{
text = _("clear all external styles"),
callback = function()
self:setStyleSheet(nil)
end
},
{
text = _("Auto"),
callback = function()
self:setStyleSheet(self.ui.document.default_css)
end
},
}
for f in lfs.dir("./data") do
if lfs.attributes("./data/"..f, "mode") == "file" and string.match(f, "%.css$") then
table.insert(file_list, {
text = f,
callback = function()
self:setStyleSheet("./data/"..f)
end
})
end
end
return file_list
end
function ReaderTypeset:setStyleSheet(new_css)
if new_css ~= self.css then
--DEBUG("setting css to ", new_css)
self.css = new_css
if new_css == nil then
new_css = ""
end
self.ui.document:setStyleSheet(new_css)
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:setEmbededStyleSheetOnly()
if self.css ~= nil then
-- clear applied css
self.ui.document:setStyleSheet("")
self.ui.document:setEmbeddedStyleSheet(1)
self.css = nil
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:toggleEmbeddedStyleSheet(toggle)
if not toggle then
self.embedded_css = false
self:setStyleSheet(self.ui.document.default_css)
self.ui.document:setEmbeddedStyleSheet(0)
else
self.embedded_css = true
--self:setStyleSheet(self.ui.document.default_css)
self.ui.document:setEmbeddedStyleSheet(1)
end
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:toggleFloatingPunctuation(toggle)
-- for some reason the toggle value read from history files may stay boolean
-- and there seems no more elegant way to convert boolean values to numbers
if toggle == true then
toggle = 1
elseif toggle == false then
toggle = 0
end
self.ui.document:setFloatingPunctuation(toggle)
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:addToMainMenu(tab_item_table)
-- insert table to main reader menu
table.insert(tab_item_table.typeset, {
text = self.css_menu_title,
sub_item_table = self:genStyleSheetMenu(),
})
table.insert(tab_item_table.typeset, {
text = _("Floating punctuation"),
checked_func = function() return self.floating_punctuation == 1 end,
callback = function()
self.floating_punctuation = self.floating_punctuation == 1 and 0 or 1
self:toggleFloatingPunctuation(self.floating_punctuation)
end,
hold_callback = function() self:makeDefaultFloatingPunctuation() end,
})
end
function ReaderTypeset:makeDefaultFloatingPunctuation()
local toggler = self.floating_punctuation == 1 and _("On") or _("Off")
UIManager:show(ConfirmBox:new{
text = T(
_("Set default floating punctuation to %1?"),
toggler
),
ok_callback = function()
G_reader_settings:saveSetting("floating_punctuation", self.floating_punctuation)
end,
})
end
function ReaderTypeset:onSetPageMargins(margins)
local left = Screen:scaleBySize(margins[1])
local top = Screen:scaleBySize(margins[2])
local right = Screen:scaleBySize(margins[3])
local bottom = Screen:scaleBySize(margins[4])
self.ui.document:setPageMargins(left, top, right, bottom)
self.ui:handleEvent(Event:new("UpdatePos"))
return true
end
return ReaderTypeset
|
read global default value for using embedded stylesheets
|
read global default value for using embedded stylesheets
The global configuration wasn't evaluated before.
Fixes #1364.
|
Lua
|
agpl-3.0
|
frankyifei/koreader,noname007/koreader,pazos/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,lgeek/koreader,poire-z/koreader,ashang/koreader,chrox/koreader,robert00s/koreader,mihailim/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,Hzj-jie/koreader,ashhher3/koreader,apletnev/koreader,mwoz123/koreader,chihyang/koreader,NickSavage/koreader,houqp/koreader,koreader/koreader,Markismus/koreader
|
fa8368ef21c1896dd4d533eaad2442ec2d46e70e
|
app/modules/creationix/coro-tcp.lua
|
app/modules/creationix/coro-tcp.lua
|
exports.name = "creationix/coro-tcp"
exports.version = "0.1.1"
exports.dependencies = {
"creationix/[email protected]"
}
local uv = require('uv')
local wrapStream = require('creationix/coro-channel').wrapStream
local function makeCallback()
local thread = coroutine.running()
return function (err, data)
if err then
return assert(coroutine.resume(thread, nil, err))
end
return assert(coroutine.resume(thread, data or true))
end
end
exports.makeCallback = makeCallback
function exports.connect(host, port)
local res, success, err
uv.getaddrinfo(host, port, { socktype = "stream", family="inet" }, makeCallback())
res, err = coroutine.yield()
if not res then return nil, err end
local socket = uv.new_tcp()
socket:connect(res[1].addr, res[1].port, makeCallback())
success, err = coroutine.yield()
if not success then return nil, err end
local read, write = wrapStream(socket)
return read, write, socket
end
function exports.createServer(addr, port, onConnect)
local server = uv.new_tcp()
assert(server:bind(addr, port))
server:listen(256, function (err)
assert(not err, err)
local socket = uv.new_tcp()
server:accept(socket)
coroutine.wrap(xpcall)(function ()
local read, write = wrapStream(socket)
return onConnect(read, write, socket)
end, function (failure)
print(debug.stacktrace(failure))
socket:close()
end)
end)
end
|
exports.name = "creationix/coro-tcp"
exports.version = "0.1.2"
exports.dependencies = {
"creationix/[email protected]"
}
local uv = require('uv')
local wrapStream = require('creationix/coro-channel').wrapStream
local function makeCallback()
local thread = coroutine.running()
return function (err, data)
if err then
return assert(coroutine.resume(thread, nil, err))
end
return assert(coroutine.resume(thread, data or true))
end
end
exports.makeCallback = makeCallback
function exports.connect(host, port)
local res, success, err
uv.getaddrinfo(host, port, { socktype = "stream", family="inet" }, makeCallback())
res, err = coroutine.yield()
if not res then return nil, err end
local socket = uv.new_tcp()
socket:connect(res[1].addr, res[1].port, makeCallback())
success, err = coroutine.yield()
if not success then return nil, err end
local read, write = wrapStream(socket)
return read, write, socket
end
function exports.createServer(addr, port, onConnect)
local server = uv.new_tcp()
assert(server:bind(addr, port))
server:listen(256, function (err)
assert(not err, err)
local socket = uv.new_tcp()
server:accept(socket)
coroutine.wrap(function ()
local success, failure = xpcall(function ()
local read, write = wrapStream(socket)
return onConnect(read, write, socket)
end, debug.traceback)
if not success then
print(failure)
socket:close()
end
end)()
end)
end
|
Fix error handling in coro-tcp server
|
Fix error handling in coro-tcp server
|
Lua
|
apache-2.0
|
kaustavha/lit,lduboeuf/lit,DBarney/lit,kidaa/lit,squeek502/lit,luvit/lit,james2doyle/lit,zhaozg/lit,1yvT0s/lit
|
cafaecbeb57771e2bfdc0c1501f2e16536a9646b
|
src/extensions/cp/blackmagic/resolve/main/PrimaryWindow.lua
|
src/extensions/cp/blackmagic/resolve/main/PrimaryWindow.lua
|
--- === cp.blackmagic.resolve.main.PrimaryWindow ===
---
--- Primary Window Module.
local require = require
local log = require "hs.logger".new "primaryWindow"
local axutils = require "cp.ui.axutils"
local Window = require "cp.ui.Window"
local Do = require "cp.rx.go.Do"
local If = require "cp.rx.go.If"
local class = require "middleclass"
local lazy = require "cp.lazy"
local childrenWithRole = axutils.childrenWithRole
local PrimaryWindow = class("PrimaryWindow"):include(lazy)
--- cp.blackmagic.resolve.main.PrimaryWindow.matches(w) -> boolean
--- Function
--- Checks to see if a window matches the PrimaryWindow requirements
---
--- Parameters:
--- * w - The window to check
---
--- Returns:
--- * `true` if matched otherwise `false`
function PrimaryWindow.static.matches(element)
local children = element and childrenWithRole(element, "AXCheckBox")
return children and #children >= 6
end
--- cp.blackmagic.resolve.main.PrimaryWindow(app) -> PrimaryWindow object
--- Constructor
--- Creates a new PrimaryWindow.
---
--- Parameters:
--- * None
---
--- Returns:
--- * PrimaryWindow
function PrimaryWindow:initialize(app)
self._app = app
end
--- cp.blackmagic.resolve.main.PrimaryWindow:app() -> cp.blackmagic.resolve
--- Method
--- Returns the application the display belongs to.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The app instance.
function PrimaryWindow:app()
return self._app
end
--- cp.blackmagic.resolve.main.PrimaryWindow:window() -> cp.ui.Window
--- Method
--- Returns the `Window` instance.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Window` instance.
function PrimaryWindow.lazy.method:window()
return Window(self:app().app, self.UI)
end
--- cp.blackmagic.resolve.main.PrimaryWindow.UI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- The main `axuielement` for the window. May be `nil` if not currently available.
function PrimaryWindow.lazy.prop:UI()
return self:app().windowsUI:mutate(function(original)
return axutils.cache(self, "_ui", function()
return axutils.childMatching(original(), PrimaryWindow.matches)
end,
PrimaryWindow.matches)
end)
end
--- cp.blackmagic.resolve.main.PrimaryWindow.hsWindow <cp.prop: hs.window; read-only>
--- Field
--- The `hs.window` instance for the window, or `nil` if it can't be found.
function PrimaryWindow.lazy.prop:hsWindow()
return self:window().hsWindow
end
--- cp.blackmagic.resolve.main.PrimaryWindow.isShowing <cp.prop: boolean>
--- Field
--- Is `true` if the window is visible.
function PrimaryWindow.lazy.prop:isShowing()
return self:window().visible
end
--- cp.blackmagic.resolve.main.PrimaryWindow.isFullScreen <cp.prop: boolean>
--- Field
--- Is `true` if the window is full-screen.
function PrimaryWindow.lazy.prop:isFullScreen()
return self:window().fullScreen
end
--- cp.blackmagic.resolve.main.PrimaryWindow.frame <cp.prop: frame>
--- Field
--- The current position (x, y, width, height) of the window.
function PrimaryWindow.lazy.prop:frame()
return self:window().frame
end
--- cp.blackmagic.resolve.main.PrimaryWindow:show() -> PrimaryWindow
--- Method
--- Shows the Primary Window.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `PrimaryWindow` instance.
function PrimaryWindow:show()
self:app():show()
if not self:isShowing() then
return self:window():focus()
end
return self
end
--- cp.blackmagic.resolve.main.PrimaryWindow:doShow() -> PrimaryWindow
--- Field
--- A [Statement](cp.rx.go.Statement.md) that attempts to show the Primary Window.
---
--- Returns:
--- * The `Statement`, which resolves as either `true` or sends an error.
function PrimaryWindow.lazy.method:doShow()
return Do(self:app():doShow())
:Then(
If(self.isShowing):Is(false)
:Then(self:window():doFocus())
)
:Label("PrimaryWindow:doShow")
end
return PrimaryWindow
|
--- === cp.blackmagic.resolve.main.PrimaryWindow ===
---
--- Primary Window Module.
local require = require
--local log = require "hs.logger".new "primaryWindow"
local axutils = require "cp.ui.axutils"
local Window = require "cp.ui.Window"
local Do = require "cp.rx.go.Do"
local If = require "cp.rx.go.If"
local class = require "middleclass"
local lazy = require "cp.lazy"
local childrenWithRole = axutils.childrenWithRole
local PrimaryWindow = class("PrimaryWindow"):include(lazy)
--- cp.blackmagic.resolve.main.PrimaryWindow.matches(w) -> boolean
--- Function
--- Checks to see if a window matches the PrimaryWindow requirements
---
--- Parameters:
--- * w - The window to check
---
--- Returns:
--- * `true` if matched otherwise `false`
function PrimaryWindow.static.matches(element)
local children = element and childrenWithRole(element, "AXCheckBox")
return children and #children >= 6
end
--- cp.blackmagic.resolve.main.PrimaryWindow(app) -> PrimaryWindow object
--- Constructor
--- Creates a new PrimaryWindow.
---
--- Parameters:
--- * None
---
--- Returns:
--- * PrimaryWindow
function PrimaryWindow:initialize(app)
self._app = app
end
--- cp.blackmagic.resolve.main.PrimaryWindow:app() -> cp.blackmagic.resolve
--- Method
--- Returns the application the display belongs to.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The app instance.
function PrimaryWindow:app()
return self._app
end
--- cp.blackmagic.resolve.main.PrimaryWindow:window() -> cp.ui.Window
--- Method
--- Returns the `Window` instance.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Window` instance.
function PrimaryWindow.lazy.method:window()
return Window(self:app().app, self.UI)
end
--- cp.blackmagic.resolve.main.PrimaryWindow.UI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- The main `axuielement` for the window. May be `nil` if not currently available.
function PrimaryWindow.lazy.prop:UI()
return self:app().windowsUI:mutate(function(original)
return axutils.cache(self, "_ui", function()
return axutils.childMatching(original(), PrimaryWindow.matches)
end,
PrimaryWindow.matches)
end)
end
--- cp.blackmagic.resolve.main.PrimaryWindow.hsWindow <cp.prop: hs.window; read-only>
--- Field
--- The `hs.window` instance for the window, or `nil` if it can't be found.
function PrimaryWindow.lazy.prop:hsWindow()
return self:window().hsWindow
end
--- cp.blackmagic.resolve.main.PrimaryWindow.isShowing <cp.prop: boolean>
--- Field
--- Is `true` if the window is visible.
function PrimaryWindow.lazy.prop:isShowing()
return self:window().visible
end
--- cp.blackmagic.resolve.main.PrimaryWindow.isFullScreen <cp.prop: boolean>
--- Field
--- Is `true` if the window is full-screen.
function PrimaryWindow.lazy.prop:isFullScreen()
return self:window().fullScreen
end
--- cp.blackmagic.resolve.main.PrimaryWindow.frame <cp.prop: frame>
--- Field
--- The current position (x, y, width, height) of the window.
function PrimaryWindow.lazy.prop:frame()
return self:window().frame
end
--- cp.blackmagic.resolve.main.PrimaryWindow:show() -> PrimaryWindow
--- Method
--- Shows the Primary Window.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `PrimaryWindow` instance.
function PrimaryWindow:show()
self:app():show()
if not self:isShowing() then
return self:window():focus()
end
return self
end
--- cp.blackmagic.resolve.main.PrimaryWindow:doShow() -> PrimaryWindow
--- Field
--- A [Statement](cp.rx.go.Statement.md) that attempts to show the Primary Window.
---
--- Returns:
--- * The `Statement`, which resolves as either `true` or sends an error.
function PrimaryWindow.lazy.method:doShow()
return Do(self:app():doShow())
:Then(
If(self.isShowing):Is(false)
:Then(self:window():doFocus())
)
:Label("PrimaryWindow:doShow")
end
return PrimaryWindow
|
Fixed @sticker-ci bugs
|
Fixed @sticker-ci bugs
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks
|
212ce606b273c65a695e0d66ba76a9897dc60458
|
mdb_test.lua
|
mdb_test.lua
|
local lightningmdb_lib=require "lightningmdb"
local lightningmdb = _VERSION=="Lua 5.2" and lightningmdb_lib or lightningmdb
local function pt(t)
for k,v in pairs(t) do
print(k,v)
end
end
local function ps(e)
print("--- env stat")
pt(e:stat())
print("---")
end
local function cursor_pairs(cursor_,key_,op_)
return coroutine.wrap(
function()
local k = key_,v
repeat
k,v = cursor_:get(k,op_ or cursor_.MDB_NEXT)
if k then
coroutine.yield(k,v)
end
until not k
end)
end
local function mtest()
print("--- mtest2")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",e.MDB_FIXEDMAP,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open(nil,0)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
lightningmdb.MDB_NOOVERWRITE)
if not rc then
j = j + 1
end
end
print(j,"duplicates skipped")
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
local k
for k,v in cursor_pairs(c) do
print(k,v)
end
c:close()
t:abort()
math.randomseed(os.time())
j = 0
for i=count,1,-math.random(5) do
j = j + 1
t = e:txn_begin(nil,0)
local key = string.format("%03x",values[i])
if not t:del(d,key,nil) then
j = j - 1
t:abort()
else
t:commit()
end
end
print("deleted",j,"values")
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
print("cursor next")
local key
for k,v in cursor_pairs(c,nil,c.MDB_NEXT) do
print(k,v)
key = k
end
print("cursor prev")
for k,v in cursor_pairs(c,key,c.MDB_PREV) do
print(k,v)
end
c:close()
e:dbi_close(d)
t:abort()
e:close()
end
local function mtest2()
print("--- mtest2")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
e:set_maxdbs(4)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",e.MDB_FIXEDMAP + e.MDB_NOSYNC,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open("id1",t.MDB_CREATE)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
lightningmdb.MDB_NOOVERWRITE)
if not rc then
j = j + 1
end
end
print(j,"duplicates skipped")
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
local k
for k,v in cursor_pairs(c) do
print(k,v)
end
c:close()
t:abort()
math.randomseed(os.time())
j = 0
for i=count,1,-math.random(5) do
j = j + 1
t = e:txn_begin(nil,0)
local key = string.format("%03x",values[i])
if not t:del(d,key,nil) then
j = j - 1
t:abort()
else
t:commit()
end
end
print("deleted",j,"values")
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
print("cursor next")
local key
for k,v in cursor_pairs(c,nil,c.MDB_NEXT) do
print(k,v)
key = k
end
print("cursor prev")
for k,v in cursor_pairs(c,key,c.MDB_PREV) do
print(k,v)
end
c:close()
e:dbi_close(d)
t:abort()
e:close()
end
local function mtest3()
print("--- mtest3")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
e:set_maxdbs(4)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",e.MDB_FIXEDMAP + e.MDB_NOSYNC,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open("id2",t.MDB_CREATE+t.MDB_DUPSORT)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
if i%5==0 then
v = values[i-1]
end
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
lightningmdb.MDB_NODUPDATA)
if not rc then
j = j + 1
end
end
if j>0 then
print("duplicate skipped",j)
end
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
for k,v in cursor_pairs(c,nil,c.MDB_NEXT) do
print(k,v)
end
end
mtest()
mtest2()
mtest3()
|
local lightningmdb_lib=require "lightningmdb"
local lightningmdb = _VERSION=="Lua 5.2" and lightningmdb_lib or lightningmdb
local MDB = setmetatable({}, {__index = function(t, k)
return lightningmdb["MDB_" .. k]
end})
local function pt(t)
for k,v in pairs(t) do
print(k,v)
end
end
local function ps(e)
print("--- env stat")
pt(e:stat())
print("---")
end
local function cursor_pairs(cursor_,key_,op_)
return coroutine.wrap(
function()
local k = key_,v
repeat
k,v = cursor_:get(k,op_ or MDB.NEXT)
if k then
coroutine.yield(k,v)
end
until not k
end)
end
local function mtest()
print("--- mtest2")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",MDB.FIXEDMAP,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open(nil,0)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
MDB.NOOVERWRITE)
if not rc then
j = j + 1
end
end
print(j,"duplicates skipped")
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
local k
for k,v in cursor_pairs(c) do
print(k,v)
end
c:close()
t:abort()
math.randomseed(os.time())
j = 0
for i=count,1,-math.random(5) do
j = j + 1
t = e:txn_begin(nil,0)
local key = string.format("%03x",values[i])
if not t:del(d,key,nil) then
j = j - 1
t:abort()
else
t:commit()
end
end
print("deleted",j,"values")
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
print("cursor next")
local key
for k,v in cursor_pairs(c,nil,MDB.NEXT) do
print(k,v)
key = k
end
print("cursor prev")
for k,v in cursor_pairs(c,key,MDB.PREV) do
print(k,v)
end
c:close()
e:dbi_close(d)
t:abort()
e:close()
end
local function mtest2()
print("--- mtest2")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
e:set_maxdbs(4)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",MDB.FIXEDMAP + MDB.NOSYNC,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open("id1",MDB.CREATE)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
MDB.NOOVERWRITE)
if not rc then
j = j + 1
end
end
print(j,"duplicates skipped")
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
local k
for k,v in cursor_pairs(c) do
print(k,v)
end
c:close()
t:abort()
math.randomseed(os.time())
j = 0
for i=count,1,-math.random(5) do
j = j + 1
t = e:txn_begin(nil,0)
local key = string.format("%03x",values[i])
if not t:del(d,key,nil) then
j = j - 1
t:abort()
else
t:commit()
end
end
print("deleted",j,"values")
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
print("cursor next")
local key
for k,v in cursor_pairs(c,nil,MDB.NEXT) do
print(k,v)
key = k
end
print("cursor prev")
for k,v in cursor_pairs(c,key,MDB.PREV) do
print(k,v)
end
c:close()
e:dbi_close(d)
t:abort()
e:close()
end
local function mtest3()
print("--- mtest3")
local count = math.random(10)+15
local values = {}
math.randomseed(os.time())
for i=1,count do
values[i] = math.random(1024)
end
local e = lightningmdb.env_create()
e:set_mapsize(10485760)
e:set_maxdbs(4)
os.execute("mkdir -p ./temp/testdb")
e:open("./temp/testdb",MDB.FIXEDMAP + MDB.NOSYNC,420)
local t = e:txn_begin(nil,0)
local d = t:dbi_open("id2",MDB.CREATE+MDB.DUPSORT)
print("adding values:",count)
local j = 0
for i,v in ipairs(values) do
if i%5==0 then
v = values[i-1]
end
local rc = t:put(d,string.format("%03x",v),string.format("%d foo bar",v),
MDB.NODUPDATA)
if not rc then
j = j + 1
end
end
if j>0 then
print("duplicate skipped",j)
end
t:commit()
ps(e)
t = e:txn_begin(nil,0)
c = t:cursor_open(d)
for k,v in cursor_pairs(c,nil,MDB.NEXT) do
print(k,v)
end
end
mtest()
mtest2()
mtest3()
|
fix mdb_test.lua (MDB_ constants)
|
fix mdb_test.lua (MDB_ constants)
|
Lua
|
mit
|
shmul/lightningmdb,shmul/lightningmdb,shmul/lightningdbm,catwell/lightningmdb
|
f9736d7918081dfed1793fee1ccfd243b58fd4f7
|
src/haka/lua/rule_group.lua
|
src/haka/lua/rule_group.lua
|
local rule_group = class('RuleGroup')
function rule_group.method:__init(args)
self.rules = {}
self.init = args.init
self.continue = args.continue
self.fini = args.fini
end
function rule_group.method:rule(eval)
table.insert(self.rules, eval)
end
function rule_group.method:eval(...)
self.init(...)
for _, rule in ipairs(self.rules) do
local ret = rule(...)
if not self.continue(ret, ...) then
return
end
end
self.fini(...)
end
function haka.rule_group(args)
if not args.hook then
error("no hook defined for rule group")
end
local group = rule_group:new(args)
haka.context.connections:register(args.hook, function (...) group:eval(...) end)
return group
end
|
local rule_group = class('RuleGroup')
function rule_group.method:__init(args, continue)
self.rules = {}
self.init = args.init or function () end
self.continue = args.continue or function () return true end
self.fini = args.fini or function () end
self.event_continue = continue
end
function rule_group.method:rule(eval)
table.insert(self.rules, eval)
end
function rule_group.method:eval(...)
self.init(...)
for _, rule in ipairs(self.rules) do
local ret = rule(...)
if not self.event_continue(...) or
not self.continue(ret, ...) then
return
end
end
self.fini(...)
end
function haka.rule_group(args)
if not args.hook then
error("no hook defined for rule group")
end
local group = rule_group:new(args, args.hook.continue)
haka.context.connections:register(args.hook, function (...) group:eval(...) end)
return group
end
|
Fix rule group issues
|
Fix rule group issues
Fix problem when the rule group is created without continue or fini
functions. Also make sure to stop the rule evaluation if one of them
drop the packet or flow.
|
Lua
|
mpl-2.0
|
Wingless-Archangel/haka,LubyRuffy/haka,haka-security/haka,lcheylus/haka,Wingless-Archangel/haka,LubyRuffy/haka,haka-security/haka,lcheylus/haka,nabilbendafi/haka,lcheylus/haka,nabilbendafi/haka,nabilbendafi/haka,haka-security/haka
|
58b6fb5591b9b7f883bd114bcd7088616fb3fd5d
|
nvim/.config/nvim/lua/lsp_conf.lua
|
nvim/.config/nvim/lua/lsp_conf.lua
|
require('nvim-lsp-installer').setup {}
local lsp = require('lspconfig')
-- configure keymaps on attach to a lsp server
local custom_attach = function(client, bufnr)
-- setup diagnostics toggle on and off
vim.g.diagnostics_visible = true
function _G.toggle_diagnostics()
if vim.g.diagnostics_visible then
vim.g.diagnostics_visible = false
vim.diagnostic.disable()
else
vim.g.diagnostics_visible = true
vim.diagnostic.enable()
end
end
vim.api.nvim_buf_set_keymap(0, 'n', '<Leader>ct', ':call v:lua.toggle_diagnostics()<CR>', { silent = true,
noremap = true })
-- setup global autocompletion
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- keymaps
local bufopts = { noremap = true, silent = true, buffer = bufnr }
vim.keymap.set('n', ']w', vim.diagnostic.goto_next, bufopts)
vim.keymap.set('n', '[w', vim.diagnostic.goto_prev, bufopts)
vim.keymap.set('n', '<leader>ch', vim.lsp.buf.hover, bufopts)
vim.keymap.set('n', '<leader>cd', vim.lsp.buf.definition, bufopts)
vim.keymap.set('n', '<leader>cD', vim.lsp.buf.declaration, bufopts)
vim.keymap.set('n', '<leader>ci', vim.lsp.buf.implementation, bufopts)
vim.keymap.set('n', '<leader>co', vim.lsp.buf.type_definition, bufopts)
vim.keymap.set('n', '<leader>cu', vim.lsp.buf.references, bufopts)
vim.keymap.set('n', '<leader>cs', vim.lsp.buf.signature_help, bufopts)
vim.keymap.set('n', '<leader>cr', vim.lsp.buf.rename, bufopts)
vim.keymap.set('n', '<leader>cf', vim.lsp.buf.formatting, bufopts)
vim.keymap.set('n', '<leader>ce', vim.diagnostic.setloclist, bufopts)
vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action, bufopts)
vim.keymap.set('x', '<leader>ca', vim.lsp.buf.range_code_action, bufopts)
end
-- configure autocompletion based on lsp
local cmp = require 'cmp'
cmp.setup({
snippet = {
-- REQUIRED - you must specify a snippet engine
expand = function(args)
-- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
-- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
-- require('snippy').expand_snippet(args.body) -- For `snippy` users.
vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
end,
},
window = {
-- completion = cmp.config.window.bordered(),
-- documentation = cmp.config.window.bordered(),
},
mapping = cmp.mapping.preset.insert({
['<C-b>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.abort(),
['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
}),
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
-- { name = 'vsnip' }, -- For vsnip users.
-- { name = 'luasnip' }, -- For luasnip users.
{ name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
}, {
{ name = 'buffer' },
},
{
{name = 'orgmode'}
})
})
-- Set configuration for specific filetype.
cmp.setup.filetype('gitcommit', {
sources = cmp.config.sources(
{
{ name = 'cmp_git' }, -- You can specify the `cmp_git` source if you were installed it.
},
{
{ name = 'buffer' },
}
)
})
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = 'buffer' }
}
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = 'path' }
}, {
{ name = 'cmdline' }
})
})
-- Setup lspconfig.
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- setup servers for each programming language
lsp.pylsp.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
lsp.sumneko_lua.setup {
on_attach = custom_attach,
capabilities = capabilities,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = 'LuaJIT',
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {'vim'},
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false,
},
},
},
}
lsp.vimls.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
lsp.perlnavigator.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
|
require('nvim-lsp-installer').setup {}
local lsp = require('lspconfig')
-- configure keymaps on attach to a lsp server
local custom_attach = function(client, bufnr)
-- setup diagnostics toggle on and off
vim.g.diagnostics_visible = true
function _G.toggle_diagnostics()
if vim.g.diagnostics_visible then
vim.g.diagnostics_visible = false
vim.diagnostic.disable()
else
vim.g.diagnostics_visible = true
vim.diagnostic.enable()
end
end
vim.api.nvim_buf_set_keymap(0, 'n', '<Leader>ct', ':call v:lua.toggle_diagnostics()<CR>', { silent = true,
noremap = true })
-- setup global autocompletion
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- keymaps
local bufopts = { noremap = true, silent = true, buffer = bufnr }
vim.keymap.set('n', ']w', vim.diagnostic.goto_next, bufopts)
vim.keymap.set('n', '[w', vim.diagnostic.goto_prev, bufopts)
vim.keymap.set('n', '<leader>ch', vim.lsp.buf.hover, bufopts)
vim.keymap.set('n', '<leader>cd', vim.lsp.buf.definition, bufopts)
vim.keymap.set('n', '<leader>cD', vim.lsp.buf.declaration, bufopts)
vim.keymap.set('n', '<leader>ci', vim.lsp.buf.implementation, bufopts)
vim.keymap.set('n', '<leader>co', vim.lsp.buf.type_definition, bufopts)
vim.keymap.set('n', '<leader>cu', vim.lsp.buf.references, bufopts)
vim.keymap.set('n', '<leader>cs', vim.lsp.buf.signature_help, bufopts)
vim.keymap.set('n', '<leader>cr', vim.lsp.buf.rename, bufopts)
vim.keymap.set('n', '<leader>cf', vim.lsp.buf.formatting, bufopts)
vim.keymap.set('n', '<leader>ce', vim.diagnostic.setloclist, bufopts)
vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action, bufopts)
vim.keymap.set('x', '<leader>ca', vim.lsp.buf.range_code_action, bufopts)
end
-- configure autocompletion based on lsp
local cmp = require 'cmp'
cmp.setup({
snippet = {
-- REQUIRED - you must specify a snippet engine
expand = function(args)
-- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
-- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
-- require('snippy').expand_snippet(args.body) -- For `snippy` users.
vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
end,
},
window = {
-- completion = cmp.config.window.bordered(),
-- documentation = cmp.config.window.bordered(),
},
mapping = cmp.mapping.preset.insert({
['<C-b>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.abort(),
['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
}),
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
-- { name = 'vsnip' }, -- For vsnip users.
-- { name = 'luasnip' }, -- For luasnip users.
{ name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
}, {
{ name = 'buffer' },
},
{
{ name = 'orgmode' }
})
})
-- Set configuration for specific filetype.
cmp.setup.filetype('gitcommit', {
sources = cmp.config.sources(
{
{ name = 'cmp_git' }, -- You can specify the `cmp_git` source if you were installed it.
},
{
{ name = 'buffer' },
}
)
})
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = 'buffer' }
}
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = 'path' }
}, {
{ name = 'cmdline' }
})
})
-- Setup lspconfig.
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- setup servers for each programming language
lsp.pylsp.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
lsp.sumneko_lua.setup {
on_attach = custom_attach,
capabilities = capabilities,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = 'LuaJIT',
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = { 'vim' },
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false,
},
},
},
}
lsp.vimls.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
lsp.perlnavigator.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
|
[nvim] quickfix format lua code
|
[nvim] quickfix format lua code
|
Lua
|
mit
|
voltux/dotfiles,voltux/dotfiles,voltux/dotfiles
|
b2247488866cd13360060c9d7282362b8c4b09bb
|
util.lua
|
util.lua
|
--LinearNoBias from elements library
local LinearNoBias, Linear = torch.class('nn.LinearNoBias', 'nn.Linear')
function LinearNoBias:__init(inputSize, outputSize)
nn.Module.__init(self)
self.weight = torch.Tensor(outputSize, inputSize)
self.gradWeight = torch.Tensor(outputSize, inputSize)
self:reset()
end
function LinearNoBias:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
if nn.oldSeed then
for i=1,self.weight:size(1) do
self.weight:select(1, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
end
else
self.weight:uniform(-stdv, stdv)
end
return self
end
function LinearNoBias:updateOutput(input)
if input:dim() == 1 then
self.output:resize(self.weight:size(1))
self.output:mv(self.weight, input)
elseif input:dim() == 2 then
local nframe = input:size(1)
local nElement = self.output:nElement()
self.output:resize(nframe, self.weight:size(1))
if self.output:nElement() ~= nElement then
self.output:zero()
end
if not self.addBuffer or self.addBuffer:nElement() ~= nframe then
self.addBuffer = input.new(nframe):fill(1)
end
self.output:addmm(0, self.output, 1, input, self.weight:t())
else
error('input must be vector or matrix')
end
return self.output
end
function LinearNoBias:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if input:dim() == 1 then
self.gradWeight:addr(scale, gradOutput, input)
elseif input:dim() == 2 then
self.gradWeight:addmm(scale, gradOutput:t(), input)
end
end
local ViewAs = torch.class('nn.ViewAs', 'nn.Module')
-- Views input[1] based on first ndim sizes of input[2]
function ViewAs:__init(ndim)
nn.Module.__init(self)
self.ndim = ndim
self.gradInput = {torch.Tensor()}
end
function ViewAs:updateOutput(input)
self.output = self.output or input.new()
assert(#input == 2, 'ViewAs can only take 2 inputs')
if self.ndim then
local sizes = {}
for i = 1, self.ndim do
sizes[#sizes+1] = input[2]:size(i)
end
self.output:view(input[1], table.unpack(sizes))
else
local sizes = input[2]:size()
self.output:view(input[1], sizes)
end
return self.output
end
function ViewAs:updateGradInput(input, gradOutput)
self.gradInput[1] = self.gradInput[1] or gradOutput.new()
self.gradInput[1]:view(gradOutput, input[1]:size())
return self.gradInput
end
local ReplicateAs = torch.class('nn.ReplicateAs', 'nn.Module')
-- Replicates dim m of input[1] based on dim n of input[2]
-- basically copies Replicate
function ReplicateAs:__init(in_dim, template_dim)
nn.Module.__init(self)
self.in_dim = in_dim
self.template_dim = template_dim
self.gradInput = {torch.Tensor()}
end
function ReplicateAs:updateOutput(input)
assert(#input == 2, 'needs 2 inputs')
local rdim = self.in_dim
local ntimes = input[2]:size(self.template_dim)
input = input[1]
local sz = torch.LongStorage(input:dim() + 1)
sz[rdim] = ntimes
for i = 1,input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
sz[i+offset] = input:size(i)
end
local st = torch.LongStorage(input:dim() + 1)
st[rdim] = 0
for i = 1,input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
st[i+offset] = input:stride(i)
end
self.output:set(input:storage(), input:storageOffset(), sz, st)
return self.output
end
function ReplicateAs:updateGradInput(input, gradOutput)
input = input[1]
self.gradInput[1]:resizeAs(input):zero()
local rdim = self.in_dim
local sz = torch.LongStorage(input:dim() + 1)
sz[rdim] = 1
for i = 1, input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
sz[i+offset] = input:size(i)
end
local gradInput = self.gradInput[1]:view(sz)
gradInput:sum(gradOutput, rdim)
return self.gradInput
end
|
--LinearNoBias from elements library
local LinearNoBias, Linear = torch.class('nn.LinearNoBias', 'nn.Linear')
function LinearNoBias:__init(inputSize, outputSize)
nn.Module.__init(self)
self.weight = torch.Tensor(outputSize, inputSize)
self.gradWeight = torch.Tensor(outputSize, inputSize)
self:reset()
end
function LinearNoBias:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
if nn.oldSeed then
for i=1,self.weight:size(1) do
self.weight:select(1, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
end
else
self.weight:uniform(-stdv, stdv)
end
return self
end
function LinearNoBias:updateOutput(input)
if input:dim() == 1 then
self.output:resize(self.weight:size(1))
self.output:mv(self.weight, input)
elseif input:dim() == 2 then
local nframe = input:size(1)
local nElement = self.output:nElement()
self.output:resize(nframe, self.weight:size(1))
if self.output:nElement() ~= nElement then
self.output:zero()
end
if not self.addBuffer or self.addBuffer:nElement() ~= nframe then
self.addBuffer = input.new(nframe):fill(1)
end
self.output:addmm(0, self.output, 1, input, self.weight:t())
else
error('input must be vector or matrix')
end
return self.output
end
function LinearNoBias:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if input:dim() == 1 then
self.gradWeight:addr(scale, gradOutput, input)
elseif input:dim() == 2 then
self.gradWeight:addmm(scale, gradOutput:t(), input)
end
end
local ViewAs = torch.class('nn.ViewAs', 'nn.Module')
-- Views input[1] based on first ndim sizes of input[2]
function ViewAs:__init(ndim)
nn.Module.__init(self)
self.ndim = ndim
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function ViewAs:updateOutput(input)
self.output = self.output or input.new()
assert(#input == 2, 'ViewAs can only take 2 inputs')
if self.ndim then
local sizes = {}
for i = 1, self.ndim do
sizes[#sizes+1] = input[2]:size(i)
end
self.output:view(input[1], table.unpack(sizes))
else
local sizes = input[2]:size()
self.output:view(input[1], sizes)
end
return self.output
end
function ViewAs:updateGradInput(input, gradOutput)
self.gradInput[2]:resizeAs(input[2]):zero() -- unused
self.gradInput[1] = self.gradInput[1] or gradOutput.new()
self.gradInput[1]:view(gradOutput, input[1]:size())
return self.gradInput
end
local ReplicateAs = torch.class('nn.ReplicateAs', 'nn.Module')
-- Replicates dim m of input[1] based on dim n of input[2]
-- basically copies Replicate
function ReplicateAs:__init(in_dim, template_dim)
nn.Module.__init(self)
self.in_dim = in_dim
self.template_dim = template_dim
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function ReplicateAs:updateOutput(input)
assert(#input == 2, 'needs 2 inputs')
local rdim = self.in_dim
local ntimes = input[2]:size(self.template_dim)
input = input[1]
local sz = torch.LongStorage(input:dim() + 1)
sz[rdim] = ntimes
for i = 1,input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
sz[i+offset] = input:size(i)
end
local st = torch.LongStorage(input:dim() + 1)
st[rdim] = 0
for i = 1,input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
st[i+offset] = input:stride(i)
end
self.output:set(input:storage(), input:storageOffset(), sz, st)
return self.output
end
function ReplicateAs:updateGradInput(input, gradOutput)
self.gradInput[2]:resizeAs(input[2]):zero() -- unused
input = input[1]
self.gradInput[1]:resizeAs(input):zero()
local rdim = self.in_dim
local sz = torch.LongStorage(input:dim() + 1)
sz[rdim] = 1
for i = 1, input:dim() do
local offset = 0
if i >= rdim then offset = 1 end
sz[i+offset] = input:size(i)
end
local gradInput = self.gradInput[1]:view(sz)
gradInput:sum(gradOutput, rdim)
return self.gradInput
end
|
fix util grad problem
|
fix util grad problem
|
Lua
|
mit
|
jeffreyling/seq2seq-hard,jeffreyling/seq2seq-hard,jeffreyling/seq2seq-hard
|
bf1ef67d1ef4bab56fd0805bcb8e2b51706ca4e7
|
kong/cmd/config.lua
|
kong/cmd/config.lua
|
local DB = require "kong.db"
local log = require "kong.cmd.utils.log"
local pl_path = require "pl.path"
local pl_file = require "pl.file"
local kong_global = require "kong.global"
local declarative = require "kong.db.declarative"
local conf_loader = require "kong.conf_loader"
local kong_yml = require "kong.templates.kong_yml"
local INIT_FILE = "kong.yml"
local accepted_formats = {
yaml = true,
json = true,
lua = true,
}
local function generate_init()
if pl_file.access_time(INIT_FILE) then
error(INIT_FILE .. " already exists in the current directory.\n" ..
"Will not overwrite it.")
end
pl_file.write(INIT_FILE, kong_yml)
end
local function execute(args)
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
assert(pl_path.exists(default_conf.kong_env),
"Kong is not running at " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
if args.command == "init" then
generate_init()
os.exit(0)
end
if args.command == "db-import" then
args.command = "db_import"
end
if args.command == "db_import" and conf.database == "off" then
error("'kong config db_import' only works with a database.\n" ..
"When using database=off, reload your declarative configuration\n" ..
"using the /config endpoint.")
end
package.path = conf.lua_package_path .. ";" .. package.path
local dc, err = declarative.new_config(conf)
if not dc then
error(err)
end
if args.command == "db_import" or args.command == "parse" then
local filename = args[1]
if not filename then
error("expected a declarative configuration file; see `kong config --help`")
end
local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats)
if not dc_table then
error("Failed parsing:\n" .. err_or_ver)
end
if args.command == "db_import" then
log("parse successful, beginning import")
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.plugins:load_plugin_schemas(conf.loaded_plugins))
_G.kong.db = db
local ok, err = declarative.load_into_db(dc_table)
if not ok then
error("Failed importing:\n" .. err)
end
log("import successful")
-- send anonymous report if reporting is not disabled
if conf.anonymous_reports then
local kong_reports = require "kong.reports"
kong_reports.configure_ping(conf)
kong_reports.toggle(true)
local report = { decl_fmt_version = err_or_ver }
kong_reports.send("config-db-import", report)
end
else -- parse
log("parse successful")
end
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong config COMMAND [OPTIONS]
Use declarative configuration files with Kong.
The available commands are:
init Generate an example config file to
get you started.
db_import <file> Import a declarative config file into
the Kong database.
parse <file> Parse a declarative config file (check
its syntax) but do not load it into Kong.
Options:
-c,--conf (optional string) Configuration file.
-p,--prefix (optional string) Override prefix directory.
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
init = true,
db_import = true,
parse = true,
},
}
|
local DB = require "kong.db"
local log = require "kong.cmd.utils.log"
local pl_path = require "pl.path"
local pl_file = require "pl.file"
local kong_global = require "kong.global"
local declarative = require "kong.db.declarative"
local conf_loader = require "kong.conf_loader"
local kong_yml = require "kong.templates.kong_yml"
local INIT_FILE = "kong.yml"
local accepted_formats = {
yaml = true,
json = true,
lua = true,
}
local function generate_init()
if pl_file.access_time(INIT_FILE) then
error(INIT_FILE .. " already exists in the current directory.\n" ..
"Will not overwrite it.")
end
pl_file.write(INIT_FILE, kong_yml)
end
local function execute(args)
if args.command == "init" then
generate_init()
os.exit(0)
end
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
assert(pl_path.exists(default_conf.kong_env),
"Kong is not running at " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
if args.command == "db-import" then
args.command = "db_import"
end
if args.command == "db_import" and conf.database == "off" then
error("'kong config db_import' only works with a database.\n" ..
"When using database=off, reload your declarative configuration\n" ..
"using the /config endpoint.")
end
package.path = conf.lua_package_path .. ";" .. package.path
local dc, err = declarative.new_config(conf)
if not dc then
error(err)
end
if args.command == "db_import" or args.command == "parse" then
local filename = args[1]
if not filename then
error("expected a declarative configuration file; see `kong config --help`")
end
local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats)
if not dc_table then
error("Failed parsing:\n" .. err_or_ver)
end
if args.command == "db_import" then
log("parse successful, beginning import")
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.plugins:load_plugin_schemas(conf.loaded_plugins))
_G.kong.db = db
local ok, err = declarative.load_into_db(dc_table)
if not ok then
error("Failed importing:\n" .. err)
end
log("import successful")
-- send anonymous report if reporting is not disabled
if conf.anonymous_reports then
local kong_reports = require "kong.reports"
kong_reports.configure_ping(conf)
kong_reports.toggle(true)
local report = { decl_fmt_version = err_or_ver }
kong_reports.send("config-db-import", report)
end
else -- parse
log("parse successful")
end
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong config COMMAND [OPTIONS]
Use declarative configuration files with Kong.
The available commands are:
init Generate an example config file to
get you started.
db_import <file> Import a declarative config file into
the Kong database.
parse <file> Parse a declarative config file (check
its syntax) but do not load it into Kong.
Options:
-c,--conf (optional string) Configuration file.
-p,--prefix (optional string) Override prefix directory.
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
init = true,
db_import = true,
parse = true,
},
}
|
fix(cmd) allow 'kong config init' to work without a prefix
|
fix(cmd) allow 'kong config init' to work without a prefix
From #4451
Signed-off-by: Thibault Charbonnier <[email protected]>
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
69f1cc431ce970365db46bf476cca53a093272b8
|
tools/premake/globals.lua
|
tools/premake/globals.lua
|
-- setup global variables to configure the projects
platform_dir = ""
platform = ""
build_cmd = ""
link_cmd = ""
renderer_dir = ""
sdk_version = ""
shared_libs_dir = ""
pmtech_dir = "../"
function setup_from_options()
if _OPTIONS["renderer"] then
renderer_dir = _OPTIONS["renderer"]
end
if _OPTIONS["sdk_version"] then
sdk_version = _OPTIONS["sdk_version"]
end
if _OPTIONS["platform_dir"] then
platform_dir = _OPTIONS["platform_dir"]
end
if _OPTIONS["toolset"] then
toolset(_OPTIONS["toolset"])
end
if _OPTIONS["pmtech_dir"] then
pmtech_dir = _OPTIONS["pmtech_dir"]
end
end
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
function windows_sdk_version()
return "10.0.16299.0"
end
function setup_from_action()
if _ACTION == "gmake" then
if platform_dir == "linux" then
build_cmd = "-std=c++11"
else
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++"
end
elseif _ACTION == "xcode4" then
platform_dir = "osx"
if not renderer_dir then
renderer_dir = "opengl"
end
if _OPTIONS["xcode_target"] then
platform_dir = _OPTIONS["xcode_target"]
end
if platform_dir == "ios" then
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++"
else
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++ -mmacosx-version-min=10.8"
end
shared_libs_dir = ( pmtech_dir .. '../../third_party/shared_libs/' .. platform_dir .. '/' )
elseif _ACTION == "android-studio" then
build_cmd = { "-std=c++11" }
elseif _ACTION == "vs2017" then
platform_dir = "win32"
build_cmd = "/Ob1" -- use force inline
shared_libs_dir = (pmtech_dir .. '../../third_party/shared_libs/' .. platform_dir)
end
platform = platform_dir
end
function setup_env_ios()
xcodebuildsettings
{
["ARCHS"] = "$(NATIVE_ARCH_ACTUAL)",
["SDKROOT"] = "iphoneos11.4",
["PRODUCT_BUNDLE_IDENTIFIER"] = "com.pmtech"
}
end
function setup_env()
if platform == "ios" then
setup_env_ios()
end
end
setup_from_options()
setup_from_action()
|
-- setup global variables to configure the projects
platform_dir = ""
platform = ""
build_cmd = ""
link_cmd = ""
renderer_dir = ""
sdk_version = ""
shared_libs_dir = ""
pmtech_dir = "../"
function setup_from_options()
if _OPTIONS["renderer"] then
renderer_dir = _OPTIONS["renderer"]
end
if _OPTIONS["sdk_version"] then
sdk_version = _OPTIONS["sdk_version"]
end
if _OPTIONS["platform_dir"] then
platform_dir = _OPTIONS["platform_dir"]
end
if _OPTIONS["toolset"] then
toolset(_OPTIONS["toolset"])
end
if _OPTIONS["pmtech_dir"] then
pmtech_dir = _OPTIONS["pmtech_dir"]
end
end
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
function windows_sdk_version()
return "10.0.16299.0"
end
function setup_from_action()
if _ACTION == "gmake" then
if platform_dir == "linux" then
build_cmd = "-std=c++11"
else
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++"
end
elseif _ACTION == "xcode4" then
platform_dir = "osx"
if not renderer_dir then
renderer_dir = "opengl"
end
if _OPTIONS["xcode_target"] then
platform_dir = _OPTIONS["xcode_target"]
end
if platform_dir == "ios" then
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++"
else
build_cmd = "-std=c++11 -stdlib=libc++"
link_cmd = "-stdlib=libc++ -mmacosx-version-min=10.8"
end
elseif _ACTION == "android-studio" then
build_cmd = { "-std=c++11" }
elseif _ACTION == "vs2017" then
platform_dir = "win32"
build_cmd = "/Ob1" -- use force inline
end
platform = platform_dir
if platform == "win32" then
shared_libs_dir = (pmtech_dir .. '../../third_party/shared_libs/' .. platform_dir)
elseif platform == "osx" then
shared_libs_dir = ( '"' .. pmtech_dir .. '../../third_party/shared_libs/' .. platform_dir .. '/"' )
end
end
function setup_env_ios()
xcodebuildsettings
{
["ARCHS"] = "$(NATIVE_ARCH_ACTUAL)",
["SDKROOT"] = "iphoneos11.4",
["PRODUCT_BUNDLE_IDENTIFIER"] = "com.pmtech"
}
end
function setup_env()
if platform == "ios" then
setup_env_ios()
end
end
setup_from_options()
setup_from_action()
|
fix osx build
|
fix osx build
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
0871d4129427cbf21849ac048b2d0e478b530f37
|
hash.lua
|
hash.lua
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function lua2Celem(lelem)
local elem
if type(lelem) == 'string' then
elem = C.tds_elem_string_new(lelem, #lelem)
elseif type(lelem) == 'number' then
elem = C.tds_elem_number_new(lelem)
else
error('string or number key/value expected')
end
if elem == nil then
error('unable to allocate C key/value')
end
return elem
end
local function lkey2obj(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = lkey2obj(self, lkey)
if obj ~= nil then
if lval then
local val = lua2Celem(lval)
C.tds_hash_object_set_value(obj, val)
else
C.tds_hash_remove(self, obj)
end
else
local key = lua2Celem(lkey)
local val = lua2Celem(lval)
local obj = C.tds_hash_object_new(key, val)
C.tds_hash_insert(self, obj)
end
end
local function objelem2lua(val)
assert(val)
local valtyp = ffi.string(C.tds_elem_typename(val))
if valtyp == 'number' then
return ffi.cast('tds_number*', val).value
elseif valtyp == 'string' then
return ffi.string(ffi.cast('tds_string*', val).data)
else
error(string.format('value type <%s> not supported yet', valtyp))
end
end
function hash:__index(lkey)
assert(self)
local obj = lkey2obj(self, lkey)
if obj ~= nil then
local val = C.tds_hash_object_value(obj)
return objelem2lua(val)
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
return objelem2lua(key), objelem2lua(val)
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function lua2Celem(lelem)
local elem
if type(lelem) == 'string' then
elem = C.tds_elem_string_new(lelem, #lelem)
elseif type(lelem) == 'number' then
elem = C.tds_elem_number_new(lelem)
else
error('string or number key/value expected')
end
if elem == nil then
error('unable to allocate C key/value')
end
return elem
end
local function lkey2obj(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = lkey2obj(self, lkey)
if obj ~= nil then
if lval then
local val = lua2Celem(lval)
C.tds_hash_object_set_value(obj, val)
else
C.tds_hash_remove(self, obj)
end
else
local key = lua2Celem(lkey)
local val = lua2Celem(lval)
local obj = C.tds_hash_object_new(key, val)
C.tds_hash_insert(self, obj)
end
end
local function objelem2lua(val)
assert(val)
local valtyp = ffi.string(C.tds_elem_typename(val))
if valtyp == 'number' then
return ffi.cast('tds_number*', val).value
elseif valtyp == 'string' then
val = ffi.cast('tds_string*', val)
return ffi.string(val.data, val.size)
else
error(string.format('value type <%s> not supported yet', valtyp))
end
end
function hash:__index(lkey)
assert(self)
local obj = lkey2obj(self, lkey)
if obj ~= nil then
local val = C.tds_hash_object_value(obj)
return objelem2lua(val)
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
return objelem2lua(key), objelem2lua(val)
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
hash: bug fix -- missing value for ffi.string
|
hash: bug fix -- missing value for ffi.string
|
Lua
|
bsd-3-clause
|
jakezhaojb/tds,Moodstocks/tds,jakezhaojb/tds,torch/tds,jakezhaojb/tds,jakezhaojb/tds
|
874ff7473e3a984892f8a1b4e38a0663d1660397
|
hash.lua
|
hash.lua
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function setelem(elem, lelem)
if type(lelem) == 'string' then
C.tds_elem_set_string(elem, lelem, #lelem)
elseif type(lelem) == 'number' then
C.tds_elem_set_number(elem, lelem)
else
error('string or number key/value expected')
end
end
local function findkey(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
if lval then
local val = C.tds_hash_object_value(obj)
C.tds_elem_free_content(val)
setelem(val, lval)
else
C.tds_hash_remove(self, obj)
C.tds_hash_object_free(obj)
end
else
local obj = C.tds_hash_object_new()
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
setelem(val, lval)
setelem(key, lkey)
C.tds_hash_insert(self, obj)
end
end
local function getelem(elem)
assert(elem)
local value
local elemtype = C.tds_elem_type(elem)
if elemtype == 110 then--string.byte('n') then
value = C.tds_elem_get_number(elem)
elseif elemtype == 115 then--string.byte('s') then
value = ffi.string(C.tds_elem_get_string(elem), C.tds_elem_get_string_size(elem))
else
error(string.format('value type <%s> not supported yet', elemtype))
end
return value
end
function hash:__index(lkey)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
local val = getelem(C.tds_hash_object_value(obj))
return val
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = getelem(C.tds_hash_object_key(obj))
local val = getelem(C.tds_hash_object_value(obj))
return key, val
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function setelem(elem, lelem)
if type(lelem) == 'string' then
C.tds_elem_set_string(elem, lelem, #lelem)
elseif type(lelem) == 'number' then
C.tds_elem_set_number(elem, lelem)
else
error('string or number key/value expected')
end
end
local function findkey(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
if lval then
local val = C.tds_hash_object_value(obj)
C.tds_elem_free_content(val)
setelem(val, lval)
else
C.tds_hash_remove(self, obj)
C.tds_hash_object_free(obj)
end
else
if lval then
local obj = C.tds_hash_object_new()
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
setelem(val, lval)
setelem(key, lkey)
C.tds_hash_insert(self, obj)
end
end
end
local function getelem(elem)
assert(elem)
local value
local elemtype = C.tds_elem_type(elem)
if elemtype == 110 then--string.byte('n') then
value = C.tds_elem_get_number(elem)
elseif elemtype == 115 then--string.byte('s') then
value = ffi.string(C.tds_elem_get_string(elem), C.tds_elem_get_string_size(elem))
else
error(string.format('value type <%s> not supported yet', elemtype))
end
return value
end
function hash:__index(lkey)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
local val = getelem(C.tds_hash_object_value(obj))
return val
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = getelem(C.tds_hash_object_key(obj))
local val = getelem(C.tds_hash_object_value(obj))
return key, val
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
hash: fix case of value is nil and key does not exist
|
hash: fix case of value is nil and key does not exist
|
Lua
|
bsd-3-clause
|
Moodstocks/tds,torch/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds
|
f11d4fbfac9359203ab6c980f97b9251a179c61c
|
redir_scripts/main.lua
|
redir_scripts/main.lua
|
-- Scratchbox2 universal redirector dynamic path translation scripts
-- Copyright (C) 2006, 2007 Lauri Leukkunen
-- Licensed under MIT license.
tools_root = os.getenv("SBOX_TOOLS_ROOT")
if (not tools_root) then
tools_root = "/scratchbox/sarge"
end
target_root = os.getenv("SBOX_TARGET_ROOT")
if (not target_root) then
target_root = "/"
end
compiler_root = os.getenv("SBOX_COMPILER_ROOT")
if (not compiler_root) then
compiler_root = "/usr"
end
verbose = os.getenv("SBOX_MAPPING_VERBOSE")
-- SBOX_REDIR_SCRIPTS environment variable controls where
-- we look for the scriptlets defining the path mappings
rsdir = os.getenv("SBOX_REDIR_SCRIPTS")
if (rsdir == nil) then
rsdir = "/scratchbox/redir_scripts"
end
function read_mode_part(mode, part)
filename = rsdir .. "/preload/" .. mode .. "/" .. part
f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n" .. err .. "\n")
else
f() -- execute the loaded chunk
-- export_chains variable contains now the chains
-- from the chunk
for i = 1,table.maxn(export_chains) do
-- fill in the default values
if (not export_chains[i].binary) then
export_chains[i].binary = ".*"
end
if (not export_chains[i].rules) then
export_chains[i].rules = {}
end
-- loop through the rules
for r = 1, table.maxn(export_chains[i].rules) do
if (not export_chains[i].rules[r].func_name) then
export_chains[i].rules[r].func_name = ".*"
end
if (not export_chains[i].rules[r].path) then
-- this is an error, report and exit
os.exit(1)
end
export_chains[i].rules[r].lua_script = filename
if (export_chains[i].binary) then
export_chains[i].rules[r].binary_name = export_chains[i].binary
else
export_chains[i].rules[r].binary_name = "nil"
end
end
export_chains[i].lua_script = filename
table.insert(modes[mode].chains, export_chains[i])
end
end
end
-- modes represent the different mapping modes supported.
-- Each mode contains its own set of chains.
-- The mode is passed from the libsb2.so to here in the first
-- argument to sbox_translate_path()
modes = {}
-- sb.sb_getdirlisting is provided by lua_bindings.c
-- it returns a table listing all files in a directory
mm = sb.sb_getdirlisting(rsdir .. "/preload")
table.sort(mm);
for m = 1, table.maxn(mm) do
local t = sb.sb_getdirlisting(rsdir .. "/preload/" .. mm[m])
local i = 0
local r = 0
if (mm[m] ~= "." and mm[m] ~= "..") then
table.sort(t)
modes[mm[m]] = {}
modes[mm[m]].chains = {}
-- load the individual parts ($SBOX_REDIR_SCRIPTS/preload/[modename]/*.lua)
for n = 1,table.maxn(t) do
if (string.match(t[n], "%a*%.lua$")) then
read_mode_part(mm[m], t[n])
end
end
end
end
function basename(path)
if (path == "/") then
return "/"
else
return string.match(path, "[^/]*$")
end
end
function dirname(path)
if (path == "/") then
return "/"
end
dir = string.match(path, ".*/")
if (dir == nil) then
return "."
end
if (dir == "/") then return dir end
-- chop off the trailing /
if (string.sub(dir, string.len(dir)) == "/") then
dir = string.sub(dir, 1, string.len(dir) - 1)
end
return dir
end
function sb_debug(msg)
local logfile = os.getenv("SBOX_MAPPING_LOGFILE")
local f
local err
if (not logfile) then return end
f, err = io.open(logfile, "a+")
if (not f) then return end
f:write(msg .. "\n")
io.close(f)
end
function adjust_for_mapping_leakage(path)
if (not path) then
return nil
end
--print("path: " .. path)
local tmp = sb.sb_readlink(path)
if (not tmp) then
-- not a symlink
return path
end
if (tmp == basename(path)) then
-- symlink refers to itself
return path
end
-- check if the file pointed to by the symlink
-- exists, if not, return path
if (sb.sb_file_exists(tmp)) then
return path
end
-- make it an absolute path if it's not
if (string.sub(tmp, 1, 1) ~= "/") then
tmp = dirname(path) .. "/" .. tmp
end
-- decolonize it
tmp = sb.sb_decolonize_path(tmp)
--print(string.format("after decolonizing: %s\n", tmp))
if (not string.match(tmp, "^" .. target_root .. ".*")) then
-- aha! tried to get out of there, now map it right back in
return adjust_for_mapping_leakage(target_root .. tmp)
else
return adjust_for_mapping_leakage(tmp)
end
end
function sbox_map_to(binary_name, func_name, work_dir, rp, path, rule)
local ret = nil
if (rule.map_to) then
if (string.sub(rule.map_to, 1, 1) == "=") then
--print(string.format("rp: %s\ntarget_root: %s", rp, target_root))
ret = target_root .. string.sub(rule.map_to, 2) .. path
elseif (string.sub(rule.map_to, 1, 1) == "-") then
ret = string.match(path, rule.path .. "(.*)")
ret = string.sub(rule.map_to, 2) .. ret
else
ret = rule.map_to .. path
end
return adjust_for_mapping_leakage(ret)
end
-- if not mapping, check if we're within the
-- target_root and adjust for mapping leakage if so
if (string.match(path, "^" .. target_root .. ".*")) then
return adjust_for_mapping_leakage(path)
else
return path
end
end
function find_rule(chain, func, path)
local i = 0
local wrk = chain
while (wrk) do
-- travel the chains
for i = 1, table.maxn(wrk.rules) do
-- loop the rules in a chain
if (string.match(func, wrk.rules[i].func_name) and
string.match(path, wrk.rules[i].path)) then
return wrk.rules[i]
end
end
wrk = wrk.next_chain
end
return nil
end
function map_using_chain(chain, binary_name, func_name, work_dir, path)
local ret = path
local rp = path
local rule = nil
-- print(string.format("looping through chains: %s", chains[n].binary))
rule = find_rule(chain, func_name, rp)
if (not rule) then
-- error, not even a default rule found
sb_debug(string.format("Unable to find a match at all: [%s][%s][%s]", binary_name, func_name, path))
return path
end
if (rule.custom_map_func ~= nil) then
ret = rule.custom_map_func(binary_name, func_name, work_dir, rp, path, rules[n])
else
ret = sbox_map_to(binary_name, func_name, work_dir, rp, path, rule)
if (verbose) then
sb_debug(string.format("[%s][%s|%s]:\n %s(%s) -> (%s)", basename(rule.lua_script), rule.binary_name, binary_name, func_name, path, ret))
end
end
return ret
end
-- sbox_translate_path is the function called from libsb2.so
-- preload library and the FUSE system for each path that needs
-- translating
function sbox_translate_path(mapping_mode, binary_name, func_name, work_dir, path)
--sb_debug(string.format("[%s]:", binary_name))
--sb_debug(string.format("debug: [%s][%s][%s][%s]", binary_name, func_name, work_dir, path))
-- loop through the chains, first match is used
for n=1,table.maxn(modes[mapping_mode].chains) do
if (not modes[mapping_mode].chains[n].noentry
and string.match(binary_name, modes[mapping_mode].chains[n].binary)) then
return map_using_chain(modes[mapping_mode].chains[n], binary_name, func_name, work_dir, path)
end
end
-- we should never ever get here, if we still do, don't do anything
return path
end
|
-- Scratchbox2 universal redirector dynamic path translation scripts
-- Copyright (C) 2006, 2007 Lauri Leukkunen
-- Licensed under MIT license.
tools_root = os.getenv("SBOX_TOOLS_ROOT")
if (not tools_root) then
tools_root = "/scratchbox/sarge"
end
target_root = os.getenv("SBOX_TARGET_ROOT")
if (not target_root) then
target_root = "/"
end
compiler_root = os.getenv("SBOX_COMPILER_ROOT")
if (not compiler_root) then
compiler_root = "/usr"
end
verbose = os.getenv("SBOX_MAPPING_VERBOSE")
-- SBOX_REDIR_SCRIPTS environment variable controls where
-- we look for the scriptlets defining the path mappings
rsdir = os.getenv("SBOX_REDIR_SCRIPTS")
if (rsdir == nil) then
rsdir = "/scratchbox/redir_scripts"
end
function read_mode_part(mode, part)
filename = rsdir .. "/preload/" .. mode .. "/" .. part
f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n" .. err .. "\n")
else
f() -- execute the loaded chunk
-- export_chains variable contains now the chains
-- from the chunk
for i = 1,table.maxn(export_chains) do
-- fill in the default values
if (not export_chains[i].binary) then
export_chains[i].binary = ".*"
end
if (not export_chains[i].rules) then
export_chains[i].rules = {}
end
-- loop through the rules
for r = 1, table.maxn(export_chains[i].rules) do
if (not export_chains[i].rules[r].func_name) then
export_chains[i].rules[r].func_name = ".*"
end
if (not export_chains[i].rules[r].path) then
-- this is an error, report and exit
os.exit(1)
end
export_chains[i].rules[r].lua_script = filename
if (export_chains[i].binary) then
export_chains[i].rules[r].binary_name = export_chains[i].binary
else
export_chains[i].rules[r].binary_name = "nil"
end
end
export_chains[i].lua_script = filename
table.insert(modes[mode].chains, export_chains[i])
end
end
end
-- modes represent the different mapping modes supported.
-- Each mode contains its own set of chains.
-- The mode is passed from the libsb2.so to here in the first
-- argument to sbox_translate_path()
modes = {}
-- sb.sb_getdirlisting is provided by lua_bindings.c
-- it returns a table listing all files in a directory
mm = sb.sb_getdirlisting(rsdir .. "/preload")
table.sort(mm);
for m = 1, table.maxn(mm) do
local t = sb.sb_getdirlisting(rsdir .. "/preload/" .. mm[m])
local i = 0
local r = 0
if (mm[m] ~= "." and mm[m] ~= "..") then
table.sort(t)
modes[mm[m]] = {}
modes[mm[m]].chains = {}
-- load the individual parts ($SBOX_REDIR_SCRIPTS/preload/[modename]/*.lua)
for n = 1,table.maxn(t) do
if (string.match(t[n], "%a*%.lua$")) then
read_mode_part(mm[m], t[n])
end
end
end
end
function basename(path)
if (path == "/") then
return "/"
else
return string.match(path, "[^/]*$")
end
end
function dirname(path)
if (path == "/") then
return "/"
end
dir = string.match(path, ".*/")
if (dir == nil) then
return "."
end
if (dir == "/") then return dir end
-- chop off the trailing /
if (string.sub(dir, string.len(dir)) == "/") then
dir = string.sub(dir, 1, string.len(dir) - 1)
end
return dir
end
function sb_debug(msg)
local logfile = os.getenv("SBOX_MAPPING_LOGFILE")
local f
local err
if (not logfile) then return end
f, err = io.open(logfile, "a+")
if (not f) then return end
f:write(msg .. "\n")
io.close(f)
end
function adjust_for_mapping_leakage(path)
if (not path) then
return nil
end
-- print("path: " .. path)
local tmp = sb.sb_readlink(path)
if (not tmp) then
-- not a symlink
return path
end
if (sb.sb_decolonize_path(tmp) == sb.sb_decolonize_path(path)) then
-- symlink refers to itself
return path
end
-- check if the file pointed to by the symlink
-- exists, if not, return path
if (not sb.sb_file_exists(tmp)) then
return path
end
-- make it an absolute path if it's not
if (string.sub(tmp, 1, 1) ~= "/") then
tmp = dirname(path) .. "/" .. tmp
end
-- decolonize it
tmp = sb.sb_decolonize_path(tmp)
--print(string.format("after decolonizing: %s\n", tmp))
if (not string.match(tmp, "^" .. target_root .. ".*")) then
-- aha! tried to get out of there, now map it right back in
--print("it tried to LEAK\n")
return adjust_for_mapping_leakage(target_root .. tmp)
else
return adjust_for_mapping_leakage(tmp)
end
end
function sbox_map_to(binary_name, func_name, work_dir, rp, path, rule)
local ret = nil
if (rule.map_to) then
if (string.sub(rule.map_to, 1, 1) == "=") then
--print(string.format("rp: %s\ntarget_root: %s", rp, target_root))
ret = target_root .. string.sub(rule.map_to, 2) .. path
elseif (string.sub(rule.map_to, 1, 1) == "-") then
ret = string.match(path, rule.path .. "(.*)")
ret = string.sub(rule.map_to, 2) .. ret
else
ret = rule.map_to .. path
end
return adjust_for_mapping_leakage(ret)
end
-- if not mapping, check if we're within the
-- target_root and adjust for mapping leakage if so
if (string.match(path, "^" .. target_root .. ".*")) then
return adjust_for_mapping_leakage(path)
else
return path
end
end
function find_rule(chain, func, path)
local i = 0
local wrk = chain
while (wrk) do
-- travel the chains
for i = 1, table.maxn(wrk.rules) do
-- loop the rules in a chain
if (string.match(func, wrk.rules[i].func_name) and
string.match(path, wrk.rules[i].path)) then
return wrk.rules[i]
end
end
wrk = wrk.next_chain
end
return nil
end
function map_using_chain(chain, binary_name, func_name, work_dir, path)
local ret = path
local rp = path
local rule = nil
-- print(string.format("looping through chains: %s", chains[n].binary))
rule = find_rule(chain, func_name, rp)
if (not rule) then
-- error, not even a default rule found
sb_debug(string.format("Unable to find a match at all: [%s][%s][%s]", binary_name, func_name, path))
return path
end
if (rule.custom_map_func ~= nil) then
ret = rule.custom_map_func(binary_name, func_name, work_dir, rp, path, rules[n])
else
ret = sbox_map_to(binary_name, func_name, work_dir, rp, path, rule)
if (verbose) then
sb_debug(string.format("[%s][%s|%s]:\n %s(%s) -> (%s)", basename(rule.lua_script), rule.binary_name, binary_name, func_name, path, ret))
end
end
return ret
end
-- sbox_translate_path is the function called from libsb2.so
-- preload library and the FUSE system for each path that needs
-- translating
function sbox_translate_path(mapping_mode, binary_name, func_name, work_dir, path)
--sb_debug(string.format("[%s]:", binary_name))
--sb_debug(string.format("debug: [%s][%s][%s][%s]", binary_name, func_name, work_dir, path))
-- loop through the chains, first match is used
for n=1,table.maxn(modes[mapping_mode].chains) do
if (not modes[mapping_mode].chains[n].noentry
and string.match(binary_name, modes[mapping_mode].chains[n].binary)) then
return map_using_chain(modes[mapping_mode].chains[n], binary_name, func_name, work_dir, path)
end
end
-- we should never ever get here, if we still do, don't do anything
return path
end
|
Fix bugs in symlink leakage handling that affected at least libtool
|
Fix bugs in symlink leakage handling that affected at least libtool
Signed-off-by: Lauri Leukkunen <[email protected]>
|
Lua
|
lgpl-2.1
|
lbt/scratchbox2,neeraj9/sbox2,lbt/scratchbox2,BinChengfei/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox,loganchien/scratchbox2,loganchien/scratchbox2,ldbox/ldbox,h113331pp/scratchbox2,neeraj9/sbox2,freedesktop-unofficial-mirror/sbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,ldbox/ldbox,neeraj9/sbox2,freedesktop-unofficial-mirror/sbox2,ldbox/ldbox,BinChengfei/scratchbox2,lbt/scratchbox2,BinChengfei/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,freedesktop-unofficial-mirror/sbox2,madscientist42/scratchbox2,loganchien/scratchbox2,freedesktop-unofficial-mirror/sbox2,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,lbt/scratchbox2,OlegGirko/ldbox,madscientist42/scratchbox2,ldbox/ldbox,freedesktop-unofficial-mirror/sbox2,loganchien/scratchbox2,neeraj9/sbox2,loganchien/scratchbox2,OlegGirko/ldbox,loganchien/scratchbox2,h113331pp/scratchbox2,h113331pp/scratchbox2,neeraj9/sbox2,BinChengfei/scratchbox2,lbt/scratchbox2,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,OlegGirko/ldbox,neeraj9/sbox2
|
d91dfecb68ca2e8746e843da25595e4fc407bc03
|
otouto/plugins/tagesschau_eil.lua
|
otouto/plugins/tagesschau_eil.lua
|
local tagesschau_eil = {}
tagesschau_eil.command = 'eil <sub/del>'
function tagesschau_eil:init(config)
tagesschau_eil.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('eil', true).table
tagesschau_eil.doc = [[*
]]..config.cmd_pat..[[eil* _sub_: Eilmeldungen abonnieren
*]]..config.cmd_pat..[[eil* _del_: Eilmeldungen deabonnieren
*]]..config.cmd_pat..[[eil* _sync_: Nach neuen Eilmeldungen prüfen (nur Superuser)]]
end
local makeOurDate = function(dateString)
local pattern = "(%d+)%-(%d+)%-(%d+)T(%d+)%:(%d+)%:(%d+)"
local year, month, day, hours, minutes, seconds = dateString:match(pattern)
return day..'.'..month..'.'..year..' um '..hours..':'..minutes..':'..seconds
end
local url = 'http://www.tagesschau.de/api'
local hash = 'telegram:tagesschau'
function tagesschau_eil:abonnieren(id)
if redis:sismember(hash..':subs', id) == false then
redis:sadd(hash..':subs', id)
return '*Eilmeldungen abonniert.*'
else
return 'Die Eilmeldungen wurden hier bereits abonniert.'
end
end
function tagesschau_eil:deabonnieren(id)
if redis:sismember(hash..':subs', id) == true then
redis:srem(hash..':subs', id)
return '*Eilmeldungen deabonniert.*'
else
return 'Die Eilmeldungen wurden hier noch nicht abonniert.'
end
end
function tagesschau_eil:action(msg, config)
local input = utilities.input(msg.text)
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
utilities.send_message(msg.chat.id, tagesschau_eil.doc, true, msg.message_id, true)
return
end
end
local id = "user#id" .. msg.from.id
if msg.chat.type == 'channel' then
print('Kanäle werden momentan nicht unterstützt')
end
if msg.chat.type == 'group' or msg.chat.type == 'supergroup' then
id = 'chat#id'..msg.chat.id
end
if input:match('(sub)$') then
local output = tagesschau_eil:abonnieren(id)
utilities.send_reply(msg, output, true)
elseif input:match('(del)$') then
local output = tagesschau_eil:deabonnieren(id)
utilities.send_reply(msg, output, true)
elseif input:match('(sync)$') then
if not is_sudo(msg, config) then
utilities.send_reply(msg, config.errors.sudo)
return
end
tagesschau_eil:cron()
end
return
end
function tagesschau_eil:cron()
-- print('EIL: Prüfe...')
local last_eil = redis:get(hash..':last_entry')
local res,code = http.request(url)
if code ~= 200 then return end
local data = json.decode(res)
if not data then return end
if data == "error" then return end
if data.error then return end
if data.breakingnews[1] then
if data.breakingnews[1].date ~= last_eil then
local title = '#EIL: <b>'..data.breakingnews[1].headline..'</b>'
local news = data.breakingnews[1].shorttext or ''
local posted_at = makeOurDate(data.breakingnews[1].date)..' Uhr'
local post_url = string.gsub(data.breakingnews[1].details, '/api/', '/')
local post_url = string.gsub(post_url, '.json', '.html')
local eil = title..'\n<i>'..posted_at..'</i>\n'..news
redis:set(hash..':last_entry', data.breakingnews[1].date)
for _,user in pairs(redis:smembers(hash..':subs')) do
local user = string.gsub(user, 'chat%#id', '')
local user = string.gsub(user, 'user%#id', '')
utilities.send_message(user, eil, true, nil, 'HTML', '{"inline_keyboard":[[{"text":"Eilmeldung aufrufen","url":"'..post_url..'"}]]}')
end
end
end
end
return tagesschau_eil
|
local tagesschau_eil = {}
tagesschau_eil.command = 'eil <sub/del>'
function tagesschau_eil:init(config)
tagesschau_eil.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('eil', true).table
tagesschau_eil.doc = [[*
]]..config.cmd_pat..[[eil* _sub_: Eilmeldungen abonnieren
*]]..config.cmd_pat..[[eil* _del_: Eilmeldungen deabonnieren
*]]..config.cmd_pat..[[eil* _sync_: Nach neuen Eilmeldungen prüfen (nur Superuser)]]
end
local makeOurDate = function(dateString)
local pattern = "(%d+)%-(%d+)%-(%d+)T(%d+)%:(%d+)%:(%d+)"
local year, month, day, hours, minutes, seconds = dateString:match(pattern)
return day..'.'..month..'.'..year..' um '..hours..':'..minutes..':'..seconds
end
local url = 'http://www.tagesschau.de/api'
local hash = 'telegram:tagesschau'
function tagesschau_eil:abonnieren(id)
if redis:sismember(hash..':subs', id) == false then
redis:sadd(hash..':subs', id)
return '*Eilmeldungen abonniert.*'
else
return 'Die Eilmeldungen wurden hier bereits abonniert.'
end
end
function tagesschau_eil:deabonnieren(id)
if redis:sismember(hash..':subs', id) == true then
redis:srem(hash..':subs', id)
return '*Eilmeldungen deabonniert.*'
else
return 'Die Eilmeldungen wurden hier noch nicht abonniert.'
end
end
function tagesschau_eil:action(msg, config)
local input = utilities.input(msg.text)
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
utilities.send_message(msg.chat.id, tagesschau_eil.doc, true, msg.message_id, true)
return
end
end
local id = "user#id" .. msg.from.id
if msg.chat.type == 'channel' then
print('Kanäle werden momentan nicht unterstützt')
end
if msg.chat.type == 'group' or msg.chat.type == 'supergroup' then
id = 'chat#id'..msg.chat.id
end
if input:match('(sub)$') then
local output = tagesschau_eil:abonnieren(id)
utilities.send_reply(msg, output, true)
elseif input:match('(del)$') then
local output = tagesschau_eil:deabonnieren(id)
utilities.send_reply(msg, output, true)
elseif input:match('(sync)$') then
if not is_sudo(msg, config) then
utilities.send_reply(msg, config.errors.sudo)
return
end
tagesschau_eil:cron()
end
return
end
function tagesschau_eil:cron()
-- print('EIL: Prüfe...')
local last_eil = redis:get(hash..':last_entry')
local res,code = http.request(url)
if code ~= 200 then return end
local data = json.decode(res)
if not data then return end
if data == "error" then return end
if data.error then return end
if data.breakingnews[1] then
if data.breakingnews[1].date ~= last_eil then
local title = '#EIL: <b>'..data.breakingnews[1].headline..'</b>'
local news = data.breakingnews[1].shorttext or ''
local posted_at = makeOurDate(data.breakingnews[1].date)..' Uhr'
post_url = 'http://tagesschau.de'
if data.breakingnews[1].details ~= "" then
post_url = string.gsub(data.breakingnews[1].details, '/api/', '/')
post_url = string.gsub(post_url, '.json', '.html')
end
local eil = title..'\n<i>'..posted_at..'</i>\n'..news
redis:set(hash..':last_entry', data.breakingnews[1].date)
for _,user in pairs(redis:smembers(hash..':subs')) do
local user = string.gsub(user, 'chat%#id', '')
local user = string.gsub(user, 'user%#id', '')
utilities.send_message(user, eil, true, nil, 'HTML', '{"inline_keyboard":[[{"text":"Eilmeldung aufrufen","url":"'..post_url..'"}]]}')
end
end
end
end
return tagesschau_eil
|
Tagesschau-Eilmeldungen Fix
|
Tagesschau-Eilmeldungen Fix
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
fb66f7059111d6b9fb0bbe13fbc7d003d592caf6
|
init.lua
|
init.lua
|
require 'action'
require 'profile'
----------------------------------------------------------------------------------------------------
-- Settings
----------------------------------------------------------------------------------------------------
local mash = {'ctrl', 'alt'}
hs.window.animationDuration = 0.15
hs.grid.setMargins({0, 0})
hs.grid.setGrid('6x4', nil)
hs.grid.HINTS = {
{'f1', 'f2','f3', 'f4', 'f5', 'f6', 'f7', 'f8'},
{'1', '2', '3', '4', '5', '6', '7', '8'},
{'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I'},
{'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K'},
{'Y', 'X', 'C', 'V', 'B', 'N', 'M', ','}
}
----------------------------------------------------------------------------------------------------
-- Profiles
----------------------------------------------------------------------------------------------------
Profile.new('Home', {69671680}, mash, {
["Atom"] = {Action.MoveToScreen(1), Action.Maximize()},
["Google Chrome"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["iTunes"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["MacPass"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Mail"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Reeder"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Safari"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["SourceTree"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Terminal"] = {Action.MoveToScreen(1), Action.MoveToUnitInScreenBounds(0.0, 0.5, 1.0, 0.5)},
["TextMate"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
}, {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'SourceTree',
['i'] = 'iTunes',
['m'] = 'Activity Monitor',
['r'] = 'Reeder',
['s'] = 'MacPass',
['t'] = 'Terminal',
['x'] = 'Xcode',
})
----------------------------------------------------------------------------------------------------
Profile.new('Work', {2077750397, 188898833, 188898834, 188898835, 188898836, 188915586}, mash, {
["Atom"] = {Action.MoveToScreen(1), Action.Maximize()},
["Dash"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.0, 0.0, 0.5, 1.0)},
["Google Chrome"] = {Action.MoveToScreen(2), Action.Maximize()},
["iTunes"] = {Action.Close()},
["MacPass"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Parallels Desktop"] = {Action.MoveToScreen(2), Action.FullScreen()},
["Safari"] = {Action.MoveToScreen(2), Action.Maximize()},
["SourceTree"] = {Action.MoveToScreen(1), Action.Maximize()},
["Terminal"] = {Action.MoveToScreen(1), Action.MoveToUnitInScreenBounds(0.0, 0.5, 1.0, 0.5)},
["TextMate"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Tower"] = {Action.MoveToScreen(1), Action.Maximize()},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
}, {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['d'] = 'Dash',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'Tower',
['i'] = 'iTunes',
['p'] = 'Parallels Desktop',
['m'] = 'Activity Monitor',
['s'] = 'MacPass',
['t'] = 'Terminal',
['x'] = 'Xcode',
})
----------------------------------------------------------------------------------------------------
-- Hotkey Bindings
----------------------------------------------------------------------------------------------------
function focusedWin() return hs.window.focusedWindow() end
hs.hotkey.bind(mash, 'UP', function() Action.Maximize()(focusedWin()) end)
hs.hotkey.bind(mash, 'DOWN', function() Action.MoveToNextScreen()(focusedWin()) end)
hs.hotkey.bind(mash, 'LEFT', function() Action.MoveToUnit(0.0, 0.0, 0.5, 1.0)(focusedWin()) end)
hs.hotkey.bind(mash, 'RIGHT', function() Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)(focusedWin()) end)
hs.hotkey.bind(mash, 'SPACE', function() for _, win in pairs(hs.window.visibleWindows()) do hs.grid.snap(win) end end)
hs.hotkey.bind(mash, '1', function() hs.hints.windowHints() end)
hs.hotkey.bind(mash, '2', function() hs.grid.toggleShow() end)
hs.hotkey.bind(mash, '^', function()
local profile = Profile.designated()
if profile then profile:activate() end
end)
----------------------------------------------------------------------------------------------------
-- Watcher
----------------------------------------------------------------------------------------------------
function appEvent(appName, event, app)
if event == hs.application.watcher.launched then
Profile.active():arrange(app)
end
end
function pathEvent(files) hs.reload() end
function screenEvent()
local profile = Profile.designated()
if not profile then
utils.notify("unknown profile, see console for screen information", 3.0, function() hs.toggleConsole() end)
for _, screen in pairs(hs.screen.allScreens()) do print("found screen: " .. screen:id()) end
return
end
profile:activate()
end
hs.application.watcher.new(appEvent):start()
hs.pathwatcher.new(hs.configdir, pathEvent):start()
hs.screen.watcher.new(screenEvent):start()
screenEvent()
|
require 'action'
require 'profile'
----------------------------------------------------------------------------------------------------
-- Settings
----------------------------------------------------------------------------------------------------
local mash = {'ctrl', 'alt'}
hs.window.animationDuration = 0.15
hs.grid.setMargins({0, 0})
hs.grid.setGrid('6x4', nil)
hs.grid.HINTS = {
{'f1', 'f2','f3', 'f4', 'f5', 'f6', 'f7', 'f8'},
{'1', '2', '3', '4', '5', '6', '7', '8'},
{'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I'},
{'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K'},
{'Y', 'X', 'C', 'V', 'B', 'N', 'M', ','}
}
----------------------------------------------------------------------------------------------------
-- Profiles
----------------------------------------------------------------------------------------------------
Profile.new('Home', {69671680}, mash, {
["Atom"] = {Action.MoveToScreen(1), Action.Maximize()},
["Google Chrome"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["iTunes"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["MacPass"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Mail"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Reeder"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Safari"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["SourceTree"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Terminal"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.5, 1.0, 0.5, 0), Action.PositionBottomRight()},
["TextMate"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
}, {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'SourceTree',
['i'] = 'iTunes',
['m'] = 'Activity Monitor',
['r'] = 'Reeder',
['s'] = 'MacPass',
['t'] = 'Terminal',
['x'] = 'Xcode',
})
----------------------------------------------------------------------------------------------------
Profile.new('Work', {2077750397, 188898833, 188898834, 188898835, 188898836, 188915586}, mash, {
["Atom"] = {Action.MoveToScreen(1), Action.Maximize()},
["Dash"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.0, 0.0, 0.5, 1.0)},
["Google Chrome"] = {Action.MoveToScreen(2), Action.Maximize()},
["iTunes"] = {Action.Close()},
["MacPass"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.0, 0.7, 1.0)},
["Parallels Desktop"] = {Action.MoveToScreen(2), Action.FullScreen()},
["Safari"] = {Action.MoveToScreen(2), Action.Maximize()},
["SourceTree"] = {Action.MoveToScreen(1), Action.Maximize()},
["Terminal"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.0, 0.5, 1.0, 0.5, 0), Action.PositionBottomRight()},
["TextMate"] = {Action.MoveToScreen(2), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Tower"] = {Action.MoveToScreen(1), Action.Maximize()},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
}, {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['d'] = 'Dash',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'Tower',
['i'] = 'iTunes',
['p'] = 'Parallels Desktop',
['m'] = 'Activity Monitor',
['s'] = 'MacPass',
['t'] = 'Terminal',
['x'] = 'Xcode',
})
----------------------------------------------------------------------------------------------------
-- Hotkey Bindings
----------------------------------------------------------------------------------------------------
function focusedWin() return hs.window.focusedWindow() end
hs.hotkey.bind(mash, 'UP', function() Action.Maximize()(focusedWin()) end)
hs.hotkey.bind(mash, 'DOWN', function() Action.MoveToNextScreen()(focusedWin()) end)
hs.hotkey.bind(mash, 'LEFT', function() Action.MoveToUnit(0.0, 0.0, 0.5, 1.0)(focusedWin()) end)
hs.hotkey.bind(mash, 'RIGHT', function() Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)(focusedWin()) end)
hs.hotkey.bind(mash, 'SPACE', function() for _, win in pairs(hs.window.visibleWindows()) do hs.grid.snap(win) end end)
hs.hotkey.bind(mash, '1', function() hs.hints.windowHints() end)
hs.hotkey.bind(mash, '2', function() hs.grid.toggleShow() end)
hs.hotkey.bind(mash, '^', function()
local profile = Profile.designated()
if profile then profile:activate() end
end)
----------------------------------------------------------------------------------------------------
-- Watcher
----------------------------------------------------------------------------------------------------
function appEvent(appName, event, app)
if event == hs.application.watcher.launched then
Profile.active():arrange(app)
end
end
function pathEvent(files) hs.reload() end
function screenEvent()
local profile = Profile.designated()
if not profile then
utils.notify("unknown profile, see console for screen information", 3.0, function() hs.toggleConsole() end)
for _, screen in pairs(hs.screen.allScreens()) do print("found screen: " .. screen:id()) end
return
end
profile:activate()
end
hs.application.watcher.new(appEvent):start()
hs.pathwatcher.new(hs.configdir, pathEvent):start()
hs.screen.watcher.new(screenEvent):start()
screenEvent()
|
Adjust Terminal window handling
|
Adjust Terminal window handling
Hopefully this will be the final fix.
|
Lua
|
mit
|
mgee/hammerspoon-config
|
8124a294050f7fa4854a18c5b130b8739ab90f5e
|
pomf.lua
|
pomf.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if status_code ~= 200 and status_code ~= 404 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
wget.callbacks.httploop_result = function(url, err, http_stat)
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if status_code ~= 200 and status_code ~= 404 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
pomf.lua: another small fix
|
pomf.lua: another small fix
|
Lua
|
unlicense
|
ArchiveTeam/pomf-grab,ArchiveTeam/pomf-grab
|
85f9c0fce51d10b04b04652fa09bc73feeb03ce5
|
main.lua
|
main.lua
|
io = require("rpiIO")
socket = require("socket") --networking lib
util = require("util") --helper functions
addr = "*"
port = 1025
running = true -- global state. set to false to end program.
pins = {}
pins.servo = 9
pins.speedL = 10
pins.speedR = 11
pins.dirL = 5
pins.dirR = 6
commands = {}
---------- command functions -------
-- change the pin mapping
function commands.remap(client, name, pin)
if not name then
for name,pin in pairs(pins) do
sendStr(client, name.."="..(tostring pin))
end
elseif not pin then
sendStr(client, name.."="..(tostring pins[name]))
else
pins.name = tonumber( pin )
print(name.."is now on pin "..pin)
end
end
function commands.motors(client, l,r)
if not l then l=0 end
if not r then r=0 end
io.setLeftMotor(l,1)
io.setRightMotor(r,1)
end
function commands.getSensors(client)
local data = "@sensor 0 100 12"
sendStr(client, data)
end
function commands.stop(client)
io.setLeftMotor(0,0)
io.setRightMotor(0,0)
print("Motors stopped")
sendStr(client, "Motors stopped")
end
function commands.init(client)
initHardware()
sendStr(client, "Initialized")
end
function commands.run(client)
print("run started.")
end
function commands.echo(client, ...)
print (...)
end
-------------------------------------
-- initialize hardware
local function initHardware()
io.initServo(pins.servo)
io.initMotors(pins.speedL,pins.dirL,pins.speedR,pins.dirR)
end
--------------- Socket Coroutine Functions -------------
local function sendStr(client, str)
client:send(str.."\n") -- no yielding for send
end
-- blocking accept call that yields!
local function accept(server)
assert(server)
local client=nil
while not client do
server:settimeout(0)
client = server:accept()
coroutine.yield()
end
return client
end
-- blocking yielding receive call.
local function receive(client, pattern)
local ret = "" -- return value
local status = "timeout"
while status=="timeout" do
client:settimeout(0) --nonblocking
s,status,part = client:receive(pattern)
if status=="timeout" then coroutine.yield() end
if s then
ret = ret..s
elseif part then
ret = ret..part
end
end
if status=="closed" then
return nil
else
return ret
end
end
-- listens and handles requests from client
local function clientWorker(client)
local c,cmdline,cmdwords,cmd -- declare local vars
while running do
cmdline = receive(client, "*l")
if not cmdline then
print("Connection from client terminated.")
return
end -- connection closed
print(">>>"..cmdline)
c = string.sub(cmdline,1,1)
cmdline = string.sub(cmdline,2)
cmdwords = util.words(cmdline)
cmd = cmdwords[1]
args = util.tail(cmdwords)
if c == "!" then -- command message from client
cmd = cmdwords[1]
if commands[cmd] then
commands[cmd](client,unpack(args))
else
print("no such command")
end
elseif c == "@" then -- data message from client
print("motors:"..args[1]..","..args[2])
io.setLeftMotor(args[1],1)
io.setRightMotor(args[2],1)
end
end
end
-- wait for connections
local function acceptConnections(server)
while running do
print("Waiting for connections...")
client = accept(server)
print("connection from "..client:getpeername())
-- create a new coroutine for worker
local worker = coroutine.create(function() clientWorker(client) end)
table.insert(co,worker)
end
end
local function mainLoop()
while running do
print(".")
socket.sleep(1)
coroutine.yield()
end
end
-- initialize control server
local server = assert(socket.bind(addr, port))
initHardware() --setup all pin modes, PWM etc.
-- init coroutine table
co = {}
table.insert( co, coroutine.create(function () acceptConnections(server) end) )
table.insert( co, coroutine.create(mainLoop) )
while running do
-- loop through all coroutines, giving time to each
for k,c in pairs(co) do
if coroutine.status(c) == "dead" then
-- remove dead coroutines
co[k] = nil
print(k,"dead")
else
print(k)
status,error = coroutine.resume(c)
if not status then print("Error with coroutine:\n"..error) end
end
end
end
|
io = require("rpiIO")
socket = require("socket") --networking lib
util = require("util") --helper functions
addr = "*"
port = 1025
running = true -- global state. set to false to end program.
pins = {}
pins.servo = 9
pins.speedL = 10
pins.speedR = 11
pins.dirL = 5
pins.dirR = 6
commands = {}
local function sendStr(client, str)
client:send(str.."\n") -- no yielding for send
end
---------- command functions -------
-- change the pin mapping
function commands.remap(client, name, pin)
if not name then
for name,pin in pairs(pins) do
sendStr(client, name.."="..(tostring(pin)))
end
elseif not pin then
sendStr(client, name.."="..(tostring(pins[name])))
else
pins.name = tonumber( pin )
print(name.."is now on pin "..pin)
end
end
function commands.motors(client, l,r)
if not l then l=0 end
if not r then r=0 end
io.setLeftMotor(l,1)
io.setRightMotor(r,1)
end
function commands.getSensors(client)
local data = "@sensor 0 100 12"
sendStr(client, data)
end
function commands.stop(client)
io.setLeftMotor(0,0)
io.setRightMotor(0,0)
print("Motors stopped")
sendStr(client, "Motors stopped")
end
function commands.init(client)
initHardware()
sendStr(client, "Initialized")
end
function commands.run(client)
print("run started.")
end
function commands.echo(client, ...)
print (...)
end
-------------------------------------
-- initialize hardware
local function initHardware()
io.initServo(pins.servo)
io.initMotors(pins.speedL,pins.dirL,pins.speedR,pins.dirR)
end
--------------- Socket Coroutine Functions -------------
-- blocking accept call that yields!
local function accept(server)
assert(server)
local client=nil
while not client do
server:settimeout(0)
client = server:accept()
coroutine.yield()
end
return client
end
-- blocking yielding receive call.
local function receive(client, pattern)
local ret = "" -- return value
local status = "timeout"
while status=="timeout" do
client:settimeout(0) --nonblocking
s,status,part = client:receive(pattern)
if status=="timeout" then coroutine.yield() end
if s then
ret = ret..s
elseif part then
ret = ret..part
end
end
if status=="closed" then
return nil
else
return ret
end
end
-- listens and handles requests from client
local function clientWorker(client)
local c,cmdline,cmdwords,cmd -- declare local vars
while running do
cmdline = receive(client, "*l")
if not cmdline then
print("Connection from client terminated.")
return
end -- connection closed
print(">>>"..cmdline)
c = string.sub(cmdline,1,1)
cmdline = string.sub(cmdline,2)
cmdwords = util.words(cmdline)
cmd = cmdwords[1]
args = util.tail(cmdwords)
if c == "!" then -- command message from client
cmd = cmdwords[1]
if commands[cmd] then
commands[cmd](client,unpack(args))
else
print("no such command")
end
elseif c == "@" then -- data message from client
print("motors:"..args[1]..","..args[2])
io.setLeftMotor(args[1],1)
io.setRightMotor(args[2],1)
end
end
end
-- wait for connections
local function acceptConnections(server)
while running do
print("Waiting for connections...")
client = accept(server)
print("connection from "..client:getpeername())
-- create a new coroutine for worker
local worker = coroutine.create(function() clientWorker(client) end)
table.insert(co,worker)
end
end
local function mainLoop()
while running do
print(".")
socket.sleep(1)
coroutine.yield()
end
end
-- initialize control server
local server = assert(socket.bind(addr, port))
initHardware() --setup all pin modes, PWM etc.
-- init coroutine table
co = {}
table.insert( co, coroutine.create(function () acceptConnections(server) end) )
table.insert( co, coroutine.create(mainLoop) )
while running do
-- loop through all coroutines, giving time to each
for k,c in pairs(co) do
if coroutine.status(c) == "dead" then
-- remove dead coroutines
co[k] = nil
print(k,"dead")
else
print(k)
status,error = coroutine.resume(c)
if not status then print("Error with coroutine:\n"..error) end
end
end
end
|
fix typos and parens
|
fix typos and parens
|
Lua
|
mit
|
o080o/mercury-robotics-2013
|
fb4926bc62c5c45fa0ee2ab90e345df113d3a4ab
|
commands/build.lua
|
commands/build.lua
|
zpm.build.commands = {}
zpm.build.rcommands = {}
function zpm.build.commands.extractdir( targets, prefix )
prefix = prefix or "./"
if type(targets) ~= "table" then
targets = {targets}
end
for i, target in ipairs(targets) do
local zipFile = path.join( zpm.temp, "submodule.zip" )
local targetPath = path.join( zpm.build._currentExportPath, prefix, target )
local depPath = path.join( zpm.build._currentDependency.dependencyPath, target )
if path.getabsolute(depPath):contains( path.getabsolute(zpm.build._currentDependency.dependencyPath) ) then
if not _OPTIONS["ignore-updates"] or not os.isdir( targetPath ) then
for _, file in ipairs( os.matchfiles( path.join( depPath, "**" ) ) ) do
local ftarget = path.join( targetPath, path.getrelative( depPath, file ) )
if ftarget:contains( ".git" ) == false then
local ftargetDir = path.getdirectory( ftarget )
if not os.isdir( ftargetDir ) then
zpm.assert( os.mkdir( ftargetDir ), "Could not create directory '%s'!", ftargetDir )
end
if ftarget:len() <= 255 then
if os.isfile( ftarget ) == false or zpm.util.isNewer( file, ftarget ) then
os.copyfile( file, ftarget )
end
zpm.assert( os.isfile(ftarget), "Could not make file '%s'!", ftarget )
else
warningf( "Failed to copy '%s' due to long path length!", ftarget )
end
end
end
end
end
end
end
function zpm.build.commands.option( opt )
zpm.assert(zpm.build._currentDependency.options ~= nil, "Option '%s' does not exist!", opt)
zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt)
return zpm.build._currentDependency.options[opt]
end
function zpm.build.commands.hasSetting( opt )
return zpm.config.settings ~= nil and zpm.config.settings[opt] ~= nil
end
function zpm.build.commands.setting( opt )
zpm.assert(zpm.config.settings ~= nil, "Setting '%s' does not exist!", opt)
zpm.assert(zpm.config.settings[opt] ~= nil, "Setting '%s' does not exist!", opt)
return zpm.config.settings[opt]
end
function zpm.build.commands.export( commands )
local name = project().name
local parent = zpm.build._currentDependency.projects[name].export
local currExp = zpm.build._currentExportPath
local currDep = zpm.build._currentDependency
zpm.build._currentDependency.projects[name].export = function()
if parent ~= nil then
parent()
end
local old = zpm.build._currentExportPath
local oldDep = zpm.build._currentDependency
zpm.build._currentExportPath = currExp
zpm.build._currentDependency = currDep
zpm.sandbox.run( commands, {env = zpm.build.getEnv()})
zpm.build._currentExportPath = old
zpm.build._currentDependency = oldDep
end
zpm.sandbox.run( commands, {env = zpm.build.getEnv()})
end
function zpm.build.commands.uses( proj )
if type(proj) ~= "table" then
proj = {proj}
end
local cname = project().name
if zpm.build._currentDependency.projects[cname] == nil then
zpm.build._currentDependency.projects[cname] = {}
end
if zpm.build._currentDependency.projects[cname].uses == nil then
zpm.build._currentDependency.projects[cname].uses = {}
end
if zpm.build._currentDependency.projects[cname].packages == nil then
zpm.build._currentDependency.projects[cname].packages = {}
end
for _, p in ipairs(proj) do
if p:contains( "/" ) then
local package = zpm.build.findProject( p )
if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then
table.insert( zpm.build._currentDependency.projects[cname].packages, package )
end
else
local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version )
if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then
table.insert( zpm.build._currentDependency.projects[cname].uses, name )
end
end
end
end
function zpm.build.rcommands.project( proj )
local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version )
project( name )
-- always touch just in case
if _ACTION and _ACTION:contains( "vs" ) or true then
dummyFile = path.join( zpm.install.getExternDirectory(), "dummy.cpp" )
file = io.open( dummyFile, "w")
file:write("typedef int Garbage; typedef int Bullshit; Garbage FuckYouCompilers%s( Bullshit arg1, Bullshit arg2 ){ return 0; }".format( string.sha1(dummyFile) ) )
files(dummyFile)
end
location( zpm.install.getExternDirectory() )
targetdir( zpm.build._currentTargetPath )
objdir( zpm.build._currentObjPath )
warnings "Off"
if zpm.build._currentDependency.projects == nil then
zpm.build._currentDependency.projects = {}
end
if zpm.build._currentDependency.projects[name] == nil then
zpm.build._currentDependency.projects[name] = {}
end
end
function zpm.build.rcommands.dependson( depdson )
if type(depdson) ~= "table" then
depdson = {depdson}
end
for _, p in ipairs(depdson) do
local dep = zpm.build._currentDependency
dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) )
end
end
function zpm.build.rcommands.kind( knd )
local name = project().name
zpm.build._currentDependency.projects[name].kind = knd
kind( knd )
end
function zpm.build.rcommands.filter( ... )
filter( ... )
end
|
zpm.build.commands = {}
zpm.build.rcommands = {}
function zpm.build.commands.extractdir( targets, prefix )
prefix = prefix or "./"
if type(targets) ~= "table" then
targets = {targets}
end
for i, target in ipairs(targets) do
local zipFile = path.join( zpm.temp, "submodule.zip" )
local targetPath = path.join( zpm.build._currentExportPath, prefix, target )
local depPath = path.join( zpm.build._currentDependency.dependencyPath, target )
if path.getabsolute(depPath):contains( path.getabsolute(zpm.build._currentDependency.dependencyPath) ) then
if not _OPTIONS["ignore-updates"] or not os.isdir( targetPath ) then
for _, file in ipairs( os.matchfiles( path.join( depPath, "**" ) ) ) do
local ftarget = path.join( targetPath, path.getrelative( depPath, file ) )
if ftarget:contains( ".git" ) == false then
local ftargetDir = path.getdirectory( ftarget )
if not os.isdir( ftargetDir ) then
zpm.assert( os.mkdir( ftargetDir ), "Could not create directory '%s'!", ftargetDir )
end
if ftarget:len() <= 255 then
if os.isfile( ftarget ) == false or zpm.util.isNewer( file, ftarget ) then
os.copyfile( file, ftarget )
end
zpm.assert( os.isfile(ftarget), "Could not make file '%s'!", ftarget )
else
warningf( "Failed to copy '%s' due to long path length!", ftarget )
end
end
end
end
end
end
end
function zpm.build.commands.option( opt )
zpm.assert(zpm.build._currentDependency.options ~= nil, "Option '%s' does not exist!", opt)
zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt)
return zpm.build._currentDependency.options[opt]
end
function zpm.build.commands.hasSetting( opt )
return zpm.config.settings ~= nil and zpm.config.settings[opt] ~= nil
end
function zpm.build.commands.setting( opt )
zpm.assert(zpm.config.settings ~= nil, "Setting '%s' does not exist!", opt)
zpm.assert(zpm.config.settings[opt] ~= nil, "Setting '%s' does not exist!", opt)
return zpm.config.settings[opt]
end
function zpm.build.commands.export( commands )
local name = project().name
local parent = zpm.build._currentDependency.projects[name].export
local currExp = zpm.build._currentExportPath
local currDep = zpm.build._currentDependency
zpm.build._currentDependency.projects[name].export = function()
if parent ~= nil then
parent()
end
local old = zpm.build._currentExportPath
local oldDep = zpm.build._currentDependency
zpm.build._currentExportPath = currExp
zpm.build._currentDependency = currDep
zpm.sandbox.run( commands, {env = zpm.build.getEnv()})
zpm.build._currentExportPath = old
zpm.build._currentDependency = oldDep
end
zpm.sandbox.run( commands, {env = zpm.build.getEnv()})
end
function zpm.build.commands.uses( proj )
if type(proj) ~= "table" then
proj = {proj}
end
local cname = project().name
if zpm.build._currentDependency.projects[cname] == nil then
zpm.build._currentDependency.projects[cname] = {}
end
if zpm.build._currentDependency.projects[cname].uses == nil then
zpm.build._currentDependency.projects[cname].uses = {}
end
if zpm.build._currentDependency.projects[cname].packages == nil then
zpm.build._currentDependency.projects[cname].packages = {}
end
for _, p in ipairs(proj) do
if p:contains( "/" ) then
local package = zpm.build.findProject( p )
if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then
table.insert( zpm.build._currentDependency.projects[cname].packages, package )
end
else
local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version )
if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then
table.insert( zpm.build._currentDependency.projects[cname].uses, name )
end
end
end
end
function zpm.build.rcommands.project( proj )
local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version )
project( name )
-- always touch just in case
if _ACTION and _ACTION:contains( "vs" ) or true then
dummyFile = path.join( zpm.install.getExternDirectory(), "dummy.cpp" )
file = io.open( dummyFile, "w")
file:write( string.format("typedef int Garbage; typedef int Bullshit; Garbage FuckYouCompilers%s( Bullshit arg1, Bullshit arg2 ){ return 0; }", string.sha1(dummyFile) ) )
files(dummyFile)
end
location( zpm.install.getExternDirectory() )
targetdir( zpm.build._currentTargetPath )
objdir( zpm.build._currentObjPath )
warnings "Off"
if zpm.build._currentDependency.projects == nil then
zpm.build._currentDependency.projects = {}
end
if zpm.build._currentDependency.projects[name] == nil then
zpm.build._currentDependency.projects[name] = {}
end
end
function zpm.build.rcommands.dependson( depdson )
if type(depdson) ~= "table" then
depdson = {depdson}
end
for _, p in ipairs(depdson) do
local dep = zpm.build._currentDependency
dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) )
end
end
function zpm.build.rcommands.kind( knd )
local name = project().name
zpm.build._currentDependency.projects[name].kind = knd
kind( knd )
end
function zpm.build.rcommands.filter( ... )
filter( ... )
end
|
Syntax fix
|
Syntax fix
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
75327e3c354cd3ea76e1d19f298247c546cb0fdb
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
|
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.nut",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
local voltages = {
title = "%H: Voltages on UPS \"%pi\"",
vlabel = "V",
number_format = "%5.1lfV",
data = {
instances = {
voltage = { "battery", "input", "output" }
},
options = {
voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true },
voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true },
voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true }
}
}
}
local currents = {
title = "%H: Current on UPS \"%pi\"",
vlabel = "A",
number_format = "%5.3lfA",
data = {
instances = {
current = { "battery", "output" }
},
options = {
current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true },
current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true },
}
}
}
local percentage = {
title = "%H: Battery charge on UPS \"%pi\"",
vlabel = "Percent",
y_min = "0",
y_max = "100",
number_format = "%5.1lf%%",
data = {
sources = {
percent = { "percent" }
},
instances = {
percent = "charge"
},
options = {
percent_charge = { color = "00ff00", title = "Charge level" }
}
}
}
-- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century.
local temperature = {
title = "%H: Battery temperature on UPS \"%pi\"",
vlabel = "\176C",
number_format = "%5.1lf\176C",
data = {
instances = {
temperature = "battery"
},
options = {
temperature_battery = { color = "ffb000", title = "Battery temperature" }
}
}
}
local timeleft = {
title = "%H: Time left on UPS \"%pi\"",
vlabel = "Minutes",
number_format = "%.1lfm",
data = {
sources = {
timeleft = { "timeleft" }
},
instances = {
timeleft = { "battery" }
},
options = {
timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" }
}
}
}
return { voltages, currents, percentage, temperature, timeleft }
end
|
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.nut",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
local voltages = {
title = "%H: Voltages on UPS \"%pi\"",
vlabel = "V",
number_format = "%5.1lfV",
data = {
instances = {
voltage = { "battery", "input", "output" }
},
options = {
voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true },
voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true },
voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true }
}
}
}
local currents = {
title = "%H: Current on UPS \"%pi\"",
vlabel = "A",
number_format = "%5.3lfA",
data = {
instances = {
current = { "battery", "output" }
},
options = {
current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true },
current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true },
}
}
}
local percentage = {
title = "%H: Battery charge on UPS \"%pi\"",
vlabel = "Percent",
y_min = "0",
y_max = "100",
number_format = "%5.1lf%%",
data = {
instances = {
percent = "charge"
},
options = {
percent_charge = { color = "00ff00", title = "Charge level" }
}
}
}
-- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century.
local temperature = {
title = "%H: Battery temperature on UPS \"%pi\"",
vlabel = "\176C",
number_format = "%5.1lf\176C",
data = {
instances = {
temperature = "battery"
},
options = {
temperature_battery = { color = "ffb000", title = "Battery temperature" }
}
}
}
local timeleft = {
title = "%H: Time left on UPS \"%pi\"",
vlabel = "Minutes",
number_format = "%.1lfm",
data = {
instances = {
timeleft = { "battery" }
},
options = {
timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" }
}
}
}
return { voltages, currents, percentage, temperature, timeleft }
end
|
luci/statistics: Fix nut UPS graphs
|
luci/statistics: Fix nut UPS graphs
At some point since I last checked, the nut plugin for collectd changed the
names of the timeleft and percent datasets. Update the luci module to match
so that those graphs are generated correctly again.
Signed-off-by: David Woodhouse <[email protected]>
(cherry picked from commit 41ec4c68adf7e6545aa10b359fea1883bec79b3e)
|
Lua
|
apache-2.0
|
david-xiao/luci,RuiChen1113/luci,RuiChen1113/luci,david-xiao/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,david-xiao/luci,david-xiao/luci,RuiChen1113/luci,david-xiao/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,david-xiao/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI
|
4dfce8309ff65d7bc53323220f7cef042a230d37
|
bin/unix/build.lua
|
bin/unix/build.lua
|
-- load functions --
local loadExtension = function (extensionsDir, extensionName)
package.path = package.path .. ";" .. extensionsDir .. "/" .. extensionName .. "/src/?.lua"
end
local loadPath = function (path)
package.path = package.path .. ";" .. path
end
local loadCPath = function (cpath)
package.cpath = package.cpath .. ";" .. cpath
end
local function loadedPackages ()
local packages = {}
for k,v in pairs(package.loaded) do packages[k] = k end
return packages
end
local function unloadPackages (whitelistedPackages)
for k,v in pairs(package.loaded) do
if whitelistedPackages[k] == nil then
package.loaded[k] = nil
end
end
end
-- nginx.conf --
local nginxConf = [[
http {
lua_package_path '../?.lua;';
lua_package_cpath 'luajit/lib/?.so;';
init_by_lua 'require = require "autowire"';
types {
text/html html;
text/css css;
application/javascript js;
image/png png;
image/gif gif;
image/jpeg jpeg;
image/jpg jpg;
image/x-icon ico;
}
# Default server
server {
listen {{port}};
listen {{sslPort}} ssl;
ssl_certificate ./ssl_certificate/server.crt;
ssl_certificate_key ./ssl_certificate/server.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
return 404;
}
# Regular servers
include nginx.config.*;
} # end of http
events {
worker_connections 1024;
} # end of events
worker_processes 2;
]]
-- set up build names --
local octopus = {
port = 7878,
sslPort = 37878,
process = {
extensions = {"../../extensions", "/config_unix.lua"},
}
}
-- arg[1] is the name of the build
if arg[1] then
print("[" .. arg[1] .. "]")
if arg[1] == "octopus" then
config = octopus
else
error(arg[1] .. " is not name of build")
end
else
config = octopus
end
-- remove old configurations and create nginx.conf--
local whitelistedPackages = loadedPackages()
local originalPackagePath = package.path
local originalPackageCPath = package.cpath
loadCPath("luajit/lib/?.so;")
loadExtension("../../extensions", "core")
local util = require "util"
util.filterFiles(".", function (fileName)
if fileName:find("nginx.config.", 1, true) then os.remove(fileName) end
end)
local parse = require "parse"
local file = assert(io.open("nginx.conf", "w"))
file:write(parse(nginxConf, config))
file:close()
unloadPackages(whitelistedPackages)
package.path = originalPackagePath
package.cpath = originalPackageCPath
-- create new configurations --
for k,v in pairs(config.process) do
extensionsDir = v[1]
local configFileName = v[2]
local whitelistedPackages = loadedPackages()
local originalPackagePath = package.path
local originalPackageCPath = package.cpath
loadCPath("luajit/lib/?.so;")
loadExtension(extensionsDir, "core")
loadExtension(extensionsDir, "orm")
local function build ()
print("build server from " .. extensionsDir .. configFileName)
nginxConfFileName = "nginx.config." .. k
dofile(extensionsDir .. configFileName)
local builder = require "builder"
builder.build()
end
local status, err = pcall(build)
if not status then print(err) end
unloadPackages(whitelistedPackages)
package.path = originalPackagePath
package.cpath = originalPackageCPath
end
|
-- load functions --
local loadExtension = function (extensionsDir, extensionName)
package.path = package.path .. ";" .. extensionsDir .. "/" .. extensionName .. "/src/?.lua"
end
local loadPath = function (path)
package.path = package.path .. ";" .. path
end
local loadCPath = function (cpath)
package.cpath = package.cpath .. ";" .. cpath
end
local function loadedPackages ()
local packages = {}
for k,v in pairs(package.loaded) do packages[k] = k end
return packages
end
local function unloadPackages (whitelistedPackages)
for k,v in pairs(package.loaded) do
if whitelistedPackages[k] == nil then
package.loaded[k] = nil
end
end
end
-- nginx.conf --
local nginxConf = [[
http {
lua_package_path '../?.lua;';
lua_package_cpath 'luajit/lib/?.so;';
init_by_lua 'require = require "autowire"';
types {
text/html html;
text/css css;
application/javascript js;
image/png png;
image/gif gif;
image/jpeg jpeg;
image/jpg jpg;
image/x-icon ico;
}
# Regular servers
include nginx.config.*;
} # end of http
events {
worker_connections 1024;
} # end of events
worker_processes 2;
]]
-- set up build names --
local octopus = {
port = 7878,
sslPort = 37878,
process = {
extensions = {"../../extensions", "/config_unix.lua"},
}
}
-- arg[1] is the name of the build
if arg[1] then
print("[" .. arg[1] .. "]")
if arg[1] == "octopus" then
config = octopus
else
error(arg[1] .. " is not name of build")
end
else
config = octopus
end
-- remove old configurations and create nginx.conf--
local whitelistedPackages = loadedPackages()
local originalPackagePath = package.path
local originalPackageCPath = package.cpath
loadCPath("luajit/lib/?.so;")
loadExtension("../../extensions", "core")
local lfs = require "lfs"
local dir = "."
for entry in lfs.dir(dir) do
if entry ~= "." and entry ~= ".." then
local path
if dir ~= "/" then
path = dir .. "/" .. entry
else
path = "/" .. entry
end
local attr = lfs.attributes(path)
if attr and attr.mode == "file" then
if path:find("nginx.config.", 1, true) then os.remove(path) end
end
end
end
local parse = require "parse"
local file = assert(io.open("nginx.conf", "w"))
file:write(parse(nginxConf, config))
file:close()
unloadPackages(whitelistedPackages)
package.path = originalPackagePath
package.cpath = originalPackageCPath
-- create new configurations --
for k,v in pairs(config.process) do
extensionsDir = v[1]
local configFileName = v[2]
local whitelistedPackages = loadedPackages()
local originalPackagePath = package.path
local originalPackageCPath = package.cpath
loadCPath("luajit/lib/?.so;")
loadExtension(extensionsDir, "core")
loadExtension(extensionsDir, "orm")
local function build ()
print("build server from " .. extensionsDir .. configFileName)
nginxConfFileName = "nginx.config." .. k
dofile(extensionsDir .. configFileName)
local builder = require "builder"
builder.build()
end
local status, err = pcall(build)
if not status then print(err) end
unloadPackages(whitelistedPackages)
package.path = originalPackagePath
package.cpath = originalPackageCPath
end
|
fix build
|
fix build
|
Lua
|
bsd-2-clause
|
cyberz-eu/octopus,cyberz-eu/octopus
|
04b42dfbbbd2d9874e159033764b023ea48514d5
|
model.lua
|
model.lua
|
-- NOTE: nothing is atomic for now
local redis = require "redis"
local bcrypt = require "bcrypt"
local redismodel = require "redismodel"
-- monkey-patch required to make rocks loading work
local lr_fetch = require "luarocks.fetch"
local lr_path = require "luarocks.path"
local lr_deps = require "luarocks.deps"
lr_path.configure_paths = function(rockspec) end
local cfg = require("lapis.config").get()
local pfx = cfg.appname
local init_redis, R
if ngx and cfg.use_resty_redis then
local redis = require "resty.redis"
R = redis:new()
R:set_timeout(1000)
init_redis = function() assert(R:connect(unpack(cfg.redis))) end
else
local redis = require "redis"
R = redis.connect(unpack(cfg.redis))
init_redis = function() end
end
--- declarations
local User = redismodel.new{
redis = R,
prefix = pfx,
name = "user",
}
User:add_attribute("email")
User:add_index("email")
User:add_attribute("fullname")
User:add_attribute("password")
User:add_attribute("trust_level")
local Module = redismodel.new{
redis = R,
prefix = pfx,
name = "module",
}
Module:add_attribute("name")
Module:add_index("name")
Module:add_attribute("version")
Module:add_attribute("url")
Module:add_attribute("description")
local Label = redismodel.new{
redis = R,
prefix = pfx,
name = "label",
}
Label:add_attribute("name")
Label:add_index("name")
redismodel.add_nn_assoc {
master = User,
slave = Module,
assoc_create = "endorse",
assoc_remove = "deendorse",
assoc_check = "endorses",
master_collection = "endorsements",
slave_collection = "endorsers",
}
redismodel.add_nn_assoc {
master = Module,
slave = Label,
assoc_create = "label",
assoc_remove = "unlabel",
assoc_check = "has_label",
master_collection = "labels",
slave_collection = "modules",
}
redismodel.add_nn_assoc {
master = Module,
slave = Module,
assoc_create = "add_dependency",
assoc_remove = "remove_dependency",
assoc_check = "depends_on",
master_collection = "dependencies",
slave_collection = "reverse_dependencies",
}
--- User
User.methods.check_password = function(self, pwd)
assert(type(pwd) == "string")
local hash = self:getattr("pwhash")
if not hash then return false end
return bcrypt.verify(pwd, hash)
end
User.methods.get_password = function(self)
return nil
end
User.methods.set_password = function(self, pwd)
assert(type(pwd) == "string")
local salt = bcrypt.salt(10)
local hash = assert(bcrypt.digest(pwd, salt))
self:setattr("pwhash", hash)
end
User.methods.get_trust_level = function(self)
return tonumber(self:getattr("trust_level")) or 0
end
User.methods.invalidate_token = function(self)
local tk = self:getattr("pwtoken")
if tk then
self.model.R:del(self.model:rk("_tk_" .. tk))
self:delattr("pwtoken")
end
end
local rand_id = function(n)
local r = {}
for i=1,n do r[i] = string.char(math.random(65,90)) end
return table.concat(r)
end
User.methods.make_token = function(self)
self:invalidate_token()
local tk = rand_id(10)
self:setattr("pwtoken", tk)
local duration = 3600 * 24 * 10 -- 10 days
self.model.R:setex(self.model:rk("_tk_" .. tk), duration, self.id)
return tk
end
User.m_methods.resolve_token = function(cls, tk)
assert(type(tk) == "string")
local id = tonumber(cls.R:get(cls:rk("_tk_" .. tk)))
if not id then return nil end
local u = cls:new(id)
assert(u:getattr("pwtoken") == tk)
return u
end
local _super = User.methods.export
User.methods.export = function(self)
local r = _super(self)
r.pwhash = self:getattr("pwhash")
return r
end
--- Module
local load_rockspec = function(rs)
if type(rs) == "string" then
rs = lr_fetch.load_rockspec(rs)
end
assert(type(rs) == "table")
if type(rs.description) == "table" then
rs.url = rs.url or rs.description.homepage
rs.description = rs.description.summary or rs.description.detailed
end
return rs
end
local _super = Module.m_methods.create
Module.m_methods.create = function(cls, t)
local rs = t.rockspec and load_rockspec(t.rockspec)
if rs then assert(rs.name) end
t.name = t.name or (rs and rs.name)
_super(cls, t)
end
Module.methods.update_with_rockspec = function(self, rs, fast)
-- -> changed?
fast = (fast ~= false)
rs = load_rockspec(rs)
assert(rs and rs.name and rs.version)
assert(rs.name == self:get_name())
local old_version = self:get_version()
if old_version then
if old_version == rs.version then
if fast and self:check_attributes(rs) then
return false
end
elseif lr_deps.compare_versions(old_version, rs.version) then
return false
end
end
for k,_ in pairs(self.model.attributes) do
if rs[k] then self["set_" .. k](self, rs[k]) end
end
local old_deps = self:dependencies()
for i=1,#old_deps do
self:remove_dependency(old_deps[i])
end
local new_deps = rs.dependencies or {}
for i=1,#new_deps do
local m = Module:get_by_name(new_deps[i].name)
if m then self:add_dependency(m) end
end
return true
end
Module.sort_by_nb_endorsers = {
function(self) return {self:nb_endorsers(), self:get_name()} end,
function(a, b) return (a[1] == b[1]) and (a[2] < b[2]) or (a[1] > b[1]) end,
}
--- others
local init = function()
init_redis()
if cfg._name == "development" then
if not User:resolve_email("[email protected]") then
User:create{
email = "[email protected]",
fullname = "John Doe",
password = "tagazok",
trust_level = 2,
}
end
end
end
return {
User = User,
Module = Module,
Label = Label,
init = init,
load_rockspec = load_rockspec,
}
|
-- NOTE: nothing is atomic for now
local redis = require "redis"
local bcrypt = require "bcrypt"
local redismodel = require "redismodel"
-- monkey-patch required to make rocks loading work
local lr_fetch = require "luarocks.fetch"
local lr_path = require "luarocks.path"
local lr_deps = require "luarocks.deps"
lr_path.configure_paths = function(rockspec) end
local cfg = require("lapis.config").get()
local pfx = cfg.appname
local init_redis, R
if ngx and cfg.use_resty_redis then
-- hack to make resty-redis return nil
-- instead of ngx.null, like redis-lua
local null = ngx.null
ngx.null = nil
local redis = require "resty.redis"
ngx.null = null
R = redis:new()
R:set_timeout(1000)
init_redis = function() assert(R:connect(unpack(cfg.redis))) end
else
local redis = require "redis"
R = redis.connect(unpack(cfg.redis))
init_redis = function() end
end
--- declarations
local User = redismodel.new{
redis = R,
prefix = pfx,
name = "user",
}
User:add_attribute("email")
User:add_index("email")
User:add_attribute("fullname")
User:add_attribute("password")
User:add_attribute("trust_level")
local Module = redismodel.new{
redis = R,
prefix = pfx,
name = "module",
}
Module:add_attribute("name")
Module:add_index("name")
Module:add_attribute("version")
Module:add_attribute("url")
Module:add_attribute("description")
local Label = redismodel.new{
redis = R,
prefix = pfx,
name = "label",
}
Label:add_attribute("name")
Label:add_index("name")
redismodel.add_nn_assoc {
master = User,
slave = Module,
assoc_create = "endorse",
assoc_remove = "deendorse",
assoc_check = "endorses",
master_collection = "endorsements",
slave_collection = "endorsers",
}
redismodel.add_nn_assoc {
master = Module,
slave = Label,
assoc_create = "label",
assoc_remove = "unlabel",
assoc_check = "has_label",
master_collection = "labels",
slave_collection = "modules",
}
redismodel.add_nn_assoc {
master = Module,
slave = Module,
assoc_create = "add_dependency",
assoc_remove = "remove_dependency",
assoc_check = "depends_on",
master_collection = "dependencies",
slave_collection = "reverse_dependencies",
}
--- User
User.methods.check_password = function(self, pwd)
assert(type(pwd) == "string")
local hash = self:getattr("pwhash")
if not hash then return false end
return bcrypt.verify(pwd, hash)
end
User.methods.get_password = function(self)
return nil
end
User.methods.set_password = function(self, pwd)
assert(type(pwd) == "string")
local salt = bcrypt.salt(10)
local hash = assert(bcrypt.digest(pwd, salt))
self:setattr("pwhash", hash)
end
User.methods.get_trust_level = function(self)
return tonumber(self:getattr("trust_level")) or 0
end
User.methods.invalidate_token = function(self)
local tk = self:getattr("pwtoken")
if tk then
self.model.R:del(self.model:rk("_tk_" .. tk))
self:delattr("pwtoken")
end
end
local rand_id = function(n)
local r = {}
for i=1,n do r[i] = string.char(math.random(65,90)) end
return table.concat(r)
end
User.methods.make_token = function(self)
self:invalidate_token()
local tk = rand_id(10)
self:setattr("pwtoken", tk)
local duration = 3600 * 24 * 10 -- 10 days
self.model.R:setex(self.model:rk("_tk_" .. tk), duration, self.id)
return tk
end
User.m_methods.resolve_token = function(cls, tk)
assert(type(tk) == "string")
local id = tonumber(cls.R:get(cls:rk("_tk_" .. tk)))
if not id then return nil end
local u = cls:new(id)
assert(u:getattr("pwtoken") == tk)
return u
end
local _super = User.methods.export
User.methods.export = function(self)
local r = _super(self)
r.pwhash = self:getattr("pwhash")
return r
end
--- Module
local load_rockspec = function(rs)
if type(rs) == "string" then
rs = lr_fetch.load_rockspec(rs)
end
assert(type(rs) == "table")
if type(rs.description) == "table" then
rs.url = rs.url or rs.description.homepage
rs.description = rs.description.summary or rs.description.detailed
end
return rs
end
local _super = Module.m_methods.create
Module.m_methods.create = function(cls, t)
local rs = t.rockspec and load_rockspec(t.rockspec)
if rs then assert(rs.name) end
t.name = t.name or (rs and rs.name)
_super(cls, t)
end
Module.methods.update_with_rockspec = function(self, rs, fast)
-- -> changed?
fast = (fast ~= false)
rs = load_rockspec(rs)
assert(rs and rs.name and rs.version)
assert(rs.name == self:get_name())
local old_version = self:get_version()
if old_version then
if old_version == rs.version then
if fast and self:check_attributes(rs) then
return false
end
elseif lr_deps.compare_versions(old_version, rs.version) then
return false
end
end
for k,_ in pairs(self.model.attributes) do
if rs[k] then self["set_" .. k](self, rs[k]) end
end
local old_deps = self:dependencies()
for i=1,#old_deps do
self:remove_dependency(old_deps[i])
end
local new_deps = rs.dependencies or {}
for i=1,#new_deps do
local m = Module:get_by_name(new_deps[i].name)
if m then self:add_dependency(m) end
end
return true
end
Module.sort_by_nb_endorsers = {
function(self) return {self:nb_endorsers(), self:get_name()} end,
function(a, b) return (a[1] == b[1]) and (a[2] < b[2]) or (a[1] > b[1]) end,
}
--- others
local init = function()
init_redis()
if cfg._name == "development" then
if not User:resolve_email("[email protected]") then
User:create{
email = "[email protected]",
fullname = "John Doe",
password = "tagazok",
trust_level = 2,
}
end
end
end
return {
User = User,
Module = Module,
Label = Label,
init = init,
load_rockspec = load_rockspec,
}
|
add a hack to make resty-redis return nil instead of ngx.null (fixes #10)
|
add a hack to make resty-redis return nil instead of ngx.null (fixes #10)
|
Lua
|
mit
|
catwell/lua-toolbox
|
5ba95751805e6d1c1131e145a2ca2ee7e7fe1d21
|
HexChat/mymsg.lua
|
HexChat/mymsg.lua
|
hexchat.register('MyMessage', '2', 'Properly show your own messages in ZNC playback')
hexchat.hook_print('Capability List', function (args)
if args[2]:find('znc.in/self%-message') then
hexchat.command('CAP REQ znc.in/self-message')
hexchat.hook_timer(1, function ()
-- Emit right after this event
hexchat.emit_print('Capability Request', 'znc.in/self-message')
end)
end
end)
local function prefix_is_channel (prefix)
local chantypes = hexchat.props['chantypes']
for i = 1, #chantypes do
if chantypes[i] == prefix then
return true
end
end
return false
end
hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs)
-- Only want private messages
if prefix_is_channel(word[3]:sub(1, 1)) then
return
end
local mynick = hexchat.get_info('nick')
local sender = word[1]:match('^:([^!]+)')
local recipient = word[3]
if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then
hexchat.command('query -nofocus ' .. recipient)
local ctx = hexchat.find_context(hexchat.get_info('network'), recipient)
local message = word_eol[4]
if message:sub(1, 1) == ':' then
message = message:sub(2)
end
if message:sub(1, 8) == '\001ACTION ' then
local action = message:sub(9, #message-1)
ctx:emit_print_attrs(attrs, 'Your Action', mynick, action)
else
ctx:emit_print_attrs(attrs, 'Your Message', mynick, message)
end
return hexchat.EAT_ALL
end
end)
|
hexchat.register('MyMessage', '2', 'Properly show your own messages in ZNC playback')
hexchat.hook_print('Capability List', function (args)
if args[2]:find('znc.in/self%-message') then
hexchat.command('CAP REQ znc.in/self-message')
ctx = hexchat.props.context
hexchat.hook_timer(1, function ()
-- Emit right after this event
if ctx:set() then
hexchat.emit_print('Capability Request', 'znc.in/self-message')
end
end)
end
end)
local function prefix_is_channel (prefix)
local chantypes = hexchat.props['chantypes']
for i = 1, #chantypes do
if chantypes[i] == prefix then
return true
end
end
return false
end
hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs)
-- Only want private messages
if prefix_is_channel(word[3]:sub(1, 1)) then
return
end
local mynick = hexchat.get_info('nick')
local sender = word[1]:match('^:([^!]+)')
local recipient = word[3]
if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then
hexchat.command('query -nofocus ' .. recipient)
local ctx = hexchat.find_context(hexchat.get_info('network'), recipient)
local message = word_eol[4]
if message:sub(1, 1) == ':' then
message = message:sub(2)
end
if message:sub(1, 8) == '\001ACTION ' then
local action = message:sub(9, #message-1)
ctx:emit_print_attrs(attrs, 'Your Action', mynick, action)
else
ctx:emit_print_attrs(attrs, 'Your Message', mynick, message)
end
return hexchat.EAT_ALL
end
end)
|
mymsg.lua: Fix cap requested emitting in wrong context
|
mymsg.lua: Fix cap requested emitting in wrong context
|
Lua
|
mit
|
TingPing/plugins,TingPing/plugins
|
bda76a729d3bf5279367b6afcd7ab365dccc898d
|
plugins/gImages.lua
|
plugins/gImages.lua
|
local doc = [[
/image <query>
Returns a randomized top result from Google Images. Safe search is enabled by default; use "/insfw" to disable it. NSFW results will not display an image preview.
]]
local triggers = {
'^/i[mage]*[nsfw]*[@'..bot.username..']*$',
'^/i[mage]*[nsfw]*[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendReply(msg, doc)
return
end
end
local url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8'
if not string.match(msg.text, '^/i[mage]*nsfw') then
url = url .. '&safe=active'
end
url = url .. '&q=' .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if #jdat.responseData.results < 1 then
sendReply(msg, config.errors.results)
return
end
local i = math.random(#jdat.responseData.results)
local result = jdat.responseData.results[i].url
if string.match(msg.text, '^/i[mage]*nsfw') then
sendReply(msg, result)
else
sendMessage(msg.chat.id, result, false, msg.message_id)
end
end
return {
action = action,
triggers = triggers,
doc = doc
}
|
local doc = [[
/image <query>
Returns a randomized top result from Google Images. Safe search is enabled by default; use "/insfw" to disable it. NSFW results will not display an image preview.
]]
local triggers = {
'^/i[mage]*[nsfw]*[@'..bot.username..']*$',
'^/i[mage]*[nsfw]*[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendReply(msg, doc)
return
end
end
local url = 'https://www.googleapis.com/customsearch/v1?&searchType=image&imgSize=xlarge&alt=json&num=8&start=1'
url = url .. '&key=0000000' -- KEY Get https://console.developers.google.com/apis/credentials
url = url .. '&cx=ABCD:000' -- CX Get https://cse.google.com/cse
if not string.match(msg.text, '^/i[mage]*nsfw') then
url = url .. '&safe=high'
end
url = url .. '&q=' .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if jdat.searchInformation.totalResults == '0' then
sendReply(msg, config.errors.results)
return
end
local i = math.random(jdat.queries.request[1].count)
local result = jdat.items[i].link
if string.match(msg.text, '^/i[mage]*nsfw') then
sendReply(msg, result)
else
sendMessage(msg.chat.id, result, false, msg.message_id)
end
end
return {
action = action,
triggers = triggers,
doc = doc
}
|
Fix Google Search Images
|
Fix Google Search Images
|
Lua
|
agpl-3.0
|
TiagoDanin/SiD,barreeeiroo/BarrePolice,Brawl345/Brawlbot-v2,topkecleon/otouto,bb010g/otouto
|
d5d5be9d621fcde03129cceb6a63f8b1f52c4a72
|
RNN-train-sample/train.lua
|
RNN-train-sample/train.lua
|
-- Eugenio Culurciello
-- September 2016
-- RNN training test: ABBA / 1221 sequence detector
-- based on: https://raw.githubusercontent.com/karpathy/char-rnn/master/model/RNN.lua
require 'nn'
require 'nngraph'
require 'optim'
dofile('RNN.lua')
local model_utils = require 'model_utils'
torch.setdefaulttensortype('torch.FloatTensor')
-- nngraph.setDebug(true)
local opt = {}
opt.dictionary_size = 2 -- sequence of 2 symbols
opt.train_size = 10000 -- train data size
opt.seq_length = 4 -- RNN time steps
print('Creating Input...')
-- create a sequence of 2 numbers: {2, 1, 2, 2, 1, 1, 2, 2, 1 ..}
local s = torch.Tensor(opt.train_size):random(2)
print('Inputs sequence:', s:view(1,-1))
local y = torch.ones(1, opt.train_size)
for i = 4, opt.train_size do -- if you find sequence ...1001... then output is class '2', otherwise is '1'
if (s[{i-3}]==1 and s[{i-2}]==2 and s[{i-1}]==2 and s[{i}]==1) then y[{1,{i}}] = 2 end
-- if (s[{i-1}]==1 and s[{i}]==2) then y[{1,{i}}] = 2 end -- detect one 1-2 sequence
end
print('Desired sequence:', y)
local x = torch.zeros(2, opt.train_size) -- create input with 1-hot encoding:
for i = 1, opt.train_size do
if s[i] > 1 then x[{{},{i}}] = torch.Tensor{0,1} else x[{{},{i}}] = torch.Tensor{1,0} end
end
print('Input vector:', x)
-- model:
print('Creating Model...')
opt.rnn_size = 10
opt.rnn_layers = 1
opt.batch_size = 1
local protos = {}
protos.rnn = RNN(opt.dictionary_size, opt.rnn_size, opt.rnn_layers, 0) -- input = 2 (classes), 1 layer, rnn_size=1, no dropout
protos.criterion = nn.ClassNLLCriterion()
-- print('Test of RNN output:', RNNmodel:forward{ torch.Tensor(2), torch.Tensor(1) })
-- the initial state of the cell/hidden states
local init_state = {}
for L = 1, opt.rnn_layers do
local h_init = torch.zeros(opt.batch_size, opt.rnn_size)
table.insert(init_state, h_init:clone())
end
local params, grad_params
-- get flattened parameters tensor
-- params, grad_params = model_utils.combine_all_parameters(protos.rnn)
params, grad_params = protos.rnn:getParameters()
print('Number of parameters in the model: ' .. params:nElement())
-- print(params, grad_params)
-- create clones of model to unroll in time:
print('Cloning RNN model:')
local clones = {}
clones.rnn = {}
clones.criterion = {}
for name, proto in pairs(protos) do
print('cloning ' .. name)
clones[name] = model_utils.clone_many_times(proto, opt.seq_length, not proto.parameters)
end
function clone_list(tensor_list, zero_too)
-- takes a list of tensors and returns a list of cloned tensors
local out = {}
for k,v in pairs(tensor_list) do
out[k] = v:clone()
if zero_too then out[k]:zero() end
end
return out
end
-- training function:
local init_state_global = clone_list(init_state)
local bo = 0 -- batch offset / counter
opt.grad_clip = 5
function feval(p)
if p ~= params then
params:copy(p)
end
grad_params:zero()
-- bo variable creates batches on the fly
-- forward pass ---------------------------------------------------------------
local rnn_state = {[0]=init_state_global} -- initial state
local predictions = {}
local loss = 0
for t = 1, opt.seq_length do
clones.rnn[t]:training() -- make sure we are in correct training mode
-- print( 'sample,target:', x[{{},{t+bo}}], y[{1,{t+bo}}] )
local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}
rnn_state[t] = {}
for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output
predictions[t] = lst[#lst]
loss = loss + clones.criterion[t]:forward(predictions[t], y[{1,{t+bo}}])
end
loss = loss / opt.seq_length
-- backward pass --------------------------------------------------------------
-- initialize gradient at time t to be zeros (there's no influence from future)
local drnn_state = {[opt.seq_length] = clone_list(init_state, true)} -- true also zeros the clones
for t = opt.seq_length, 1, -1 do
-- print(drnn_state)
-- backprop through loss, and softmax/linear
-- print( 'prediction,target:', predictions[t], y[{1,{t+bo}}] )
local doutput_t = clones.criterion[t]:backward(predictions[t], y[{1,{t+bo}}])
-- print('douptut', doutput_t)
table.insert(drnn_state[t], doutput_t)
local dlst = clones.rnn[t]:backward({x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}, drnn_state[t])
drnn_state[t-1] = {}
for k,v in pairs(dlst) do
if k > 1 then -- k == 1 is gradient on x, which we dont need
-- note we do k-1 because first item is dembeddings, and then follow the
-- derivatives of the state, starting at index 2. I know...
drnn_state[t-1][k-1] = v
end
end
end
-- transfer final state to initial state (BPTT)
init_state_global = rnn_state[#rnn_state]
-- grad_params:div(opt.seq_length)
-- clip gradient element-wise
grad_params:clamp(-opt.grad_clip, opt.grad_clip)
-- print(params,grad_params)
-- point to next batch:
bo = bo + opt.seq_length
return loss, grad_params
end
-- training:
opt.learning_rate = 2e-3
opt.decay_rate = 0.95
print('Training...')
local losses = {}
local optim_state = {learningRate = opt.learning_rate, alpha = opt.decay_rate}
local iterations = opt.train_size/opt.seq_length
for i = 1, iterations do
local _, loss = optim.rmsprop(feval, params, optim_state)
losses[#losses + 1] = loss[1]
if i % (iterations/10) == 0 then
print(string.format("Iteration %8d, loss = %4.4f, loss/seq_len = %4.4f, gradnorm = %4.4e", i, loss[1], loss[1] / opt.seq_length, grad_params:norm()))
end
end
-- testing function:
bo = 0
function test()
-- bo variable creates batches on the fly
-- forward pass ---------------------------------------------------------------
local rnn_state = {[0]=init_state} -- initial state
local predictions = {}
local loss = 0
for t = 1, opt.seq_length do
clones.rnn[t]:evaluate() -- make sure we are in correct testing mode
local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}
rnn_state[t] = {}
for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output
predictions[t] = lst[#lst]
end
-- carry over lstm state
rnn_state[0] = init_state -- here we want to test all steps
-- print(predictions[opt.seq_length])
-- print results:
local max, idx
max,idx = torch.max( predictions[opt.seq_length], 2)
print('Prediction:', idx[1][1], 'Label:', y[{1,{opt.seq_length+bo}}][1])
-- point to next batch:
bo = bo + 1 -- here we want to test all steps
end
-- and test!
opt.test_samples = 50
for i = 1, opt.test_samples do
test()
end
|
-- Eugenio Culurciello
-- September 2016
-- RNN training test: ABBA / 1221 sequence detector
-- based on: https://raw.githubusercontent.com/karpathy/char-rnn/master/model/RNN.lua
require 'nn'
require 'nngraph'
require 'optim'
dofile('RNN.lua')
local model_utils = require 'model_utils'
torch.setdefaulttensortype('torch.FloatTensor')
-- nngraph.setDebug(true)
local opt = {}
opt.dictionary_size = 2 -- sequence of 2 symbols
opt.train_size = 10000 -- train data size
opt.seq_length = 4 -- RNN time steps
print('Creating Input...')
-- create a sequence of 2 numbers: {2, 1, 2, 2, 1, 1, 2, 2, 1 ..}
local s = torch.Tensor(opt.train_size):random(2)
print('Inputs sequence:', s:view(1,-1))
local y = torch.ones(1, opt.train_size)
for i = 4, opt.train_size do -- if you find sequence ...1001... then output is class '2', otherwise is '1'
if (s[{i-3}]==1 and s[{i-2}]==2 and s[{i-1}]==2 and s[{i}]==1) then y[{1,{i}}] = 2 end
-- if (s[{i-1}]==1 and s[{i}]==2) then y[{1,{i}}] = 2 end -- detect one 1-2 sequence
end
print('Desired sequence:', y)
local x = torch.zeros(2, opt.train_size) -- create input with 1-hot encoding:
for i = 1, opt.train_size do
if s[i] > 1 then x[{{},{i}}] = torch.Tensor{0,1} else x[{{},{i}}] = torch.Tensor{1,0} end
end
print('Input vector:', x)
-- model:
print('Creating Model...')
opt.rnn_size = 10
opt.rnn_layers = 1
opt.batch_size = 1
local protos = {}
protos.rnn = RNN(opt.dictionary_size, opt.rnn_size, opt.rnn_layers, 0) -- input = 2 (classes), 1 layer, rnn_size=1, no dropout
protos.criterion = nn.ClassNLLCriterion()
-- print('Test of RNN output:', RNNmodel:forward{ torch.Tensor(2), torch.Tensor(1) })
-- the initial state of the cell/hidden states
local init_state = {}
for L = 1, opt.rnn_layers do
local h_init = torch.zeros(opt.batch_size, opt.rnn_size)
table.insert(init_state, h_init:clone())
end
local params, grad_params
-- get flattened parameters tensor
-- params, grad_params = model_utils.combine_all_parameters(protos.rnn)
params, grad_params = protos.rnn:getParameters()
print('Number of parameters in the model: ' .. params:nElement())
-- print(params, grad_params)
-- create clones of model to unroll in time:
print('Cloning RNN model:')
local clones = {}
clones.rnn = {}
clones.criterion = {}
for name, proto in pairs(protos) do
print('cloning ' .. name)
--clones[name] = model_utils.clone_many_times(proto, opt.seq_length, not proto.parameters)
for i=1,opt.seq_length do
clones[name][i] = proto:clone('weight','bias','gradWeight','gradBias')
end
end
function clone_list(tensor_list, zero_too)
-- takes a list of tensors and returns a list of cloned tensors
local out = {}
for k,v in pairs(tensor_list) do
out[k] = v:clone()
if zero_too then out[k]:zero() end
end
return out
end
-- training function:
local init_state_global = clone_list(init_state)
local bo = 0 -- batch offset / counter
opt.grad_clip = 5
function feval(p)
if p ~= params then
params:copy(p)
end
grad_params:zero()
-- bo variable creates batches on the fly
-- forward pass ---------------------------------------------------------------
local rnn_state = {[0]=init_state_global} -- initial state
local predictions = {}
local loss = 0
for t = 1, opt.seq_length do
clones.rnn[t]:training() -- make sure we are in correct training mode
-- print( 'sample,target:', x[{{},{t+bo}}], y[{1,{t+bo}}] )
local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}
rnn_state[t] = {}
for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output
predictions[t] = lst[#lst]
loss = loss + clones.criterion[t]:forward(predictions[t], y[{1,{t+bo}}])
end
loss = loss / opt.seq_length
-- backward pass --------------------------------------------------------------
-- initialize gradient at time t to be zeros (there's no influence from future)
local drnn_state = {[opt.seq_length] = clone_list(init_state, true)} -- true also zeros the clones
for t = opt.seq_length, 1, -1 do
-- print(drnn_state)
-- backprop through loss, and softmax/linear
-- print( 'prediction,target:', predictions[t], y[{1,{t+bo}}] )
local doutput_t = clones.criterion[t]:backward(predictions[t], y[{1,{t+bo}}])
-- print('douptut', doutput_t)
table.insert(drnn_state[t], doutput_t)
local dlst = clones.rnn[t]:backward({x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}, drnn_state[t])
drnn_state[t-1] = {}
for k,v in pairs(dlst) do
if k > 1 then -- k == 1 is gradient on x, which we dont need
-- note we do k-1 because first item is dembeddings, and then follow the
-- derivatives of the state, starting at index 2. I know...
drnn_state[t-1][k-1] = v
end
end
end
-- transfer final state to initial state (BPTT)
init_state_global = rnn_state[#rnn_state]
-- grad_params:div(opt.seq_length)
-- clip gradient element-wise
grad_params:clamp(-opt.grad_clip, opt.grad_clip)
-- print(params,grad_params)
-- point to next batch:
bo = bo + opt.seq_length
return loss, grad_params
end
-- training:
opt.learning_rate = 2e-3
opt.decay_rate = 0.95
print('Training...')
local losses = {}
local optim_state = {learningRate = opt.learning_rate, alpha = opt.decay_rate}
local iterations = opt.train_size/opt.seq_length
for i = 1, iterations do
local _, loss = optim.rmsprop(feval, params, optim_state)
losses[#losses + 1] = loss[1]
if i % (iterations/10) == 0 then
print(string.format("Iteration %8d, loss = %4.4f, loss/seq_len = %4.4f, gradnorm = %4.4e", i, loss[1], loss[1] / opt.seq_length, grad_params:norm()))
end
end
-- testing function:
bo = 0
function test()
-- bo variable creates batches on the fly
-- forward pass ---------------------------------------------------------------
local rnn_state = {[0]=init_state} -- initial state
local predictions = {}
local loss = 0
for t = 1, opt.seq_length do
clones.rnn[t]:evaluate() -- make sure we are in correct testing mode
local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}
rnn_state[t] = {}
for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output
predictions[t] = lst[#lst]
end
-- carry over lstm state
rnn_state[0] = init_state -- here we want to test all steps
-- print(predictions[opt.seq_length])
-- print results:
local max, idx
max,idx = torch.max( predictions[opt.seq_length], 2)
print('Prediction:', idx[1][1], 'Label:', y[{1,{opt.seq_length+bo}}][1])
-- point to next batch:
bo = bo + 1 -- here we want to test all steps
end
-- and test!
opt.test_samples = 50
for i = 1, opt.test_samples do
test()
end
|
fix to work with clone
|
fix to work with clone
|
Lua
|
bsd-3-clause
|
e-lab/torch7-demos,e-lab/torch7-demos
|
c14f0aa0bbe90188d403c3761740276bf62c83c2
|
kong/cmd/vault.lua
|
kong/cmd/vault.lua
|
local kong_global = require "kong.global"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local log = require "kong.cmd.utils.log"
local DB = require "kong.db"
local assert = assert
local error = error
local print = print
local exit = os.exit
local fmt = string.format
local function init_db(args)
-- retrieve default prefix or use given one
log.disable()
local conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
if pl_path.exists(conf.kong_env) then
-- load <PREFIX>/kong.conf containing running node's config
conf = assert(conf_loader(conf.kong_env))
end
package.path = conf.lua_package_path .. ";" .. package.path
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf)
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.vaults:load_vault_schemas(conf.loaded_vaults))
_G.kong.db = db
end
local function get(args)
if args.command == "get" then
local reference = args[1]
if not reference then
return error("the 'get' command needs a <reference> argument \nkong vault get <reference>")
end
init_db(args)
local vault = kong.vault
if not vault.is_reference(reference) then
-- assuming short form: <name>/<resource>[/<key>]
reference = fmt("{vault://%s}", reference)
end
local opts, err = vault.parse_reference(reference)
if not opts then
return error(err)
end
local res, err = vault.get(reference)
if err then
return error(err)
end
print(res)
end
end
local function execute(args)
if args.command == "" then
exit(0)
end
if args.command == "get" then
get(args)
end
end
local lapp = [[
Usage: kong vault COMMAND [OPTIONS]
Vault utilities for Kong.
Example usage:
TEST=hello kong vault get env/test
The available commands are:
get <reference> Retrieves a value for <reference>
Options:
-c,--conf (optional string) configuration file
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
get = true,
},
}
|
local kong_global = require "kong.global"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local log = require "kong.cmd.utils.log"
local DB = require "kong.db"
local assert = assert
local error = error
local print = print
local exit = os.exit
local fmt = string.format
local function init_db(args)
-- retrieve default prefix or use given one
log.disable()
local conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
if pl_path.exists(conf.kong_env) then
-- load <PREFIX>/kong.conf containing running node's config
conf = assert(conf_loader(conf.kong_env))
end
package.path = conf.lua_package_path .. ";" .. package.path
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf)
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.vaults:load_vault_schemas(conf.loaded_vaults))
_G.kong.db = db
end
local function get(args)
if args.command == "get" then
local reference = args[1]
if not reference then
return error("the 'get' command needs a <reference> argument \nkong vault get <reference>")
end
init_db(args)
local vault = kong.vault
if not vault.is_reference(reference) then
-- assuming short form: <name>/<resource>[/<key>]
reference = fmt("{vault://%s}", reference)
end
local opts, err = vault.parse_reference(reference)
if not opts then
return error(err)
end
local res, err = vault.get(reference)
if err then
return error(err)
end
print(res)
end
end
local function execute(args)
if args.command == "" then
exit(0)
end
if args.command == "get" then
get(args)
end
end
local lapp = [[
Usage: kong vault COMMAND [OPTIONS]
Vault utilities for Kong.
Example usage:
TEST=hello kong vault get env/test
The available commands are:
get <reference> Retrieves a value for <reference>
Options:
-c,--conf (optional string) configuration file
-p,--prefix (optional string) override prefix directory
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
get = true,
},
}
|
fix(cli) add support for `-p`/`--prefix` option to `kong vault` command
|
fix(cli) add support for `-p`/`--prefix` option to `kong vault` command
### Summary
Adds support for `-p` and `--prefix` options to `kong vault` commands.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
6626912bb0d1e7f1b36ed49ca83b293ee08ed890
|
core/inputs-texlike.lua
|
core/inputs-texlike.lua
|
SILE.inputs.TeXlike = {}
local epnf = require( "epnf" )
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = lpeg.S(",;") * _
local quotedString = (P("\"") * C((1-lpeg.S("\""))^1) * P("\""))
local value = (quotedString + (1-lpeg.S(",;]"))^1 )
local myID = C( SILE.inputs.TeXlike.identifier + lpeg.P(1) ) / function (t) return t end
local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end
local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end
local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1)
local lineEndLineStartSpace = (lpeg.S(" ")^0 * lpeg.S("\r\n")^1 * lpeg.S(" ")^0)^-1
local comment = ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^-1) /function () return "" end)
START "document";
document = V("stuff") * (-1 + E("Unexpected character at end of input"))
text = (anything + C(WS))^1 / function(...) return table.concat({...}, "") end
stuff = Cg(V"environment" +
comment
+ V("text") + V"bracketed_stuff" + V"command")^0
bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected"))
command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0)-P("\\end{")
environment =
P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}")
* V("stuff")
* (P("\\end{") * (
Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) +
E("Environment mismatch")
) * (P("}") * _) + E("Environment begun but never ended"))
end
local linecache = {}
local lno, col, lastpos
local function resetCache()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline( s, p )
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast(t,doc)
-- Sort out pos
if type(t) == "string" then return t end
if t.pos then
t.line, t.col = getline(doc, t.pos)
end
if t.id == "document" then return massage_ast(t[1],doc) end
if t.id == "text" then return t[1] end
if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end
for k,v in ipairs(t) do
if v.id == "stuff" then
local val = massage_ast(v,doc)
SU.splice(t, k,k, val)
else
t[k] = massage_ast(v,doc)
end
end
return t
end
function SILE.inputs.TeXlike.process(fn)
local fh = io.open(fn)
resetCache()
local doc = fh:read("*all")
local t = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if root then
if not(t.tag == "document") then SU.error("Should begin with \\begin{document}") end
SILE.inputs.common.init(fn, t)
end
SILE.process(t)
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree(doc)
local t = epnf.parsestring(_parser, doc)
-- a document always consists of one stuff
t = t[1][1]
if not t then return end
resetCache()
t = massage_ast(t,doc)
return t
end
|
SILE.inputs.TeXlike = {}
local epnf = require( "epnf" )
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = lpeg.S(",;") * _
local quotedString = (P("\"") * C((1-lpeg.S("\""))^1) * P("\""))
local value = (quotedString + (1-lpeg.S(",;]"))^1 )
local myID = C( SILE.inputs.TeXlike.identifier + lpeg.P(1) ) / function (t) return t end
local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end
local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end
local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1)
local lineEndLineStartSpace = (lpeg.S(" ")^0 * lpeg.S("\r\n")^1 * lpeg.S(" ")^0)^-1
local comment = ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^-1) /function () return "" end)
START "document";
document = V("stuff") * (-1 + E("Unexpected character at end of input"))
text = C( (1-lpeg.S("\\{}%")) ^1)
stuff = Cg(V"environment" +
comment
+ V("text") + V"bracketed_stuff" + V"command")^0
bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected"))
command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0)-P("\\end{")
environment =
P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}")
* V("stuff")
* (P("\\end{") * (
Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) +
E("Environment mismatch")
) * (P("}") * _) + E("Environment begun but never ended"))
end
local linecache = {}
local lno, col, lastpos
local function resetCache()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline( s, p )
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast(t,doc)
-- Sort out pos
if type(t) == "string" then return t end
if t.pos then
t.line, t.col = getline(doc, t.pos)
end
if t.id == "document" then return massage_ast(t[1],doc) end
if t.id == "text" then return t[1] end
if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end
for k,v in ipairs(t) do
if v.id == "stuff" then
local val = massage_ast(v,doc)
SU.splice(t, k,k, val)
else
t[k] = massage_ast(v,doc)
end
end
return t
end
function SILE.inputs.TeXlike.process(fn)
local fh = io.open(fn)
resetCache()
local doc = fh:read("*all")
local t = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if root then
if not(t.tag == "document") then SU.error("Should begin with \\begin{document}") end
SILE.inputs.common.init(fn, t)
end
SILE.process(t)
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree(doc)
local t = epnf.parsestring(_parser, doc)
-- a document always consists of one stuff
t = t[1][1]
if not t then return end
resetCache()
t = massage_ast(t,doc)
return t
end
|
Simplify “text” match in TeX-like grammar. Fixes #174.
|
Simplify “text” match in TeX-like grammar. Fixes #174.
|
Lua
|
mit
|
simoncozens/sile,alerque/sile,alerque/sile,alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile
|
a915b0bdc80452ee768ad25b7e6911093265eb1f
|
plugins/lua/serialize/serialize.lua
|
plugins/lua/serialize/serialize.lua
|
local types = require "./serialize/types"
local encoders = {
boolean = function( v )
return string.pack( ">B", v and 1 or 0 )
end,
number = function( v )
return string.pack( ">n", v )
end,
integer = function( v )
return string.pack( ">j", v )
end,
string = function( v )
return string.pack( ">s4", v )
end,
["function"] = function( v )
return string.pack( ">s4", string.dump( v ) )
end
}
local function serialize( t )
local tabArray, tabAssoc = {}, {}
local valArray, valAssoc = {}, {}
local function populateDictionary( v )
if type( v ) == "table" then
if not tabAssoc[ v ] then
table.insert( tabArray, v )
tabAssoc[ v ] = #tabArray
for k, v in pairs( v ) do
populateDictionary( k )
populateDictionary( v )
end
end
else
if not valAssoc[ v ] then
table.insert( valArray, v )
valAssoc[ v ] = #valArray
end
end
end
populateDictionary( t )
local outBuf = {}
--
-- Write value data to output
--
for k, v in ipairs( valArray ) do
local vType = type( v )
if math.type( v ) == "integer" then
vType = "integer"
end
if not encoders[ vType ] then
error( "attempt to write unsupported type (" .. vType .. ")", 2 )
end
table.insert( outBuf, string.pack( ">B", types[ vType ] ) )
table.insert( outBuf, encoders[ vType ]( v ) )
end
--
-- Type of 0 signals end of value-set
--
table.insert( outBuf, string.pack( ">B", 0 ) )
--
-- Write table data to output
--
table.insert( outBuf, string.pack( ">j", #tabArray ) )
for k, v in ipairs( tabArray ) do
for k, v in pairs( v ) do
--
-- Write key data
--
if type( k ) ~= "table" then
table.insert( outBuf, string.pack( ">B", 1 ) )
table.insert( outBuf, string.pack( ">j", valAssoc[ k ] ) )
else
table.insert( outBuf, string.pack( ">B", 2 ) )
table.insert( outBuf, string.pack( ">j", tabAssoc[ k ] ) )
end
--
-- Write value data
--
if type( v ) ~= "table" then
table.insert( outBuf, string.pack( ">B", 1 ) )
table.insert( outBuf, string.pack( ">j", valAssoc[ v ] ) )
else
table.insert( outBuf, string.pack( ">B", 2 ) )
table.insert( outBuf, string.pack( ">j", tabAssoc[ v ] ) )
end
end
--
-- Data-Type of 0 signals end of table
--
table.insert( outBuf, string.pack( ">B", 0 ) )
end
return table.concat( outBuf )
end
return serialize
|
local types = require "./serialize/types"
local encoders = {
boolean = function( v )
return string.pack( ">B", v and 1 or 0 )
end,
number = function( v )
return string.pack( ">n", v )
end,
integer = function( v )
return string.pack( ">j", v )
end,
string = function( v )
return string.pack( ">s4", v )
end,
["function"] = function( v )
local success, data = pcall( string.dump, v )
return string.pack( ">s4", success and data or string.dump( function() end ) )
end
}
local function serialize( t )
local tabArray, tabAssoc = {}, {}
local valArray, valAssoc = {}, {}
local function populateDictionary( v )
if type( v ) == "table" then
if not tabAssoc[ v ] then
table.insert( tabArray, v )
tabAssoc[ v ] = #tabArray
for k, v in pairs( v ) do
populateDictionary( k )
populateDictionary( v )
end
end
else
if not valAssoc[ v ] then
table.insert( valArray, v )
valAssoc[ v ] = #valArray
end
end
end
populateDictionary( t )
local outBuf = {}
--
-- Write value data to output
--
for k, v in ipairs( valArray ) do
local vType = type( v )
if math.type( v ) == "integer" then
vType = "integer"
end
if not encoders[ vType ] then
error( "attempt to write unsupported type (" .. vType .. ")", 2 )
end
table.insert( outBuf, string.pack( ">B", types[ vType ] ) )
table.insert( outBuf, encoders[ vType ]( v ) )
end
--
-- Type of 0 signals end of value-set
--
table.insert( outBuf, string.pack( ">B", 0 ) )
--
-- Write table data to output
--
table.insert( outBuf, string.pack( ">j", #tabArray ) )
for k, v in ipairs( tabArray ) do
for k, v in pairs( v ) do
--
-- Write key data
--
if type( k ) ~= "table" then
table.insert( outBuf, string.pack( ">B", 1 ) )
table.insert( outBuf, string.pack( ">j", valAssoc[ k ] ) )
else
table.insert( outBuf, string.pack( ">B", 2 ) )
table.insert( outBuf, string.pack( ">j", tabAssoc[ k ] ) )
end
--
-- Write value data
--
if type( v ) ~= "table" then
table.insert( outBuf, string.pack( ">B", 1 ) )
table.insert( outBuf, string.pack( ">j", valAssoc[ v ] ) )
else
table.insert( outBuf, string.pack( ">B", 2 ) )
table.insert( outBuf, string.pack( ">j", tabAssoc[ v ] ) )
end
end
--
-- Data-Type of 0 signals end of table
--
table.insert( outBuf, string.pack( ">B", 0 ) )
end
return table.concat( outBuf )
end
return serialize
|
Hacky fix for nested functions in cookies
|
Hacky fix for nested functions in cookies
|
Lua
|
cc0-1.0
|
mcd1992/hash.js,meepdarknessmeep/hash.js,ModMountain/hash.js,SwadicalRag/hash.js
|
f0684dd3e8e546141ed5e71a9e9ecb78a244667b
|
premake5.lua
|
premake5.lua
|
solution "gluacacheextract"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
language "C++"
characterset "MBCS"
location "project"
targetdir "bin"
filter "platforms:x32"
architecture "x32"
filter "platforms:x64"
architecture "x64"
project "gluacacheextract"
kind "ConsoleApp"
targetname "gluaextract"
flags { "Symbols", "NoEditAndContinue", "NoPCH", "StaticRuntime", "EnableSSE" }
links "bootil_static"
includedirs "Bootil/include"
files { "src/main.cpp" }
include "Bootil/projects/bootil_premake5.lua"
|
solution "gluacacheextract"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
language "C++"
characterset "MBCS"
location "project"
targetdir "bin"
filter "platforms:x32"
architecture "x32"
filter "platforms:x64"
architecture "x64"
project "gluacacheextract"
kind "ConsoleApp"
targetname "gluaextract"
flags { "Symbols", "NoEditAndContinue", "NoPCH", "StaticRuntime", "EnableSSE" }
links "bootil_static"
includedirs "Bootil/include"
if os.is( "linux" ) then
buildoptions { "-fPIC", "-pthread" }
linkoptions { "-pthread" }
end
files { "src/main.cpp" }
include "Bootil/projects/bootil_premake5.lua"
|
fix linux build: specify -pthread linkage as we link statically with Bootil
|
fix linux build: specify -pthread linkage as we link statically with Bootil
|
Lua
|
mit
|
HandsomeMatt/glua-cache-extract
|
ea5a23bd9941637396b894900b7f2eadd123e2f2
|
core/webserver.lua
|
core/webserver.lua
|
local util = require'util'
local httpserver = require'handler.http.server'
local ev = require'ev'
require'logging.console'
local log = logging.console()
local loop = ev.Loop.default
local server = nil
local webserver = {}
local handlers = {
['/favicon.ico'] = function(req, res)
-- return 404 Not found error
res:set_status(404)
res:send()
return
end,
}
local on_response_sent = function(res)
end
local on_data = function(req, res, data)
-- Save the body into the request
req.body = data or ''
end
local on_request = function(server, req, res)
local found = false
for pattern, handler in pairs(handlers) do
if req.url:match(pattern) then
log:info('webserver> request for pattern :%s', pattern)
found = true
req.on_finished = handler
req.on_data = on_data
break
end
end
if not found then
log:info('webserver> returning 404 for request: %s', req.url)
req.on_finished = function(req, res)
res:set_status(404)
res:send()
return
end
end
res.on_response_sent = on_response_sent
end
webserver.start = function(host, port)
if not (host and port) then
return
end
log:info('webserver> starting webserver: %s:%s', host, port)
server = httpserver.new(loop, {
name = "ivar2-HTTPServer/0.0.1",
on_request = on_request,
request_head_timeout = 15.0,
request_body_timeout = 15.0,
write_timeout = 15.0,
keep_alive_timeout = 15.0,
max_keep_alive_requests = 10,
})
server:listen_uri("tcp://"..host..":"..tostring(port).."/")
end
webserver.stop = function()
log:info('webserver> stopping webserver.')
server.acceptors[1]:close()
end
webserver.regUrl = function(pattern, handler)
log:info('webserver> registering new handler for URL pattern: %s', pattern)
handlers[pattern] = handler
end
webserver.unRegUrl = function(pattern)
log:info('webserver> unregistering handler for URL pattern: %s', pattern)
handlers[pattern] = nil
end
return webserver
|
local util = require'util'
local httpserver = require'handler.http.server'
local ev = require'ev'
require'logging.console'
local log = logging.console()
local loop = ev.Loop.default
local server = nil
local webserver = {}
local handlers = {
['/favicon.ico'] = function(req, res)
-- return 404 Not found error
res:set_status(404)
res:send()
return
end,
}
local on_response_sent = function(res)
end
local on_data = function(req, res, data)
-- Save the body into the request
req.body = data or ''
end
local on_request = function(server, req, res)
local found = false
for pattern, handler in pairs(handlers) do
if req.url:match(pattern) then
log:info('webserver> request for pattern :%s', pattern)
found = true
req.on_finished = handler
req.on_data = on_data
break
end
end
if not found then
log:info('webserver> returning 404 for request: %s', req.url)
req.on_finished = function(req, res)
res:set_status(404)
res:send()
return
end
end
res.on_response_sent = on_response_sent
end
webserver.start = function(host, port)
if not (host and port) then
return
end
log:info('webserver> starting webserver: %s:%s', host, port)
server = httpserver.new(loop, {
name = "ivar2-HTTPServer/0.0.1",
on_request = on_request,
request_head_timeout = 15.0,
request_body_timeout = 15.0,
write_timeout = 15.0,
keep_alive_timeout = 15.0,
max_keep_alive_requests = 10,
})
server:listen_uri("tcp://"..host..":"..tostring(port).."/")
end
webserver.stop = function()
log:info('webserver> stopping webserver.')
server.acceptors[1]:close()
end
webserver.regUrl = function(pattern, handler)
log:info('webserver> registering new handler for URL pattern: %s', pattern)
handlers[pattern] = handler
end
webserver.unRegUrl = function(pattern)
log:info('webserver> unregistering handler for URL pattern: %s', pattern)
handlers[pattern] = nil
end
return webserver
|
core: Fix indent of webserver.
|
core: Fix indent of webserver.
|
Lua
|
mit
|
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
|
04b2d5977124a5f14f5fce1f97fda607c0e7e00c
|
lualib/sys/dns.lua
|
lualib/sys/dns.lua
|
local core = require "sys.core"
local socket = require "sys.socket"
local assert = assert
local sub = string.sub
local concat = table.concat
local pack = string.pack
local unpack = string.unpack
local format = string.format
local match = string.match
local gmatch = string.gmatch
local dns = {}
local A = 1
local CNAME = 5
local AAAA = 28
local name_cache = {}
local wait_coroutine = {}
local weakmt = {__mode = "kv"}
local session = 0
local dns_server
local connectfd
setmetatable(name_cache, weakmt)
local timenow = core.monotonicsec
--[[
ID:16
QR:1 0 -> request 1-> acknowledge
OPCODE:4 0 -> QUERY 1 -> IQUERY 2 -> STATUS
AA:1 authoriative Answer
TC:1 trun cation
RD:1 recursion desiered
RA:1 rescursion availavle
Z:3 0
RCODE:4 0 -> ok 1 -> FormatError 2 -> Server Failure 3 -> NameError
4 -> NotEmplemented 5 -> Refresued
QDCOUNT:16 quest descriptor count
ANCOUNT:16 anser RRs
NSCOUNT:16 authority RRs
ARCOUNT:16 Additional RRs
QNAME:z question name
QTYPE:16 0x01 -> IP... 0x05 -> CNAME
QCLASS:16 0x01 -> IN
]]--
local parseformat = ">I2I2I2I2I2I2zI2I2"
local headerformat = ">I2I2I2I2I2I2"
local function QNAME(name, n)
local i = #n
for k in gmatch(name, "([^%.]+)") do
i = i + 1
n[i] = pack(">I1", #k)
i = i + 1
n[i] = k
end
i = i + 1
n[i] = '\0'
end
local function question(name, typ)
if typ == "AAAA" then
typ = AAAA
else
typ = A
end
session = session + 1
local ID = session
--[[ FLAG
QR = 0,
OPCODE = 0, (4bit)
AA = 0,
TC = 0,
RD = 1,
RA = 0,
--3 bit zero
RCCODE = 0,
]]--
local FLAG = 0x0100
local QDCOUNT = 1
local ANCOUNT = 0
local NSCOUNT = 0
local ARCOUNT = 0
local QTYPE = typ
local QCLASS = 1
local dat = {
pack(headerformat,
ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT)
}
QNAME(name, dat)
dat[#dat + 1] = pack(">I2I2", QTYPE, QCLASS)
return ID, concat(dat)
end
local function readptr(init, dat, pos)
local n, pos = unpack(">I1", dat, pos)
if n >= 0xc0 then
n = n & 0x3f
local l, pos = unpack(">I1", dat, pos)
n = n << 8 | l
return readptr(init, dat, n + 1)
elseif n > 0 then
local nxt = pos + n
init[#init + 1] = sub(dat, pos, nxt - 1)
init[#init + 1] = "."
return readptr(init, dat, nxt)
else
return
end
end
local function readname(dat, i)
local tbl = {}
while true do --first
local n, j = unpack(">I1", dat, i)
if n >= 0xc0 then
readptr(tbl, dat, i)
i = i + 2
break
elseif n == 0 then
i = j
break
end
tbl[#tbl + 1] = sub(dat, j, i + n)
tbl[#tbl + 1] = "."
i = j + n
end
tbl[#tbl] = nil
return concat(tbl), i
end
local function answer(dat, pos, n)
for i = 1, n do
local src, pos = readname(dat, pos)
local qtype, qclass, ttl, rdlen, pos
= unpack(">I2I2I4I2", dat, pos)
if qtype == A then
local d1, d2, d3, d4 =
unpack(">I1I1I1I1", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "A",
A = format("%d.%d.%d.%d", d1, d2, d3, d4),
}
elseif qtype == CNAME then
local cname = readname(dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "CNAME",
CNAME = cname,
}
elseif qtype == AAAA then
local x1, x2, x3, x4, x5, x6, x7, x8 =
unpack(">I2I2I2I2I2I2I2I2", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "AAAA",
AAAA = format("%x:%x:%x:%x:%x%x:%x:%x",
x1, x2, x3, x4, x5, x6, x7, x8),
}
end
end
end
local function callback(msg, _)
local pos
if msg then
local ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT,
QNAME,
QTYPE, QCLASS, pos = unpack(parseformat, msg)
answer(msg, pos, ANCOUNT)
local co = wait_coroutine[ID]
if not co then --already timeout
return
end
wait_coroutine[ID] = nil
core.wakeup(co, ANCOUNT > 0)
else --udp closed
for k, co in pairs(wait_coroutine) do
core.wakeup(co, false)
wait_coroutine[k] = nil
end
connectfd = nil
end
end
local function suspend(session, timeout)
local co = core.running()
wait_coroutine[session] = co
core.fork(function()
core.sleep(timeout)
local co = wait_coroutine[session]
if not co then
return
end
wait_coroutine[session] = nil
core.wakeup(co, false)
end)
return core.wait(co)
end
local function connectserver()
if not dns_server then
local f = io.open("/etc/resolv.conf", "r")
for l in f:lines() do
dns_server = l:match("^%s*nameserver%s+([^%s]+)")
if dns_server then
dns_server = format("%s:53", dns_server)
break
end
end
end
assert(dns_server)
return socket.udp(dns_server, callback)
end
local function query(name, typ, timeout)
if not connectfd then
connectfd = connectserver()
end
assert(connectfd > 0)
local retry = 1
local s, r = question(name, typ)
--RFC 1123 #page-76, the default timeout
--should be less than 5 seconds
timeout = timeout or 5000
while true do
local ok = socket.udpwrite(connectfd, r)
if not ok then
return false
end
local ok = suspend(s, timeout)
if ok then
return ok
end
retry = retry + 1
if retry > 3 then
return false
end
core.sleep(timeout * retry)
end
end
local function lookup(name)
local d
local now = timenow()
for i = 1, 100 do
d = name_cache[name]
if not d then
return nil, name
end
if d.TTL < now then
name_cache[name] = nil
return nil, name
end
if d.TYPE == "CNAME" then
name = d.CNAME
else
return d
end
end
return nil, name
end
local function isname(name)
local right = name:match("([%x])", #name)
if right then
return false
end
return true
end
function dns.resolve(name, typ, timeout)
if not isname(name) then
return name
end
local d , cname = lookup(name)
if not d then
for i = 1, 100 do
local res = query(cname, typ, timeout)
if not res then
return
end
d, cname = lookup(cname)
if not cname then
goto FIND
end
end
return
end
::FIND::
if typ then
return d[typ], typ
else
return d.A or d.AAAA, d.TYPE
end
end
function dns.server(ip)
dns_server = ip
end
dns.isname = isname
return dns
|
local core = require "sys.core"
local socket = require "sys.socket"
local assert = assert
local sub = string.sub
local concat = table.concat
local pack = string.pack
local unpack = string.unpack
local format = string.format
local match = string.match
local gmatch = string.gmatch
local dns = {}
local A = 1
local CNAME = 5
local AAAA = 28
local name_cache = {}
local wait_coroutine = {}
local weakmt = {__mode = "kv"}
local session = 0
local dns_server
local connectfd
setmetatable(name_cache, weakmt)
local timenow = core.monotonicsec
--[[
ID:16
QR:1 0 -> request 1-> acknowledge
OPCODE:4 0 -> QUERY 1 -> IQUERY 2 -> STATUS
AA:1 authoriative Answer
TC:1 trun cation
RD:1 recursion desiered
RA:1 rescursion availavle
Z:3 0
RCODE:4 0 -> ok 1 -> FormatError 2 -> Server Failure 3 -> NameError
4 -> NotEmplemented 5 -> Refresued
QDCOUNT:16 quest descriptor count
ANCOUNT:16 anser RRs
NSCOUNT:16 authority RRs
ARCOUNT:16 Additional RRs
QNAME:z question name
QTYPE:16 0x01 -> IP... 0x05 -> CNAME
QCLASS:16 0x01 -> IN
]]--
local parseformat = ">I2I2I2I2I2I2zI2I2"
local headerformat = ">I2I2I2I2I2I2"
local function QNAME(name, n)
local i = #n
for k in gmatch(name, "([^%.]+)") do
i = i + 1
n[i] = pack(">I1", #k)
i = i + 1
n[i] = k
end
i = i + 1
n[i] = '\0'
end
local function question(name, typ)
if typ == "AAAA" then
typ = AAAA
else
typ = A
end
session = session + 1
local ID = session
--[[ FLAG
QR = 0,
OPCODE = 0, (4bit)
AA = 0,
TC = 0,
RD = 1,
RA = 0,
--3 bit zero
RCCODE = 0,
]]--
local FLAG = 0x0100
local QDCOUNT = 1
local ANCOUNT = 0
local NSCOUNT = 0
local ARCOUNT = 0
local QTYPE = typ
local QCLASS = 1
local dat = {
pack(headerformat,
ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT)
}
QNAME(name, dat)
dat[#dat + 1] = pack(">I2I2", QTYPE, QCLASS)
return ID, concat(dat)
end
local function readptr(init, dat, pos)
local n, pos = unpack(">I1", dat, pos)
if n >= 0xc0 then
n = n & 0x3f
local l, pos = unpack(">I1", dat, pos)
n = n << 8 | l
return readptr(init, dat, n + 1)
elseif n > 0 then
local nxt = pos + n
init[#init + 1] = sub(dat, pos, nxt - 1)
init[#init + 1] = "."
return readptr(init, dat, nxt)
else
return
end
end
local function readname(dat, i)
local tbl = {}
while true do --first
local n, j = unpack(">I1", dat, i)
if n >= 0xc0 then
readptr(tbl, dat, i)
i = i + 2
break
elseif n == 0 then
i = j
break
end
tbl[#tbl + 1] = sub(dat, j, i + n)
tbl[#tbl + 1] = "."
i = j + n
end
tbl[#tbl] = nil
return concat(tbl), i
end
local function answer(dat, pos, n)
for i = 1, n do
local src, pos = readname(dat, pos)
local qtype, qclass, ttl, rdlen, pos
= unpack(">I2I2I4I2", dat, pos)
if qtype == A then
local d1, d2, d3, d4 =
unpack(">I1I1I1I1", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "A",
A = format("%d.%d.%d.%d", d1, d2, d3, d4),
}
elseif qtype == CNAME then
local cname = readname(dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "CNAME",
CNAME = cname,
}
elseif qtype == AAAA then
local x1, x2, x3, x4, x5, x6, x7, x8 =
unpack(">I2I2I2I2I2I2I2I2", dat, pos)
name_cache[src] = {
TTL = timenow() + ttl,
TYPE = "AAAA",
AAAA = format("%x:%x:%x:%x:%x%x:%x:%x",
x1, x2, x3, x4, x5, x6, x7, x8),
}
end
end
end
local function callback(msg, _)
local pos
if msg then
local ID, FLAG,
QDCOUNT, ANCOUNT,
NSCOUNT, ARCOUNT,
QNAME,
QTYPE, QCLASS, pos = unpack(parseformat, msg)
answer(msg, pos, ANCOUNT)
local co = wait_coroutine[ID]
if not co then --already timeout
return
end
wait_coroutine[ID] = nil
core.wakeup(co, ANCOUNT > 0)
else --udp closed
for k, co in pairs(wait_coroutine) do
core.wakeup(co, false)
wait_coroutine[k] = nil
end
connectfd = nil
end
end
local function suspend(session, timeout)
local co = core.running()
wait_coroutine[session] = co
core.fork(function()
core.sleep(timeout)
local co = wait_coroutine[session]
if not co then
return
end
wait_coroutine[session] = nil
core.wakeup(co, false)
end)
return core.wait(co)
end
local function connectserver()
if not dns_server then
local f = io.open("/etc/resolv.conf", "r")
for l in f:lines() do
dns_server = l:match("^%s*nameserver%s+([^%s]+)")
if dns_server then
if dns_server:find(':') then
dns_server = '[' .. dns_server .. ']'
end
dns_server = format("%s:53", dns_server)
break
end
end
end
assert(dns_server)
return socket.udp(dns_server, callback)
end
local function query(name, typ, timeout)
if not connectfd then
connectfd = connectserver()
end
assert(connectfd > 0)
local retry = 1
local s, r = question(name, typ)
--RFC 1123 #page-76, the default timeout
--should be less than 5 seconds
timeout = timeout or 5000
while true do
local ok = socket.udpwrite(connectfd, r)
if not ok then
return false
end
local ok = suspend(s, timeout)
if ok then
return ok
end
retry = retry + 1
if retry > 3 then
return false
end
core.sleep(timeout * retry)
end
end
local function lookup(name)
local d
local now = timenow()
for i = 1, 100 do
d = name_cache[name]
if not d then
return nil, name
end
if d.TTL < now then
name_cache[name] = nil
return nil, name
end
if d.TYPE == "CNAME" then
name = d.CNAME
else
return d
end
end
return nil, name
end
local function isname(name)
local right = name:match("([%x])", #name)
if right then
return false
end
return true
end
function dns.resolve(name, typ, timeout)
if not isname(name) then
return name
end
local d , cname = lookup(name)
if not d then
for i = 1, 100 do
local res = query(cname, typ, timeout)
if not res then
return
end
d, cname = lookup(cname)
if not cname then
goto FIND
end
end
return
end
::FIND::
if typ then
return d[typ], typ
else
return d.A or d.AAAA, d.TYPE
end
end
function dns.server(ip)
dns_server = ip
end
dns.isname = isname
return dns
|
dns fix ipv6 address generate
|
dns fix ipv6 address generate
|
Lua
|
mit
|
findstr/silly
|
36945b9aa52e68a55ea0c5d6b8e2fcd8a9688c44
|
samples/gtk-demo/demo-uimanager.lua
|
samples/gtk-demo/demo-uimanager.lua
|
return function(parent, dir)
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local log = lgi.log.domain('uimanager-demo')
local function activate_action(action)
log.message('Action "%s" activated', action.name)
end
local function activate_radio_action(action)
log.message('Radio action "%s" selected', action.name)
end
local COLOR = { RED = 1, GREEN = 2, BLUE = 3 }
local SHAPE = { SQUARE = 1, RECTANGLE = 2, OVAL = 3 }
local actions = Gtk.ActionGroup {
Gtk.Action { name = 'FileMenu', label = "_File" },
Gtk.Action { name = 'PreferencesMenu', label = "_Preferences" },
Gtk.Action { name = 'ColorMenu', label = "_Color" },
Gtk.Action { name = 'ShapeMenu', label = "_Shape" },
Gtk.Action { name = 'HelpMenu', label = "_Help" },
{ Gtk.Action { name = 'New', stock_id = Gtk.STOCK_NEW, label = "_New",
tooltip = "Create a new file",
on_activate = activate_action, },
accelerator = '<control>N', },
{ Gtk.Action { name = 'Open', stock_id = Gtk.STOCK_OPEN, label = "_Open",
tooltip = "Open a file",
on_activate = activate_action, },
accelerator = '<control>O', },
{ Gtk.Action { name = 'Save', stock_id = Gtk.STOCK_SAVE, label = "_Save",
tooltip = "Save current file",
on_activate = activate_action, },
accelerator = '<control>S', },
Gtk.Action { name = 'SaveAs', stock_id = Gtk.STOCK_SAVE,
label = "Save _As...", tooltip = "Save to a file",
on_activate = activate_action, },
{ Gtk.Action { name = 'Quit', stock_id = Gtk.STOCK_QUIT, label = "_Quit",
tooltip = "Quit",
on_activate = activate_action, },
accelerator = '<control>Q', },
{ Gtk.Action { name = 'About', stock_id = Gtk.STOCK_ABOUT, label = "_About",
tooltip = "About",
on_activate = activate_action, },
accelerator = '<control>A', },
Gtk.Action { name = 'Logo', stock_id = 'demo-gtk-logo', tooltip = "GTK+",
on_activate = activate_action, },
{ Gtk.ToggleAction { name = 'Bold', stock_id = Gtk.STOCK_BOLD,
label = "_Bold", tooltip = "Bold", active = true,
on_activate = activate_action },
accelerator = "<control>B", },
{
{ Gtk.RadioAction { name = 'Red', label = "_Red", tooltip = "Blood",
value = COLOR.RED, active = true, },
accelerator = '<control>R', },
{ Gtk.RadioAction { name = 'Green', label = "_Green", tooltip = "Grass",
value = COLOR.GREEN },
accelerator = '<control>G', },
{ Gtk.RadioAction { name = 'Blue', label = "_Blue", tooltip = "Sky",
value = COLOR.BLUE },
accelerator = '<control>B', },
on_change = activate_radio_action,
},
{
{ Gtk.RadioAction { name = 'Square', label = "_Square",
tooltip = "Square", value = SHAPE.SQUARE, },
accelerator = '<control>S', },
{ Gtk.RadioAction { name = 'Rectangle', label = "_Rectangle",
tooltip = "Rectangle", value = SHAPE.RECTANGLE },
accelerator = '<control>R', },
{ Gtk.RadioAction { name = 'Oval', label = "_Oval",
tooltip = "Oval", value = SHAPE.OVAL, active = true },
accelerator = '<control>O', },
on_change = activate_radio_action,
},
}
local ui = Gtk.UIManager()
ui:insert_action_group(actions, 0)
local ok, err = ui:add_ui_from_string(
[[
<ui>
<menubar name='MenuBar'>
<menu action='FileMenu'>
<menuitem action='New'/>
<menuitem action='Open'/>
<menuitem action='Save'/>
<menuitem action='SaveAs'/>
<separator/>
<menuitem action='Quit'/>
</menu>
<menu action='PreferencesMenu'>
<menu action='ColorMenu'>
<menuitem action='Red'/>
<menuitem action='Green'/>
<menuitem action='Blue'/>
</menu>
<menu action='ShapeMenu'>
<menuitem action='Square'/>
<menuitem action='Rectangle'/>
<menuitem action='Oval'/>
</menu>
<menuitem action='Bold'/>
</menu>
<menu action='HelpMenu'>
<menuitem action='About'/>
</menu>
</menubar>
<toolbar name='ToolBar'>
<toolitem action='Open'/>
<toolitem action='Quit'/>
<separator action='Sep1'/>
<toolitem action='Logo'/>
</toolbar>
</ui>]], -1)
if not ok then
log.message('building menus failed: %s', err)
end
local window = Gtk.Window {
title = "UI Manager",
Gtk.Box {
orientation = 'VERTICAL',
ui:get_widget('/MenuBar'),
Gtk.Label {
id = 'label',
label = "Type\n<alt>\n to start",
halign = 'CENTER',
valign = 'CENTER',
expand = true,
},
Gtk.Separator {
orientation = 'HORIZONTAL',
},
Gtk.Box {
orientation = 'VERTICAL',
spacing = 10,
Gtk.Button {
id = 'close',
label = "close",
can_default = true,
},
},
},
}
window:add_accel_group(ui:get_accel_group())
function window.child.close:on_clicked()
window:destroy()
end
window.child.close:grab_default()
window.child.label:set_size_request(200, 200)
window:show_all()
return window
end,
"UI Manager",
table.concat {
[[The Gtk.UIManager object allows the easy creation of menus from ]],
[[an array of actions and a description of the menu hierarchy.]],
}
|
return function(parent, dir)
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local log = lgi.log.domain('uimanager-demo')
local function activate_action(action)
log.message('Action "%s" activated', action.name)
end
local function activate_radio_action(action)
log.message('Radio action "%s" selected', action.name)
end
local COLOR = { RED = 1, GREEN = 2, BLUE = 3 }
local SHAPE = { SQUARE = 1, RECTANGLE = 2, OVAL = 3 }
local actions = Gtk.ActionGroup {
name = 'Actions',
Gtk.Action { name = 'FileMenu', label = "_File" },
Gtk.Action { name = 'PreferencesMenu', label = "_Preferences" },
Gtk.Action { name = 'ColorMenu', label = "_Color" },
Gtk.Action { name = 'ShapeMenu', label = "_Shape" },
Gtk.Action { name = 'HelpMenu', label = "_Help" },
{ Gtk.Action { name = 'New', stock_id = Gtk.STOCK_NEW, label = "_New",
tooltip = "Create a new file",
on_activate = activate_action, },
accelerator = '<control>N', },
{ Gtk.Action { name = 'Open', stock_id = Gtk.STOCK_OPEN, label = "_Open",
tooltip = "Open a file",
on_activate = activate_action, },
accelerator = '<control>O', },
{ Gtk.Action { name = 'Save', stock_id = Gtk.STOCK_SAVE, label = "_Save",
tooltip = "Save current file",
on_activate = activate_action, },
accelerator = '<control>S', },
Gtk.Action { name = 'SaveAs', stock_id = Gtk.STOCK_SAVE,
label = "Save _As...", tooltip = "Save to a file",
on_activate = activate_action, },
{ Gtk.Action { name = 'Quit', stock_id = Gtk.STOCK_QUIT, label = "_Quit",
tooltip = "Quit",
on_activate = activate_action, },
accelerator = '<control>Q', },
{ Gtk.Action { name = 'About', stock_id = Gtk.STOCK_ABOUT, label = "_About",
tooltip = "About",
on_activate = activate_action, },
accelerator = '<control>A', },
Gtk.Action { name = 'Logo', stock_id = 'demo-gtk-logo', tooltip = "GTK+",
on_activate = activate_action, },
{ Gtk.ToggleAction { name = 'Bold', stock_id = Gtk.STOCK_BOLD,
label = "_Bold", tooltip = "Bold", active = true,
on_activate = activate_action },
accelerator = "<control>B", },
{
{ Gtk.RadioAction { name = 'Red', label = "_Red", tooltip = "Blood",
value = COLOR.RED, active = true, },
accelerator = '<control>R', },
{ Gtk.RadioAction { name = 'Green', label = "_Green", tooltip = "Grass",
value = COLOR.GREEN },
accelerator = '<control>G', },
{ Gtk.RadioAction { name = 'Blue', label = "_Blue", tooltip = "Sky",
value = COLOR.BLUE },
accelerator = '<control>B', },
on_change = activate_radio_action,
},
{
{ Gtk.RadioAction { name = 'Square', label = "_Square",
tooltip = "Square", value = SHAPE.SQUARE, },
accelerator = '<control>S', },
{ Gtk.RadioAction { name = 'Rectangle', label = "_Rectangle",
tooltip = "Rectangle", value = SHAPE.RECTANGLE },
accelerator = '<control>R', },
{ Gtk.RadioAction { name = 'Oval', label = "_Oval",
tooltip = "Oval", value = SHAPE.OVAL, active = true },
accelerator = '<control>O', },
on_change = activate_radio_action,
},
}
local ui = Gtk.UIManager()
ui:insert_action_group(actions, 0)
local ok, err = ui:add_ui_from_string(
[[
<ui>
<menubar name='MenuBar'>
<menu action='FileMenu'>
<menuitem action='New'/>
<menuitem action='Open'/>
<menuitem action='Save'/>
<menuitem action='SaveAs'/>
<separator/>
<menuitem action='Quit'/>
</menu>
<menu action='PreferencesMenu'>
<menu action='ColorMenu'>
<menuitem action='Red'/>
<menuitem action='Green'/>
<menuitem action='Blue'/>
</menu>
<menu action='ShapeMenu'>
<menuitem action='Square'/>
<menuitem action='Rectangle'/>
<menuitem action='Oval'/>
</menu>
<menuitem action='Bold'/>
</menu>
<menu action='HelpMenu'>
<menuitem action='About'/>
</menu>
</menubar>
<toolbar name='ToolBar'>
<toolitem action='Open'/>
<toolitem action='Quit'/>
<separator action='Sep1'/>
<toolitem action='Logo'/>
</toolbar>
</ui>]], -1)
if not ok then
log.message('building menus failed: %s', err)
end
local window = Gtk.Window {
title = "UI Manager",
Gtk.Box {
orientation = 'VERTICAL',
ui:get_widget('/MenuBar'),
Gtk.Label {
id = 'label',
label = "Type\n<alt>\n to start",
halign = 'CENTER',
valign = 'CENTER',
expand = true,
},
Gtk.Separator {
orientation = 'HORIZONTAL',
},
Gtk.Box {
orientation = 'VERTICAL',
spacing = 10,
border_width = 10,
Gtk.Button {
id = 'close',
label = "close",
can_default = true,
},
},
},
}
window:add_accel_group(ui:get_accel_group())
function window.child.close:on_clicked()
window:destroy()
end
window.child.close:grab_default()
window.child.label:set_size_request(200, 200)
window:show_all()
return window
end,
"UI Manager",
table.concat {
[[The Gtk.UIManager object allows the easy creation of menus from ]],
[[an array of actions and a description of the menu hierarchy.]],
}
|
gtk-demo: fix uimanager demo, which assigned the same value to all accelerators
|
gtk-demo: fix uimanager demo, which assigned the same value to all accelerators
|
Lua
|
mit
|
pavouk/lgi,psychon/lgi,zevv/lgi
|
40880ecda5cc964fdfd97539c4272eb447dcd0c2
|
xmake/actions/build/statistics.lua
|
xmake/actions/build/statistics.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file statistics.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.platform.platform")
import("core.platform.environment")
-- statistics is enabled?
function _is_enabled()
-- disable statistics? need not post it
local stats = (os.getenv("XMAKE_STATS") or ""):lower()
if stats == "false" then
return false
end
-- is in ci(travis/appveyor/...)? need not post it
local ci = (os.getenv("CI") or ""):lower()
if ci == "true" then
os.setenv("XMAKE_STATS", "false")
return false
end
-- ok
return true
end
-- post statistics info and only post once everyday when building each project
--
-- clone the xmake-stats(only an empty repo) to update the traffic(git clones) info in github
--
-- the traffic info in github (just be approximate numbers):
--
-- Clones: the number of projects which build using xmake everyday
-- Unique cloners: the number of users everyday
--
function post()
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- has been posted today or statistics is disable?
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
local markfile = outputdir .. ".mark"
if os.isdir(outputdir) or os.isfile(markfile) or not _is_enabled() then
return
end
-- mark as posted first, avoid to post it repeatly
io.writefile(markfile, "ok")
-- init argument list
local argv = {"lua", path.join(os.scriptdir(), "statistics.lua")}
for _, name in ipairs({"root", "file", "project", "backtrace", "verbose", "quiet", "yes"}) 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
-- try to post it in background
try
{
function ()
local proc = process.openv("xmake", argv, path.join(os.tmpdir(), projectname .. ".stats.log"))
if proc ~= nil then
process.wait(proc, -1)
process.close(proc)
end
end
}
end
-- the main function
function main()
-- in project?
if not os.isfile(os.projectfile()) then
return
end
-- load config
config.load()
-- load platform
platform.load(config.plat())
-- enter environment
environment.enter("toolchains")
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- clone the xmake-stats repo to update the traffic(git clones) info in github
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
if not os.isdir(outputdir) then
import("devel.git.clone")
clone("https://github.com/tboox/xmake-stats.git", {depth = 1, branch = "master", outputdir = outputdir})
print("post to traffic ok!")
end
-- download the xmake-stats releases to update the release stats info in github
local releasefile = outputdir .. ".release"
if not os.isfile(releasefile) then
import("net.http.download")
local version = os.versioninfo().version
download(format("https://github.com/tboox/xmake-stats/releases/download/v%d.%d.%d/%s", version.major, version.minor, version.alter, os.host()), releasefile)
print("post to releases ok!")
end
-- leave environment
environment.leave("toolchains")
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file statistics.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.platform.platform")
import("core.platform.environment")
-- statistics is enabled?
function _is_enabled()
-- disable statistics? need not post it
local stats = (os.getenv("XMAKE_STATS") or ""):lower()
if stats == "false" then
return false
end
-- is in ci(travis/appveyor/...)? need not post it
local ci = (os.getenv("CI") or ""):lower()
if ci == "true" then
os.setenv("XMAKE_STATS", "false")
return false
end
-- ok
return true
end
-- post statistics info and only post once everyday when building each project
--
-- clone the xmake-stats(only an empty repo) to update the traffic(git clones) info in github
--
-- the traffic info in github (just be approximate numbers):
--
-- Clones: the number of projects which build using xmake everyday
-- Unique cloners: the number of users everyday
--
function post()
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- has been posted today or statistics is disable?
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
local markfile = outputdir .. ".mark"
if os.isdir(outputdir) or os.isfile(markfile) or not _is_enabled() then
return
end
-- mark as posted first, avoid to post it repeatly
io.writefile(markfile, "ok")
-- init argument list
local argv = {"lua", path.join(os.scriptdir(), "statistics.lua")}
for _, name in ipairs({"root", "file", "project", "backtrace", "verbose", "quiet", "yes"}) 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
-- try to post it in background
try
{
function ()
local proc = process.openv("xmake", argv, path.join(os.tmpdir(), projectname .. ".stats.log"))
if proc ~= nil then
process.close(proc)
end
end
}
end
-- the main function
function main()
-- in project?
if not os.isfile(os.projectfile()) then
return
end
-- load config
config.load()
-- load platform
platform.load(config.plat())
-- enter environment
environment.enter("toolchains")
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- clone the xmake-stats repo to update the traffic(git clones) info in github
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
if not os.isdir(outputdir) then
import("devel.git.clone")
clone("https://github.com/tboox/xmake-stats.git", {depth = 1, branch = "master", outputdir = outputdir})
print("post to traffic ok!")
end
-- download the xmake-stats releases to update the release stats info in github
local releasefile = outputdir .. ".release"
if not os.isfile(releasefile) then
import("net.http.download")
local version = os.versioninfo().version
download(format("https://github.com/tboox/xmake-stats/releases/download/v%d.%d.%d/%s", version.major, version.minor, version.alter, os.host()), releasefile)
print("post to releases ok!")
end
-- leave environment
environment.leave("toolchains")
end
|
fix build block
|
fix build block
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
567a6630266fd7ee8e838f0c07a0f7e83a32564c
|
tmps.lua
|
tmps.lua
|
local VARS = {}
if not ANA then
return -- isTmp=false for all vars
end
F = {
Dcl_var_pre = function (me)
local var = me.var
if var.cls then
VARS = {} -- org dcls eliminate all current possible tmps
return
end
if var.pre~='var' or var.cls or var.inTop then
return -- only normal vars can be tmp
end
VARS[var] = true
var.isTmp = true
end,
Var = function (me)
local var = me.var
-- all threads vars are "tmp"
if AST.iter'Thread'() then
return
end
-- all function vars are "tmp"
if AST.iter'Dcl_fun'() then
return
end
-- only normal vars can be tmp
if var.pre~='var' or var.cls then
var.isTmp = false
return
end
--[[
-- var int i;
-- var T[2] t with
-- i = i + 1; // "i" cannot be tmp
-- end;
--]]
local constr = AST.par(me, 'Dcl_constr')
if constr and (var.blk.__depth < constr.__depth) then
local org = AST.par(me, 'Dcl_var')
if org then
local _, tp = unpack(org)
if tp.arr then
var.isTmp = false
end
end
end
local glb = ENV.clss.Global
if var.inTop or
(var.blk==ENV.clss.Main.blk_ifc and glb and glb.is_ifc and
glb.blk_ifc.vars[var.id])
then
var.isTmp = false
return -- vars in interfaces cannot be tmp
end
local dcl = AST.iter'Dcl_var'()
if dcl and dcl[1]==var.id then
return -- my declaration is not an access
end
if me.__par.tag == 'SetBlock' then
return -- set is performed on respective `return´
end
local v = VARS[var]
local op = AST.iter'Op1_&'()
local isRef = op and (op.base == me)
if AST.iter'Finally'() or -- finally executes through "call"
AST.iter'AwaitInt'() or -- await ptr:a (ptr is tested on awake)
isRef or -- reference may escape
var.tp.arr -- array may escape: TODO conservative
-- (arrays as parameters)
then
var.isTmp = false
VARS[var] = nil
return
end
-- Not tmp if defined in the same block of an org:
-- var T t;
-- var int ret = 1;
-- becomes
-- var int ret;
-- start t
-- ret = 1;
for _,oth in pairs(var.blk.vars) do
if oth.cls then
v = false
end
end
if v == true then
VARS[var] = me.ana.pre
return -- first access
end
if not (v and ANA.CMP(v,me.ana.pre)) then
var.isTmp = false -- found a Par or Await in the path
return
end
end,
EmitNoTmp = 'EmitInt',
EmitInt = function (me)
VARS = {} -- NO: run in different ceu_call
end,
Spawn_pre = function (me)
VARS = {} -- NO: start organism
end,
Loop_pre = function (me)
local awaits = false
AST.visit(
{
AwaitT = function (me)
awaits = true
end,
AwaitInt = 'AwaitT',
AwaitExt = 'AwaitT',
AwaitN = 'AwaitT',
AwaitS = 'AwaitT',
EmitInt = 'AwaitT',
Async = 'AwaitT',
Thread = 'AwaitT',
Spawn = 'AwaitT',
},
me)
if ((not awaits) and (not AST.iter(AST.pred_async)())) or
me.isAwaitUntil then
return -- OK: (tight loop outside Async) or (await ... until)
end
VARS = {} -- NO: loop in between Dcl/Accs is dangerous
--[[
-- x is on the stack but may be written in two diff reactions
-- a non-ceu code can reuse the stack in between
input int E;
var int x;
loop do
var int tmp = await E;
if tmp == 0 then
break;
end
x = tmp;
end
return x;
]]
end,
--[[
]]
ParOr_pre = function (me)
for var, v in pairs(VARS) do
if v ~= true then
VARS[var] = nil -- remove previously accessed vars
end
end
end,
ParAnd_pre = 'ParOr_pre',
ParEver_pre = 'ParOr_pre',
ParOr = 'ParOr_pre',
ParAnd = 'ParOr_pre',
ParEver = 'ParOr_pre',
-- TODO: should pre's be already different?
Async_pre = 'ParOr_pre',
Async = 'ParOr_pre',
}
AST.visit(F)
|
local VARS = {}
if not ANA then
return -- isTmp=false for all vars
end
F = {
Dcl_var_pre = function (me)
local var = me.var
if var.cls then
VARS = {} -- org dcls eliminate all current possible tmps
return
end
if var.pre~='var' or var.cls or var.inTop then
return -- only normal vars can be tmp
end
VARS[var] = true
var.isTmp = true
end,
Var = function (me)
local var = me.var
-- all threads vars are "tmp"
if AST.iter'Thread'() then
return
end
-- all function vars are "tmp"
if AST.iter'Dcl_fun'() then
return
end
-- only normal vars can be tmp
if var.pre~='var' or var.cls then
var.isTmp = false
return
end
--[[
-- var int i;
-- var T[2] t with
-- i = i + 1; // "i" cannot be tmp
-- end;
--]]
local constr = AST.par(me, 'Dcl_constr')
if constr and (var.blk.__depth < constr.__depth) then
local org = AST.par(me, 'Dcl_var')
if org then
local _, tp = unpack(org)
if tp.arr then
var.isTmp = false
end
end
end
local glb = ENV.clss.Global
if var.inTop or
(var.blk==ENV.clss.Main.blk_ifc and glb and glb.is_ifc and
glb.blk_ifc.vars[var.id])
then
var.isTmp = false
return -- vars in interfaces cannot be tmp
end
local dcl = AST.iter'Dcl_var'()
if dcl and dcl[1]==var.id then
return -- my declaration is not an access
end
if me.__par.tag == 'SetBlock' then
return -- set is performed on respective `return´
end
local v = VARS[var]
local op = AST.iter'Op1_&'()
local isRef = op and (op.base == me)
if AST.iter'Finally'() or -- finally executes through "call"
AST.iter'AwaitInt'() or -- await ptr:a (ptr is tested on awake)
isRef or -- reference may escape
var.tp.arr -- array may escape: TODO conservative
-- (arrays as parameters)
then
var.isTmp = false
VARS[var] = nil
return
end
-- Not tmp if defined in the same block of an org:
-- var T t;
-- var int ret = 1;
-- becomes
-- var int ret;
-- start t
-- ret = 1;
for _,oth in pairs(var.blk.vars) do
if oth.cls then
v = false
end
end
if v == true then
VARS[var] = me.ana.pre
return -- first access
end
if not (v and ANA.CMP(v,me.ana.pre)) then
var.isTmp = false -- found a Par or Await in the path
return
end
end,
EmitNoTmp = 'EmitInt',
EmitInt = function (me)
VARS = {} -- NO: run in different ceu_call
end,
EmitExt = function (me)
local op, ext, param = unpack(me)
local evt = ext.evt
if evt.pre == 'input' then
VARS = {}
end
end,
Spawn_pre = function (me)
VARS = {} -- NO: start organism
end,
Loop_pre = function (me)
local awaits = false
AST.visit(
{
AwaitT = function (me)
awaits = true
end,
AwaitInt = 'AwaitT',
AwaitExt = 'AwaitT',
AwaitN = 'AwaitT',
AwaitS = 'AwaitT',
EmitInt = 'AwaitT',
Async = 'AwaitT',
Thread = 'AwaitT',
Spawn = 'AwaitT',
},
me)
if ((not awaits) and (not AST.iter(AST.pred_async)())) or
me.isAwaitUntil then
return -- OK: (tight loop outside Async) or (await ... until)
end
VARS = {} -- NO: loop in between Dcl/Accs is dangerous
--[[
-- x is on the stack but may be written in two diff reactions
-- a non-ceu code can reuse the stack in between
input int E;
var int x;
loop do
var int tmp = await E;
if tmp == 0 then
break;
end
x = tmp;
end
return x;
]]
end,
--[[
]]
ParOr_pre = function (me)
for var, v in pairs(VARS) do
if v ~= true then
VARS[var] = nil -- remove previously accessed vars
end
end
end,
ParAnd_pre = 'ParOr_pre',
ParEver_pre = 'ParOr_pre',
ParOr = 'ParOr_pre',
ParAnd = 'ParOr_pre',
ParEver = 'ParOr_pre',
-- TODO: should pre's be already different?
Async_pre = 'ParOr_pre',
Async = 'ParOr_pre',
}
AST.visit(F)
|
(-) bug: tmps across emit INPUT
|
(-) bug: tmps across emit INPUT
|
Lua
|
mit
|
Johnicholas/ceu,Johnicholas/ceu
|
64addcc8418b8907ff2a5a8679d5f1e528e18372
|
frontend/ui/ui.lua
|
frontend/ui/ui.lua
|
require "ui/geometry"
require "ui/device"
require "ui/inputevent"
require "ui/widget"
require "ui/screen"
require "settings" -- for DEBUG(), TODO: put DEBUG() somewhere else
-- initialize output module, this must be initialized before Input
Screen:init()
-- initialize the input handling
Input:init()
-- there is only one instance of this
UIManager = {
-- change this to set refresh type for next refresh
-- defaults to 1 initially and will be set to 1 after each refresh
refresh_type = 1,
-- force to repaint all the widget is stack, will be reset to false
-- after each ui loop
repaint_all = false,
-- trigger a full refresh when counter reaches FULL_REFRESH_COUNT
FULL_REFRESH_COUNT = 6,
refresh_count = 0,
_running = true,
_window_stack = {},
_execution_stack = {},
_dirty = {}
}
-- register & show a widget
function UIManager:show(widget, x, y)
-- put widget on top of stack
table.insert(self._window_stack, {x = x or 0, y = y or 0, widget = widget})
-- and schedule it to be painted
self:setDirty(widget)
-- tell the widget that it is shown now
widget:handleEvent(Event:new("Show"))
end
-- unregister a widget
function UIManager:close(widget)
local dirty = false
for i = #self._window_stack, 1, -1 do
if self._window_stack[i].widget == widget then
table.remove(self._window_stack, i)
dirty = true
break
end
end
if dirty then
-- schedule remaining widgets to be painted
for i = 1, #self._window_stack do
self:setDirty(self._window_stack[i].widget)
end
end
end
-- schedule an execution task
function UIManager:schedule(time, action)
table.insert(self._execution_stack, { time = time, action = action })
end
-- schedule task in a certain amount of seconds (fractions allowed) from now
function UIManager:scheduleIn(seconds, action)
local when = { util.gettime() }
local s = math.floor(seconds)
local usecs = (seconds - s) * 1000000
when[1] = when[1] + s
when[2] = when[2] + usecs
if when[2] > 1000000 then
when[1] = when[1] + 1
when[2] = when[2] - 1000000
end
self:schedule(when, action)
end
-- register a widget to be repainted
function UIManager:setDirty(widget, refresh_type)
if not refresh_type then
refresh_type = "full"
elseif refresh_type == 0 then
refresh_type = "full"
elseif refresh_type == 1 then
refresh_type = "partial"
end
self._dirty[widget] = refresh_type
end
-- signal to quit
function UIManager:quit()
self._running = false
end
-- transmit an event to registered widgets
function UIManager:sendEvent(event)
-- top level widget has first access to the event
local consumed = self._window_stack[#self._window_stack].widget:handleEvent(event)
-- if the event is not consumed, always-active widgets can access it
for _, widget in ipairs(self._window_stack) do
if consumed then
break
end
if widget.widget.is_always_active then
consumed = widget.widget:handleEvent(event)
end
end
end
function UIManager:checkTasks()
local now = { util.gettime() }
-- check if we have timed events in our queue and search next one
local wait_until = nil
local all_tasks_checked
repeat
all_tasks_checked = true
for i = #self._execution_stack, 1, -1 do
local task = self._execution_stack[i]
if not task.time
or task.time[1] < now[1]
or task.time[1] == now[1] and task.time[2] < now[2] then
-- task is pending to be executed right now. do it.
task.action()
-- and remove from table
table.remove(self._execution_stack, i)
-- start loop again, since new tasks might be on the
-- queue now
all_tasks_checked = false
elseif not wait_until
or wait_until[1] > task.time[1]
or wait_until[1] == task.time[1] and wait_until[2] > task.time[2] then
-- task is to be run in the future _and_ is scheduled
-- earlier than the tasks we looked at already
-- so adjust to the currently examined task instead.
wait_until = task.time
end
end
until all_tasks_checked
return wait_until
end
-- this is the main loop of the UI controller
-- it is intended to manage input events and delegate
-- them to dialogs
function UIManager:run()
self._running = true
while self._running do
local now = { util.gettime() }
local wait_until = self:checkTasks()
--DEBUG("---------------------------------------------------")
--DEBUG("exec stack", self._execution_stack)
--DEBUG("window stack", self._window_stack)
--DEBUG("dirty stack", self._dirty)
--DEBUG("---------------------------------------------------")
-- stop when we have no window to show
if #self._window_stack == 0 then
DEBUG("no dialog left to show, would loop endlessly")
return nil
end
-- repaint dirty widgets
local dirty = false
local full_refresh = false
for _, widget in ipairs(self._window_stack) do
if self.repaint_all or self._dirty[widget.widget] then
widget.widget:paintTo(Screen.bb, widget.x, widget.y)
if self._dirty[widget.widget] == "full" then
full_refresh = true
end
-- and remove from list after painting
self._dirty[widget.widget] = nil
-- trigger repaint
dirty = true
end
end
self.repaint_all = false
if dirty then
if self.refresh_count == self.FULL_REFRESH_COUNT - 1 then
self.refresh_type = 0
else
self.refresh_type = 1
end
-- refresh FB
Screen:refresh(self.refresh_type) -- TODO: refresh explicitly only repainted area
-- reset refresh_type
self.refresh_type = 1
-- increase refresh_count only when full refresh is requested
self.refresh_count = (self.refresh_count + (full_refresh and 1 or 0))%self.FULL_REFRESH_COUNT
end
self:checkTasks()
-- wait for next event
-- note that we will skip that if in the meantime we have tasks that are ready to run
local input_event = nil
if not wait_until then
-- no pending task, wait endlessly
input_event = Input:waitEvent()
elseif wait_until[1] > now[1]
or wait_until[1] == now[1] and wait_until[2] > now[2] then
local wait_for = { s = wait_until[1] - now[1], us = wait_until[2] - now[2] }
if wait_for.us < 0 then
wait_for.s = wait_for.s - 1
wait_for.us = 1000000 + wait_for.us
end
-- wait until next task is pending
input_event = Input:waitEvent(wait_for.us, wait_for.s)
end
-- delegate input_event to handler
if input_event then
--DEBUG("in ui.lua:", input_event)
if input_event == "IntoSS" then
Device:intoScreenSaver()
elseif input_event == "OutOfSS" then
Device:outofScreenSaver()
elseif input_event == "Charging" then
Device:usbPlugIn()
elseif input_event == "NotCharging" then
Device:usbPlugOut()
else
self:sendEvent(input_event)
end
end
end
end
|
require "ui/geometry"
require "ui/device"
require "ui/inputevent"
require "ui/widget"
require "ui/screen"
require "settings" -- for DEBUG(), TODO: put DEBUG() somewhere else
-- initialize output module, this must be initialized before Input
Screen:init()
-- initialize the input handling
Input:init()
-- there is only one instance of this
UIManager = {
-- change this to set refresh type for next refresh
-- defaults to 1 initially and will be set to 1 after each refresh
refresh_type = 1,
-- force to repaint all the widget is stack, will be reset to false
-- after each ui loop
repaint_all = false,
-- trigger a full refresh when counter reaches FULL_REFRESH_COUNT
FULL_REFRESH_COUNT = 6,
refresh_count = 0,
_running = true,
_window_stack = {},
_execution_stack = {},
_dirty = {}
}
-- register & show a widget
function UIManager:show(widget, x, y)
-- put widget on top of stack
table.insert(self._window_stack, {x = x or 0, y = y or 0, widget = widget})
-- and schedule it to be painted
self:setDirty(widget)
-- tell the widget that it is shown now
widget:handleEvent(Event:new("Show"))
end
-- unregister a widget
function UIManager:close(widget)
local dirty = false
for i = #self._window_stack, 1, -1 do
if self._window_stack[i].widget == widget then
table.remove(self._window_stack, i)
dirty = true
break
end
end
if dirty then
-- schedule remaining widgets to be painted
for i = 1, #self._window_stack do
self:setDirty(self._window_stack[i].widget)
end
end
end
-- schedule an execution task
function UIManager:schedule(time, action)
table.insert(self._execution_stack, { time = time, action = action })
end
-- schedule task in a certain amount of seconds (fractions allowed) from now
function UIManager:scheduleIn(seconds, action)
local when = { util.gettime() }
local s = math.floor(seconds)
local usecs = (seconds - s) * 1000000
when[1] = when[1] + s
when[2] = when[2] + usecs
if when[2] > 1000000 then
when[1] = when[1] + 1
when[2] = when[2] - 1000000
end
self:schedule(when, action)
end
-- register a widget to be repainted
function UIManager:setDirty(widget, refresh_type)
if not refresh_type then
refresh_type = "full"
elseif refresh_type == 0 then
refresh_type = "full"
elseif refresh_type == 1 then
refresh_type = "partial"
end
self._dirty[widget] = refresh_type
end
-- signal to quit
function UIManager:quit()
self._running = false
end
-- transmit an event to registered widgets
function UIManager:sendEvent(event)
-- top level widget has first access to the event
local consumed = self._window_stack[#self._window_stack].widget:handleEvent(event)
-- if the event is not consumed, always-active widgets can access it
for _, widget in ipairs(self._window_stack) do
if consumed then
break
end
if widget.widget.is_always_active then
consumed = widget.widget:handleEvent(event)
end
end
end
function UIManager:checkTasks()
local now = { util.gettime() }
-- check if we have timed events in our queue and search next one
local wait_until = nil
local all_tasks_checked
repeat
all_tasks_checked = true
for i = #self._execution_stack, 1, -1 do
local task = self._execution_stack[i]
if not task.time
or task.time[1] < now[1]
or task.time[1] == now[1] and task.time[2] < now[2] then
-- task is pending to be executed right now. do it.
task.action()
-- and remove from table
table.remove(self._execution_stack, i)
-- start loop again, since new tasks might be on the
-- queue now
all_tasks_checked = false
elseif not wait_until
or wait_until[1] > task.time[1]
or wait_until[1] == task.time[1] and wait_until[2] > task.time[2] then
-- task is to be run in the future _and_ is scheduled
-- earlier than the tasks we looked at already
-- so adjust to the currently examined task instead.
wait_until = task.time
end
end
until all_tasks_checked
return wait_until
end
-- this is the main loop of the UI controller
-- it is intended to manage input events and delegate
-- them to dialogs
function UIManager:run()
self._running = true
while self._running do
local now = { util.gettime() }
local wait_until = self:checkTasks()
--DEBUG("---------------------------------------------------")
--DEBUG("exec stack", self._execution_stack)
--DEBUG("window stack", self._window_stack)
--DEBUG("dirty stack", self._dirty)
--DEBUG("---------------------------------------------------")
-- stop when we have no window to show
if #self._window_stack == 0 then
DEBUG("no dialog left to show, would loop endlessly")
return nil
end
-- repaint dirty widgets
local dirty = false
local full_refresh = false
for _, widget in ipairs(self._window_stack) do
if self.repaint_all or self._dirty[widget.widget] then
widget.widget:paintTo(Screen.bb, widget.x, widget.y)
if self._dirty[widget.widget] == "full" then
full_refresh = true
end
-- and remove from list after painting
self._dirty[widget.widget] = nil
-- trigger repaint
dirty = true
end
end
self.repaint_all = false
if dirty then
if self.refresh_count == self.FULL_REFRESH_COUNT - 1 then
self.refresh_type = 0
else
self.refresh_type = 1
end
-- refresh FB
Screen:refresh(self.refresh_type) -- TODO: refresh explicitly only repainted area
-- increase refresh_count only when full refresh is requested or performed
local refresh_increment = (full_refresh or self.refresh_type == 0) and 1 or 0
self.refresh_count = (self.refresh_count + refresh_increment)%self.FULL_REFRESH_COUNT
-- reset refresh_type
self.refresh_type = 1
end
self:checkTasks()
-- wait for next event
-- note that we will skip that if in the meantime we have tasks that are ready to run
local input_event = nil
if not wait_until then
-- no pending task, wait endlessly
input_event = Input:waitEvent()
elseif wait_until[1] > now[1]
or wait_until[1] == now[1] and wait_until[2] > now[2] then
local wait_for = { s = wait_until[1] - now[1], us = wait_until[2] - now[2] }
if wait_for.us < 0 then
wait_for.s = wait_for.s - 1
wait_for.us = 1000000 + wait_for.us
end
-- wait until next task is pending
input_event = Input:waitEvent(wait_for.us, wait_for.s)
end
-- delegate input_event to handler
if input_event then
--DEBUG("in ui.lua:", input_event)
if input_event == "IntoSS" then
Device:intoScreenSaver()
elseif input_event == "OutOfSS" then
Device:outofScreenSaver()
elseif input_event == "Charging" then
Device:usbPlugIn()
elseif input_event == "NotCharging" then
Device:usbPlugOut()
else
self:sendEvent(input_event)
end
end
end
end
|
bugfix: fix increment of refresh count If full refresh is false and refresh count is FULL_REFRESH_COUNT - 1, every refresh becomes full refresh. This patch increases refresh count when a full refresh is performed no matter whether full refresh is requested.
|
bugfix: fix increment of refresh count
If full refresh is false and refresh count is FULL_REFRESH_COUNT - 1,
every refresh becomes full refresh. This patch increases refresh count
when a full refresh is performed no matter whether full refresh is
requested.
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,poire-z/koreader,ashhher3/koreader,NiLuJe/koreader-base,Frenzie/koreader,koreader/koreader,frankyifei/koreader-base,Frenzie/koreader-base,ashang/koreader,houqp/koreader,apletnev/koreader-base,Markismus/koreader,koreader/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,pazos/koreader,koreader/koreader-base,chihyang/koreader,apletnev/koreader,houqp/koreader-base,koreader/koreader-base,mwoz123/koreader,noname007/koreader,mihailim/koreader,frankyifei/koreader,koreader/koreader,Frenzie/koreader-base,poire-z/koreader,robert00s/koreader,NiLuJe/koreader-base,NiLuJe/koreader,Frenzie/koreader,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,NickSavage/koreader,apletnev/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,NiLuJe/koreader,apletnev/koreader-base,chrox/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader,lgeek/koreader,houqp/koreader-base
|
d239e43302a1e91c467dced940825d5e62527156
|
wget.lua
|
wget.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- 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.
--
-- @endcond
--]]
-- WGet
zpm.wget = {}
zpm.wget.downloadUrl = zpm.config.wget.downloadUrl
zpm.wget.dependenciesUrl = zpm.config.wget.dependenciesUrl
function zpm.wget.downloadWget( destination )
local zipFile = path.join( zpm.temp, "wget.zip" )
if not os.isfile( zipFile ) then
print( "wget not detected - start downloading" )
http.download( zpm.wget.downloadUrl, zipFile )
else
print( "wget archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "wget-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/wget.exe" ), destination )
zpm.assert( os.isfile( path.join( zipTemp, "bin/wget.exe" ) ), "Wget is not installed!" )
print( "wget succesfully installed" )
end
function zpm.wget.downloadDependencies()
local eay32 = path.join( zpm.cache, "libeay32.dll" )
local iconv2 = path.join( zpm.cache, "libiconv2.dll" )
local intl3 = path.join( zpm.cache, "libintl3.dll" )
local ssl32 = path.join( zpm.cache, "libssl32.dll" )
local zipFile = path.join( zpm.temp, "dependencies.zip" )
if not ( os.isfile( eay32 ) and
os.isfile( iconv2 ) and
os.isfile( intl3 ) and
os.isfile( ssl32 ) ) then
print( "wget dependencies not detected - start downloading" )
http.download( zpm.wget.dependenciesUrl, zipFile )
else
print( "wget dependencies archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "dependencies-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/libeay32.dll" ), eay32 )
os.rename( path.join( zipTemp, "bin/libiconv2.dll" ), iconv2 )
os.rename( path.join( zipTemp, "bin/libintl3.dll" ), intl3 )
os.rename( path.join( zipTemp, "bin/libssl32.dll" ), ssl32 )
print( "wget dependencies succesfully installed" )
end
function zpm.wget.initialise()
local dest = path.join( zpm.cache, "wget.exe" )
if os.get() == "windows" then
if not os.isfile( dest ) then
print( "\nLoading wget..." )
zpm.wget.downloadWget( dest )
zpm.wget.downloadDependencies()
end
zpm.wget.location = dest
else
zpm.wget.location = "wget"
end
end
function zpm.wget.get( url, header )
if header == nil or not header then
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul" )
end
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
function zpm.wget.download( destination, url, header )
if header == nil or not header then
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\"" )
end
end
function zpm.wget.downloadFile( destination, url, header )
if header == nil or not header then
os.execute( zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate --header \"" .. header .. "\"" )
end
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- 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.
--
-- @endcond
--]]
-- WGet
zpm.wget = {}
zpm.wget.downloadUrl = zpm.config.wget.downloadUrl
zpm.wget.dependenciesUrl = zpm.config.wget.dependenciesUrl
function zpm.wget.downloadWget( destination )
local zipFile = path.join( zpm.temp, "wget.zip" )
if not os.isfile( zipFile ) then
print( "wget not detected - start downloading" )
http.download( zpm.wget.downloadUrl, zipFile )
else
print( "wget archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "wget-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/wget.exe" ), destination )
zpm.assert( os.isfile( destination ), "Wget is not installed!" )
print( "wget succesfully installed" )
end
function zpm.wget.downloadDependencies()
local eay32 = path.join( zpm.cache, "libeay32.dll" )
local iconv2 = path.join( zpm.cache, "libiconv2.dll" )
local intl3 = path.join( zpm.cache, "libintl3.dll" )
local ssl32 = path.join( zpm.cache, "libssl32.dll" )
local zipFile = path.join( zpm.temp, "dependencies.zip" )
if not ( os.isfile( eay32 ) and
os.isfile( iconv2 ) and
os.isfile( intl3 ) and
os.isfile( ssl32 ) ) then
print( "wget dependencies not detected - start downloading" )
http.download( zpm.wget.dependenciesUrl, zipFile )
else
print( "wget dependencies archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "dependencies-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/libeay32.dll" ), eay32 )
os.rename( path.join( zipTemp, "bin/libiconv2.dll" ), iconv2 )
os.rename( path.join( zipTemp, "bin/libintl3.dll" ), intl3 )
os.rename( path.join( zipTemp, "bin/libssl32.dll" ), ssl32 )
print( "wget dependencies succesfully installed" )
end
function zpm.wget.initialise()
local dest = path.join( zpm.cache, "wget.exe" )
if os.get() == "windows" then
if not os.isfile( dest ) then
print( "\nLoading wget..." )
zpm.wget.downloadWget( dest )
zpm.wget.downloadDependencies()
end
zpm.wget.location = dest
else
zpm.wget.location = "wget"
end
end
function zpm.wget.get( url, header )
if header == nil or not header then
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul" )
end
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
function zpm.wget.download( destination, url, header )
if header == nil or not header then
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\"" )
end
end
function zpm.wget.downloadFile( destination, url, header )
if header == nil or not header then
os.execute( zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate --header \"" .. header .. "\"" )
end
end
|
Assert fix
|
Assert fix
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
a1ec1adedc2802566ab8e493d524efeb046f5758
|
src/syntax/lua/main.lua
|
src/syntax/lua/main.lua
|
-- Generate syntax highlighting for LOVE functions
package.path = package.path .. ';../love-api/love_api.lua;love-api/?.lua'
local api = require 'love-api/love_api'
local funcstr = ''
local typestr = ''
local callbackstr = ''
print( 'syntax include @loveconf <sfile>:p:h/love-conf.vim' )
local function extractData( tab, index )
for i, v in pairs( tab ) do
if i == 'functions' or i == 'callbacks' then
if tab.name and ( tab.name or '' ):sub( 1, 1 ):match( '%l' ) then funcstr = funcstr .. tab.name .. '\\.\\%(' end
local func = false
local typ = false
local callback = false
for _, vv in pairs( v ) do
if tab.name then
if tab.name:sub( 1, 1 ):match( '%l' ) then
func = true
funcstr = funcstr .. vv.name .. '\\|'
else -- types
typ = true
typestr = typestr .. vv.name .. '\\|'
end
else
callback = true
callbackstr = callbackstr .. vv.name .. '\\|'
end
end
if func then
-- We don't want to be able to have underscores after the word
funcstr = funcstr:sub( 1, -3 ) .. '\\)\\)\\|\\%('
end
if typ then
-- We don't want to be able to have underscores after the word or highlight the . or :
typestr = typestr:sub( 1, -3 ) .. '\\)\\|\\%('
end
if callback then
-- We don't want to be able to have underscores after the word
callbackstr = callbackstr:sub( 1, -3 ) .. '\\)\\|\\%('
end
end
if type( v ) == 'table' then extractData( v ) end
end
end
extractData( api )
-- If syntax matches are too long, they are ignored
-- If each function gets individual syntax matches, it runs too slowly
-- Break each group to minimize the number of syntax matches
-- (2500 is an arbitraty limit that seems to work)
local textLimit = 2500
local function limit( text, pre, post )
while #text > 0 do
local start, stop = text:sub( 1, textLimit ):find( '.*\\%)\\|' )
local current
if start then
current = text:sub( start, stop - 2 )
text = text:sub( stop + 1 )
else
current = text .. ')'
text = ''
end
print( pre .. current .. post )
end
end
limit( '\\%(' .. funcstr:sub( 1, -7 ), 'syntax match lovefunction "\\<love\\.\\%(', '\\)\\>"' )
limit( '\\%(' .. typestr:sub( 1, -7 ), 'syntax match lovetype "[\\:\\.]\\%(', '\\)\\>"ms=s+1' )
limit( '\\%(' .. callbackstr:sub( 1, -7 ), 'syntax match lovecallback "\\<love\\.\\%(', '\\)\\>"' )
print( 'syntax region loveconfregion start="\\<love\\.conf\\>" end="\\<end\\>"me=e-3,he=e-3,re=e-3 skipwhite skipempty contains=ALL' )
print( 'execute( "highlight lovefunction " . g:lovedocs_colors )' )
print( 'execute( "highlight lovetype " . g:lovedocs_colors )' )
print( 'execute( "highlight lovecallback " . g:lovedocs_colors )' )
print( 'execute( "highlight loveconf " . g:lovedocs_colors )' )
love.event.quit()
|
-- Generate syntax highlighting for LOVE functions
package.path = package.path .. ';../love-api/love_api.lua;love-api/?.lua'
local api = require 'love-api/love_api'
local funcstr = ''
local typestr = ''
local callbackstr = ''
print( 'syntax include @loveconf <sfile>:p:h/love-conf.vim' )
local function extractData( tab, index )
for i, v in pairs( tab ) do
if i == 'functions' or i == 'callbacks' then
if tab.name and ( tab.name or '' ):sub( 1, 1 ):match( '%l' ) then funcstr = funcstr .. tab.name .. '\\.\\%(' end
local func = false
local typ = false
local callback = false
for _, vv in pairs( v ) do
if tab.name then
if tab.name:sub( 1, 1 ):match( '%l' ) then
func = true
funcstr = funcstr .. vv.name .. '\\|'
else -- types
typ = true
typestr = typestr .. vv.name .. '\\|'
end
else
callback = true
callbackstr = callbackstr .. vv.name .. '\\|'
end
end
if func then
-- We don't want to be able to have underscores after the word
funcstr = funcstr:sub( 1, -3 ) .. '\\)\\)\\|\\%('
end
if typ then
-- We don't want to be able to have underscores after the word or highlight the . or :
typestr = typestr:sub( 1, -3 ) .. '\\)\\|\\%('
end
if callback then
-- We don't want to be able to have underscores after the word
callbackstr = callbackstr:sub( 1, -3 ) .. '\\)\\|\\%('
end
end
if type( v ) == 'table' then extractData( v ) end
end
end
extractData( api )
-- If syntax matches are too long, they are ignored
-- If each function gets individual syntax matches, it runs too slowly
-- Break each group to minimize the number of syntax matches
-- (2500 is an arbitraty limit that seems to work)
local textLimit = 2500
local function limit( text, pre, post )
while #text > 0 do
local start, stop = text:sub( 1, textLimit ):find( '.*\\%)\\|' )
local current
if start then
current = text:sub( start, stop - 2 )
text = text:sub( stop + 1 )
else
current = text .. ')'
text = ''
end
print( pre .. current .. post )
end
end
limit( '\\%(' .. funcstr:sub( 1, -7 ), 'syntax match lovefunction "\\<love\\.\\%(', '\\)\\>" containedin=ALLBUT,luaString' )
limit( '\\%(' .. typestr:sub( 1, -7 ), 'syntax match lovetype "[\\:\\.]\\%(', '\\)\\>"ms=s+1 containedin=ALLBUT,luaString' )
limit( '\\%(' .. callbackstr:sub( 1, -7 ), 'syntax match lovecallback "\\<love\\.\\%(', '\\)\\>" containedin=ALLBUT,luaString' )
print( 'syntax region loveconfregion start="\\<love\\.conf\\>" end="\\<end\\>"me=e-3,he=e-3,re=e-3 skipwhite skipempty containedin=ALLBUT,luaString contains=ALL' )
print( 'execute( "highlight lovefunction " . g:lovedocs_colors )' )
print( 'execute( "highlight lovetype " . g:lovedocs_colors )' )
print( 'execute( "highlight lovecallback " . g:lovedocs_colors )' )
print( 'execute( "highlight loveconf " . g:lovedocs_colors )' )
love.event.quit()
|
Fixed #14
|
Fixed #14
|
Lua
|
mit
|
davisdude/vim-love-docs
|
1a4fd48679b746e9edab4039440c253b57a4db61
|
src/cli/config.lua
|
src/cli/config.lua
|
#!/usr/bin/env lua
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local args = require("lapp")(string.format([[
Duplicate an existing configuration for given environment.
Usage: kong config [options]
Options:
-c,--config (default %s) configuration file
-o,--output (default .) ouput
-e,--env (string) environment name
]], constants.CLI.GLOBAL_KONG_CONF))
local CONFIG_FILENAME = string.format("kong%s.yml", args.env ~= "" and "_"..args.env or "")
local config_path = cutils.get_kong_config_path(args.config)
local config_content = cutils.read_file(config_path)
local DEFAULT_ENV_VALUES = {
TEST = {
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_tests",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["listen 8000"] = "listen 8100",
["listen 8001"] = "listen 8101"
},
DEVELOPMENT = {
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_development",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["lua_code_cache on"] = "lua_code_cache off",
["daemon on"] = "daemon off"
}
}
-- Create a new default kong config for given environment
if DEFAULT_ENV_VALUES[args.env:upper()] then
-- If we know the environment we can override some of the variables
for k, v in pairs(DEFAULT_ENV_VALUES[args.env:upper()]) do
config_content = config_content:gsub(k, v)
end
end
cutils.write_to_file(cutils.path:join(args.output, CONFIG_FILENAME), config_content)
|
#!/usr/bin/env lua
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local args = require("lapp")(string.format([[
Duplicate an existing configuration for given environment.
Usage: kong config [options]
Options:
-c,--config (default %s) configuration file
-o,--output (default .) ouput
-e,--env (string) environment name
]], constants.CLI.GLOBAL_KONG_CONF))
local CONFIG_FILENAME = string.format("kong%s.yml", args.env ~= "" and "_"..args.env or "")
local config_path = cutils.get_kong_config_path(args.config)
local config_content = cutils.read_file(config_path)
local DEFAULT_ENV_VALUES = {
TEST = {
["nginx_working_dir: /usr/local/kong/"] = "nginx_working_dir: nginx_tmp",
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_tests",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["listen 8000"] = "listen 8100",
["listen 8001"] = "listen 8101"
},
DEVELOPMENT = {
["nginx_working_dir: /usr/local/kong/"] = "nginx_working_dir: nginx_tmp",
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_development",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["lua_code_cache on"] = "lua_code_cache off",
["daemon on"] = "daemon off"
}
}
-- Create a new default kong config for given environment
if DEFAULT_ENV_VALUES[args.env:upper()] then
-- If we know the environment we can override some of the variables
for k, v in pairs(DEFAULT_ENV_VALUES[args.env:upper()]) do
config_content = config_content:gsub(k, v)
end
end
cutils.write_to_file(cutils.path:join(args.output, CONFIG_FILENAME), config_content)
|
fix: TEST and DEVELOPMENT run in ./nginx_tmp
|
fix: TEST and DEVELOPMENT run in ./nginx_tmp
|
Lua
|
apache-2.0
|
Kong/kong,kyroskoh/kong,xvaara/kong,ejoncas/kong,smanolache/kong,vzaramel/kong,shiprabehera/kong,akh00/kong,kyroskoh/kong,ccyphers/kong,isdom/kong,jerizm/kong,isdom/kong,beauli/kong,rafael/kong,Kong/kong,ind9/kong,ejoncas/kong,vzaramel/kong,Vermeille/kong,rafael/kong,streamdataio/kong,ind9/kong,Kong/kong,ajayk/kong,li-wl/kong,icyxp/kong,salazar/kong,streamdataio/kong,jebenexer/kong,Mashape/kong
|
a692b9e81fcab25b8d417328d5fc7bea9da12bbf
|
src/lua-factory/sources/grl-metrolyrics.lua
|
src/lua-factory/sources/grl-metrolyrics.lua
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, "fetch_page_cb", netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, "fetch_page_cb", netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.warning ("This Lyrics do not match our parser! Please file a bug!")
return nil
end
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
metrolyrics: Do not crash when parser fails
|
metrolyrics: Do not crash when parser fails
(lt-grilo-test-ui-0.2:8463): Grilo-WARNING **: [lua-library]
grl-lua-library.c:509: calling source callback function fail
(fetch_page_cb) grl-metrolyrics.lua:99:
attempt to index a nil value (local 'feed')'
https://bugzilla.gnome.org/show_bug.cgi?id=754275
|
Lua
|
lgpl-2.1
|
grilofw/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins
|
92d4714e9a25ac011dcff2cf107a630cda5a597f
|
hostinfo/login.lua
|
hostinfo/login.lua
|
--[[
Copyright 2014 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.
--]]
local HostInfo = require('./base').HostInfo
local io = require('io')
local string = require('string')
local table = require('table')
--[[ Login ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
local obj = {}
local file = io.lines('/etc/login.defs')
local append = table.insert
obj['login.defs'] = {}
-- loop through lines in file
for line in file do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
-- find defs
if not iscomment and not isblank then
local items = {}
local i = 0
-- split and assign key/values
for item in line:gmatch("%S+") do
i = i + 1
items[i] = item;
end
local key = items[1]
local value = items[2]
-- add def
obj['login.defs'][key] = value
end
end
table.insert(self._params, obj)
callback()
end
function Info:getType()
return 'LOGIN'
end
return Info
|
--[[
Copyright 2014 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.
--]]
local HostInfo = require('./base').HostInfo
local fs = require('fs');
local string = require('string')
local table = require('table')
--[[ Login ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
local obj = {}
local filename = "/etc/login.defs"
obj['login.defs'] = {}
-- open /etc/login.defs
fs.readFile(filename, function (err, data)
if (err) then
return
end
-- split and assign key/values
for line in data:gmatch("[^\r\n]+") do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
-- find defs
if not iscomment and not isblank then
local items = {}
local i = 0
-- split and assign key/values
for item in line:gmatch("%S+") do
i = i + 1
items[i] = item;
end
local key = items[1]
local value = items[2]
-- add def
obj['login.defs'][key] = value
end
end
table.insert(self._params, obj)
callback()
end)
end
function Info:getType()
return 'LOGIN'
end
return Info
|
fix(HostInfo): login uses fs and not io
|
fix(HostInfo): login uses fs and not io
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent
|
bd8acc96e14992236541add365b8d13206b4f714
|
lunamark/writer/tex.lua
|
lunamark/writer/tex.lua
|
-- Generic TeX writer for lunamark
local gsub = string.gsub
local entities = require("lunamark.entities")
local TeX = {}
TeX.options = { containers = false }
TeX.sep = { interblock = {compact = "\n\n", default = "\n\n", minimal = "\n\n"},
container = { compact = "\n", default = "\n", minimal = "\n"}
}
TeX.interblocksep = TeX.sep.interblock.default
TeX.containersep = TeX.sep.container.default
TeX.linebreak = "\\\\"
TeX.space = " "
local escaped = {
["{"] = "\\{",
["}"] = "\\}",
["$"] = "\\$",
["%"] = "\\%",
["&"] = "\\&",
["_"] = "\\_",
["#"] = "\\#",
["^"] = "\\^{}",
["\\"] = "\\char92{}",
["~"] = "\\char126{}",
["|"] = "\\char124{}",
["<"] = "\\char60{}",
[">"] = "\\char62{}",
["["] = "{[}", -- to avoid interpretation as optional argument
["]"] = "{]}",
["\160"] = "~",
["\0x2018"] = "`",
["\0x2019"] = "'",
["\0x201C"] = "``",
["\0x201D"] = "''",
}
function TeX.string(s)
return s:gsub(".",escaped)
end
function TeX.start_document()
return ""
end
function TeX.stop_document()
return ""
end
function TeX.inline_html(s)
end
function TeX.display_html(s)
end
function TeX.paragraph(s)
return s
end
function TeX.plain(s)
return s
end
local meta = {}
meta.__index =
function(_, key)
io.stderr:write(string.format("WARNING: Undefined writer function '%s'\n",key))
return (function(...) return table.concat(arg," ") end)
end
setmetatable(TeX, meta)
return TeX
|
-- Generic TeX writer for lunamark
local gsub = string.gsub
local entities = require("lunamark.entities")
local TeX = {}
TeX.options = { containers = false }
TeX.sep = { interblock = {compact = "\n\n", default = "\n\n", minimal = "\n\n"},
container = { compact = "\n", default = "\n", minimal = "\n"}
}
TeX.interblocksep = TeX.sep.interblock.default
TeX.containersep = TeX.sep.container.default
TeX.linebreak = "\\\\"
TeX.space = " "
local escaped = {
["{"] = "\\{",
["}"] = "\\}",
["$"] = "\\$",
["%"] = "\\%",
["&"] = "\\&",
["_"] = "\\_",
["#"] = "\\#",
["^"] = "\\^{}",
["\\"] = "\\char92{}",
["~"] = "\\char126{}",
["|"] = "\\char124{}",
["<"] = "\\char60{}",
[">"] = "\\char62{}",
["["] = "{[}", -- to avoid interpretation as optional argument
["]"] = "{]}",
}
local escaped_utf8_triplet = {
["\226\128\156"] = "``",
["\226\128\157"] = "''",
["\226\128\152"] = "`",
["\226\128\153"] = "'",
["\226\128\148"] = "---",
["\226\128\147"] = "--",
}
function TeX.string(s)
return s:gsub(".",escaped):gsub("\226\128.",escaped_utf8_triplet):gsub("\194\160","~")
end
function TeX.start_document()
return ""
end
function TeX.stop_document()
return ""
end
function TeX.inline_html(s)
end
function TeX.display_html(s)
end
function TeX.paragraph(s)
return s
end
function TeX.plain(s)
return s
end
local meta = {}
meta.__index =
function(_, key)
io.stderr:write(string.format("WARNING: Undefined writer function '%s'\n",key))
return (function(...) return table.concat(arg," ") end)
end
setmetatable(TeX, meta)
return TeX
|
Fixed TeX escaping for UTF8 quotes and dashes.
|
Fixed TeX escaping for UTF8 quotes and dashes.
|
Lua
|
mit
|
tst2005/lunamark,simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,tst2005/lunamark,jgm/lunamark,jgm/lunamark,simoncozens/lunamark
|
e6993dd131272de5d88fdbed112bc89207414e09
|
battery-widget/battery.lua
|
battery-widget/battery.lua
|
-------------------------------------------------
-- Battery Widget for Awesome Window Manager
-- Shows the battery status using the ACPI tool
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/battery-widget
-- @author Pavel Makhov
-- @copyright 2017 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local naughty = require("naughty")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
local gfs = require("gears.filesystem")
local dpi = require('beautiful').xresources.apply_dpi
-- acpi sample outputs
-- Battery 0: Discharging, 75%, 01:51:38 remaining
-- Battery 0: Charging, 53%, 00:57:43 until charged
local HOME = os.getenv("HOME")
local battery_widget = {}
local function worker(args)
local args = args or {}
local font = args.font or 'Play 8'
local path_to_icons = args.path_to_icons or "/usr/share/icons/Arc/status/symbolic/"
local show_current_level = args.show_current_level or false
local margin_left = args.margin_left or 0
local margin_right = args.margin_right or 0
local display_notification = args.display_notification or false
local position = args.notification_position or "top_right"
local warning_msg_title = args.warning_msg_title or 'Huston, we have a problem'
local warning_msg_text = args.warning_msg_text or 'Battery is dying'
local warning_msg_position = args.warning_msg_position or 'bottom_right'
local warning_msg_icon = args.warning_msg_icon or HOME .. '/.config/awesome/awesome-wm-widgets/batteryarc-widget/spaceman.jpg'
if not gfs.dir_readable(path_to_icons) then
naughty.notify{
title = "Battery Widget",
text = "Folder with icons doesn't exist: " .. path_to_icons,
preset = naughty.config.presets.critical
}
end
local icon_widget = wibox.widget {
{
id = "icon",
widget = wibox.widget.imagebox,
resize = false
},
layout = wibox.container.margin(_, 0, 0, 3)
}
local level_widget = wibox.widget {
font = font,
widget = wibox.widget.textbox
}
battery_widget = wibox.widget {
icon_widget,
level_widget,
layout = wibox.layout.fixed.horizontal,
}
-- Popup with battery info
-- One way of creating a pop-up notification - naughty.notify
local notification
local function show_battery_status(batteryType)
awful.spawn.easy_async([[bash -c 'acpi']],
function(stdout, _, _, _)
naughty.destroy(notification)
notification = naughty.notify{
text = stdout,
title = "Battery status",
icon = path_to_icons .. batteryType .. ".svg",
icon_size = dpi(16),
position = position,
timeout = 5, hover_timeout = 0.5,
width = 200,
}
end
)
end
-- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one
--battery_popup = awful.tooltip({objects = {battery_widget}})
-- To use colors from beautiful theme put
-- following lines in rc.lua before require("battery"):
-- beautiful.tooltip_fg = beautiful.fg_normal
-- beautiful.tooltip_bg = beautiful.bg_normal
local function show_battery_warning()
naughty.notify {
icon = warning_msg_icon,
icon_size = 100,
text = warning_msg_text,
title = warning_msg_title,
timeout = 25, -- show the warning for a longer time
hover_timeout = 0.5,
position = warning_msg_position,
bg = "#F06060",
fg = "#EEE9EF",
width = 300,
}
end
local last_battery_check = os.time()
local batteryType = "battery-good-symbolic"
watch("acpi -i", 10,
function(widget, stdout, stderr, exitreason, exitcode)
local battery_info = {}
local capacities = {}
for s in stdout:gmatch("[^\r\n]+") do
local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*')
if string.match(s, 'rate information') then
-- ignore such line
elseif status ~= nil then
table.insert(battery_info, {status = status, charge = tonumber(charge_str)})
else
local cap_str = string.match(s, '.+:.+last full capacity (%d+)')
table.insert(capacities, tonumber(cap_str))
end
end
local capacity = 0
for i, cap in ipairs(capacities) do
capacity = capacity + cap
end
local charge = 0
local status
for i, batt in ipairs(battery_info) do
if batt.charge >= charge then
status = batt.status -- use most charged battery status
-- this is arbitrary, and maybe another metric should be used
end
charge = charge + batt.charge * capacities[i]
end
charge = charge / capacity
if show_current_level then
level_widget.text = string.format('%d%%', charge)
end
if (charge >= 0 and charge < 15) then
batteryType = "battery-empty%s-symbolic"
if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then
-- if 5 minutes have elapsed since the last warning
last_battery_check = os.time()
show_battery_warning()
end
elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic"
elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic"
elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic"
elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic"
end
if status == 'Charging' then
batteryType = string.format(batteryType, '-charging')
else
batteryType = string.format(batteryType, '')
end
widget.icon:set_image(path_to_icons .. batteryType .. ".svg")
-- Update popup text
-- battery_popup.text = string.gsub(stdout, "\n$", "")
end,
icon_widget)
if display_notification then
battery_widget:connect_signal("mouse::enter", function() show_battery_status(batteryType) end)
battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
end
return wibox.container.margin(battery_widget, margin_left, margin_right)
end
return setmetatable(battery_widget, { __call = function(_, ...) return worker(...) end })
|
-------------------------------------------------
-- Battery Widget for Awesome Window Manager
-- Shows the battery status using the ACPI tool
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/battery-widget
-- @author Pavel Makhov
-- @copyright 2017 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local naughty = require("naughty")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
local gfs = require("gears.filesystem")
local dpi = require('beautiful').xresources.apply_dpi
-- acpi sample outputs
-- Battery 0: Discharging, 75%, 01:51:38 remaining
-- Battery 0: Charging, 53%, 00:57:43 until charged
local HOME = os.getenv("HOME")
local battery_widget = {}
local function worker(args)
local args = args or {}
local font = args.font or 'Play 8'
local path_to_icons = args.path_to_icons or "/usr/share/icons/Arc/status/symbolic/"
local show_current_level = args.show_current_level or false
local margin_left = args.margin_left or 0
local margin_right = args.margin_right or 0
local display_notification = args.display_notification or false
local position = args.notification_position or "top_right"
local warning_msg_title = args.warning_msg_title or 'Huston, we have a problem'
local warning_msg_text = args.warning_msg_text or 'Battery is dying'
local warning_msg_position = args.warning_msg_position or 'bottom_right'
local warning_msg_icon = args.warning_msg_icon or HOME .. '/.config/awesome/awesome-wm-widgets/batteryarc-widget/spaceman.jpg'
if not gfs.dir_readable(path_to_icons) then
naughty.notify{
title = "Battery Widget",
text = "Folder with icons doesn't exist: " .. path_to_icons,
preset = naughty.config.presets.critical
}
end
local icon_widget = wibox.widget {
{
id = "icon",
widget = wibox.widget.imagebox,
resize = false
},
layout = wibox.container.margin(_, 0, 0, 3)
}
local level_widget = wibox.widget {
font = font,
widget = wibox.widget.textbox
}
battery_widget = wibox.widget {
icon_widget,
level_widget,
layout = wibox.layout.fixed.horizontal,
}
-- Popup with battery info
-- One way of creating a pop-up notification - naughty.notify
local notification
local function show_battery_status(batteryType)
awful.spawn.easy_async([[bash -c 'acpi']],
function(stdout, _, _, _)
naughty.destroy(notification)
notification = naughty.notify{
text = stdout,
title = "Battery status",
icon = path_to_icons .. batteryType .. ".svg",
icon_size = dpi(16),
position = position,
timeout = 5, hover_timeout = 0.5,
width = 200,
}
end
)
end
-- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one
--battery_popup = awful.tooltip({objects = {battery_widget}})
-- To use colors from beautiful theme put
-- following lines in rc.lua before require("battery"):
-- beautiful.tooltip_fg = beautiful.fg_normal
-- beautiful.tooltip_bg = beautiful.bg_normal
local function show_battery_warning()
naughty.notify {
icon = warning_msg_icon,
icon_size = 100,
text = warning_msg_text,
title = warning_msg_title,
timeout = 25, -- show the warning for a longer time
hover_timeout = 0.5,
position = warning_msg_position,
bg = "#F06060",
fg = "#EEE9EF",
width = 300,
}
end
local last_battery_check = os.time()
local batteryType = "battery-good-symbolic"
watch("acpi -i", 10,
function(widget, stdout, stderr, exitreason, exitcode)
local battery_info = {}
local capacities = {}
for s in stdout:gmatch("[^\r\n]+") do
local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?(.*)')
if status ~= nil then
table.insert(battery_info, {status = status, charge = tonumber(charge_str)})
else
local cap_str = string.match(s, '.+:.+last full capacity (%d+)')
table.insert(capacities, tonumber(cap_str))
end
end
local capacity = 0
for i, cap in ipairs(capacities) do
capacity = capacity + cap
end
local charge = 0
local status
for i, batt in ipairs(battery_info) do
if batt.charge >= charge then
status = batt.status -- use most charged battery status
-- this is arbitrary, and maybe another metric should be used
end
charge = charge + batt.charge * capacities[i]
end
charge = charge / capacity
if show_current_level then
level_widget.text = string.format('%d%%', charge)
end
if (charge >= 0 and charge < 15) then
batteryType = "battery-empty%s-symbolic"
if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then
-- if 5 minutes have elapsed since the last warning
last_battery_check = os.time()
show_battery_warning()
end
elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic"
elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic"
elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic"
elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic"
end
if status == 'Charging' then
batteryType = string.format(batteryType, '-charging')
else
batteryType = string.format(batteryType, '')
end
widget.icon:set_image(path_to_icons .. batteryType .. ".svg")
-- Update popup text
-- battery_popup.text = string.gsub(stdout, "\n$", "")
end,
icon_widget)
if display_notification then
battery_widget:connect_signal("mouse::enter", function() show_battery_status(batteryType) end)
battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
end
return wibox.container.margin(battery_widget, margin_left, margin_right)
end
return setmetatable(battery_widget, { __call = function(_, ...) return worker(...) end })
|
fix battery widget
|
fix battery widget
remove extra branch that broke acpi output with 'rate informration unavailable'
same fix as 95cc9b94 (#108) for batteryarc widget
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.