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
|
---|---|---|---|---|---|---|---|---|---|
8314eaf15bfe72f89dce9366ab2597f7a3ac8da9
|
modules/admin/config.lua
|
modules/admin/config.lua
|
--[[
modules/admin/config.lua
]]
local config = {
--nice name
name = 'Admin',
order = 7,
objects = {
},
--requests to capture
requests = {
get = {
default = { file = 'get/dashboard' },
users = { file = 'get/users' },
permissions = { file = 'get/permissions' },
groups = { file = 'get/groups' }
},
post = {
users = { file = 'post/users' },
permissions = { file = 'post/permissions' },
groups = { file = 'post/groups' }
}
},
--additional permissions
permissions = {
'AddUser',
'ViewUser',
'EditUser',
'DeleteUser',
'ViewPermission',
'EditPermission',
'AddUserGroup',
'ViewUserGroup',
'EditUserGroup',
'DeleteUserGroup',
'ViewLog'
}
}
return config
|
--[[
modules/admin/config.lua
]]
local config = {
--nice name
name = 'Admin',
order = 7,
objects = {
},
--requests to capture
requests = {
get = {
default = { file = 'get/dashboard' },
users = { file = 'get/users' },
permissions = { file = 'get/permissions' },
groups = { file = 'get/groups' },
logs = { file = 'get/logs' }
},
post = {
users = { file = 'post/users' },
permissions = { file = 'post/permissions' },
groups = { file = 'post/groups' }
}
},
--additional permissions
permissions = {
'AddUser',
'ViewUser',
'EditUser',
'DeleteUser',
'ViewPermission',
'EditPermission',
'AddUserGroup',
'ViewUserGroup',
'EditUserGroup',
'DeleteUserGroup',
'ViewLog'
}
}
return config
|
refix logs endpoint
|
refix logs endpoint
|
Lua
|
mit
|
Oxygem/Oxycore,Oxygem/Oxycore,Oxygem/Oxycore
|
1f96aba38723354f6f0b389b370096b246427ff3
|
projeto_final/hcsr04.lua
|
projeto_final/hcsr04.lua
|
trig = 7 -- D7
echo = 8 -- D8
gpio.mode(trig, gpio.OUTPUT)
gpio.mode(echo, gpio.INT)
function echocb(level, when)
print(level, when)
if level == 1 then
start = when
gpio.trig(echo, "down")
else
finish = when
end
end
function measure()
gpio.trig(echo, "up", echocb)
gpio.write(trig, gpio.HIGH)
tmr.delay(100)
gpio.write(trig, gpio.LOW)
tmr.delay(100000)
print(((finish - start)/2)/29.1 .. " cm")
end
tmr.create():alarm(10, tmr.ALARM_AUTO, measure)
|
local start = 0
local finish = 0
gpio.mode(7, gpio.OUTPUT)
gpio.mode(8, gpio.INT)
function interruptUP(level, when)
start_time = tmr.now()
print("START " .. start_time)
gpio.trig(8, "down", interruptDOWN)
end
function interruptDOWN(level, when)
finish = tmr.now()
print("FINISH " .. finish)
gpio.trig(8, "up")
print(((finish - start_time)/5800))
tmr.create():alarm(1500, tmr.ALARM_SINGLE, pulse)
end
function pulse()
gpio.trig(8, "up", interruptUP)
gpio.write(7, gpio.HIGH)
tmr.delay(10)
gpio.write(7, gpio.LOW)
tmr.alarm(0, 200, tmr.ALARM_SINGLE, interruptDOWN)
end
pulse()
|
fixup! projeto final, inicio
|
fixup! projeto final, inicio
|
Lua
|
mit
|
brunaaleixo/Sistemas-Reativos
|
695f966b80bd262e14c93eb481278897a991a54b
|
pud/level/MapNode.lua
|
pud/level/MapNode.lua
|
require 'pud.util'
local Class = require 'lib.hump.class'
local MapType = require 'pud.level.MapType'
-- MapNode
-- represents a single map position
local MapNode = Class{name='MapNode',
function(self, ...)
self._isAccessible = false
self._isLit = false
self._isTransparent = false
self._wasSeen = false
self:setMapType(...)
end
}
-- destructor
function MapNode:destroy()
self._isAccessible = nil
self._isLit = nil
self._isTransparent = nil
self._wasSeen = nil
self._mapType:destroy()
self._mapType = nil
end
-- getters and setters
function MapNode:setAccessible(b)
verify('boolean', b)
self._isAccessible = b
end
function MapNode:isAccessible() return self._isAccessible end
function MapNode:setLit(b)
verify('boolean', b)
self._isLit = b
end
function MapNode:isLit() return self._isLit end
function MapNode:setTransparent(b)
verify('boolean', b)
self._isTransparent = b
end
function MapNode:isTransparent() return self._isTransparent end
function MapNode:setSeen(b)
verify('boolean', b)
self._wasSeen = b
end
function MapNode:wasSeen() return self._wasSeen end
function MapNode:setMapType(...)
self._mapType = MapType(...)
end
function MapNode:getMapType() return self._mapType end
-- the class
return MapNode
|
require 'pud.util'
local Class = require 'lib.hump.class'
local MapType = require 'pud.level.MapType'
-- MapNode
-- represents a single map position
local MapNode = Class{name='MapNode',
function(self, ...)
self._isAccessible = false
self._isLit = false
self._isTransparent = false
self._wasSeen = false
self:setMapType(...)
end
}
-- destructor
function MapNode:destroy()
self._isAccessible = nil
self._isLit = nil
self._isTransparent = nil
self._wasSeen = nil
self._mapType:destroy()
self._mapType = nil
end
-- getters and setters
function MapNode:setAccessible(b)
verify('boolean', b)
self._isAccessible = b
end
function MapNode:isAccessible() return self._isAccessible end
function MapNode:setLit(b)
verify('boolean', b)
self._isLit = b
end
function MapNode:isLit() return self._isLit end
function MapNode:setTransparent(b)
verify('boolean', b)
self._isTransparent = b
end
function MapNode:isTransparent() return self._isTransparent end
function MapNode:setSeen(b)
verify('boolean', b)
self._wasSeen = b
end
function MapNode:wasSeen() return self._wasSeen end
function MapNode:setMapType(mapType, variation)
if mapType and mapType.is_a and mapType:is_a(MapType) then
self._mapType = mapType
else
self._mapType = MapType(mapType, variation)
end
end
function MapNode:getMapType() return self._mapType end
-- the class
return MapNode
|
fix setType() to not create a new MapType if one is passed in
|
fix setType() to not create a new MapType if one is passed in
|
Lua
|
mit
|
scottcs/wyx
|
c6813635411bc8ee6ad3908817a6c1420ea428ed
|
neovim/.config/nvim/lua/user/keymaps.lua
|
neovim/.config/nvim/lua/user/keymaps.lua
|
local opts = { noremap = true, silent = true }
local term_opts = { silent = true }
-- Shorten function name
local keymap = vim.api.nvim_set_keymap
--Remap space as leader key
keymap("", "<Space>", "<Nop>", opts)
vim.g.mapleader = " "
vim.g.maplocalleader = " "
-- Modes
-- normal_mode = "n",
-- insert_mode = "i",
-- visual_mode = "v",
-- visual_block_mode = "x",
-- term_mode = "t",
-- command_mode = "c",
-- Normal --
-- Map ; to : so instead of Shift+; just use ;
keymap("n", ";", ":", opts)
-- Better window navigation
keymap("n", "<C-h>", "<C-w>h", opts)
keymap("n", "<C-j>", "<C-w>j", opts)
keymap("n", "<C-k>", "<C-w>k", opts)
keymap("n", "<C-l>", "<C-w>l", opts)
-- Resize with arrows
keymap("n", "<C-Up>", ":resize -2<CR>", opts)
keymap("n", "<C-Down>", ":resize +2<CR>", opts)
keymap("n", "<C-Left>", ":vertical resize -2<CR>", opts)
keymap("n", "<C-Right>", ":vertical resize +2<CR>", opts)
-- Navigate buffers
keymap("n", "<S-l>", ":bnext<CR>", opts)
keymap("n", "<S-h>", ":bprevious<CR>", opts)
-- Move text up and down
keymap("n", "<A-j>", "<Esc>:m .+1<CR>==gi", opts)
keymap("n", "<A-k>", "<Esc>:m .-2<CR>==gi", opts)
-- Clear highlighting
keymap("n", "<CR>", ":nohlsearch<CR>/<BS>", opts)
-- Corrects the spelling under the cursor with first suggestion
keymap("n", "<leader-z>", "1z=", opts)
-- Insert --
-- Press jk fast to exit insert mode
keymap("i", "jk", "<ESC>", opts)
-- Make word uppercase with <C-u>
keymap("i", "<C-u>", "<Esc>mzgUiw`za", opts)
-- Visual --
-- Stay in indent mode
keymap("v", "<", "<gv", opts)
keymap("v", ">", ">gv", opts)
-- Move text up and down
keymap("v", "<A-j>", ":m .+1<CR>==", opts)
keymap("v", "<A-k>", ":m .-2<CR>==", opts)
keymap("v", "p", '"_dP', opts)
-- Visual Block --
-- Move text up and down
keymap("x", "J", ":move '>+1<CR>gv-gv", opts)
keymap("x", "K", ":move '<-2<CR>gv-gv", opts)
keymap("x", "<A-j>", ":move '>+1<CR>gv-gv", opts)
keymap("x", "<A-k>", ":move '<-2<CR>gv-gv", opts)
|
local opts = { noremap = true, silent = true }
local term_opts = { silent = true }
-- Shorten function name
local keymap = vim.api.nvim_set_keymap
--Remap space as leader key
keymap("", "<Space>", "<Nop>", opts)
vim.g.mapleader = " "
vim.g.maplocalleader = " "
-- Modes
-- normal_mode = "n",
-- insert_mode = "i",
-- visual_mode = "v",
-- visual_block_mode = "x",
-- term_mode = "t",
-- command_mode = "c",
-- Normal --
-- Map ; to : so instead of Shift+; just use ;
keymap("n", ";", ":", opts)
-- Better window navigation
keymap("n", "<C-h>", "<C-w>h", opts)
keymap("n", "<C-j>", "<C-w>j", opts)
keymap("n", "<C-k>", "<C-w>k", opts)
keymap("n", "<C-l>", "<C-w>l", opts)
-- Resize with arrows
keymap("n", "<C-Up>", ":resize -2<CR>", opts)
keymap("n", "<C-Down>", ":resize +2<CR>", opts)
keymap("n", "<C-Left>", ":vertical resize -2<CR>", opts)
keymap("n", "<C-Right>", ":vertical resize +2<CR>", opts)
-- Navigate buffers
keymap("n", "<S-l>", ":bnext<CR>", opts)
keymap("n", "<S-h>", ":bprevious<CR>", opts)
-- Move text up and down
keymap("n", "<A-j>", "<Esc>:m .+1<CR>==gi", opts)
keymap("n", "<A-k>", "<Esc>:m .-2<CR>==gi", opts)
-- Clear highlighting
keymap("n", "<CR>", ":nohlsearch<CR>/<BS>", opts)
-- Corrects the spelling under the cursor with first suggestion
keymap("n", "<S-z>", "1z=", {silent = true}) -- FIXME Does not work
-- Insert --
-- Press jk fast to exit insert mode
keymap("i", "jk", "<ESC>", opts)
-- Make word uppercase with <C-u>
keymap("i", "<C-u>", "<Esc>mzgUiw`za", opts)
-- Visual --
-- Stay in indent mode
keymap("v", "<", "<gv", opts)
keymap("v", ">", ">gv", opts)
-- Move text up and down
keymap("v", "<A-j>", ":m .+1<CR>==", opts)
keymap("v", "<A-k>", ":m .-2<CR>==", opts)
-- Put in visual mode
keymap("v", "p", '"_dP', opts)
-- Visual Block --
-- Move text up and down
keymap("x", "J", ":move '>+1<CR>gv-gv", opts)
keymap("x", "K", ":move '<-2<CR>gv-gv", opts)
keymap("x", "<A-j>", ":move '>+1<CR>gv-gv", opts)
keymap("x", "<A-k>", ":move '<-2<CR>gv-gv", opts)
|
Nvim/lua - fix keymaps
|
Nvim/lua - fix keymaps
|
Lua
|
unlicense
|
nexusstar/dotfiles
|
72a23645a82866840fc34db67800c8c1d406b0b2
|
profiles/lib/measure.lua
|
profiles/lib/measure.lua
|
local Sequence = require('lib/sequence')
Measure = {}
-- measurements conversion constants
local inch_to_meters = 0.0254
local feet_to_inches = 12
--- Parse string as a height in meters.
--- according to http://wiki.openstreetmap.org/wiki/Key:maxheight
function Measure.parse_value_meters(value)
local n = tonumber(value:gsub(",", "."):match("%d+%.?%d*"))
if n then
inches = value:match("'.*")
if inches then -- Imperial unit to metric
-- try to parse feets/inch
n = n * feet_to_inches
local m = tonumber(inches:match("%d+"))
if m then
n = n + m
end
n = n * inch_to_meters
end
return n
end
print("Can't parse value: ", value)
end
--- according to http://wiki.openstreetmap.org/wiki/Map_Features/Units#Explicit_specifications
local tonns_parse_patterns = Sequence {
"%d+",
"%d+.%d+",
"%d+.%d+ ?t"
}
local kg_parse_patterns = Sequence {
"%d+ ?kg"
}
--- Parse weight value in kilograms
function Measure.parse_value_kilograms(value)
-- try to parse kilograms
for i, templ in ipairs(kg_parse_patterns) do
m = string.match(value, templ)
if m then
return tonumber(m)
end
end
-- try to parse tonns
for i, templ in ipairs(tonns_parse_patterns) do
m = string.match(value, templ)
if m then
return tonumber(m) * 1000
end
end
--
print("Can't parse value: ", value)
return
end
--- Get maxheight of specified way in meters. If there are no
--- max height, then return nil
function Measure.get_max_height(raw_value)
if raw_value then
return Measure.parse_value_meters(raw_value)
end
end
--- Get maxwidth of specified way in meters.
function Measure.get_max_width(raw_value)
if raw_value then
return Measure.parse_value_meters(raw_value)
end
end
--- Get maxweight of specified way in kilogramms
function Measure.get_max_weight(raw_value)
if raw_value then
return Measure.parse_value_kilograms(raw_value)
end
end
return Measure;
|
local Sequence = require('lib/sequence')
Measure = {}
-- measurements conversion constants
local inch_to_meters = 0.0254
local feet_to_inches = 12
--- Parse string as a height in meters.
--- according to http://wiki.openstreetmap.org/wiki/Key:maxheight
function Measure.parse_value_meters(value)
local n = tonumber(value:gsub(",", "."):match("%d+%.?%d*"))
if n then
inches = value:match("'.*")
if inches then -- Imperial unit to metric
-- try to parse feets/inch
n = n * feet_to_inches
local m = tonumber(inches:match("%d+"))
if m then
n = n + m
end
n = n * inch_to_meters
end
return n
end
end
--- according to http://wiki.openstreetmap.org/wiki/Map_Features/Units#Explicit_specifications
local tonns_parse_patterns = Sequence {
"%d+",
"%d+.%d+",
"%d+.%d+ ?t"
}
local kg_parse_patterns = Sequence {
"%d+ ?kg"
}
--- Parse weight value in kilograms
function Measure.parse_value_kilograms(value)
-- try to parse kilograms
for i, templ in ipairs(kg_parse_patterns) do
m = string.match(value, templ)
if m then
return tonumber(m)
end
end
-- try to parse tonns
for i, templ in ipairs(tonns_parse_patterns) do
m = string.match(value, templ)
if m then
return tonumber(m) * 1000
end
end
end
--- Get maxheight of specified way in meters. If there are no
--- max height, then return nil
function Measure.get_max_height(raw_value)
if raw_value then
return Measure.parse_value_meters(raw_value)
end
end
--- Get maxwidth of specified way in meters.
function Measure.get_max_width(raw_value)
if raw_value then
return Measure.parse_value_meters(raw_value)
end
end
--- Get maxweight of specified way in kilogramms
function Measure.get_max_weight(raw_value)
if raw_value then
return Measure.parse_value_kilograms(raw_value)
end
end
return Measure;
|
Remove "can't parse value" log messages (#4810)
|
Remove "can't parse value" log messages (#4810)
* remove log output of measure.lua
* remove unneccessary return
* quick fix of #4794
|
Lua
|
bsd-2-clause
|
felixguendling/osrm-backend,frodrigo/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,oxidase/osrm-backend,felixguendling/osrm-backend,felixguendling/osrm-backend,bjtaylor1/osrm-backend,oxidase/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,oxidase/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend
|
d6e0e80b8c3827b7daa6bb96117d80413ddbcbb6
|
test/test.lua
|
test/test.lua
|
scanning = true
pcall(require, "luacov")
print("------------------------------------")
print("Lua version: " .. (jit and jit.version or _VERSION))
print("------------------------------------")
print("")
local HAS_RUNNER = not not lunit
local lunit = require "lunit"
local TEST_CASE = lunit.TEST_CASE
local ci18n = require 'cocos-i18n'
local function pcall_m(...)
local arg = {...};
return pcall(arg[1][arg[2]], arg[1], select(3, ...));
end
local function pget(tab, key) -- protected get
return pcall(function() return tab[key] end)
end
do -- Base test
local s, obj = pcall(ci18n)
if not s or not obj then
error('Constructor failure: '..tostring(obj))
end
assert(pcall_m(obj, 'cleanup'))
end
local _ENV = TEST_CASE "converter"
local typemap = ci18n.typemap
local answer = i18n.langMap['ru-ru']
function test_numbers() -- Test LangType from cocos
assert_equal(answer, typemap[6])
end
function test_strings() -- Test string notation
assert_equal(answer, typemap['ru-ru'])
assert_equal(answer, typemap['ru_ru'])
end
function test_english() -- Test everything, that mean english (nil in `langt`)
assert_equal(nil, typemap['en-en'])
assert_equal(nil, typemap['en_en'])
assert_equal(nil, typemap['nil'])
assert_equal(nil, typemap[''])
assert_equal(nil, typemap[nil])
assert_equal(nil, typemap[0])
end
function test_langt() -- Test raw accepting
assert_equal(answer, typemap[answer])
end
function test_failure()
assert_false(pget(typemap, {}))
assert_false(pget(typemap, -1))
assert_false(pget(typemap, 100500)) -- Стопицот!
assert_false(pget(typemap, ''))
assert_false(pget(typemap, 'ujygfj'))
assert_false(pget(typemap, 'retretgtf-jhncfy'))
end
local _ENV = TEST_CASE "default"
local obj
function setup()
obj = ci18n(i18n.D_DEFAULT, 'locale')
end
function teardown()
assert_true(pcall_m(obj, 'cleanup'))
end
function test_base_filemap()
end
if not HAS_RUNNER then lunit.run() end
|
scanning = true
pcall(require, "luacov")
print("------------------------------------")
print("Lua version: " .. (jit and jit.version or _VERSION))
print("------------------------------------")
print("")
local HAS_RUNNER = not not lunit
local lunit = require "lunit"
local TEST_CASE = lunit.TEST_CASE
local ci18n = require 'cocos-i18n'
local function pcall_m(...)
local arg = {...};
return pcall(arg[1][arg[2]], arg[1], select(3, ...));
end
local function pget(tab, key) -- protected get
return pcall(function() return tab[key] end)
end
do -- Base test
local s, obj = pcall(ci18n)
if not s or not obj then
error('Constructor failure: '..tostring(obj))
end
assert(pcall_m(obj, 'cleanup'))
end
local _ENV = TEST_CASE "converter"
local typemap = ci18n.typemap
local answer = i18n.langMap['ru-ru']
function test_numbers() -- Test LangType from cocos
assert_equal(answer, typemap[6])
end
function test_strings() -- Test string notation
assert_equal(answer, typemap['ru-ru'])
assert_equal(answer, typemap['ru_ru'])
end
function test_english() -- Test everything, that mean english (nil in `langt`)
assert_equal(nil, typemap['en-en'])
assert_equal(nil, typemap['en_en'])
assert_equal(nil, typemap['nil'])
assert_equal(nil, typemap[''])
assert_equal(nil, typemap[nil])
assert_equal(nil, typemap[0])
end
function test_langt() -- Test raw accepting
assert_equal(answer, typemap[answer])
end
function test_failure()
assert_false(pget(typemap, {}))
assert_false(pget(typemap, -1))
assert_false(pget(typemap, 100500)) -- Стопицот!
assert_false(pget(typemap, 'ujygfj'))
assert_false(pget(typemap, 'retretgtf-jhncfy'))
end
local _ENV = TEST_CASE "default"
local obj
function setup()
obj = ci18n(i18n.D_DEFAULT, 'locale')
end
function teardown()
assert_true(pcall_m(obj, 'cleanup'))
end
function test_base_filemap()
end
if not HAS_RUNNER then lunit.run() end
|
Test fixed
|
Test fixed
|
Lua
|
mit
|
v1993/cocos2d-x-lua-i18n
|
02cafb772341394c9c9836391af8aeb4affd5fc7
|
lua-project/src/convert-creator-build.lua
|
lua-project/src/convert-creator-build.lua
|
require "cocos.framework.init"
cc.DEBUG = cc.DEBUG_VERBOSE
cc.DEBUG_DISABLE_DUMP_TRACEBACK = true
local args = {...}
local function help()
print [[
Convert Cocos Creator web-mobile build to Lua project.
syntax:
lua convert-creator-build.lua <BUILD_PATH>
example:
lua convert-creator-build.lua ../../creator-project/build/web-mobile
]]
end
if #args < 1 then
help()
os.exit(1)
end
local inputDir = args[1]
local last = string.sub(inputDir, -1)
if last == "/" or last == "\\" then
inputDir = string.sub(inputDir, 1, -2)
end
local Reader = require "creator.Reader"
local config = {inputDir = inputDir}
local reader = Reader.new(config)
local vars = reader:loadJSON()
if not vars then
print("")
help()
os.exit(1)
end
--
local _mkdir, _copyfile, _fixpath
local _HOME = os.getenv("HOME")
if _HOME and string.sub(_HOME, 1, 1) == "/" then
-- mac
_fixpath = function(path)
return string.gsub(path, "\\", "/")
end
_mkdir = function(dir)
local command = string.format("if [ ! -d %s ]; then mkdir -p %s; fi", dir, dir)
local ok, status, code = os.execute(command)
if not ok or status ~= "exit" or code ~= 0 then
cc.printf("[ERR] Create directory %s failed", dir)
os.exit(1)
end
end
_copyfile = function(src, dst)
local pi = io.pathinfo(dst)
_mkdir(pi.dirname)
local command = string.format("cp %s %s", src, dst)
local ok, status, code = os.execute(command)
if not ok or status ~= "exit" or code ~= 0 then
cc.printf("[ERR] Copy file %s to %s failed", src, dst)
os.exit(1)
end
cc.printf("[OK] Copy file %s", dst)
end
else
-- windows
_fixpath = function(path)
return string.gsub(path, "/", "\\")
end
_mkdir = function(dir)
dir = _fixpath(dir)
local command = string.format("IF NOT EXIST \"%s\" MKDIR \"%s\"", dir, dir)
local code = os.execute(command)
if code ~= 0 then
cc.printf("[ERR] Create directory %s failed", dir)
os.exit(1)
end
end
_copyfile = function(src, dst)
src = _fixpath(src)
dst = _fixpath(dst)
local pi = io.pathinfo(dst)
_mkdir(pi.dirname)
local command = string.format("COPY /Y /B %s %s > NUL", src, dst)
local code = os.execute(command)
if code ~= 0 then
cc.printf("[ERR] Copy file %s to %s failed", src, dst)
os.exit(1)
end
cc.printf("[OK] Copy file %s", dst)
end
end
local destDir = args[2] or ".."
if string.sub(destDir, -1) == "/" or string.sub(destDir, -1) == "\\" then
destDir = string.sub(destDir, 1, -2)
end
for _, file in pairs(vars.files) do
local src = inputDir .. "/res/" .. file
local dst = destDir .. "/res/" .. file
_copyfile(src, dst)
end
local function _validateLuaFile(filename)
local ok, err = loadfile(filename)
if not ok then
cc.printf("Valid file %s failed", filename)
os.exit(1)
end
return true
end
local function _dumpToLuaFile(filename, varname, var)
local lines = cc.dumpval(var, string.format("local %s =", varname), "", true)
table.insert(lines, 1, "")
lines[#lines + 1] = ""
lines[#lines + 1] = string.format("return %s", varname)
lines[#lines + 1] = ""
local contents = table.concat(lines, "\n")
filename = _fixpath(filename)
io.writefile(filename, contents)
_validateLuaFile(filename)
cc.printf("[OK] write file %s", filename)
end
_mkdir(destDir .. "/src/assets")
_dumpToLuaFile(destDir .. "/src/assets/scenes.lua", "scenes", vars.scenes)
_dumpToLuaFile(destDir .. "/src/assets/assets.lua", "assets", vars.assets)
_dumpToLuaFile(destDir .. "/src/assets/files.lua", "files", vars.files)
_dumpToLuaFile(destDir .. "/src/assets/prefabs.lua", "prefabs", vars.prefabs)
print("done.")
print("")
|
require "cocos.framework.init"
cc.DEBUG = cc.DEBUG_VERBOSE
cc.DEBUG_DISABLE_DUMP_TRACEBACK = true
local args = {...}
local function help()
print [[
Convert Cocos Creator web-mobile build to Lua project.
syntax:
lua convert-creator-build.lua <BUILD_PATH>
example:
lua convert-creator-build.lua ../../creator-project/build/web-mobile
]]
end
if #args < 1 then
help()
os.exit(1)
end
local inputDir = args[1]
local last = string.sub(inputDir, -1)
if last == "/" or last == "\\" then
inputDir = string.sub(inputDir, 1, -2)
end
local Reader = require "creator.Reader"
local config = {inputDir = inputDir}
local reader = Reader.new(config)
local vars = reader:loadJSON()
if not vars then
print("")
help()
os.exit(1)
end
--
local _mkdir, _copyfile, _fixpath
local _osexecute
if string.sub(_VERSION, 5) > "5.1" then
-- 5.2+
_osexecute = function(cmd)
local ok, status, code = os.execute(cmd)
if not ok or status ~= "exit" or code ~= 0 then
cc.printf("[CMD FAILED] %s, %s, exit code = %s", cmd, status, tostring(code))
return false
end
return true
end
else
-- 5.1
_osexecute = function(cmd)
local code = os.execute(cmd)
if code ~= 0 then
cc.printf("[CMD FAILED] %s, exit code = %s", cmd, tostring(code))
return false
end
return true
end
end
local _HOME = os.getenv("HOME")
if _HOME and string.sub(_HOME, 1, 1) == "/" then
-- mac
_fixpath = function(path)
return string.gsub(path, "\\", "/")
end
_mkdir = function(dir)
local command = string.format("if [ ! -d %s ]; then mkdir -p %s; fi", dir, dir)
if not _osexecute(command) then
cc.printf("[ERR] Create directory %s failed", dir)
os.exit(1)
end
end
_copyfile = function(src, dst)
local pi = io.pathinfo(dst)
_mkdir(pi.dirname)
local command = string.format("cp %s %s", src, dst)
if not _osexecute(command) then
cc.printf("[ERR] Copy file %s to %s failed", src, dst)
os.exit(1)
end
cc.printf("[OK] Copy file %s", dst)
end
else
-- windows
_fixpath = function(path)
return string.gsub(path, "/", "\\")
end
_mkdir = function(dir)
dir = _fixpath(dir)
local command = string.format("IF NOT EXIST \"%s\" MKDIR \"%s\"", dir, dir)
if not _osexecute(command) then
cc.printf("[ERR] Create directory %s failed", dir)
os.exit(1)
end
end
_copyfile = function(src, dst)
src = _fixpath(src)
dst = _fixpath(dst)
local pi = io.pathinfo(dst)
_mkdir(pi.dirname)
local command = string.format("COPY /Y /B %s %s > NUL", src, dst)
if not _osexecute(command) then
cc.printf("[ERR] Copy file %s to %s failed", src, dst)
os.exit(1)
end
cc.printf("[OK] Copy file %s", dst)
end
end
local destDir = args[2] or ".."
if string.sub(destDir, -1) == "/" or string.sub(destDir, -1) == "\\" then
destDir = string.sub(destDir, 1, -2)
end
for _, file in pairs(vars.files) do
local src = inputDir .. "/res/" .. file
local dst = destDir .. "/res/" .. file
_copyfile(src, dst)
end
local function _validateLuaFile(filename)
local ok, err = loadfile(filename)
if not ok then
cc.printf("Valid file %s failed", filename)
os.exit(1)
end
return true
end
local function _dumpToLuaFile(filename, varname, var)
local lines = cc.dumpval(var, string.format("local %s =", varname), "", true)
table.insert(lines, 1, "")
lines[#lines + 1] = ""
lines[#lines + 1] = string.format("return %s", varname)
lines[#lines + 1] = ""
local contents = table.concat(lines, "\n")
filename = _fixpath(filename)
io.writefile(filename, contents)
_validateLuaFile(filename)
cc.printf("[OK] write file %s", filename)
end
_mkdir(destDir .. "/src/assets")
_dumpToLuaFile(destDir .. "/src/assets/scenes.lua", "scenes", vars.scenes)
_dumpToLuaFile(destDir .. "/src/assets/assets.lua", "assets", vars.assets)
_dumpToLuaFile(destDir .. "/src/assets/files.lua", "files", vars.files)
_dumpToLuaFile(destDir .. "/src/assets/prefabs.lua", "prefabs", vars.prefabs)
print("done.")
print("")
|
fix Lua 5.1 and 5.2+ support
|
fix Lua 5.1 and 5.2+ support
|
Lua
|
mit
|
dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua
|
0c1097fc1e60a5f64461f6883522abd983890db0
|
src/remy/nginx.lua
|
src/remy/nginx.lua
|
-- Remy - Nginx compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return ngx.decode_base64(...) end,
base64_encode = function(_,...) return ngx.encode_base64(...) end,
escape = function(_,...) return ngx.escape_uri(...) end,
unescape = function(_,...) return ngx.unescape_uri(...) end,
md5 = function(_,...) return ngx.md5(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return ngx.req.get_uri_args(), {} end,
parsebody = function(_) return ngx.req.get_post_args(), {} end,
requestbody = function(_,...) return ngx.req.get_body_data() end,
-- REQUEST RESPONSE FUNCTIONS
puts = function(_,...) ngx.print(...) end,
write = function(_,...) ngx.print(...) end
}
local M = {
mode = "nginx",
request = request
}
function M.init()
local r = request
local filename = ngx.var.request_filename
local uri = ngx.var.uri
apache2.version = M.mode.."/"..ngx.var.nginx_version
r = remy.loadrequestrec(r)
r.headers_out = ngx.resp.get_headers()
r.headers_in = ngx.req.get_headers()
local auth = ngx.decode_base64((r.headers_in["Authorization"] or ""):sub(7))
local _,_,user,pass = auth:find("([^:]+)%:([^:]+)")
r.started = ngx.req.start_time
r.method = ngx.var.request_method
r.args = remy.splitstring(ngx.var.request_uri,'?')
r.banner = M.mode.."/"..ngx.var.nginx_version
r.basic_auth_pw = pass
r.canonical_filename = filename
r.context_document_root = ngx.var.document_root
r.document_root = r.context_document_root
r.filename = filename
r.hostname = ngx.var.hostname
r.port = ngx.var.server_port
r.protocol = ngx.var.server_protocol
r.range = r.headers_in["Range"]
r.server_name = r.hostname
r.the_request = r.method.." "..ngx.var.request_uri.." "..r.protocol
r.unparsed_uri = uri
r.uri = uri
r.user = user
r.useragent_ip = ngx.var.remote_addr
end
function M.contentheader(content_type)
request.content_type = content_type
ngx.header.content_type = content_type
end
function M.finish(code)
if request.content_type ~= nil then
ngx.header.content_type = request.content_type
end
-- TODO: translate request_rec's exit code and call ngx.exit(code)
end
return M
|
-- Remy - Nginx compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return ngx.decode_base64(...) end,
base64_encode = function(_,...) return ngx.encode_base64(...) end,
escape = function(_,...) return ngx.escape_uri(...) end,
unescape = function(_,...) return ngx.unescape_uri(...) end,
md5 = function(_,...) return ngx.md5(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return ngx.req.get_uri_args(), {} end,
parsebody = function(_) return ngx.req.get_post_args(), {} end,
requestbody = function(_,...) return ngx.req.get_body_data() end,
-- REQUEST RESPONSE FUNCTIONS
puts = function(_,...) ngx.print(...) end,
write = function(_,...) ngx.print(...) end
}
local M = {
mode = "nginx",
request = request
}
function M.init()
local r = request
local filename = ngx.var.request_filename
local uri = ngx.var.uri
apache2.version = M.mode.."/"..ngx.var.nginx_version
r = remy.loadrequestrec(r)
r.headers_out = ngx.resp.get_headers()
r.headers_in = ngx.req.get_headers()
local auth = ngx.decode_base64((r.headers_in["Authorization"] or ""):sub(7))
local _,_,user,pass = auth:find("([^:]+)%:([^:]+)")
r.started = ngx.req.start_time
r.method = ngx.var.request_method
r.args = remy.splitstring(ngx.var.request_uri,'?')
r.banner = M.mode.."/"..ngx.var.nginx_version
r.basic_auth_pw = pass
r.canonical_filename = filename
r.context_document_root = ngx.var.document_root
r.document_root = r.context_document_root
r.filename = filename
r.hostname = ngx.var.hostname
r.port = ngx.var.server_port
r.protocol = ngx.var.server_protocol
r.range = r.headers_in["Range"]
r.server_name = r.hostname
r.the_request = r.method.." "..ngx.var.request_uri.." "..r.protocol
r.unparsed_uri = uri
r.uri = uri
r.user = user
r.useragent_ip = ngx.var.remote_addr
end
function M.contentheader(content_type)
request.content_type = content_type
ngx.header.content_type = content_type
end
function M.finish(code)
if request.content_type ~= nil and ngx.header.content_type == nil then
ngx.header.content_type = request.content_type
end
-- TODO: translate request_rec's exit code and call ngx.exit(code)
end
return M
|
Fixes #41 (error when trying to reset ngx_lua header)
|
Fixes #41 (error when trying to reset ngx_lua header)
|
Lua
|
mit
|
sailorproject/sailor,Etiene/sailor,felipedaragon/sailor,felipedaragon/sailor,ignacio/sailor,noname007/sailor,jeary/sailor,mpeterv/sailor,mpeterv/sailor,ignacio/sailor,Etiene/sailor
|
54da93216e8e5cef5c3dbeeb91bcf1606aae3ae3
|
lualib/sys/socketdispatch.lua
|
lualib/sys/socketdispatch.lua
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
tbl:close()
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
socket = false,
status = CLOSE,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if (self.status == CLOSE) then
return
end
assert(self.sock >= 0)
socket.close(self.sock)
self.sock = false
self.dispatchco = false
self.status = CLOSE;
wakeup_all(self, false, "disconnected")
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while true do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = core.pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
return
end
else
local co = core.running()
self.dispatchco = co
core.wait(co)
end
end
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.dispatchco then --the first request
local co = self.dispatchco
self.dispatchco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true;
end
if status == FINAL then
return false, "already closed"
end
local res
if status == CLOSE then
local err
self.status = CONNECTING;
self.sock = socket.connect(self.addr)
if not self.sock then
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
else
res = true
self.status = CONNECTED;
end
if res then
assert(self.dispatchco == false)
core.fork(dispatch_response(self))
local auth = self.auth
if auth then
local ok, msg
ok, res, msg = core.pcall(auth, self)
if not ok then
err = res
res = err
doclose(self)
elseif not res then
err = msg
doclose(self)
end
end
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the socketfifo coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, ...)
return func(self.sock, ...)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
tbl:close()
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
sock = false,
status = CLOSE,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if (self.status == CLOSE) then
return
end
assert(self.sock >= 0)
socket.close(self.sock)
self.sock = false
self.dispatchco = false
self.status = CLOSE;
wakeup_all(self, false, "disconnected")
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local pcall = core.pcall
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while true do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
return
end
else
local co = core.running()
self.dispatchco = co
core.wait(co)
end
end
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.dispatchco then --the first request
local co = self.dispatchco
self.dispatchco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true;
end
if status == FINAL then
return false, "already closed"
end
local res
if status == CLOSE then
local err
self.status = CONNECTING;
self.sock = socket.connect(self.addr)
if not self.sock then
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
else
res = true
self.status = CONNECTED;
end
if res then
assert(self.dispatchco == false)
core.fork(dispatch_response(self))
local auth = self.auth
if auth then
local ok, msg
ok, res, msg = core.pcall(auth, self)
if not ok then
err = res
res = err
doclose(self)
elseif not res then
err = msg
doclose(self)
end
end
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the socketfifo coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, p)
return func(self.sock, p)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
fix typo
|
fix typo
|
Lua
|
mit
|
findstr/silly
|
cc93050019ed4e8b92bd2f8f05d3d96269cc7535
|
src/parser.lua
|
src/parser.lua
|
local lpeg = require "lpeg"
local type = type
local tonumber = tonumber
local match = lpeg.match
lpeg.locale(lpeg)
lpeg.setmaxstack(10000)
local R, S, V, P, C, Ct, Cp, Cg, Cb, Cc, Cf =
lpeg.R, lpeg.S, lpeg.V, lpeg.P, lpeg.C, lpeg.Ct,
lpeg.Cp, lpeg.Cg, lpeg.Cb, lpeg.Cc, lpeg.Cf
local Break = P"\r"^-1 * P"\n"
local Comment = P"#" * (1 - P"\n")^0
local White = S" \t\r\n"
local Space = (White + Comment)^0
local Alpha = lpeg.alpha
local AlphaNum = R("az", "AZ", "09", "__")
local mark = function(name)
return function(...)
return {
name,
...
}
end
end
local remark = function(name)
return function(cap)
cap[1] = name
return cap
end
end
local pos = function(patt)
return (Cp() * patt) / function(pos, value)
if type(value) == "table" then
value[-1] = pos
end
return value
end
end
local keyword = function(chars)
return Space * chars * -AlphaNum
end
local sym = function(chars)
return Space * chars
end
local op = function(chars)
return Space * C(chars)
end
local function binaryOp(lhs, op, rhs)
if not op then
return lhs
end
return { op, lhs, rhs }
end
local function sepBy(patt, sep)
return patt * Cg(sep * patt)^0
end
local function chainOp(patt, sep)
return Cf(sepBy(patt, sep), binaryOp)
end
local function chain(patt, sep)
return patt * (sep * patt)^0
end
local Keywords = P"if" + P"else" + P"end" + P"def" + P"while" +
P"return" + P"break" + P"continue"
local Id = Space * (C((Alpha + P"_") * AlphaNum^0) - Keywords)
local Num = Space * (P"-"^-1 * (R"09"^1 * P".")^-1 * R"09"^1 / tonumber) / mark("number")
local String = Space * (P'"' * C(((P"\\" * P(1)) + (P(1) - P'"'))^0) * P'"' +
P"'" * C(((P"\\" * P(1)) + (P(1) - P"'"))^0) * P"'")
/ mark("string")
local CompOp = op(S"><!=" * P"="^-1)
local AddOp = op(S"+-%")
local MulOp = op(S"*/")
local program = P({
"Program",
Program = V"Block" + Ct"",
Block = Ct(V"Stat"^0),
Stat = V"Def" + V"Assign" + V"LocalAssign" + V"Return"
+ V"Call" + V"If" + V"While",
Assign = Id * sym("=") * V"Expr" / mark("assign"),
LocalAssign = keyword("local") * V"Assign" / remark("local"),
Return = keyword("return") * (V"Expr" + Cc(nil)) / mark("return"),
CompExpr = V"Expr" * CompOp * V"Expr" / binaryOp,
Cond = V"CompExpr" + sym("(") * V"CompExpr" * sym(")") + V"Expr",
Expr = V"AddExpr",
AddExpr = chainOp(V"MulExpr", AddOp),
MulExpr = chainOp(V"Value", MulOp),
Ref = Id / mark("ref"),
Value = Num + String + V"Call" + V"Ref" + sym("(") * V"Expr" * sym(")"),
ParsList = Ct(chain(Id, sym(","))^0),
Pars = sym("(") * V"ParsList" * sym(")"),
Def = keyword("def") * Id * V"Pars" * V"Block" * keyword("end") / mark("def"),
ArgsList = Ct(chain(V"Expr", sym(","))^0),
Args = sym("(") * V"ArgsList" * sym(")"),
Call = Id * V"Args" / mark("call"),
IfElse = keyword("else") * V"Block" / mark("else"),
If = keyword("if") * V"Cond" * V"Block" * V"IfElse"^-1 * keyword("end") / mark("if"),
While = keyword("while") * V"Cond" * V"Block" * keyword("end") / mark("while"),
})
local function parse(source)
return match(program, source)
end
return { parse = parse }
|
local lpeg = require "lpeg"
local type = type
local tonumber = tonumber
local match = lpeg.match
lpeg.locale(lpeg)
lpeg.setmaxstack(10000)
local R, S, V, P, C, Ct, Cp, Cg, Cb, Cc, Cf =
lpeg.R, lpeg.S, lpeg.V, lpeg.P, lpeg.C, lpeg.Ct,
lpeg.Cp, lpeg.Cg, lpeg.Cb, lpeg.Cc, lpeg.Cf
local Break = P"\r"^-1 * P"\n"
local Comment = P"#" * (1 - P"\n")^0
local White = S" \t\r\n"
local Space = (White + Comment)^0
local Alpha = lpeg.alpha
local AlphaNum = R("az", "AZ", "09", "__")
local function mark(name)
return function(...)
return { name, ... }
end
end
local function remark(name)
return function(cap)
cap[1] = name
return cap
end
end
local function pos(patt)
return (Cp() * patt) / function(pos, cap)
if type(cap) == "table" then
cap[-1] = pos
end
return cap
end
end
local function keyword(chars)
return Space * chars * -AlphaNum
end
local function sym(chars)
return Space * chars
end
local function op(chars)
return Space * C(chars)
end
local function binaryOp(lhs, op, rhs)
if not op then
return lhs
end
return { op, lhs, rhs }
end
local function sepBy(patt, sep)
return patt * Cg(sep * patt)^0
end
local function chainOp(patt, sep)
return Cf(sepBy(patt, sep), binaryOp)
end
local function chain(patt, sep)
return patt * (sep * patt)^0
end
local Keywords = P"if" + P"else" + P"end" + P"def" + P"while" +
P"return" + P"break" + P"continue"
local Id = Space * (C((Alpha + P"_") * AlphaNum^0) - Keywords)
local Num = Space * (P"-"^-1 * (R"09"^1 * P".")^-1 * R"09"^1 / tonumber) / mark("number")
local String = Space * (P'"' * C(((P"\\" * P(1)) + (P(1) - P'"'))^0) * P'"' +
P"'" * C(((P"\\" * P(1)) + (P(1) - P"'"))^0) * P"'")
/ mark("string")
local CompOp = op(S"><!=" * P"="^-1)
local AddOp = op(S"+-%")
local MulOp = op(S"*/")
local program = P({
"Program",
Program = V"Block" + Ct"",
Block = Ct(V"Stat"^0),
Stat = V"Def" + V"Assign" + V"LocalAssign" + V"Return"
+ V"Call" + V"If" + V"While",
Assign = Id * sym("=") * V"Expr" / mark("assign"),
LocalAssign = keyword("local") * V"Assign" / remark("local"),
Return = keyword("return") * (V"Expr" + Cc(nil)) / mark("return"),
CompExpr = V"Expr" * CompOp * V"Expr" / binaryOp,
Cond = V"CompExpr" + sym("(") * V"CompExpr" * sym(")") + V"Expr",
Expr = V"AddExpr",
AddExpr = chainOp(V"MulExpr", AddOp),
MulExpr = chainOp(V"Value", MulOp),
Ref = Id / mark("ref"),
Value = Num + String + V"Call" + V"Ref" + sym("(") * V"Expr" * sym(")"),
ParsList = Ct(chain(Id, sym(","))^0),
Pars = sym("(") * V"ParsList" * sym(")"),
Def = keyword("def") * Id * V"Pars" * V"Block" * keyword("end") / mark("def"),
ArgsList = Ct(chain(V"Expr", sym(","))^0),
Args = sym("(") * V"ArgsList" * sym(")"),
Call = Id * V"Args" / mark("call"),
IfElse = keyword("else") * V"Block" / mark("else"),
If = keyword("if") * V"Cond" * V"Block" * V"IfElse"^-1 * keyword("end") / mark("if"),
While = keyword("while") * V"Cond" * V"Block" * keyword("end") / mark("while"),
})
local function parse(source)
return match(program, source)
end
return { parse = parse }
|
Fix style
|
Fix style
|
Lua
|
mit
|
tianchaijz/lua-helium,tianchaijz/lua-helium
|
e55b496585389a4a46b4820a9d43b1b866130b16
|
busted/outputHandlers/base.lua
|
busted/outputHandlers/base.lua
|
local socket = require 'socket'
return function()
local busted = require 'busted'
local handler = {
successes = {},
successesCount = 0,
pendings = {},
pendingsCount = 0,
failures = {},
failuresCount = 0,
errors = {},
errorsCount = 0,
inProgress = {}
}
handler.cancelOnPending = function(element, parent, status)
return not ((element.descriptor == 'pending' or status == 'pending') and handler.options.suppressPending)
end
handler.subscribe = function(handler, options)
require('busted.languages.en')
handler.options = options
if options.language ~= 'en' then
require('busted.languages.' .. options.language)
end
busted.subscribe({ 'suite', 'reset' }, handler.baseSuiteReset, { priority = 1 })
busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart, { priority = 1 })
busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd, { priority = 1 })
busted.subscribe({ 'test', 'start' }, handler.baseTestStart, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'test', 'end' }, handler.baseTestEnd, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'pending' }, handler.basePending, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'failure', 'it' }, handler.baseTestFailure, { priority = 1 })
busted.subscribe({ 'error', 'it' }, handler.baseTestError, { priority = 1 })
busted.subscribe({ 'failure' }, handler.baseError, { priority = 1 })
busted.subscribe({ 'error' }, handler.baseError, { priority = 1 })
end
handler.getFullName = function(context)
local parent = busted.parent(context)
local names = { (context.name or context.descriptor) }
while parent and (parent.name or parent.descriptor) and
parent.descriptor ~= 'file' do
table.insert(names, 1, parent.name or parent.descriptor)
parent = busted.parent(parent)
end
return table.concat(names, ' ')
end
handler.format = function(element, parent, message, debug, isError)
local formatted = {
trace = debug or element.trace,
element = element,
name = handler.getFullName(element),
message = message,
randomseed = parent and parent.randomseed,
isError = isError
}
formatted.element.trace = element.trace or debug
return formatted
end
handler.getDuration = function()
if not handler.endTime or not handler.startTime then
return 0
end
return handler.endTime - handler.startTime
end
handler.baseSuiteStart = function()
handler.startTime = socket.gettime()
return nil, true
end
handler.baseSuiteReset = function()
handler.successes = {}
handler.successesCount = 0
handler.pendings = {}
handler.pendingsCount = 0
handler.failures = {}
handler.failuresCount = 0
handler.errors = {}
handler.errorsCount = 0
handler.inProgress = {}
return nil, true
end
handler.baseSuiteEnd = function()
handler.endTime = socket.gettime()
return nil, true
end
handler.baseTestStart = function(element, parent)
handler.inProgress[tostring(element)] = {}
return nil, true
end
handler.baseTestEnd = function(element, parent, status, debug)
local insertTable
if status == 'success' then
insertTable = handler.successes
handler.successesCount = handler.successesCount + 1
elseif status == 'pending' then
insertTable = handler.pendings
handler.pendingsCount = handler.pendingsCount + 1
elseif status == 'failure' then
-- failure already saved in failure handler
handler.failuresCount = handler.failuresCount + 1
return nil, true
elseif status == 'error' then
-- error count already incremented and saved in error handler
insertTable = handler.errors
return nil, true
end
local formatted = handler.format(element, parent, element.message, debug)
local id = tostring(element)
if handler.inProgress[id] then
for k, v in pairs(handler.inProgress[id]) do
formatted[k] = v
end
handler.inProgress[id] = nil
end
table.insert(insertTable, formatted)
return nil, true
end
handler.basePending = function(element, parent, message, debug)
local id = tostring(element)
handler.inProgress[id].message = message
handler.inProgress[id].trace = debug
return nil, true
end
handler.baseTestFailure = function(element, parent, message, debug)
table.insert(handler.failures, handler.format(element, parent, message, debug))
return nil, true
end
handler.baseTestError = function(element, parent, message, debug)
handler.errorsCount = handler.errorsCount + 1
table.insert(handler.errors, handler.format(element, parent, message, debug, true))
return nil, true
end
handler.baseError = function(element, parent, message, debug)
if element.descriptor ~= 'it' then
handler.errorsCount = handler.errorsCount + 1
table.insert(handler.errors, handler.format(element, parent, message, debug, true))
end
return nil, true
end
return handler
end
|
local socket = require 'socket'
return function()
local busted = require 'busted'
local handler = {
successes = {},
successesCount = 0,
pendings = {},
pendingsCount = 0,
failures = {},
failuresCount = 0,
errors = {},
errorsCount = 0,
inProgress = {}
}
handler.cancelOnPending = function(element, parent, status)
return not ((element.descriptor == 'pending' or status == 'pending') and handler.options.suppressPending)
end
handler.subscribe = function(handler, options)
require('busted.languages.en')
handler.options = options
if options.language ~= 'en' then
require('busted.languages.' .. options.language)
end
busted.subscribe({ 'suite', 'reset' }, handler.baseSuiteReset, { priority = 1 })
busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart, { priority = 1 })
busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd, { priority = 1 })
busted.subscribe({ 'test', 'start' }, handler.baseTestStart, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'test', 'end' }, handler.baseTestEnd, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'pending' }, handler.basePending, { priority = 1, predicate = handler.cancelOnPending })
busted.subscribe({ 'failure', 'it' }, handler.baseTestFailure, { priority = 1 })
busted.subscribe({ 'error', 'it' }, handler.baseTestError, { priority = 1 })
busted.subscribe({ 'failure' }, handler.baseError, { priority = 1 })
busted.subscribe({ 'error' }, handler.baseError, { priority = 1 })
end
handler.getFullName = function(context)
local parent = busted.parent(context)
local names = { (context.name or context.descriptor) }
while parent and (parent.name or parent.descriptor) and
parent.descriptor ~= 'file' do
table.insert(names, 1, parent.name or parent.descriptor)
parent = busted.parent(parent)
end
return table.concat(names, ' ')
end
handler.format = function(element, parent, message, debug, isError)
local formatted = {
trace = debug or element.trace,
element = {
name = element.name,
descriptor = element.descriptor,
attributes = element.attributes,
trace = element.trace or debug,
},
name = handler.getFullName(element),
message = message,
randomseed = parent and parent.randomseed,
isError = isError
}
return formatted
end
handler.getDuration = function()
if not handler.endTime or not handler.startTime then
return 0
end
return handler.endTime - handler.startTime
end
handler.baseSuiteStart = function()
handler.startTime = socket.gettime()
return nil, true
end
handler.baseSuiteReset = function()
handler.successes = {}
handler.successesCount = 0
handler.pendings = {}
handler.pendingsCount = 0
handler.failures = {}
handler.failuresCount = 0
handler.errors = {}
handler.errorsCount = 0
handler.inProgress = {}
return nil, true
end
handler.baseSuiteEnd = function()
handler.endTime = socket.gettime()
return nil, true
end
handler.baseTestStart = function(element, parent)
handler.inProgress[tostring(element)] = {}
return nil, true
end
handler.baseTestEnd = function(element, parent, status, debug)
local insertTable
if status == 'success' then
insertTable = handler.successes
handler.successesCount = handler.successesCount + 1
elseif status == 'pending' then
insertTable = handler.pendings
handler.pendingsCount = handler.pendingsCount + 1
elseif status == 'failure' then
-- failure already saved in failure handler
handler.failuresCount = handler.failuresCount + 1
return nil, true
elseif status == 'error' then
-- error count already incremented and saved in error handler
insertTable = handler.errors
return nil, true
end
local formatted = handler.format(element, parent, element.message, debug)
local id = tostring(element)
if handler.inProgress[id] then
for k, v in pairs(handler.inProgress[id]) do
formatted[k] = v
end
handler.inProgress[id] = nil
end
table.insert(insertTable, formatted)
return nil, true
end
handler.basePending = function(element, parent, message, debug)
local id = tostring(element)
handler.inProgress[id].message = message
handler.inProgress[id].trace = debug
return nil, true
end
handler.baseTestFailure = function(element, parent, message, debug)
table.insert(handler.failures, handler.format(element, parent, message, debug))
return nil, true
end
handler.baseTestError = function(element, parent, message, debug)
handler.errorsCount = handler.errorsCount + 1
table.insert(handler.errors, handler.format(element, parent, message, debug, true))
return nil, true
end
handler.baseError = function(element, parent, message, debug)
if element.descriptor ~= 'it' then
handler.errorsCount = handler.errorsCount + 1
table.insert(handler.errors, handler.format(element, parent, message, debug, true))
end
return nil, true
end
return handler
end
|
Fix json output
|
Fix json output
Looks like the json module has issues with tables that have functions
in them. So remove output tables that have functions.
|
Lua
|
mit
|
xyliuke/busted,istr/busted,DorianGray/busted,ryanplusplus/busted,o-lim/busted,Olivine-Labs/busted,sobrinho/busted,mpeterv/busted
|
cb33fa6f2003ff4b3147b9c75c1002b9ff631371
|
src/actions/vstudio/vs2010_rules_xml.lua
|
src/actions/vstudio/vs2010_rules_xml.lua
|
---
-- vs2010_rules_xml.lua
-- Generate a Visual Studio 201x custom rules XML file.
-- Copyright (c) 2014 Jason Perkins and the Premake project
--
premake.vstudio.vs2010.rules.xml = {}
local m = premake.vstudio.vs2010.rules.xml
m.elements = {}
local p = premake
---
-- Entry point; generate the root <ProjectSchemaDefinitions> element.
---
m.elements.project = function(r)
return {
p.xmlUtf8,
m.projectSchemaDefinitions,
m.rule,
m.ruleItem,
m.fileExtension,
m.contentType,
}
end
function m.generate(r)
p.callArray(m.elements.project, r)
p.pop('</ProjectSchemaDefinitions>')
end
---
-- Generate the main <Rule> element.
---
m.elements.rule = function(r)
return {
m.dataSource,
m.categories,
m.inputs,
m.properties,
}
end
function m.rule(r)
p.push('<Rule')
p.w('Name="%s"', r.name)
p.w('PageTemplate="tool"')
p.w('DisplayName="%s"', r.description or r.name)
p.w('Order="200">')
p.callArray(m.elements.rule, r)
p.pop('</Rule>')
end
---
-- Generate the list of categories.
---
function m.categories(r)
local categories = {
[1] = { name="General" },
[2] = { name="Command Line", subtype="CommandLine" },
}
p.push('<Rule.Categories>')
for i = 1, #categories do
m.category(categories[i])
end
p.pop('</Rule.Categories>')
end
function m.category(cat)
local attribs = p.capture(function()
p.push()
p.w('Name="%s"', cat.name)
if cat.subtype then
p.w('Subtype="%s"', cat.subtype)
end
p.pop()
end)
p.push('<Category')
p.outln(attribs .. '>')
p.push('<Category.DisplayName>')
p.w('<sys:String>%s</sys:String>', cat.name)
p.pop('</Category.DisplayName>')
p.pop('</Category>')
end
---
-- Generate the list of property definitions.
---
function m.properties(r)
local defs = r.propertyDefinition
for i = 1, #defs do
local def = defs[i]
if def.kind == "list" then
m.stringListProperty(def)
elseif type(def.values) == "table" then
m.enumProperty(def)
else
m.stringProperty(def)
end
end
end
function m.baseProperty(def)
p.w('Name="%s"', def.name)
p.w('HelpContext="0"')
p.w('DisplayName="%s"', def.display or def.name)
p.w('Description="%s"', def.description or def.display or def.name)
end
function m.enumProperty(def)
p.push('<EnumProperty')
m.baseProperty(def)
local values = def.values
local switches = def.switch or {}
local keys = table.keys(def.values)
table.sort(keys)
for _, key in pairs(keys) do
p.push('<EnumValue')
p.w('Name="%d"', key)
p.w('DisplayName="%s"', values[key])
p.w('Switch="%s" />', switches[key] or values[key])
p.pop()
end
p.pop('</EnumProperty>')
end
function m.stringProperty(def)
p.push('<StringProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
function m.stringListProperty(def)
p.push('<StringListProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
---
-- Implementations of individual elements.
---
function m.contentType(r)
p.push('<ContentType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s"', r.name)
p.w('ItemType="%s" />', r.name)
p.pop()
end
function m.dataSource(r)
p.push('<Rule.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s" />', r.name)
p.pop()
p.pop('</Rule.DataSource>')
end
function m.fileExtension(r)
p.push('<FileExtension')
p.w('Name="*.XYZ"')
p.w('ContentType="%s" />', r.name)
p.pop()
end
function m.inputs(r)
p.push('<StringListProperty')
p.w('Name="Inputs"')
p.w('Category="Command Line"')
p.w('IsRequired="true"')
p.w('Switch=" ">')
p.push('<StringListProperty.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s"', r.name)
p.w('SourceType="Item" />')
p.pop()
p.pop('</StringListProperty.DataSource>')
p.pop('</StringListProperty>')
end
function m.ruleItem(r)
p.push('<ItemType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s" />', r.name)
p.pop()
end
function m.projectSchemaDefinitions(r)
p.push('<ProjectSchemaDefinitions xmlns="http://schemas.microsoft.com/build/2009/properties" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">')
end
|
---
-- vs2010_rules_xml.lua
-- Generate a Visual Studio 201x custom rules XML file.
-- Copyright (c) 2014 Jason Perkins and the Premake project
--
premake.vstudio.vs2010.rules.xml = {}
local m = premake.vstudio.vs2010.rules.xml
m.elements = {}
local p = premake
---
-- Entry point; generate the root <ProjectSchemaDefinitions> element.
---
m.elements.project = function(r)
return {
p.xmlUtf8,
m.projectSchemaDefinitions,
m.rule,
m.ruleItem,
m.fileExtension,
m.contentType,
}
end
function m.generate(r)
p.callArray(m.elements.project, r)
p.pop('</ProjectSchemaDefinitions>')
end
---
-- Generate the main <Rule> element.
---
m.elements.rule = function(r)
return {
m.dataSource,
m.categories,
m.inputs,
m.properties,
}
end
function m.rule(r)
p.push('<Rule')
p.w('Name="%s"', r.name)
p.w('PageTemplate="tool"')
p.w('DisplayName="%s"', r.display or r.name)
p.w('Order="200">')
p.callArray(m.elements.rule, r)
p.pop('</Rule>')
end
---
-- Generate the list of categories.
---
function m.categories(r)
local categories = {
[1] = { name="General" },
[2] = { name="Command Line", subtype="CommandLine" },
}
p.push('<Rule.Categories>')
for i = 1, #categories do
m.category(categories[i])
end
p.pop('</Rule.Categories>')
end
function m.category(cat)
local attribs = p.capture(function()
p.push()
p.w('Name="%s"', cat.name)
if cat.subtype then
p.w('Subtype="%s"', cat.subtype)
end
p.pop()
end)
p.push('<Category')
p.outln(attribs .. '>')
p.push('<Category.DisplayName>')
p.w('<sys:String>%s</sys:String>', cat.name)
p.pop('</Category.DisplayName>')
p.pop('</Category>')
end
---
-- Generate the list of property definitions.
---
function m.properties(r)
local defs = r.propertyDefinition
for i = 1, #defs do
local def = defs[i]
if def.kind == "boolean" then
m.boolProperty(def)
elseif def.kind == "list" then
m.stringListProperty(def)
elseif type(def.values) == "table" then
m.enumProperty(def)
else
m.stringProperty(def)
end
end
end
function m.baseProperty(def, close)
p.w('Name="%s"', def.name)
p.w('HelpContext="0"')
p.w('DisplayName="%s"', def.display or def.name)
p.w('Description="%s"%s', def.description or def.display or def.name, iif(close, ">", ""))
end
function m.boolProperty(def)
p.push('<BoolProperty')
m.baseProperty(def)
if def.switch then
p.w('Switch="%s" />', def.switch)
end
p.pop()
end
function m.enumProperty(def)
p.push('<EnumProperty')
m.baseProperty(def, true)
local values = def.values
local switches = def.switch or {}
local keys = table.keys(def.values)
table.sort(keys)
for _, key in pairs(keys) do
p.push('<EnumValue')
p.w('Name="%d"', key)
if switches[key] then
p.w('DisplayName="%s"', values[key])
p.w('Switch="%s" />', switches[key])
else
p.w('DisplayName="%s" />', values[key])
end
p.pop()
end
p.pop('</EnumProperty>')
end
function m.stringProperty(def)
p.push('<StringProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
function m.stringListProperty(def)
p.push('<StringListProperty')
m.baseProperty(def)
if def.separator then
p.w('Separator="%s"', def.separator)
end
p.w('Switch="[value]" />')
p.pop()
end
---
-- Implementations of individual elements.
---
function m.contentType(r)
p.push('<ContentType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s"', r.name)
p.w('ItemType="%s" />', r.name)
p.pop()
end
function m.dataSource(r)
p.push('<Rule.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s" />', r.name)
p.pop()
p.pop('</Rule.DataSource>')
end
function m.fileExtension(r)
p.push('<FileExtension')
p.w('Name="*.XYZ"')
p.w('ContentType="%s" />', r.name)
p.pop()
end
function m.inputs(r)
p.push('<StringListProperty')
p.w('Name="Inputs"')
p.w('Category="Command Line"')
p.w('IsRequired="true"')
p.w('Switch=" ">')
p.push('<StringListProperty.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s"', r.name)
p.w('SourceType="Item" />')
p.pop()
p.pop('</StringListProperty.DataSource>')
p.pop('</StringListProperty>')
end
function m.ruleItem(r)
p.push('<ItemType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s" />', r.name)
p.pop()
end
function m.projectSchemaDefinitions(r)
p.push('<ProjectSchemaDefinitions xmlns="http://schemas.microsoft.com/build/2009/properties" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">')
end
|
Basic support for boolean properties, some fixes
|
Basic support for boolean properties, some fixes
--HG--
branch : feature/rules
|
Lua
|
bsd-3-clause
|
annulen/premake,annulen/premake,annulen/premake,annulen/premake
|
d1b570fa5c1d98c1e98bcfc98d87ea10a975f772
|
src/sailor/access.lua
|
src/sailor/access.lua
|
--------------------------------------------------------------------------------
-- access.lua, v0.2.2: controls access of sailor apps
-- This file is a part of Sailor project
-- Copyright (c) 2014 Etiene Dalcol <[email protected]>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local session = require "sailor.session"
local access = {}
session.open(sailor.r)
-- Uncomment to login with "demo" / "demo"
-- Comment to login through db (user model)
--access.default = "demo"
--access.default_pass = "demo"
--access.salt = "sailorisawesome" -- uncomment to use unhashed passwords
local INVALID = "Invalid username or password."
-- Simple hashing algorithm for encrypting passworsd
function access.hash(username, password)
local hash = username .. password
-- Check if bcrypt is embedded
if sailor.r.htpassword then
return sailor.r:htpassword(hash, 2, 100) -- Use bcrypt on pwd
-- If not, fall back to sha1 hashing
else
if access.salt and sailor.r.sha1 then
for i = 1, 500 do
hash = sailor.r:sha1(access.salt .. hash)
end
end
end
return hash
end
function access.is_guest()
return not session.data.username
end
function access.grant(data,time)
session.setsessiontimeout (time or 604800) -- 1 week
if not data.username then return false end
access.data = data
return session.save(data)
end
function access.login(username,password)
local id
if not access.default then
local User = sailor.model("user")
local u = User:find_by_attributes{
username=username,
password=access.hash(username, password)
}
if not u then
return false, INVALID
end
id = u.id
else
if username ~= access.default or password ~= access.default_pass then
return false, INVALID
end
id = 1
end
return access.grant({username=username,id=id})
end
function access.logout()
session.destroy(sailor.r)
end
return access
|
--------------------------------------------------------------------------------
-- access.lua, v0.2.3: controls access of sailor apps
-- This file is a part of Sailor project
-- Copyright (c) 2014 Etiene Dalcol <[email protected]>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local session = require "sailor.session"
local access = {}
session.open(sailor.r)
-- Uncomment to login with "demo" / "demo"
-- Comment to login through db (user model)
--access.default = "demo"
--access.default_pass = "demo"
--access.salt = "sailorisawesome" -- set to nil to use unhashed passwords
local INVALID = "Invalid username or password."
-- Simple hashing algorithm for encrypting passworsd
function access.hash(username, password, salt)
salt = salt or access.salt
local hash = username .. password
-- Check if bcrypt is embedded
if sailor.r.htpassword then
return sailor.r:htpassword(hash, 2, 100) -- Use bcrypt on pwd
-- If not, fall back to sha1 hashing
else
if salt and sailor.r.sha1 then
for i = 1, 500 do
hash = sailor.r:sha1(salt .. hash)
end
end
end
return hash
end
function access.is_guest()
return not session.data.username
end
function access.grant(data,time)
session.setsessiontimeout (time or 604800) -- 1 week
if not data.username then return false end
access.data = data
return session.save(data)
end
function access.login(username,password,salt)
local id
if not access.default then
local User = sailor.model("user")
local u = User:find_by_attributes{
username=username,
password=access.hash(username, password, salt)
}
if not u then
return false, INVALID
end
id = u.id
else
if username ~= access.default or password ~= access.default_pass then
return false, INVALID
end
id = 1
end
return access.grant({username=username,id=id})
end
function access.logout()
session.destroy(sailor.r)
end
return access
|
Fixing salt workflow on access module
|
Fixing salt workflow on access module
|
Lua
|
mit
|
ignacio/sailor,ignacio/sailor,Etiene/sailor,jeary/sailor,mpeterv/sailor,mpeterv/sailor,noname007/sailor,felipedaragon/sailor,hallison/sailor,sailorproject/sailor,Etiene/sailor,felipedaragon/sailor
|
de71e6f774e7239c17266ff1f5999c673a08614e
|
Peripherals/GPU/modules/miscellaneous.lua
|
Peripherals/GPU/modules/miscellaneous.lua
|
--GPU: Miscellaneous Things.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local events = require("Engine.events")
local MiscVars = GPUVars.Misc
local RenderVars = GPUVars.Render
--==System Message==--
MiscVars.LastMSG = "" --Last system message.
MiscVars.LastMSGTColor = 4 --Last system message text color.
MiscVars.LastMSGColor = 9 --Last system message color.
MiscVars.LastMSGGif = false --Show Last system message in the gif recording ?
MiscVars.MSGTimer = 0 --The message timer.
local function systemMessage(msg,time,tcol,col,hideInGif)
if not msg then MiscVars.MSGTimer = 0 end --Clear last message
if type(msg) ~= "string" then return false, "Message must be a string, provided: "..type(msg) end
if time and type(time) ~= "number" then return false, "Time must be a number or a nil, provided: "..type(time) end
if tcol and type(tcol) ~= "number" then return false, "Text color must be a number or a nil, provided: "..type(tcol) end
if col and type(col) ~= "number" then return false, "Body Color must be a number or a nil, provided: "..type(col) end
time, tcol, col = time or 1, math.floor(tcol or 4), math.floor(col or 9)
if time <= 0 then return false, "Time must be bigger than 0" end
if tcol < 0 or tcol > 15 then return false, "Text Color ID out of range ("..tcol..") Must be [0,15]" end
if col < 0 or col > 15 then return false, "Body Color ID out of range ("..col..") Must be [0,15]" end
MiscVars.LastMSG = msg
MiscVars.LastMSGTColor = tcol
MiscVars.LastMSGColor = col
MiscVars.LastMSGGif = not hideInGif
MiscVars.MSGTimer = time
return true
end
function GPU._systemMessage(msg,time,tcol,col,hideInGif)
return systemMessage(msg,time,tcol,col,hideInGif)
end
events.register("love:update",function(dt)
if MiscVars.MSGTimer > 0 then
MiscVars.MSGTimer = MiscVars.MSGTimer - dt
RenderVars.ShouldDraw = true
end
end)
MiscVars.systemMessage = systemMessage
|
--GPU: Miscellaneous Things.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local events = require("Engine.events")
local MiscVars = GPUVars.Misc
local RenderVars = GPUVars.Render
--==System Message==--
MiscVars.LastMSG = "" --Last system message.
MiscVars.LastMSGTColor = 4 --Last system message text color.
MiscVars.LastMSGColor = 9 --Last system message color.
MiscVars.LastMSGGif = false --Show Last system message in the gif recording ?
MiscVars.MSGTimer = 0 --The message timer.
local function systemMessage(msg,time,tcol,col,hideInGif)
if not msg then MiscVars.MSGTimer = 0 end --Clear last message
if type(msg) ~= "string" then return error("Message must be a string, provided: "..type(msg)) end
if time and type(time) ~= "number" then return error("Time must be a number or a nil, provided: "..type(time)) end
if tcol and type(tcol) ~= "number" then return error("Text color must be a number or a nil, provided: "..type(tcol)) end
if col and type(col) ~= "number" then return error("Body Color must be a number or a nil, provided: "..type(col)) end
time, tcol, col = time or 1, math.floor(tcol or 4), math.floor(col or 9)
if time < 0 then return error("Time can't be negative") end
if tcol < 0 or tcol > 15 then return error("Text Color ID out of range ("..tcol..") Must be [0,15]") end
if col < 0 or col > 15 then return error("Body Color ID out of range ("..col..") Must be [0,15]") end
MiscVars.LastMSG = msg
MiscVars.LastMSGTColor = tcol
MiscVars.LastMSGColor = col
MiscVars.LastMSGGif = not hideInGif
MiscVars.MSGTimer = time
return true
end
function GPU._systemMessage(msg,time,tcol,col,hideInGif)
local ok, err = pcall(systemMessage,msg,time,tcol,col,hideInGif)
if not ok then return error(err) end
end
events.register("love:update",function(dt)
if MiscVars.MSGTimer > 0 then
MiscVars.MSGTimer = MiscVars.MSGTimer - dt
RenderVars.ShouldDraw = true
end
end)
MiscVars.systemMessage = systemMessage
|
Fix GPU system message errors, and allow time to be 0 (for cancelling messages)
|
Fix GPU system message errors, and allow time to be 0 (for cancelling messages)
Former-commit-id: f21ed68153bf11327751c641ed39b930943efc63
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b9d887e674eb574b1693dd1b6d77f917f41353a4
|
hikyuu_pywrap/xmake.lua
|
hikyuu_pywrap/xmake.lua
|
option("boost-python-suffix")
set_default("3X")
set_showmenu(true)
set_category("hikyuu")
set_description("Set suffix of libboost_python. ",
"Boost.python 1.67 later use 3x like libboost_python35, ",
"but older is libboost_python3",
" - 3X autocheck for 35, 36, 37, 3x")
option_end()
add_includedirs("../hikyuu_cpp")
-- Can't use static boost.python lib, the function that using 'arg' will load failed!
--add_defines("BOOST_PYTHON_STATIC_LIB")
if is_plat("windows") then
add_defines("HKU_API=__declspec(dllimport)")
add_cxflags("-wd4566")
end
local cc = get_config("cc")
local cxx = get_config("cxx")
if (cc and string.find(cc, "clang")) or (cxx and string.find(cxx, "clang")) then
add_cxflags("-Wno-error=parentheses-equality -Wno-error=missing-braces")
end
--on_load("xmake_on_load")
target("core")
set_kind("shared")
if is_mode("debug") then
set_default(false) --会默认禁用这个target的编译,除非显示指定xmake build _hikyuu才会去编译,但是target还存在,里面的files会保留到vcproj
--set_enable(false) --set_enable(false)会彻底禁用这个target,连target的meta也不会被加载,vcproj不会保留它
end
add_packages("fmt", "spdlog")
add_deps("hikyuu")
if is_plat("windows") then
set_filename("core.pyd")
add_cxflags("-wd4251")
else
set_filename("core.so")
end
add_files("./**.cpp")
add_rpathdirs("$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib")
on_load(function(target)
import("lib.detect.find_tool")
if is_plat("windows") then
-- detect installed python3
local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0")
assert(python.version > "3", python.version .. " python version must > 3.0, please use python3.0 or later!")
-- find python include and libs directory
local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"")
pydir = path.directory(pydir)
target:add("includedirs", pydir .. "/include")
target:add("linkdirs", pydir .. "/libs")
return
end
if is_plat("macosx") then
local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib"
target:add("linkdirs", libdir)
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
--local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10))
local python_lib = format("python%s.%s", string.sub(ver,8,8), string.sub(ver,10,10))
target:add("links", python_lib)
end
-- get python include directory.
local pydir = try { function () return os.iorun("python3-config --includes"):trim() end }
assert(pydir, "python3-config not found!")
target:add("cxflags", pydir)
-- get suffix configure for link libboost_pythonX.so
local suffix = get_config("boost-python-suffix")
if suffix == nil then
raise("You need to config --boost-python-suffix specify libboost_python suffix")
end
suffix = string.upper(suffix)
if suffix == "3X" then
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10)
target:add("links", boost_python_lib)
else
target:add("links", "boost_python"..suffix)
end
end)
after_build(function(target)
if is_plat("macosx") then
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local boost_python_lib = format("libboost_python%s%s.dylib", string.sub(ver,8,8), string.sub(ver,10,10))
os.run(format("install_name_tool -change @rpath/libhikyuu.dylib @loader_path/libhikyuu.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_date_time.dylib @loader_path/libboost_date_time.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_filesystem.dylib @loader_path/libboost_filesystem.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_system.dylib @loader_path/libboost_system.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_serialization.dylib @loader_path/libboost_serialization.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/%s @loader_path/%s %s/%s", boost_python_lib, boost_python_lib, target:targetdir(), "core.so"))
end
local dst_dir = "$(projectdir)/hikyuu/cpp/"
os.cp(target:targetdir() .. '/*.pyd', dst_dir)
os.cp(target:targetdir() .. '/*.dll', dst_dir)
os.cp(target:targetdir() .. '/*.so', dst_dir)
os.cp(target:targetdir() .. '/*.dylib', dst_dir)
os.cp("$(env BOOST_LIB)/boost_date_time*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_filesystem*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_python3*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_serialization*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_system*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_date_time*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_filesystem*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_python3*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_serialization*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_system*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_date_time*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_filesystem*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_python3*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_serialization*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_system*.dylib", dst_dir)
if is_plat("windows") then
if is_mode("release") then
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
else
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5_D.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
end
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/mysql.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
end
end)
|
option("boost-python-suffix")
set_default("3X")
set_showmenu(true)
set_category("hikyuu")
set_description("Set suffix of libboost_python. ",
"Boost.python 1.67 later use 3x like libboost_python35, ",
"but older is libboost_python3",
" - 3X autocheck for 35, 36, 37, 3x")
option_end()
add_includedirs("../hikyuu_cpp")
-- Can't use static boost.python lib, the function that using 'arg' will load failed!
--add_defines("BOOST_PYTHON_STATIC_LIB")
if is_plat("windows") then
add_defines("HKU_API=__declspec(dllimport)")
add_cxflags("-wd4566")
end
local cc = get_config("cc")
local cxx = get_config("cxx")
if (cc and string.find(cc, "clang")) or (cxx and string.find(cxx, "clang")) then
add_cxflags("-Wno-error=parentheses-equality -Wno-error=missing-braces")
end
--on_load("xmake_on_load")
target("core")
set_kind("shared")
if is_mode("debug") then
set_default(false) --会默认禁用这个target的编译,除非显示指定xmake build _hikyuu才会去编译,但是target还存在,里面的files会保留到vcproj
--set_enable(false) --set_enable(false)会彻底禁用这个target,连target的meta也不会被加载,vcproj不会保留它
end
add_packages("fmt", "spdlog")
add_deps("hikyuu")
if is_plat("windows") then
set_filename("core.pyd")
add_cxflags("-wd4251")
else
set_filename("core.so")
end
add_files("./**.cpp")
add_rpathdirs("$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib")
on_load(function(target)
import("lib.detect.find_tool")
if is_plat("windows") then
-- detect installed python3
local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0")
assert(python.version > "3", python.version .. " python version must > 3.0, please use python3.0 or later!")
-- find python include and libs directory
local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"")
pydir = path.directory(pydir)
target:add("includedirs", pydir .. "/include")
target:add("linkdirs", pydir .. "/libs")
return
end
if is_plat("macosx") then
local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib"
target:add("linkdirs", libdir)
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
--local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10))
local python_lib = format("python%s.%s", string.sub(ver,8,8), string.sub(ver,10,10))
target:add("links", python_lib)
end
-- get python include directory.
local pydir = try { function () return os.iorun("python3-config --includes"):trim() end }
assert(pydir, "python3-config not found!")
target:add("cxflags", pydir)
-- get suffix configure for link libboost_pythonX.so
local suffix = get_config("boost-python-suffix")
if suffix == nil then
raise("You need to config --boost-python-suffix specify libboost_python suffix")
end
suffix = string.upper(suffix)
if suffix == "3X" then
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10)
target:add("links", boost_python_lib)
else
target:add("links", "boost_python"..suffix)
end
end)
after_build(function(target)
if is_plat("macosx") then
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local boost_python_lib = format("libboost_python%s%s.dylib", string.sub(ver,8,8), string.sub(ver,10,10))
os.run(format("install_name_tool -change @rpath/libhikyuu.dylib @loader_path/libhikyuu.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_date_time.dylib @loader_path/libboost_date_time.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_filesystem.dylib @loader_path/libboost_filesystem.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_system.dylib @loader_path/libboost_system.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/libboost_serialization.dylib @loader_path/libboost_serialization.dylib %s/%s", target:targetdir(), "core.so"))
os.run(format("install_name_tool -change @rpath/%s @loader_path/%s %s/%s", boost_python_lib, boost_python_lib, target:targetdir(), "core.so"))
end
local dst_dir = "$(projectdir)/hikyuu/cpp/"
if is_plat("windows") then
os.cp(target:targetdir() .. '/core.pyd', dst_dir)
os.cp(target:targetdir() .. '/hikyuu.dll', dst_dir)
elseif is_plat("macosx") then
os.cp(target:targetdir() .. '/core.so', dst_dir)
os.cp(target:targetdir() .. '/hikyuu.dylib', dst_dir)
else
os.cp(target:targetdir() .. '/core.so', dst_dir)
os.cp(target:targetdir() .. '/hikyuu.so', dst_dir)
end
os.cp("$(env BOOST_LIB)/boost_date_time*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_filesystem*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_python3*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_serialization*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/boost_system*.dll", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_date_time*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_filesystem*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_python3*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_serialization*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_system*.so.*", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_date_time*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_filesystem*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_python3*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_serialization*.dylib", dst_dir)
os.cp("$(env BOOST_LIB)/libboost_system*.dylib", dst_dir)
if is_plat("windows") then
if is_mode("release") then
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
else
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5_D.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
end
os.cp("$(projectdir)/hikyuu_extern_libs/pkg/mysql.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir)
end
end)
|
fixed xmake cp
|
fixed xmake cp
|
Lua
|
mit
|
fasiondog/hikyuu
|
7b8ca3618287e6c75aaa85c0c57fbf0bac5260ec
|
food-chain/food-chain_test.lua
|
food-chain/food-chain_test.lua
|
local song = require('./food-chain')
describe('Food Chain', function ()
it('fly', function ()
local expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equals(song.verse(1),expected)
end)
it('spider', function ()
local expected = "I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n"
.."She swallowed the spider to catch the fly.\n"
.."I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equals(song.verse(2), expected)
end)
it('bird', function ()
local expected = "I know an old lady who swallowed a bird.\n"..
"How absurd to swallow a bird!\n"..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equals(song.verse(3),expected)
end)
it('cat', function ()
local expected = "I know an old lady who swallowed a cat.\n"..
"Imagine that, to swallow a cat!\n"..
"She swallowed the cat to catch the bird.\n"..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. "..
"Perhaps she'll die.\n"
assert.are.equals(song.verse(4),expected)
end)
it('dog', function ()
local expected = "I know an old lady who swallowed a dog.\n"..
"What a hog, to swallow a dog!\n"..
"She swallowed the dog to catch the cat.\n"..
"She swallowed the cat to catch the bird.\n"..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. "..
"Perhaps she'll die.\n"
assert.are.equals(song.verse(5),expected)
end)
it('goat', function ()
local expected = "I know an old lady who swallowed a goat.\n"..
"Just opened her throat and swallowed a goat!\n"..
"She swallowed the goat to catch the dog.\n"..
"She swallowed the dog to catch the cat.\n"..
"She swallowed the cat to catch the bird.\n"..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. "..
"Perhaps she'll die.\n"
assert.are.equals(song.verse(6),expected)
end)
it('cow', function ()
local expected = "I know an old lady who swallowed a cow.\n"..
"I don't know how she swallowed a cow!\n"..
"She swallowed the cow to catch the goat.\n"..
"She swallowed the goat to catch the dog.\n"..
"She swallowed the dog to catch the cat.\n"..
"She swallowed the cat to catch the bird.\n"..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. "..
"Perhaps she'll die.\n"
assert.are.equals(song.verse(7),expected)
end)
it('horse', function ()
local expected = "I know an old lady who swallowed a horse.\n".. "She's dead, of course!\n"
assert.are.equals(song.verse(8),expected)
end)
it('multiple verses', function ()
local expected = ""
expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n\n"
expected = expected.."I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n"..
"She swallowed the spider to catch the fly.\n"..
"I don't know why she swallowed the fly. Perhaps she'll die.\n\n"
assert.are.equals(song.verses(1, 2),expected)
end)
it('the whole song', function ()
assert.are.equals(song.verses(1, 8),song.sing())
end)
end)
|
local song = require('./food-chain')
describe('Food Chain', function ()
it('fly', function ()
local expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(1))
end)
it('spider', function ()
local expected = "I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(2))
end)
it('bird', function ()
local expected = "I know an old lady who swallowed a bird.\n" ..
"How absurd to swallow a bird!\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(3))
end)
it('cat', function ()
local expected = "I know an old lady who swallowed a cat.\n" ..
"Imagine that, to swallow a cat!\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(4))
end)
it('dog', function ()
local expected = "I know an old lady who swallowed a dog.\n" ..
"What a hog, to swallow a dog!\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(5))
end)
it('goat', function ()
local expected = "I know an old lady who swallowed a goat.\n" ..
"Just opened her throat and swallowed a goat!\n" ..
"She swallowed the goat to catch the dog.\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(6))
end)
it('cow', function ()
local expected = "I know an old lady who swallowed a cow.\n" ..
"I don't know how she swallowed a cow!\n" ..
"She swallowed the cow to catch the goat.\n" ..
"She swallowed the goat to catch the dog.\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(7))
end)
it('horse', function ()
local expected = "I know an old lady who swallowed a horse.\n" ..
"She's dead, of course!\n"
assert.are.equal(expected, song.verse(8))
end)
it('multiple verses', function ()
local expected = ""
expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n\n"
expected = expected .."I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n\n"
assert.are.equal(expected, song.verses(1, 2))
end)
it('the whole song', function ()
assert.are.equal(song.verses(1, 8), song.sing())
end)
end)
|
Updated to match the provided style guide. Fixed expected and actual mix-up in assertions.
|
Updated to match the provided style guide. Fixed expected and actual mix-up in assertions.
|
Lua
|
mit
|
exercism/xlua,fyrchik/xlua,ryanplusplus/xlua
|
63de53d118b70b60e905e6e6f9479716d105af3c
|
mods/locked_sign/init.lua
|
mods/locked_sign/init.lua
|
--[[
Mod by kotolegokot
Version 2012.8.13.0
]]
minetest.register_privilege("sign_editor", "Can edit all locked signs")
minetest.register_node("locked_sign:sign_wall_locked", {
description = "Locked Sign",
drawtype = "signlike",
tiles = {"locked_sign_sign_wall_lock.png"},
inventory_image = "locked_sign_sign_wall_lock.png",
wield_image = "locked_sign_sign_wall_lock.png",
paramtype = "light",
paramtype2 = "wallmounted",
sunlight_propagates = true,
walkable = false,
metadata_name = "sign",
selection_box = {
type = "wallmounted",
},
groups = {choppy=2,dig_immediate=2},
legacy_wallmounted = true,
sounds = default.node_sound_defaults(),
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "\"\" (owned by " .. placer:get_player_name() .. ")")
end,
on_construct = function(pos)
--local n = minetest.get_node(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", "hack:sign_text_input")
meta:set_string("infotext", "\"\"")
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local owner = meta:get_string("owner")
local pname = player:get_player_name()
return pname == owner or pname == minetest.setting_get("name")
or minetest.check_player_privs(pname, {sign_editor=true})
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local owner = meta:get_string("owner")
local pname = sender:get_player_name()
if pname ~= owner and pname ~= minetest.setting_get("name")
and not minetest.check_player_privs(pname, {sign_editor=true}) then
return
end
local meta = minetest.get_meta(pos)
fields.text = fields.text or ""
print((sender:get_player_name() or "").." wrote \""..fields.text..
"\" to sign at "..minetest.pos_to_string(pos))
meta:set_string("text", fields.text)
meta:set_string("infotext", "\"" .. fields.text .. "\" (owned by " .. sender:get_player_name() .. ")")
end,
})
minetest.register_craft({
output = "locked_sign:sign_wall_locked",
recipe = {
{"default:wood", "default:wood", "default:wood"},
{"default:wood", "default:wood", "default:steel_ingot"},
{"", "default:stick", ""},
}
})
minetest.register_alias("sign_wall_locked", "locked_sign:sign_wall_locked")
|
--[[
Mod by kotolegokot
Version 2012.8.13.0
]]
minetest.register_privilege("sign_editor", "Can edit all locked signs")
minetest.register_node("locked_sign:sign_wall_locked", {
description = "Locked Sign",
drawtype = "signlike",
tiles = {"locked_sign_sign_wall_lock.png"},
inventory_image = "locked_sign_sign_wall_lock.png",
wield_image = "locked_sign_sign_wall_lock.png",
paramtype = "light",
paramtype2 = "wallmounted",
sunlight_propagates = true,
walkable = false,
metadata_name = "sign",
selection_box = {
type = "wallmounted",
},
groups = {choppy=2,dig_immediate=2},
legacy_wallmounted = true,
sounds = default.node_sound_defaults(),
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "\"\" (owned by " .. placer:get_player_name() .. ")")
end,
on_construct = function(pos)
--local n = minetest.get_node(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", "field[text;;${text}]")
meta:set_string("infotext", "\"\"")
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local owner = meta:get_string("owner")
local pname = player:get_player_name()
return pname == owner or pname == minetest.setting_get("name")
or minetest.check_player_privs(pname, {sign_editor=true})
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local owner = meta:get_string("owner")
local pname = sender:get_player_name()
if pname ~= owner and pname ~= minetest.setting_get("name") then
return
end
local meta = minetest.get_meta(pos)
fields.text = fields.text or ""
print((sender:get_player_name() or "").." wrote \""..fields.text..
"\" to sign at "..minetest.pos_to_string(pos))
meta:set_string("text", fields.text)
meta:set_string("infotext", "\"" .. fields.text .. "\" (owned by " .. sender:get_player_name() .. ")")
end,
})
minetest.register_craft({
output = "locked_sign:sign_wall_locked",
recipe = {
{"default:wood", "default:wood", "default:wood"},
{"default:wood", "default:wood", "default:steel_ingot"},
{"", "default:stick", ""},
}
})
minetest.register_alias("sign_wall_locked", "locked_sign:sign_wall_locked")
|
[locked_sign] Lock sign for individual players, and fix formspec - Fix #20
|
[locked_sign] Lock sign for individual players, and fix formspec
- Fix #20
|
Lua
|
unlicense
|
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
|
f2d52bd28171c4779ceb85f755768d2ec5bc658f
|
libs/httpd/luasrc/httpd.lua
|
libs/httpd/luasrc/httpd.lua
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
(c) 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
(c) 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
threadm[client] = nil
threadi[client] = nil
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
* libs/httpd: Fixed a memleak
|
* libs/httpd: Fixed a memleak
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
11f0fa32c74c8af092691ae8624670408657b502
|
durden/tools/advfloat.lua
|
durden/tools/advfloat.lua
|
--
-- Advanced float handler
--
-- Kept here as a means to start removing policy from tiler.lua
-- and letting more parts of the codebase be "opt out"
--
-- Since it is rather big, it have been split out into multiple subscripts,
-- while this one is kept as an entry point for consolidating menu
-- mapping and configuration keys.
--
-- cactions : cursor regions - path activation on mouse behavior
-- gridfit : split the screen into a 9-cell region for pseudo-tiler
-- autolay : automatic reposition/relayouting heuristics
-- spawnctl : intercept and regulate initial window position and size
-- minimize : minimize- target controls
-- bginput : input handlers for the wallpaper image (if one is set)
--
system_load("tools/advfloat/cactions.lua")();
system_load("tools/advfloat/minimize.lua")();
system_load("tools/advfloat/spawnctl.lua")();
system_load("tools/advfloat/bginput.lua")();
local workspace_menu = {
{
kind = "action",
submenu = true,
name = "autolayout",
label = "Layouter",
description = "Apply an automatic layouting technique",
handler = system_load("tools/advfloat/autolay.lua")()
}
};
shared_menu_register("window",
{
kind = "action",
submenu = true,
name = "gridalign",
label = "Grid-Fit",
eval = function()
local wnd = active_display().selected;
return (wnd and wnd.space.mode == "float");
end,
description = "Size and fit the current window to a virtual grid cell",
handler = system_load("tools/advfloat/gridfit.lua")()
});
global_menu_register("workspace",
{
kind = "action",
name = "float",
label = "Float",
submenu = true,
description = "(advfloat-tool) active workspace specific actions",
eval = function()
return active_display().spaces[active_display().space_ind].mode == "float";
end,
handler = workspace_menu
});
global_menu_register("settings/wspaces/float",
{
kind = "value",
name = "spawn_action",
initial = gconfig_get("advfloat_spawn"),
label = "Spawn Method",
description = "Change how new windows are being sized and positioned",
-- missing (split/share selected) or join selected
set = {"click", "cursor", "draw", "auto"},
handler = function(ctx, val)
mode = val;
gconfig_set("advfloat_spawn", val);
end
});
global_menu_register("settings/wspaces/float",
{
kind = "value",
name = "icons",
label = "Icons",
description = "Control how the tool should manage icons",
eval = function() return false; end,
set = {"disabled", "global", "workspace"},
initial = gconfig_get("advfloat_icon"),
handler = function(ctx, val)
gconfig_set("advfloat_icon", val);
end
});
|
--
-- Advanced float handler
--
-- Kept here as a means to start removing policy from tiler.lua
-- and letting more parts of the codebase be "opt out"
--
-- Since it is rather big, it have been split out into multiple subscripts,
-- while this one is kept as an entry point for consolidating menu
-- mapping and configuration keys.
--
-- cactions : cursor regions - path activation on mouse behavior
-- gridfit : split the screen into a 9-cell region for pseudo-tiler
-- autolay : automatic reposition/relayouting heuristics
-- spawnctl : intercept and regulate initial window position and size
-- minimize : minimize- target controls
-- bginput : input handlers for the wallpaper image (if one is set)
--
local floatmenu = {
{
kind = "value",
name = "spawn_action",
initial = gconfig_get("advfloat_spawn"),
label = "Spawn Method",
description = "Change how new windows are being sized and positioned",
-- missing (split/share selected) or join selected
set = {"click", "cursor", "draw", "auto"},
handler = function(ctx, val)
mode = val;
gconfig_set("advfloat_spawn", val);
end
},
{
kind = "value",
name = "icons",
label = "Icons",
description = "Control how the tool should manage icons",
eval = function() return false; end,
set = {"disabled", "global", "workspace"},
initial = gconfig_get("advfloat_icon"),
handler = function(ctx, val)
gconfig_set("advfloat_icon", val);
end
}
};
global_menu_register("settings/wspaces",
{
kind = "action",
name = "float",
submenu = true,
label = "Float",
description = "Advanced float workspace layout",
handler = floatmenu
});
system_load("tools/advfloat/cactions.lua")();
system_load("tools/advfloat/minimize.lua")();
system_load("tools/advfloat/spawnctl.lua")();
system_load("tools/advfloat/bginput.lua")();
local workspace_menu = {
{
kind = "action",
submenu = true,
name = "autolayout",
label = "Layouter",
description = "Apply an automatic layouting technique",
handler = system_load("tools/advfloat/autolay.lua")()
}
};
shared_menu_register("window",
{
kind = "action",
submenu = true,
name = "gridalign",
label = "Grid-Fit",
eval = function()
local wnd = active_display().selected;
return (wnd and wnd.space.mode == "float");
end,
description = "Size and fit the current window to a virtual grid cell",
handler = system_load("tools/advfloat/gridfit.lua")()
});
global_menu_register("workspace",
{
kind = "action",
name = "float",
label = "Float",
submenu = true,
description = "(advfloat-tool) active workspace specific actions",
eval = function()
return active_display().spaces[active_display().space_ind].mode == "float";
end,
handler = workspace_menu
});
|
advfloat, fix settings menu path registration
|
advfloat, fix settings menu path registration
|
Lua
|
bsd-3-clause
|
letoram/durden
|
c02879d6263354c77f09abccd7a015203095d037
|
modules/android/vsandroid_androidproj.lua
|
modules/android/vsandroid_androidproj.lua
|
--
-- android/vsandroid_androidproj.lua
-- vs-android integration for vstudio.
-- Copyright (c) 2012-2015 Manu Evans and the Premake project
--
local p = premake
local android = p.modules.android
local vsandroid = p.modules.vsandroid
local vc2010 = p.vstudio.vc2010
local vstudio = p.vstudio
local project = p.project
--
-- Add android tools to vstudio actions.
--
premake.override(vstudio.vs2010, "generateProject", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.eol("\r\n")
p.indent(" ")
p.escaper(vstudio.vs2010.esc)
if project.iscpp(prj) then
p.generate(prj, ".androidproj", vc2010.generate)
-- Skip generation of empty user files
local user = p.capture(function() vc2010.generateUser(prj) end)
if #user > 0 then
p.generate(prj, ".androidproj.user", function() p.outln(user) end)
end
end
else
oldfn(prj)
end
end)
premake.override(vstudio, "projectfile", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
return premake.filename(prj, ".androidproj")
else
return oldfn(prj)
end
end)
premake.override(vstudio, "tool", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
return "39E2626F-3545-4960-A6E8-258AD8476CE5"
else
return oldfn(prj)
end
end)
premake.override(vc2010.elements, "globals", function (oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == premake.ANDROIDPROJ then
-- Remove "IgnoreWarnCompileDuplicatedFilename".
local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename)
table.remove(elements, pos)
elements = table.join(elements, {
android.projectVersion
})
end
return elements
end)
function android.projectVersion(cfg)
_p(2, "<RootNamespace>%s</RootNamespace>", cfg.project.name)
_p(2, "<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>")
_p(2, "<ProjectVersion>1.0</ProjectVersion>")
end
premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == p.ANDROIDPROJ then
elements = {
vc2010.useDebugLibraries,
}
end
return elements
end)
premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == p.ANDROIDPROJ then
elements = {
android.antPackage,
}
end
return elements
end)
premake.override(vc2010, "importDefaultProps", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.Default.props" />')
else
oldfn(prj)
end
end)
premake.override(vc2010, "importLanguageSettings", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.props" />')
else
oldfn(prj)
end
end)
premake.override(vc2010, "propertySheets", function(oldfn, cfg)
if cfg.kind ~= p.ANDROIDPROJ then
oldfn(cfg)
end
end)
premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg)
if cfg.kind == p.ANDROIDPROJ then
return {
android.outDir,
}
else
return oldfn(cfg)
end
end)
function android.outDir(cfg)
vc2010.element("OutDir", nil, "%s\\", cfg.buildtarget.directory)
end
premake.override(vc2010, "importLanguageTargets", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.targets" />')
else
oldfn(prj)
end
end)
function android.link(cfg, file)
local fname = path.translate(file.relpath)
-- Files that live outside of the project tree need to be "linked"
-- and provided with a project relative pseudo-path. Check for any
-- leading "../" sequences and, if found, remove them and mark this
-- path as external.
local link, count = fname:gsub("%.%.%/", "")
local external = (count > 0) or fname:find(':', 1, true)
-- Try to provide a little bit of flexibility by allowing virtual
-- paths for external files. Would be great to support them for all
-- files but Visual Studio chokes if file is already in project area.
if external and file.vpath ~= file.relpath then
link = file.vpath
end
if external then
vc2010.element("Link", nil, path.translate(link))
end
end
vc2010.categories.AndroidManifest = {
name = "AndroidManifest",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AndroidManifest", {vc2010.generatedFile, android.link, android.manifestSubType})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AndroidManifest")
end
}
function android.manifestSubType(cfg, file)
vc2010.element("SubType", nil, "Designer")
end
vc2010.categories.AntBuildXml = {
name = "AntBuildXml",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AntBuildXml", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AntBuildXml")
end
}
vc2010.categories.AntProjectPropertiesFile = {
name = "AntProjectPropertiesFile",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AntProjectPropertiesFile", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AntProjectPropertiesFile")
end
}
vc2010.categories.Content = {
name = "Content",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "Content", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "Content")
end
}
premake.override(vc2010, "categorizeFile", function(base, prj, file)
if prj.kind ~= p.ANDROIDPROJ then
return base(prj, file)
end
local filename = path.getname(file.name):lower()
if filename == "androidmanifest.xml" then
return vc2010.categories.AndroidManifest
elseif filename == "build.xml" then
return vc2010.categories.AntBuildXml
elseif filename == "project.properties" then
return vc2010.categories.AntProjectPropertiesFile
else
return vc2010.categories.Content
end
end)
|
--
-- android/vsandroid_androidproj.lua
-- vs-android integration for vstudio.
-- Copyright (c) 2012-2015 Manu Evans and the Premake project
--
local p = premake
local android = p.modules.android
local vsandroid = p.modules.vsandroid
local vc2010 = p.vstudio.vc2010
local vstudio = p.vstudio
local project = p.project
--
-- Add android tools to vstudio actions.
--
premake.override(vstudio.vs2010, "generateProject", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.eol("\r\n")
p.indent(" ")
p.escaper(vstudio.vs2010.esc)
if project.iscpp(prj) then
p.generate(prj, ".androidproj", vc2010.generate)
-- Skip generation of empty user files
local user = p.capture(function() vc2010.generateUser(prj) end)
if #user > 0 then
p.generate(prj, ".androidproj.user", function() p.outln(user) end)
end
end
else
oldfn(prj)
end
end)
premake.override(vstudio, "projectfile", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
return premake.filename(prj, ".androidproj")
else
return oldfn(prj)
end
end)
premake.override(vstudio, "tool", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
return "39E2626F-3545-4960-A6E8-258AD8476CE5"
else
return oldfn(prj)
end
end)
premake.override(vc2010.elements, "globals", function (oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == premake.ANDROIDPROJ then
-- Remove "IgnoreWarnCompileDuplicatedFilename".
local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename)
table.remove(elements, pos)
elements = table.join(elements, {
android.projectVersion
})
end
return elements
end)
function android.projectVersion(cfg)
_p(2, "<RootNamespace>%s</RootNamespace>", cfg.project.name)
_p(2, "<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>")
_p(2, "<ProjectVersion>1.0</ProjectVersion>")
end
premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == p.ANDROIDPROJ then
elements = {
vc2010.useDebugLibraries,
}
end
return elements
end)
premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind == p.ANDROIDPROJ then
elements = {
android.antPackage,
}
end
return elements
end)
premake.override(vc2010, "importDefaultProps", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.Default.props" />')
else
oldfn(prj)
end
end)
premake.override(vc2010, "importLanguageSettings", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.props" />')
else
oldfn(prj)
end
end)
premake.override(vc2010, "propertySheets", function(oldfn, cfg)
if cfg.kind ~= p.ANDROIDPROJ then
oldfn(cfg)
end
end)
premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg)
if cfg.kind == p.ANDROIDPROJ then
return {
android.outDir,
}
else
return oldfn(cfg)
end
end)
function android.outDir(cfg)
vc2010.element("OutDir", nil, "%s\\", cfg.buildtarget.directory)
end
premake.override(vc2010, "importLanguageTargets", function(oldfn, prj)
if prj.kind == p.ANDROIDPROJ then
p.w('<Import Project="$(AndroidTargetsPath)\\Android.targets" />')
else
oldfn(prj)
end
end)
function android.link(cfg, file)
-- default the seperator to '/' as that is what is searched for
-- below. Otherwise the function will use target seperator which
-- could be '\\' and result in failure to create links.
local fname = path.translate(file.relpath, '/')
-- Files that live outside of the project tree need to be "linked"
-- and provided with a project relative pseudo-path. Check for any
-- leading "../" sequences and, if found, remove them and mark this
-- path as external.
local link, count = fname:gsub("%.%.%/", "")
local external = (count > 0) or fname:find(':', 1, true) or (file.vpath and file.vpath ~= file.relpath)
-- Try to provide a little bit of flexibility by allowing virtual
-- paths for external files. Would be great to support them for all
-- files but Visual Studio chokes if file is already in project area.
if external and file.vpath ~= file.relpath then
link = file.vpath
end
if external then
vc2010.element("Link", nil, path.translate(link))
end
end
vc2010.categories.AndroidManifest = {
name = "AndroidManifest",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AndroidManifest", {vc2010.generatedFile, android.link, android.manifestSubType})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AndroidManifest")
end
}
function android.manifestSubType(cfg, file)
vc2010.element("SubType", nil, "Designer")
end
vc2010.categories.AntBuildXml = {
name = "AntBuildXml",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AntBuildXml", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AntBuildXml")
end
}
vc2010.categories.AntProjectPropertiesFile = {
name = "AntProjectPropertiesFile",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "AntProjectPropertiesFile", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "AntProjectPropertiesFile")
end
}
vc2010.categories.Content = {
name = "Content",
priority = 99,
emitFiles = function(prj, group)
vc2010.emitFiles(prj, group, "Content", {vc2010.generatedFile, android.link})
end,
emitFilter = function(prj, group)
vc2010.filterGroup(prj, group, "Content")
end
}
premake.override(vc2010, "categorizeFile", function(base, prj, file)
if prj.kind ~= p.ANDROIDPROJ then
return base(prj, file)
end
local filename = path.getname(file.name):lower()
if filename == "androidmanifest.xml" then
return vc2010.categories.AndroidManifest
elseif filename == "build.xml" then
return vc2010.categories.AntBuildXml
elseif filename == "project.properties" then
return vc2010.categories.AntProjectPropertiesFile
else
return vc2010.categories.Content
end
end)
|
vpath android.link fix
|
vpath android.link fix
The issue that this solves is that if vpaths is used to resolve the
android needed file paths when they are referenced from other directories
within the directory structure but not considered external files.
|
Lua
|
bsd-3-clause
|
premake/premake-core,dcourtois/premake-core,mandersan/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,starkos/premake-core,noresources/premake-core,tvandijck/premake-core,starkos/premake-core,sleepingwit/premake-core,premake/premake-core,dcourtois/premake-core,starkos/premake-core,LORgames/premake-core,mandersan/premake-core,sleepingwit/premake-core,premake/premake-core,dcourtois/premake-core,dcourtois/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,LORgames/premake-core,starkos/premake-core,noresources/premake-core,premake/premake-core,mandersan/premake-core,noresources/premake-core,sleepingwit/premake-core,LORgames/premake-core,noresources/premake-core,LORgames/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,mandersan/premake-core,starkos/premake-core,starkos/premake-core,tvandijck/premake-core,dcourtois/premake-core,soundsrc/premake-core,tvandijck/premake-core,soundsrc/premake-core,dcourtois/premake-core,LORgames/premake-core,noresources/premake-core,soundsrc/premake-core,noresources/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,noresources/premake-core,premake/premake-core,premake/premake-core,tvandijck/premake-core,mandersan/premake-core,premake/premake-core,starkos/premake-core
|
37f6659ce4191efa66ca8e30002759797e1d1adc
|
MMOCoreORB/bin/scripts/object/tangible/powerup/weapon/melee_generic.lua
|
MMOCoreORB/bin/scripts/object/tangible/powerup/weapon/melee_generic.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_powerup_weapon_melee_generic = object_tangible_powerup_weapon_shared_melee_generic:new {
templateType = POWERUP,
pupType = "Melee",
baseName = "Melee Powerup",
primary = {
{"idealRange", "Ideal Range", "cat_pup.pup_wpn_range_mid"},
{"healthAttackCost", "Balancing", "cat_pup.pup_wpn_attack_cost_health"},
{"mindAttackCost", "Compensating", "cat_pup.pup_wpn_attack_cost_mind"},
{"pointBlankAccuracy", "Precision", "cat_pup.pup_wpn_range_attack_mod_zero"}
},
secondary = {
{"idealAccuracy", "Accuracy", "cat_pup.pup_wpn_range_attack_mod_mid"},
{"attackSpeed", "Control Enhancement", "cat_pup.pup_wpn_attack_speed"},
{"woundsRatio", "Wounding", "cat_pup.pup_wpn_wound_chance"},
{"maxDamage", "Refining", "cat_pup.pup_wpn_damage_max"}
},
factoryCrateSize = 10,
numberExperimentalProperties = {1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "OQ"},
experimentalWeights = {1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "exp_effectiveness"},
experimentalSubGroupTitles = {"null", "null", "hitpoints", "effect"},
experimentalMin = {0, 0, 1000, 1},
experimentalMax = {0, 0, 1000, 100},
experimentalPrecision = {0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 1},
}
ObjectTemplates:addTemplate(object_tangible_powerup_weapon_melee_generic, "object/tangible/powerup/weapon/melee_generic.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_powerup_weapon_melee_generic = object_tangible_powerup_weapon_shared_melee_generic:new {
templateType = POWERUP,
pupType = "Melee",
baseName = "Melee Powerup",
primary = {
{"idealRange", "Ideal Range", "cat_pup.pup_wpn_range_mid"},
{"healthAttackCost", "Balancing", "cat_pup.pup_wpn_attack_cost_health"},
{"mindAttackCost", "Compensating", "cat_pup.pup_wpn_attack_cost_mind"},
{"actionAttackCost", "Cushioning", "cat_pup.pup_wpn_attack_cost_action"},
{"pointBlankAccuracy", "Precision", "cat_pup.pup_wpn_range_attack_mod_zero"}
},
secondary = {
{"idealAccuracy", "Accuracy", "cat_pup.pup_wpn_range_attack_mod_mid"},
{"attackSpeed", "Control Enhancement", "cat_pup.pup_wpn_attack_speed"},
{"woundsRatio", "Wounding", "cat_pup.pup_wpn_wound_chance"},
{"minDamage", "Precision", "cat_pup.pup_wpn_damage_min"},
{"maxDamage", "Refining", "cat_pup.pup_wpn_damage_max"}
},
factoryCrateSize = 10,
numberExperimentalProperties = {1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "OQ"},
experimentalWeights = {1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "exp_effectiveness"},
experimentalSubGroupTitles = {"null", "null", "hitpoints", "effect"},
experimentalMin = {0, 0, 1000, 1},
experimentalMax = {0, 0, 1000, 100},
experimentalPrecision = {0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 1},
}
ObjectTemplates:addTemplate(object_tangible_powerup_weapon_melee_generic, "object/tangible/powerup/weapon/melee_generic.iff")
|
[fixed]mantis 0003683 melee power ups able to have min as a secondary stat and added action cost as a primary stat.
|
[fixed]mantis 0003683 melee power ups able to have min as a secondary
stat and added action cost as a primary stat.
Change-Id: I0fce5f91d84791fc1ea260d160c413947f9d353b
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
c518a94eabc1a27b0efe71a230a42fd1e146176f
|
src/cosy/fixpath/cli.lua
|
src/cosy/fixpath/cli.lua
|
local Lfs = require "lfs"
local Lustache = require "lustache"
local Colors = require 'ansicolors'
local Arguments = require "argparse"
local parser = Arguments () {
name = "cosy-fixpath",
description = "Fix PATH, CPATH, *LIBRARY_PATH in cosy binaries",
}
parser:argument "prefix" {
description = "cosy prefix directory",
}
local arguments = parser:parse ()
local string_mt = getmetatable ""
function string_mt.__mod (pattern, variables)
return Lustache:render (pattern, variables)
end
if Lfs.attributes (arguments.prefix, "mode") ~= "directory" then
print (Colors ("%{bright red blackbg}failure%{reset}"))
end
for filename in Lfs.dir (arguments.prefix .. "/bin") do
if filename:match "^cosy" then
local lines = {}
for line in io.lines (arguments.prefix .. "/bin/" .. filename) do
lines [#lines+1] = line
end
table.insert (lines, 3, "")
table.insert (lines, 3, [[export CPATH="{{{prefix}}}/include:\${CPATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 3, [[export LIBRARY_PATH="{{{prefix}}}/lib:\${LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 3, [[export LD_LIBRARY_PATH="{{{prefix}}}/lib:\${LD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 3, [[export DYLD_LIBRARY_PATH="{{{prefix}}}/lib:\${DYLD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
local file = io.open (arguments.prefix .. "/bin/" .. filename, "w")
file:write (table.concat (lines, "\n") .. "\n")
file:close ()
end
end
print (Colors ("%{bright green blackbg}success%{reset}"))
|
local Lfs = require "lfs"
local Lustache = require "lustache"
local Colors = require 'ansicolors'
local Arguments = require "argparse"
local parser = Arguments () {
name = "cosy-fixpath",
description = "Fix PATH, CPATH, *LIBRARY_PATH in cosy binaries",
}
parser:argument "prefix" {
description = "cosy prefix directory",
}
local arguments = parser:parse ()
local string_mt = getmetatable ""
function string_mt.__mod (pattern, variables)
return Lustache:render (pattern, variables)
end
if Lfs.attributes (arguments.prefix, "mode") ~= "directory" then
print (Colors ("%{bright red blackbg}failure%{reset}"))
end
for filename in Lfs.dir (arguments.prefix .. "/bin") do
if filename:match "^cosy" then
local lines = {}
for line in io.lines (arguments.prefix .. "/bin/" .. filename) do
lines [#lines+1] = line
end
table.insert (lines, 3, [[export CPATH="{{{prefix}}}/include:${CPATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 4, [[export LIBRARY_PATH="{{{prefix}}}/lib:${LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 5, [[export LD_LIBRARY_PATH="{{{prefix}}}/lib:${LD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 6, [[export DYLD_LIBRARY_PATH="{{{prefix}}}/lib:${DYLD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 7, "")
local file = io.open (arguments.prefix .. "/bin/" .. filename, "w")
file:write (table.concat (lines, "\n") .. "\n")
file:close ()
end
end
print (Colors ("%{bright green blackbg}success%{reset}"))
|
Fix fixpath script.
|
Fix fixpath script.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
2efa26b4ad5dd515459ff0bd9fb1d13adc0bf02f
|
util/dependencies.lua
|
util/dependencies.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local fatal;
local function softreq(...) local ok, lib = pcall(require, ...); if ok then return lib; else return nil, lib; end end
local function missingdep(name, sources, msg)
print("");
print("**************************");
print("Prosody was unable to find "..tostring(name));
print("This package can be obtained in the following ways:");
print("");
local longest_platform = 0;
for platform in pairs(sources) do
longest_platform = math.max(longest_platform, #platform);
end
for platform, source in pairs(sources) do
print("", platform..":"..(" "):rep(4+longest_platform-#platform)..source);
end
print("");
print(msg or (name.." is required for Prosody to run, so we will now exit."));
print("More help can be found on our website, at http://prosody.im/doc/depends");
print("**************************");
print("");
end
local lxp = softreq "lxp"
if not lxp then
missingdep("luaexpat", {
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-expat0";
["luarocks"] = "luarocks install luaexpat";
["Source"] = "http://www.keplerproject.org/luaexpat/";
});
fatal = true;
end
local socket = softreq "socket"
if not socket then
missingdep("luasocket", {
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-socket2";
["luarocks"] = "luarocks install luasocket";
["Source"] = "http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/";
});
fatal = true;
end
local lfs, err = softreq "lfs"
if not lfs then
missingdep("luafilesystem", {
["luarocks"] = "luarocks install luafilesystem";
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-luafilesystem0";
["Source"] = "http://www.keplerproject.org/luafilesystem/";
});
fatal = true;
end
local ssl = softreq "ssl"
if not ssl then
if config.get("*", "core", "run_without_ssl") then
log("warn", "Running without SSL support because run_without_ssl is defined in the config");
else
missingdep("LuaSec", {
["Debian/Ubuntu"] = "http://prosody.im/download/start#debian_and_ubuntu";
["luarocks"] = "luarocks install luasec";
["Source"] = "http://www.inf.puc-rio.br/~brunoos/luasec/";
}, "SSL/TLS support will not be available");
end
else
local major, minor, veryminor, patched = ssl._VERSION:match("(%d+)%.(%d+)%.?(%d*)(M?)");
if not major or ((tonumber(major) == 0 and (tonumber(minor) or 0) <= 3 and (tonumber(veryminor) or 0) <= 2) and patched ~= "M") then
log("error", "This version of LuaSec contains a known bug that causes disconnects, see http://prosody.im/doc/depends");
end
end
local encodings, err = softreq "util.encodings"
if not encodings then
if err:match("not found") then
missingdep("util.encodings", { ["Windows"] = "Make sure you have encodings.dll from the Prosody distribution in util/";
["GNU/Linux"] = "Run './configure' and 'make' in the Prosody source directory to build util/encodings.so";
});
else
print "***********************************"
print("util/encodings couldn't be loaded. Check that you have a recent version of libidn");
print ""
print("The full error was:");
print(err)
print "***********************************"
end
fatal = true;
end
local hashes, err = softreq "util.hashes"
if not hashes then
if err:match("not found") then
missingdep("util.hashes", { ["Windows"] = "Make sure you have hashes.dll from the Prosody distribution in util/";
["GNU/Linux"] = "Run './configure' and 'make' in the Prosody source directory to build util/hashes.so";
});
else
print "***********************************"
print("util/hashes couldn't be loaded. Check that you have a recent version of OpenSSL (libcrypto in particular)");
print ""
print("The full error was:");
print(err)
print "***********************************"
end
fatal = true;
end
if fatal then os.exit(1); end
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local fatal;
local function softreq(...) local ok, lib = pcall(require, ...); if ok then return lib; else return nil, lib; end end
local function missingdep(name, sources, msg)
print("");
print("**************************");
print("Prosody was unable to find "..tostring(name));
print("This package can be obtained in the following ways:");
print("");
for k,v in pairs(sources) do
print("", k, v);
end
print("");
print(msg or (name.." is required for Prosody to run, so we will now exit."));
print("More help can be found on our website, at http://prosody.im/doc/depends");
print("**************************");
print("");
end
local lxp = softreq "lxp"
if not lxp then
missingdep("luaexpat", {
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-expat0";
["luarocks"] = "luarocks install luaexpat";
["Source"] = "http://www.keplerproject.org/luaexpat/";
});
fatal = true;
end
local socket = softreq "socket"
if not socket then
missingdep("luasocket", {
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-socket2";
["luarocks"] = "luarocks install luasocket";
["Source"] = "http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/";
});
fatal = true;
end
local lfs, err = softreq "lfs"
if not lfs then
missingdep("luafilesystem", {
["luarocks"] = "luarocks install luafilesystem";
["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-filesystem0";
["Source"] = "http://www.keplerproject.org/luafilesystem/";
});
fatal = true;
end
local ssl = softreq "ssl"
if not ssl then
if config.get("*", "core", "run_without_ssl") then
log("warn", "Running without SSL support because run_without_ssl is defined in the config");
else
missingdep("LuaSec", {
["Debian/Ubuntu"] = "http://prosody.im/download/start#debian_and_ubuntu";
["luarocks"] = "luarocks install luasec";
["Source"] = "http://www.inf.puc-rio.br/~brunoos/luasec/";
}, "SSL/TLS support will not be available");
end
else
local major, minor, veryminor, patched = ssl._VERSION:match("(%d+)%.(%d+)%.?(%d*)(M?)");
if not major or ((tonumber(major) == 0 and (tonumber(minor) or 0) <= 3 and (tonumber(veryminor) or 0) <= 2) and patched ~= "M") then
log("error", "This version of LuaSec contains a known bug that causes disconnects, see http://prosody.im/doc/depends");
end
end
local encodings, err = softreq "util.encodings"
if not encodings then
if err:match("not found") then
missingdep("util.encodings", { ["Windows"] = "Make sure you have encodings.dll from the Prosody distribution in util/";
["GNU/Linux"] = "Run './configure' and 'make' in the Prosody source directory to build util/encodings.so";
});
else
print "***********************************"
print("util/encodings couldn't be loaded. Check that you have a recent version of libidn");
print ""
print("The full error was:");
print(err)
print "***********************************"
end
fatal = true;
end
local hashes, err = softreq "util.hashes"
if not hashes then
if err:match("not found") then
missingdep("util.hashes", { ["Windows"] = "Make sure you have hashes.dll from the Prosody distribution in util/";
["GNU/Linux"] = "Run './configure' and 'make' in the Prosody source directory to build util/hashes.so";
});
else
print "***********************************"
print("util/hashes couldn't be loaded. Check that you have a recent version of OpenSSL (libcrypto in particular)");
print ""
print("The full error was:");
print(err)
print "***********************************"
end
fatal = true;
end
if fatal then os.exit(1); end
|
util.dependencies: Fix package name of LuaFilesystem
|
util.dependencies: Fix package name of LuaFilesystem
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
f69b04373f6a76a1797d9bca69109e5faf729bc3
|
.config/nvim/lua/modules/lsp/lua-language-server.lua
|
.config/nvim/lua/modules/lsp/lua-language-server.lua
|
-- see https://www.chrisatmachine.com/Neovim/28-neovim-lua-development/ for how to
--install the lua-language-server
local M = {}
local system_name
if vim.fn.has("mac") == 1 then
system_name = "macOS"
elseif vim.fn.has("unix") == 1 then
system_name = "Linux"
elseif vim.fn.has("win32") == 1 then
system_name = "Windows"
else
print("Unsupported system for sumneko")
end
-- install the language server at ~/code/lua-language-server
-- see https://github.com/sumneko/lua-language-server/wiki/Build-and-Run
local sumneko_root_path = os.getenv("HOME") .. "/code/lua-language-server"
local sumneko_binary = sumneko_root_path .. "/bin/" .. system_name .. "/lua-language-server"
function M.setup(opts)
opts = opts or {}
opts.cmd = {sumneko_binary, "-E", sumneko_root_path .. "/main.lua"}
opts.settings = {
Lua = {
runtime = {
version = "LuaJIT",
path = vim.split(package.path, ";")
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {"vim"}
},
workspace = {
-- Make the server aware of Neovim runtime files
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true
}
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false
}
}
}
require "lspconfig".sumneko_lua.setup(opts)
end
return M
|
-- see https://www.chrisatmachine.com/Neovim/28-neovim-lua-development/ for how to
--install the lua-language-server
local M = {}
-- install the language server at ~/code/lua-language-server
-- see https://github.com/sumneko/lua-language-server/wiki/Build-and-Run
local sumneko_root_path = os.getenv("HOME") .. "/code/lua-language-server"
local sumneko_binary = sumneko_root_path .. "/bin/lua-language-server"
function M.setup(opts)
opts = opts or {}
opts.cmd = {sumneko_binary, "-E", sumneko_root_path .. "/main.lua"}
opts.settings = {
Lua = {
runtime = {
version = "LuaJIT",
path = vim.split(package.path, ";")
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {"vim"}
},
workspace = {
-- Make the server aware of Neovim runtime files
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true
}
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false
}
}
}
require "lspconfig".sumneko_lua.setup(opts)
end
return M
|
fix(lua-language-server.lua): update lua binary path
|
fix(lua-language-server.lua): update lua binary path
|
Lua
|
mit
|
larrybotha/dotfiles,larrybotha/dotfiles
|
887edd8b53b1bdd9bf8ab8d75a7d4faa4779142b
|
src/luarocks/persist.lua
|
src/luarocks/persist.lua
|
--- Utility module for loading files into tables and
-- saving tables into files.
-- Implemented separately to avoid interdependencies,
-- as it is used in the bootstrapping stage of the cfg module.
local persist = {}
package.loaded["luarocks.persist"] = persist
local util = require("luarocks.util")
--- Load and run a Lua file in an environment.
-- @param filename string: the name of the file.
-- @param env table: the environment table.
-- @return (true, any) or (nil, string, string): true and the return value
-- of the file, or nil, an error message and an error code ("open", "load"
-- or "run") in case of errors.
local function run_file(filename, env)
local fd, err = io.open(filename)
if not fd then
return nil, err, "open"
end
local str, err = fd:read("*a")
fd:close()
if not str then
return nil, err, "open"
end
str = str:gsub("^#![^\n]*\n", "")
local chunk, ran
if _VERSION == "Lua 5.1" then -- Lua 5.1
chunk, err = loadstring(str, filename)
if chunk then
setfenv(chunk, env)
ran, err = pcall(chunk)
end
else -- Lua 5.2
chunk, err = load(str, filename, "t", env)
if chunk then
ran, err = pcall(chunk)
end
end
if not chunk then
return nil, "Error loading file: "..err, "load"
end
if not ran then
return nil, "Error running file: "..err, "run"
end
return true, err
end
--- Load a Lua file containing assignments, storing them in a table.
-- The global environment is not propagated to the loaded file.
-- @param filename string: the name of the file.
-- @param tbl table or nil: if given, this table is used to store
-- loaded values.
-- @return (table, table) or (nil, string, string): a table with the file's assignments
-- as fields and set of undefined globals accessed in file,
-- or nil, an error message and an error code ("open"; couldn't open the file,
-- "load"; compile-time error, or "run"; run-time error)
-- in case of errors.
function persist.load_into_table(filename, tbl)
assert(type(filename) == "string")
assert(type(tbl) == "table" or not tbl)
local result = tbl or {}
local globals = {}
local globals_mt = {
__index = function(t, k)
globals[k] = true
end
}
local save_mt = getmetatable(result)
setmetatable(result, globals_mt)
local ok, err, errcode = run_file(filename, result)
setmetatable(result, save_mt)
if not ok then
return nil, err, errcode
end
return result, globals
end
local write_table
--- Write a value as Lua code.
-- This function handles only numbers and strings, invoking write_table
-- to write tables.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param v: the value to be written.
-- @param level number: the indentation level
-- @param sub_order table: optional prioritization table
-- @see write_table
local function write_value(out, v, level, sub_order)
if type(v) == "table" then
write_table(out, v, level + 1, sub_order)
elseif type(v) == "string" then
if v:match("[\r\n]") then
local open, close = "[[", "]]"
local equals = 0
while v:find(close, 1, true) do
equals = equals + 1
local eqs = ("="):rep(equals)
open, close = "["..eqs.."[", "]"..eqs.."]"
end
out:write(open.."\n"..v..close)
else
out:write("\""..v:gsub("\\", "\\\\"):gsub("\"", "\\\"").."\"")
end
else
out:write(tostring(v))
end
end
--- Write a table as Lua code in curly brackets notation to a writer object.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param level number: the indentation level
-- @param field_order table: optional prioritization table
write_table = function(out, tbl, level, field_order)
out:write("{")
local sep = "\n"
local indentation = " "
local indent = true
local i = 1
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(sep)
if indent then
for n = 1,level do out:write(indentation) end
end
if k == i then
i = i + 1
else
if type(k) == "string" and k:match("^[a-zA-Z_][a-zA-Z0-9_]*$") then
out:write(k)
else
out:write("[")
write_value(out, k, level)
out:write("]")
end
out:write(" = ")
end
write_value(out, v, level, sub_order)
if type(v) == "number" then
sep = ", "
indent = false
else
sep = ",\n"
indent = true
end
end
if sep ~= "\n" then
out:write("\n")
for n = 1,level-1 do out:write(indentation) end
end
out:write("}")
end
--- Write a table as series of assignments to a writer object.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param field_order table: optional prioritization table
local function write_table_as_assignments(out, tbl, field_order)
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(k.." = ")
write_value(out, v, 0, sub_order)
out:write("\n")
end
end
--- Save the contents of a table to a string.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return string
function persist.save_from_table_to_string(tbl, field_order)
local out = {buffer = {}}
function out:write(data) table.insert(self.buffer, data) end
write_table_as_assignments(out, tbl, field_order)
return table.concat(out.buffer)
end
--- Save the contents of a table in a file.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param filename string: the output filename
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return boolean or (nil, string): true if successful, or nil and a
-- message in case of errors.
function persist.save_from_table(filename, tbl, field_order)
local out = io.open(filename, "w")
if not out then
return nil, "Cannot create file at "..filename
end
write_table_as_assignments(out, tbl, field_order)
out:close()
return true
end
return persist
|
--- Utility module for loading files into tables and
-- saving tables into files.
-- Implemented separately to avoid interdependencies,
-- as it is used in the bootstrapping stage of the cfg module.
local persist = {}
package.loaded["luarocks.persist"] = persist
local util = require("luarocks.util")
--- Load and run a Lua file in an environment.
-- @param filename string: the name of the file.
-- @param env table: the environment table.
-- @return (true, any) or (nil, string, string): true and the return value
-- of the file, or nil, an error message and an error code ("open", "load"
-- or "run") in case of errors.
local function run_file(filename, env)
local fd, err = io.open(filename)
if not fd then
return nil, err, "open"
end
local str, err = fd:read("*a")
fd:close()
if not str then
return nil, err, "open"
end
str = str:gsub("^#![^\n]*\n", "")
local chunk, ran
if _VERSION == "Lua 5.1" then -- Lua 5.1
chunk, err = loadstring(str, filename)
if chunk then
setfenv(chunk, env)
ran, err = pcall(chunk)
end
else -- Lua 5.2
chunk, err = load(str, filename, "t", env)
if chunk then
ran, err = pcall(chunk)
end
end
if not chunk then
return nil, "Error loading file: "..err, "load"
end
if not ran then
return nil, "Error running file: "..err, "run"
end
return true, err
end
--- Load a Lua file containing assignments, storing them in a table.
-- The global environment is not propagated to the loaded file.
-- @param filename string: the name of the file.
-- @param tbl table or nil: if given, this table is used to store
-- loaded values.
-- @return (table, table) or (nil, string, string): a table with the file's assignments
-- as fields and set of undefined globals accessed in file,
-- or nil, an error message and an error code ("open"; couldn't open the file,
-- "load"; compile-time error, or "run"; run-time error)
-- in case of errors.
function persist.load_into_table(filename, tbl)
assert(type(filename) == "string")
assert(type(tbl) == "table" or not tbl)
local result = tbl or {}
local globals = {}
local globals_mt = {
__index = function(t, k)
globals[k] = true
end
}
local save_mt = getmetatable(result)
setmetatable(result, globals_mt)
local ok, err, errcode = run_file(filename, result)
setmetatable(result, save_mt)
if not ok then
return nil, err, errcode
end
return result, globals
end
local write_table
--- Write a value as Lua code.
-- This function handles only numbers and strings, invoking write_table
-- to write tables.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param v: the value to be written.
-- @param level number: the indentation level
-- @param sub_order table: optional prioritization table
-- @see write_table
local function write_value(out, v, level, sub_order)
if type(v) == "table" then
write_table(out, v, level + 1, sub_order)
elseif type(v) == "string" then
if v:match("[\r\n]") then
local open, close = "[[", "]]"
local equals = 0
local v_with_bracket = v.."]"
while v_with_bracket:find(close, 1, true) do
equals = equals + 1
local eqs = ("="):rep(equals)
open, close = "["..eqs.."[", "]"..eqs.."]"
end
out:write(open.."\n"..v..close)
else
out:write("\""..v:gsub("\\", "\\\\"):gsub("\"", "\\\"").."\"")
end
else
out:write(tostring(v))
end
end
--- Write a table as Lua code in curly brackets notation to a writer object.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param level number: the indentation level
-- @param field_order table: optional prioritization table
write_table = function(out, tbl, level, field_order)
out:write("{")
local sep = "\n"
local indentation = " "
local indent = true
local i = 1
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(sep)
if indent then
for n = 1,level do out:write(indentation) end
end
if k == i then
i = i + 1
else
if type(k) == "string" and k:match("^[a-zA-Z_][a-zA-Z0-9_]*$") then
out:write(k)
else
out:write("[")
write_value(out, k, level)
out:write("]")
end
out:write(" = ")
end
write_value(out, v, level, sub_order)
if type(v) == "number" then
sep = ", "
indent = false
else
sep = ",\n"
indent = true
end
end
if sep ~= "\n" then
out:write("\n")
for n = 1,level-1 do out:write(indentation) end
end
out:write("}")
end
--- Write a table as series of assignments to a writer object.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param field_order table: optional prioritization table
local function write_table_as_assignments(out, tbl, field_order)
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(k.." = ")
write_value(out, v, 0, sub_order)
out:write("\n")
end
end
--- Save the contents of a table to a string.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return string
function persist.save_from_table_to_string(tbl, field_order)
local out = {buffer = {}}
function out:write(data) table.insert(self.buffer, data) end
write_table_as_assignments(out, tbl, field_order)
return table.concat(out.buffer)
end
--- Save the contents of a table in a file.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param filename string: the output filename
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return boolean or (nil, string): true if successful, or nil and a
-- message in case of errors.
function persist.save_from_table(filename, tbl, field_order)
local out = io.open(filename, "w")
if not out then
return nil, "Cannot create file at "..filename
end
write_table_as_assignments(out, tbl, field_order)
out:close()
return true
end
return persist
|
Fix persist for multiline strings ending with closing bracket prefix
|
Fix persist for multiline strings ending with closing bracket prefix
|
Lua
|
mit
|
xpol/luavm,xpol/luainstaller,tarantool/luarocks,robooo/luarocks,tarantool/luarocks,tarantool/luarocks,xpol/luavm,xpol/luavm,luarocks/luarocks,keplerproject/luarocks,robooo/luarocks,xpol/luarocks,xpol/luavm,keplerproject/luarocks,xpol/luainstaller,robooo/luarocks,xpol/luavm,xpol/luarocks,luarocks/luarocks,xpol/luarocks,luarocks/luarocks,xpol/luarocks,xpol/luainstaller,robooo/luarocks,keplerproject/luarocks,keplerproject/luarocks,xpol/luainstaller
|
ee2dd7bdf774c414674e06b3ff273521062ab7f1
|
whisper.lua
|
whisper.lua
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if not msg:match("epgp standby") then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
member = member:sub(1,1):upper()..member:sub(2):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(event_name, names, reason, amount)
EPGP:GetModule("announce"):Announce(
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
for member, sender in pairs(senderMap) do
if EPGP:IsMemberInExtrasList(member) then
SendChatMessage(L["%+d EP (%s) to %s"]:format(amount, reason, member),
"WHISPER", nil, sender)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
end
senderMap[member] = nil
end
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if not msg:match("epgp standby") then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
member = member:sub(1,1):upper()..member:sub(2):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(event_name, names, reason, amount)
EPGP:GetModule("announce"):Announce(
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
for member, sender in pairs(senderMap) do
if EPGP:IsMemberInExtrasList(member) then
SendChatMessage(L["%+d EP (%s) to %s"]:format(amount, reason, member),
"WHISPER", nil, sender)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
end
senderMap[member] = nil
end
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
Fix issue 343. Whisper mod now disables announces properly when disabled.
|
Fix issue 343. Whisper mod now disables announces properly when disabled.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,ceason/epgp-tfatf,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp
|
75180c469475818247e0ce09d73a4cadcb25620d
|
stdlib/event/changes.lua
|
stdlib/event/changes.lua
|
--- Configuration changed event handling.
-- This module registers events
-- @module Changes
-- @usage require('__stdlib__/stdlib/event/changes')
local Event = require('__stdlib__/stdlib/event/event')
local Changes = {
_module = 'Changes'
}
setmetatable(Changes, require('__stdlib__/stdlib/core'))
--[[
ConfigurationChangedData
Table with the following fields:
old_version :: string (optional): Old version of the map. Present only when loading map version other than the current version.
new_version :: string (optional): New version of the map. Present only when loading map version other than the current version.
mod_changes :: dictionary string → ModConfigurationChangedData: Dictionary of mod changes. It is indexed by mod name.
ModConfigurationChangedData
Table with the following fields:
old_version :: string: Old version of the mod. May be nil if the mod wasn't previously present (i.e. it was just added).
new_version :: string: New version of the mod. May be nil if the mod is no longer present (i.e. it was just removed).
--]]
Changes.versions = prequire('__stdlib__/stdlib/changes/versions') or {}
Changes['map-change-always-first'] = prequire('__stdlib__/stdlib/changes/map-change-always-first')
Changes['any-change-always-first'] = prequire('__stdlib__/stdlib/changes/any-change-always-first')
Changes['mod-change-always-first'] = prequire('__stdlib__/stdlib/changes/mod-change-always-first')
Changes['mod-change-always-last'] = prequire('__stdlib__/stdlib/changes/mod-change-always-last')
Changes['any-change-always-last'] = prequire('__stdlib__/stdlib/changes/any-change-always-last')
Changes['map-change-always-last'] = prequire('__stdlib__/stdlib/changes/map-change-always-last')
local function run_if_exists(func)
return func and type(func) == 'function' and func()
end
--[Mark all migrations as complete during Init]--
function Changes.on_init()
local list = {}
local cur_version = game.active_mods[script.mod_name]
for ver in pairs(Changes.versions) do
list[ver] = cur_version
end
global._changes = list
end
function Changes.on_configuration_changed(event)
run_if_exists(Changes['map-change-always-first'])
if event.mod_changes then
run_if_exists(Changes['any-change-always-first'])
if event.mod_changes[script.mod_name] then
run_if_exists(Changes['mod-change-always-first'])
local this_mod_changes = event.mod_changes[script.mod_name]
Changes.on_mod_changed(this_mod_changes)
log('Version changed from ' .. tostring(this_mod_changes.old_version) .. ' to ' .. tostring(this_mod_changes.new_version))
run_if_exists(Changes['mod-change-always-last'])
end
run_if_exists(Changes['any-change-always-last'])
end
run_if_exists(Changes['map-change-always-last'])
end
function Changes.on_mod_changed(this_mod_changes)
global._changes = global._changes or {}
local old = this_mod_changes.old_version
if old then -- Find the last installed version
for ver, func in pairs(Changes.versions) do
if not global._changes[ver] then
run_if_exists(func)
global._changes[ver] = old
log('Migration completed for version ' .. ver)
end
end
end
end
function Changes.register_events()
Event.register(Event.core_events.configuration_changed, Changes.on_configuration_changed)
Event.register(Event.core_events.init, Changes.on_init)
return Changes
end
--[Always run these before any migrations]--
--Changes["map-change-always-first"] = function() end
--Changes["any-change-always-first"] = function() end
--Changes["mod-change-always-first"] = function() end
--Mod version changes made
--Changes.version["0.0.1"] = function() end
--[Always run these at the end]--
--Changes["mod-change-always-last"] = function() end
--Changes["any-change-always-last"] = function() end
--Changes["map-change-always-last"] = function() end
return Changes
|
--- Configuration changed event handling.
-- This module registers events
-- @module Changes
-- @usage require('__stdlib__/stdlib/event/changes')
local Event = require('__stdlib__/stdlib/event/event')
local Changes = {
_module = 'Changes'
}
setmetatable(Changes, require('__stdlib__/stdlib/core'))
--[[
ConfigurationChangedData
Table with the following fields:
old_version :: string (optional): Old version of the map. Present only when loading map version other than the current version.
new_version :: string (optional): New version of the map. Present only when loading map version other than the current version.
mod_changes :: dictionary string → ModConfigurationChangedData: Dictionary of mod changes. It is indexed by mod name.
ModConfigurationChangedData
Table with the following fields:
old_version :: string: Old version of the mod. May be nil if the mod wasn't previously present (i.e. it was just added).
new_version :: string: New version of the mod. May be nil if the mod is no longer present (i.e. it was just removed).
--]]
Changes.versions = prequire('changes/versions') or {}
Changes['map-change-always-first'] = prequire('changes/map-change-always-first')
Changes['any-change-always-first'] = prequire('changes/any-change-always-first')
Changes['mod-change-always-first'] = prequire('changes/mod-change-always-first')
Changes['mod-change-always-last'] = prequire('changes/mod-change-always-last')
Changes['any-change-always-last'] = prequire('changes/any-change-always-last')
Changes['map-change-always-last'] = prequire('changes/map-change-always-last')
local function run_if_exists(func)
return func and type(func) == 'function' and func()
end
--[Mark all migrations as complete during Init]--
function Changes.on_init()
local list = {}
local cur_version = game.active_mods[script.mod_name]
for ver in pairs(Changes.versions) do
list[ver] = cur_version
end
global._changes = list
end
function Changes.on_configuration_changed(event)
run_if_exists(Changes['map-change-always-first'])
if event.mod_changes then
run_if_exists(Changes['any-change-always-first'])
if event.mod_changes[script.mod_name] then
run_if_exists(Changes['mod-change-always-first'])
local this_mod_changes = event.mod_changes[script.mod_name]
Changes.on_mod_changed(this_mod_changes)
log('Version changed from ' .. tostring(this_mod_changes.old_version) .. ' to ' .. tostring(this_mod_changes.new_version))
run_if_exists(Changes['mod-change-always-last'])
end
run_if_exists(Changes['any-change-always-last'])
end
run_if_exists(Changes['map-change-always-last'])
end
function Changes.on_mod_changed(this_mod_changes)
global._changes = global._changes or {}
local old = this_mod_changes.old_version
if old then -- Find the last installed version
for ver, func in pairs(Changes.versions) do
if not global._changes[ver] then
run_if_exists(func)
global._changes[ver] = old
log('Migration completed for version ' .. ver)
end
end
end
end
function Changes.register_events()
Event.register(Event.core_events.configuration_changed, Changes.on_configuration_changed)
Event.register(Event.core_events.init, Changes.on_init)
return Changes
end
--[Always run these before any migrations]--
--Changes["map-change-always-first"] = function() end
--Changes["any-change-always-first"] = function() end
--Changes["mod-change-always-first"] = function() end
--Mod version changes made
--Changes.version["0.0.1"] = function() end
--[Always run these at the end]--
--Changes["mod-change-always-last"] = function() end
--Changes["any-change-always-last"] = function() end
--Changes["map-change-always-last"] = function() end
return Changes
|
Fix Changes not loading version files correctly
|
Fix Changes not loading version files correctly
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
552f1026aa1f9ae903bfdce05b8ec954c7df8e36
|
tasks/dm1.lua
|
tasks/dm1.lua
|
local M = {}
local toribio = require 'toribio'
local sched = require 'lumen.sched'
local log = require 'lumen.log'
local selector = require 'lumen.tasks.selector'
local encoder_lib = require ('lumen.lib.dkjson')
local encode_f = encoder_lib.encode
local decode_f = encoder_lib.decode
local assert, tonumber, io_open = assert, tonumber, io.open
local cos, sin, tan, abs = math.cos, math.sin, math.tan, math.abs
local p, d = 0.182, 0.190 --dimensions
local d_p = d/p
local sig_drive_control = {}
local sigs_drive = {
[0] = sig_drive_control
}
local function read_pote(filepot)
local fdpot = assert(io_open(filepot, 'rb'))
local data, err = fdpot:read('*l')
fdpot:close()
return data, err
end
M.init = function(conf)
for i, chassis in ipairs(conf.motors) do
log('DM1', 'INFO', 'Initializing chassis %i', i)
local sig_angle = {}
sigs_drive[i] = {}
local angle, last_pot, fmodule, fangle = 0, -1000000, 0, 0
if i>1 then
local ipot=i-1
local pot_calibration = conf.pots[ipot].calibration or conf.pot.calibration or {{0,-90}, {2048, 0}, {4096, 90}}
log('DM1', 'INFO', 'Calibrating potentiometer as %s -> %s, %s -> %s, %s -> %s',
tostring(pot_calibration[1][1]), tostring(pot_calibration[1][2]),
tostring(pot_calibration[2][1]), tostring(pot_calibration[2][2]),
tostring(pot_calibration[3][1]), tostring(pot_calibration[3][2]))
local calibrator = require 'tasks.dm1.calibrator'(pot_calibration)
local filepot = conf.pots[ipot].file or conf.pot.file or '/sys/devices/ocp.3/helper.15/AIN1'
log('DM1', 'INFO', 'Using %s as potentiometer input', filepot)
--task to poll the pot
sched.run(function()
local rate, threshold = conf.pot.rate, conf.pot.threshold
while true do
local pot_reading = tonumber( assert(read_pote(filepot)) )
if abs(pot_reading-last_pot) > threshold then
last_pot, angle = pot_reading, calibrator(tonumber(pot_reading))
sched.signal(sig_angle)
end
sched.sleep(rate)
end
end):set_as_attached()
else
--TODO
end
sched.run(function()
log('DM1', 'INFO', 'Motors: left %s, right %s', chassis.left, chassis.right)
local motor_left = toribio.wait_for_device(chassis.left)
local motor_right = toribio.wait_for_device(chassis.right)
motor_left.set.rotation_mode('wheel')
motor_right.set.rotation_mode('wheel')
local sig_drive_in = sigs_drive[i-1]
local sig_drive_out = sigs_drive[i]
sched.sigrun( {sig_drive_in, sig_angle, buff_mode='keep_last'}, function(sig,in_fmodule,in_fangle)
if sig==sig_drive_in then fmodule, fangle = in_fmodule, in_fangle end
log('DM1', 'DEBUG', 'Drive: module %s, angle %s', tostring(fmodule), tostring(fangle))
local fx = fmodule * cos(fangle)
local fy = fmodule * sin(fangle)
local out_r = fx - d_p*fy
local out_l = fx + d_p*fy
log('DM1', 'DEBUG', 'Out: left %s, right %s', tostring(out_l), tostring(out_r))
motor_left.set.moving_speed(-out_r)
motor_right.set.moving_speed(out_l)
sched.signal(sig_drive_out, fmodule, fangle)
end)
log('DM1', 'INFO', 'Motors left %s and right %s ready', chassis.left, chassis.right)
end)
end
-- HTTP RC
if conf.http_server then
local http_server = require "lumen.tasks.http-server"
--http_server.serve_static_content_from_stream('/docs/', './docs')
http_server.serve_static_content_from_ram('/', './tasks/dm1/www')
http_server.set_websocket_protocol('dm1-rc-protocol', function(ws)
sched.run(function()
while true do
local message,opcode = ws:receive()
log('DM1', 'DEBUG', 'websocket traffic "%s"', tostring(message))
if not message then
sched.signal(sig_drive_control, 0, 0)
ws:close()
return
end
if opcode == ws.TEXT then
local decoded, index, e = decode_f(message)
if decoded then
if decoded.action == 'drive' then
sched.signal(sig_drive_control, decoded.module, decoded.angle)
end
else
log('DM1', 'ERROR', 'failed to decode message with length %s with error "%s"',
tostring(#message), tostring(index).." "..tostring(e))
end
end
end
end) --:set_as_attached()
end)
conf.http_server.ws_enable = true
http_server.init(conf.http_server)
end
-- /HTTP RC
-- UDP RC
if conf.udp then
local udp = selector.new_udp(nil, nil, conf.udp.ip, conf.udp.port, -1)
--listen for messages
sched.sigrun({udp.events.data, buff_mode='keep_last'}, function(_, msg)
local fmodule, fangle
if msg then
fmodule, fangle = msg:match('^([^,]+),([^,]+)$')
--print("!U", left, right)
else
fmodule, fangle = 0, 0
end
sched.signal(sig_drive_control, fmodule, fangle)
end)
end
-- /UDP RC
end
return M
|
local M = {}
local toribio = require 'toribio'
local sched = require 'lumen.sched'
local log = require 'lumen.log'
local selector = require 'lumen.tasks.selector'
local encoder_lib = require ('lumen.lib.dkjson')
local encode_f = encoder_lib.encode
local decode_f = encoder_lib.decode
local assert, tonumber, io_open, tostring = assert, tonumber, io.open, tostring
local cos, sin, tan, abs = math.cos, math.sin, math.tan, math.abs
local p, d = 0.182, 0.190 --dimensions
local d_p = d/p
local sig_drive_control = {}
local sigs_drive = {
[0] = sig_drive_control
}
local function read_pote(filepot)
local fdpot = assert(io_open(filepot, 'rb'))
local data, err = fdpot:read('*l')
fdpot:close()
return data, err
end
M.init = function(conf)
for i, chassis in ipairs(conf.motors) do
log('DM1', 'INFO', 'Initializing chassis %i', i)
local sig_angle = {}
sigs_drive[i] = {}
if i>1 then
local ipot=i-1
local filepot = conf.pots[ipot].file or conf.pot.file or '/sys/devices/ocp.3/helper.15/AIN1'
log('DM1', 'INFO', 'Using %s as potentiometer input', filepot)
local pot_calibration = assert(conf.pots[ipot].calibration or conf.pot.calibration,
'Missing calibration for '..filepot )
log('DM1', 'INFO', 'Calibrating potentiometer as %s -> %s, %s -> %s, %s -> %s',
tostring(pot_calibration[1][1]), tostring(pot_calibration[1][2]),
tostring(pot_calibration[2][1]), tostring(pot_calibration[2][2]),
tostring(pot_calibration[3][1]), tostring(pot_calibration[3][2]))
local calibrator = require 'tasks.dm1.calibrator'(pot_calibration)
--task to poll the pot
sched.run(function()
local last_pot = -1000000
local rate, threshold = conf.pot.rate, conf.pot.threshold
while true do
local pot_reading = tonumber( assert(read_pote(filepot)) )
if abs(pot_reading-last_pot) > threshold then
last_pot = pot_reading
sched.signal(sig_angle, calibrator(tonumber(pot_reading)))
end
sched.sleep(rate)
end
end):set_as_attached()
end
sched.run(function()
log('DM1', 'INFO', 'Motors: left %s, right %s', chassis.left, chassis.right)
local motor_left = toribio.wait_for_device(chassis.left)
local motor_right = toribio.wait_for_device(chassis.right)
motor_left.set.rotation_mode('wheel')
motor_right.set.rotation_mode('wheel')
local sig_drive_in = sigs_drive[i-1]
local sig_drive_out = sigs_drive[i]
local pangle, fmodule, fangle = 0, 0, 0
sched.sigrun( {sig_drive_in, sig_angle, buff_mode='keep_last'}, function(sig,par1,par2)
if sig==sig_drive_in then
fmodule, fangle = par1, par2
elseif sig==sig_angle then
pangle = par1
end
log('DM1', 'DEBUG', 'Drive: module %s, angle %s, pot %s',
tostring(fmodule), tostring(fangle), tostring(pangle))
local fx = fmodule * cos(fangle+pangle)
local fy = fmodule * sin(fangle+pangle)
local out_r = fx - d_p*fy
local out_l = fx + d_p*fy
log('DM1', 'DEBUG', 'Out: left %s, right %s', tostring(out_l), tostring(out_r))
motor_left.set.moving_speed(-out_r)
motor_right.set.moving_speed(out_l)
sched.signal(sig_drive_out, fmodule, fangle)
end)
log('DM1', 'INFO', 'Motors left %s and right %s ready', chassis.left, chassis.right)
end)
end
-- HTTP RC
if conf.http_server then
local http_server = require "lumen.tasks.http-server"
--http_server.serve_static_content_from_stream('/docs/', './docs')
http_server.serve_static_content_from_ram('/', './tasks/dm1/www')
http_server.set_websocket_protocol('dm1-rc-protocol', function(ws)
sched.run(function()
while true do
local message,opcode = ws:receive()
log('DM1', 'DEBUG', 'websocket traffic "%s"', tostring(message))
if not message then
sched.signal(sig_drive_control, 0, 0)
ws:close()
return
end
if opcode == ws.TEXT then
local decoded, index, e = decode_f(message)
if decoded then
if decoded.action == 'drive' then
sched.signal(sig_drive_control, decoded.module, decoded.angle)
end
else
log('DM1', 'ERROR', 'failed to decode message with length %s with error "%s"',
tostring(#message), tostring(index).." "..tostring(e))
end
end
end
end) --:set_as_attached()
end)
conf.http_server.ws_enable = true
http_server.init(conf.http_server)
end
-- /HTTP RC
-- UDP RC
if conf.udp then
local udp = selector.new_udp(nil, nil, conf.udp.ip, conf.udp.port, -1)
--listen for messages
sched.sigrun({udp.events.data, buff_mode='keep_last'}, function(_, msg)
local fmodule, fangle
if msg then
fmodule, fangle = msg:match('^([^,]+),([^,]+)$')
--print("!U", left, right)
else
fmodule, fangle = 0, 0
end
sched.signal(sig_drive_control, fmodule, fangle)
end)
end
-- /UDP RC
end
return M
|
fix pot angle handling, cleanup
|
fix pot angle handling, cleanup
|
Lua
|
mit
|
xopxe/Toribio,xopxe/Toribio,xopxe/Toribio
|
6f4b1b9b1a215f5baf6dcdb2484fb33421d1f3fc
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:hook("stream-features",
function (event)
event.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (event)
event.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fixed to use the correct events API.
|
mod_smacks: Fixed to use the correct events API.
|
Lua
|
mit
|
vince06fr/prosody-modules,olax/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,softer/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,prosody-modules/import,dhotson/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules
|
aed97d24433c87ae8f25f45bedb6e7c7672b1823
|
src/armor.lua
|
src/armor.lua
|
function getArmor(index)
local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1]
return armor
end
function armorCheck(index)
local armor = getArmor(index)
if armor.grid ~= nil then
return true
end
return false
end
script.on_event(defines.events.on_player_armor_inventory_changed, function(event)
local index = event.player_index
if armorCheck(index) then
local armor = getArmor(index)
local equipment = armor.grid.equipment
for i, e in ipairs(equipment) do
if e.name == "hoverboard" then
activateEquipment(index)
end
end
else
deactivateEquipment(index)
end
end)
|
function getArmor(index)
local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1]
if armor ~= nil and armor.valid_for_read == true then
return armor
end
return false
end
script.on_event(defines.events.on_player_armor_inventory_changed, function(event)
local index = event.player_index
local armor = getArmor(index)
if armor ~= false then
local equipment = armor.grid.equipment
for i, e in ipairs(equipment) do
if e.name == "hoverboard" then
activateEquipment(index)
end
end
else
deactivateEquipment(index)
end
end)
|
fix and cleanup
|
fix and cleanup
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
4b6aec11efe19d453961465753168d27f473e22c
|
generative-tree/generative-tree.lua
|
generative-tree/generative-tree.lua
|
function shallowcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
function vrandom()
return v(math.random(), math.random(), math.random())
end
function rand_float(min, max)
return min + math.random() * (max-min)
end
function rand_rotate(min, max)
return rotate(rand_float(min, max), rand_float(min, max), rand_float(min, max))
end
function rand_angle(state)
return rand_rotate(-state.angle, state.angle)
end
function flip(limit)
return (math.random() < limit)
end
function tree(state)
local radius = math.sqrt(dot(state.direction, state.direction))
if (radius < state.min_radius) then
return
end
emit(translate(state.origin) * sphere(radius), state.brush)
state.origin = state.origin + state.direction
state.direction = (2/3 + math.random()/3) * state.direction
local rotation = state.rand_angle(state)
state.direction = rotation * state.direction
if flip(state.branching) then
-- print("branching")
local d = shallowcopy(state)
-- d.brush = state.brush + 1
d.direction = rotation * state.direction
tree(d)
end
tree(state)
end
-- UI
if ui_scalar == nil then
function ui_scalar(a, b ,c , d)
return b
end
end
seed = ui_scalar('seed', 1, 1, 1024)
math.randomseed(seed)
radius = ui_scalar('radius', 5, 10, 100)
min_radius = ui_scalar('min radius', 1, 0, 100)
branching = ui_scalar('branching', 20, 0, 100) / 100
max_angle = ui_scalar('max angle', 20, 0, 360)
-- Main
tree{
radius=radius,
branching=branching,
origin=v(0,0,0),
direction=v(0,0,radius),
min_radius=min_radius,
angle=max_angle,
rand_angle = rand_angle,
brush=0
}
emit(intersection(translate(0, 0, -1.3*radius) * sphere(1.3*radius), box(2*1.3*radius)), 1)
|
function shallowcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
function vrandom()
return v(math.random(), math.random(), math.random())
end
function rand_float(min, max)
return min + math.random() * (max-min)
end
function rand_rotate(min, max)
return rotate(rand_float(min, max), rand_float(min, max), rand_float(min, max))
end
function rand_angle(state)
return rand_rotate(-state.angle, state.angle)
end
function flip(limit)
return (math.random() < limit)
end
function tree(state, accShapes)
local radius = math.sqrt(dot(state.direction, state.direction))
if (radius < state.min_radius) then
return accShapes
end
table.insert(accShapes, translate(state.origin) * sphere(radius))
state.origin = state.origin + state.direction
state.direction = (2/3 + math.random()/3) * state.direction
local rotation = state.rand_angle(state)
state.direction = rotation * state.direction
if flip(state.branching) then
-- print("branching")
local d = shallowcopy(state)
-- d.brush = state.brush + 1
d.direction = rotation * state.direction
accShapes = tree(d, accShapes)
end
return tree(state, accShapes)
end
-- UI
if ui_scalar == nil then
function ui_scalar(a, b ,c , d)
return b
end
end
seed = ui_scalar('seed', 1, 1, 1024)
math.randomseed(seed)
radius = ui_scalar('radius', 5, 10, 100)
min_radius = ui_scalar('min radius', 1, 0, 100)
branching = ui_scalar('branching', 20, 0, 100) / 100
max_angle = ui_scalar('max angle', 20, 0, 360)
-- Main
spheres = tree({
radius=radius,
branching=branching,
origin=v(0,0,0),
direction=v(0,0,radius),
min_radius=min_radius,
angle=max_angle,
rand_angle = rand_angle,
brush=0
}, {})
emit(scale(1.5) * merge(spheres))
emit(intersection(translate(0, 0, -1.3*radius) * sphere(1.3*radius), box(2*1.3*radius)), 1)
|
fix(generative-tree): use merge instead of emit
|
fix(generative-tree): use merge instead of emit
|
Lua
|
mit
|
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
|
8f4e283a7121fe0ca64aa03661e00ae8426cd4cf
|
src/conf/ConfigReader.lua
|
src/conf/ConfigReader.lua
|
local ConfigReader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local FILE_NAME = 'settings.cfg';
local TEMPLATE_PATH = 'res/templates/settings_template.cfg';
local INVALID_CONFIG_HEADER = 'Invalid config file';
local MISSING_SECTION_WARNING = 'Seems like the loaded configuration file is missing the [%s] section. The default settings will be used instead.';
local MISSING_VALUE_WARNING = 'Seems like the loaded configuration file is missing the [%s] value in the [%s] section. The default settings will be used instead.';
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local config;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Checks if the settings file exists on the user's system.
--
local function hasConfigFile()
return love.filesystem.isFile( FILE_NAME );
end
---
-- Creates a new settings file on the user's system based on the default template.
-- @param filename - The file name to use for the config file.
-- @param templatePath - The path to the template settings file.
--
local function createConfigFile( filename, templatePath )
for line in love.filesystem.lines( templatePath ) do
love.filesystem.append( filename, line .. '\r\n' );
end
end
---
-- Tries to transform strings to their actual types if possible.
-- @param value - The value to transform.
--
local function toType( value )
value = value:match( '^%s*(.-)%s*$' );
if value == 'true' then
return true;
elseif value == 'false' then
return false;
elseif tonumber( value ) then
return tonumber( value );
else
return value;
end
end
local function loadFile( filePath )
local loadedConfig = {};
local section;
for line in love.filesystem.lines( filePath ) do
if line == '' or line:find( ';' ) == 1 then
-- Ignore comments and empty lines.
elseif line:match( '^%[(%w*)%]$' ) then
-- Create a new section.
local header = line:match( '^%[(%w*)%]$' );
loadedConfig[header] = {};
section = loadedConfig[header];
else
-- Store values in the section.
local key, value = line:match( '^([%g]+)%s-=%s-(.+)' );
-- Store multiple values in a table.
if value and value:find( ',' ) then
section[key] = {};
for val in value:gmatch( '[^, ]+' ) do
section[key][#section[key] + 1] = toType( val );
end
elseif value then
section[key] = toType( value );
end
end
end
return loadedConfig;
end
---
-- Validates a loaded config file by comparing it to the default config file.
-- It checks if the file contains all the necessary sections and values. If it
-- doesn't a warning is displayed and the default config will be used.
-- @param default - The default file to use for comparison.
--
local function validateFile( default )
print( 'Validating configuration file ... ' );
for skey, section in pairs( default ) do
-- If loaded config file doesn't contain section return default.
if config[skey] == nil then
love.window.showMessageBox( INVALID_CONFIG_HEADER, string.format( MISSING_SECTION_WARNING, skey ), 'warning', false );
return default;
end
-- If the loaded config file is missing a value, display warning and return default.
if type( section ) == 'table' then
for vkey, _ in pairs( section ) do
if config[skey][vkey] == nil then
love.window.showMessageBox( INVALID_CONFIG_HEADER, string.format( MISSING_VALUE_WARNING, vkey, skey ), 'warning', false );
return default;
end
end
end
end
print( 'Done!' );
end
---
-- Replaces backslashes in paths with forwardslashes.
--
local function validateRepositoryPaths()
for project, path in pairs( config.repositories ) do
config.repositories[project] = path:gsub( '\\+', '/' );
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function ConfigReader.init()
local default = loadFile( TEMPLATE_PATH );
if not hasConfigFile() then
createConfigFile( FILE_NAME, TEMPLATE_PATH );
end
-- If the config hasn't been loaded yet, load and validate it.
if not config then
config = loadFile( FILE_NAME );
validateFile( default, config );
validateRepositoryPaths();
end
return config;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return ConfigReader;
|
local ConfigReader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local FILE_NAME = 'settings.cfg';
local TEMPLATE_PATH = 'res/templates/settings_template.cfg';
local INVALID_CONFIG_HEADER = 'Invalid config file';
local MISSING_SECTION_WARNING = 'Seems like the loaded configuration file is missing the [%s] section. The default settings will be used instead.';
local MISSING_VALUE_WARNING = 'Seems like the loaded configuration file is missing the [%s] value in the [%s] section. The default settings will be used instead.';
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local config;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Checks if the settings file exists on the user's system.
--
local function hasConfigFile()
return love.filesystem.isFile( FILE_NAME );
end
---
-- Creates a new settings file on the user's system based on the default template.
-- @param filename - The file name to use for the config file.
-- @param templatePath - The path to the template settings file.
--
local function createConfigFile( filename, templatePath )
for line in love.filesystem.lines( templatePath ) do
love.filesystem.append( filename, line .. '\r\n' );
end
end
---
-- Tries to transform strings to their actual types if possible.
-- @param value - The value to transform.
--
local function toType( value )
value = value:match( '^%s*(.-)%s*$' );
if value == 'true' then
return true;
elseif value == 'false' then
return false;
elseif tonumber( value ) then
return tonumber( value );
else
return value;
end
end
local function loadFile( filePath )
local loadedConfig = {};
local section;
for line in love.filesystem.lines( filePath ) do
if line == '' or line:find( ';' ) == 1 then
-- Ignore comments and empty lines.
elseif line:match( '^%[(%w*)%]$' ) then
-- Create a new section.
local header = line:match( '^%[(%w*)%]$' );
loadedConfig[header] = {};
section = loadedConfig[header];
else
-- Store values in the section.
local key, value = line:match( '^([%g]+)%s-=%s-(.+)' );
-- Store multiple values in a table.
if value and value:find( ',' ) then
section[key] = {};
for val in value:gmatch( '[^, ]+' ) do
section[key][#section[key] + 1] = toType( val );
end
elseif value then
section[key] = toType( value );
end
end
end
return loadedConfig;
end
---
-- Validates a loaded config file by comparing it to the default config file.
-- It checks if the file contains all the necessary sections and values. If it
-- doesn't, a warning is displayed and the default config will be used.
-- @param default (table) The default config file to use for comparison.
-- @param config (table) The loaded config file to check.
-- @param (table) Either the default config file or the loaded one.
--
local function validateFile( default, config )
print( 'Validating configuration file ... ' );
for skey, section in pairs( default ) do
-- If loaded config file doesn't contain section return default.
if config[skey] == nil then
love.window.showMessageBox( INVALID_CONFIG_HEADER, string.format( MISSING_SECTION_WARNING, skey ), 'warning', false );
return default;
end
-- If the loaded config file is missing a value, display warning and return default.
if type( section ) == 'table' then
for vkey, _ in pairs( section ) do
if config[skey][vkey] == nil then
love.window.showMessageBox( INVALID_CONFIG_HEADER, string.format( MISSING_VALUE_WARNING, vkey, skey ), 'warning', false );
return default;
end
end
end
end
print( 'Done!' );
return config;
end
---
-- Replaces backslashes in paths with forwardslashes.
--
local function validateRepositoryPaths()
for project, path in pairs( config.repositories ) do
config.repositories[project] = path:gsub( '\\+', '/' );
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function ConfigReader.init()
local default = loadFile( TEMPLATE_PATH );
if not hasConfigFile() then
createConfigFile( FILE_NAME, TEMPLATE_PATH );
end
-- If the config hasn't been loaded yet, load and validate it.
if not config then
config = loadFile( FILE_NAME );
config = validateFile( default, config );
validateRepositoryPaths();
end
return config;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return ConfigReader;
|
Fix default config file not being used
|
Fix default config file not being used
It looks like the default config file was never properly used.
|
Lua
|
mit
|
rm-code/logivi
|
18ca6465c64fdcfab915d3e56a3a1311604b5127
|
kong/plugins/zipkin/opentracing.lua
|
kong/plugins/zipkin/opentracing.lua
|
--[[
This file is not a kong plugin; but the prototype for one.
A plugin that derives this should:
- Implement a :new_tracer(cond) method that returns an opentracing tracer
- The tracer must support the "http_headers" format.
- Implement a :initialise_request(conf, ctx) method if it needs to do per-request initialisation
]]
local BasePlugin = require "kong.plugins.base_plugin"
local ngx_set_header = ngx.req.set_header
local OpenTracingHandler = BasePlugin:extend()
OpenTracingHandler.VERSION = "scm"
-- We want to run first so that timestamps taken are at start of the phase
-- also so that other plugins might be able to use our structures
OpenTracingHandler.PRIORITY = 100000
function OpenTracingHandler:new(name)
OpenTracingHandler.super.new(self, name or "opentracing")
self.conf_to_tracer = setmetatable({}, {__mode = "k"})
end
function OpenTracingHandler:get_tracer(conf)
local tracer = self.conf_to_tracer[conf]
if tracer == nil then
assert(self.new_tracer, "derived class must implement :new_tracer()")
tracer = self:new_tracer(conf)
assert(type(tracer) == "table", ":new_tracer() must return an opentracing tracer object")
self.conf_to_tracer[conf] = tracer
end
return tracer
end
-- Utility function to set either ipv4 or ipv6 tags
-- nginx apis don't have a flag to indicate whether an address is v4 or v6
local function ip_tag(addr)
-- use the presence of "." to signal v4 (v6 uses ":")
if addr:find(".", 1, true) then
return "peer.ipv4"
else
return "peer.ipv6"
end
end
function OpenTracingHandler:initialise_request(conf, ctx)
local tracer = self:get_tracer(conf)
local wire_context = tracer:extract("http_headers", ngx.req.get_headers()) -- could be nil
local request_span = tracer:start_span("kong.request", {
child_of = wire_context;
start_timestamp = ngx.req.start_time(),
tags = {
component = "kong";
["span.kind"] = "server";
["http.method"] = ngx.req.get_method();
["http.url"] = ngx.var.scheme .. "://" .. ngx.var.host .. ":" .. ngx.var.server_port .. ngx.var.request_uri;
[ip_tag(ngx.var.remote_addr)] = ngx.var.remote_addr;
["peer.ipv6"] = nil;
["peer.port"] = tonumber(ngx.var.remote_port, 10);
}
})
ctx.opentracing = {
tracer = tracer;
wire_context = wire_context;
request_span = request_span;
rewrite_span = nil;
access_span = nil;
proxy_span = nil;
header_filter_span = nil;
header_filter_finished = false;
body_filter_span = nil;
}
end
function OpenTracingHandler:get_context(conf, ctx)
local opentracing = ctx.opentracing
if not opentracing then
self:initialise_request(conf, ctx)
opentracing = ctx.opentracing
end
return opentracing
end
function OpenTracingHandler:access(conf)
OpenTracingHandler.super.access(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
opentracing.proxy_span = opentracing.request_span:start_child_span(
"kong.proxy",
ctx.KONG_ACCESS_START / 1000
)
opentracing.access_span = opentracing.proxy_span:start_child_span(
"kong.access",
ctx.KONG_ACCESS_START / 1000
)
-- Want to send headers to upstream
local outgoing_headers = {}
opentracing.tracer:inject(opentracing.proxy_span, "http_headers", outgoing_headers)
for k, v in pairs(outgoing_headers) do
ngx_set_header(k, v)
end
end
function OpenTracingHandler:header_filter(conf)
OpenTracingHandler.super.header_filter(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
local header_started = ctx.KONG_HEADER_FILTER_STARTED_AT and ctx.KONG_HEADER_FILTER_STARTED_AT / 1000 or ngx.now()
if not opentracing.proxy_span then
opentracing.proxy_span = opentracing.request_span:start_child_span(
"kong.proxy",
header_started
)
end
opentracing.header_filter_span = opentracing.proxy_span:start_child_span(
"kong.header_filter",
header_started
)
end
function OpenTracingHandler:body_filter(conf)
OpenTracingHandler.super.body_filter(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
-- Finish header filter when body filter starts
if not opentracing.header_filter_finished then
local now = ngx.now()
opentracing.header_filter_span:finish(now)
opentracing.header_filter_finished = true
opentracing.body_filter_span = opentracing.proxy_span:start_child_span("kong.body_filter", now)
end
end
function OpenTracingHandler:log(conf)
local now = ngx.now()
OpenTracingHandler.super.log(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
local request_span = opentracing.request_span
local proxy_span = opentracing.proxy_span
if not proxy_span then
proxy_span = request_span:start_child_span("kong.proxy", now)
opentracing.proxy_span = proxy_span
end
proxy_span:set_tag("span.kind", "client")
local proxy_end = ctx.KONG_BODY_FILTER_ENDED_AT and ctx.KONG_BODY_FILTER_ENDED_AT/1000 or now
-- We'd run this in rewrite phase, but then we wouldn't have per-service configuration of this plugin
if ctx.KONG_REWRITE_TIME then
opentracing.rewrite_span = opentracing.request_span:start_child_span(
"kong.rewrite",
ctx.KONG_REWRITE_START / 1000
):finish((ctx.KONG_REWRITE_START + ctx.KONG_REWRITE_TIME) / 1000)
end
if opentracing.access_span then
opentracing.access_span:finish(ctx.KONG_ACCESS_ENDED_AT / 1000)
end
local balancer_address = ctx.balancer_address
if balancer_address then
local balancer_tries = balancer_address.tries
for i=1, balancer_address.try_count do
local try = balancer_tries[i]
local span = proxy_span:start_child_span("kong.balancer", try.balancer_start / 1000)
span:set_tag(ip_tag(try.ip), try.ip)
span:set_tag("peer.port", try.port)
span:set_tag("kong.balancer.try", i)
if i < balancer_address.try_count then
span:set_tag("error", true)
span:set_tag("kong.balancer.state", try.state)
span:set_tag("kong.balancer.code", try.code)
end
span:finish((try.balancer_start + try.balancer_latency) / 1000)
end
proxy_span:set_tag("peer.hostname", balancer_address.hostname) -- could be nil
proxy_span:set_tag(ip_tag(balancer_address.ip), balancer_address.ip)
proxy_span:set_tag("peer.port", balancer_address.port)
end
if not opentracing.header_filter_finished and opentracing.header_filter_span then
opentracing.header_filter_span:finish(now)
opentracing.header_filter_finished = true
end
if opentracing.body_filter_span then
opentracing.body_filter_span:finish(proxy_end)
end
request_span:set_tag("http.status_code", ngx.status)
if ctx.authenticated_consumer then
request_span:set_tag("kong.consumer", ctx.authenticated_consumer.id)
end
if ctx.authenticated_credentials then
request_span:set_tag("kong.credential", ctx.authenticated_credentials.id)
end
if ctx.service then
proxy_span:set_tag("kong.service", ctx.service.id)
if ctx.route then
proxy_span:set_tag("kong.route", ctx.route.id)
end
if ctx.service.name ~= ngx.null then
proxy_span:set_tag("peer.service", ctx.service.name)
end
end
proxy_span:finish(proxy_end)
request_span:finish(now)
end
return OpenTracingHandler
|
--[[
This file is not a kong plugin; but the prototype for one.
A plugin that derives this should:
- Implement a :new_tracer(cond) method that returns an opentracing tracer
- The tracer must support the "http_headers" format.
- Implement a :initialise_request(conf, ctx) method if it needs to do per-request initialisation
]]
local BasePlugin = require "kong.plugins.base_plugin"
local ngx_set_header = ngx.req.set_header
local OpenTracingHandler = BasePlugin:extend()
OpenTracingHandler.VERSION = "scm"
-- We want to run first so that timestamps taken are at start of the phase
-- also so that other plugins might be able to use our structures
OpenTracingHandler.PRIORITY = 100000
function OpenTracingHandler:new(name)
OpenTracingHandler.super.new(self, name or "opentracing")
self.conf_to_tracer = setmetatable({}, {__mode = "k"})
end
function OpenTracingHandler:get_tracer(conf)
local tracer = self.conf_to_tracer[conf]
if tracer == nil then
assert(self.new_tracer, "derived class must implement :new_tracer()")
tracer = self:new_tracer(conf)
assert(type(tracer) == "table", ":new_tracer() must return an opentracing tracer object")
self.conf_to_tracer[conf] = tracer
end
return tracer
end
-- Utility function to set either ipv4 or ipv6 tags
-- nginx apis don't have a flag to indicate whether an address is v4 or v6
local function ip_tag(addr)
-- use the presence of "." to signal v4 (v6 uses ":")
if addr:find(".", 1, true) then
return "peer.ipv4"
else
return "peer.ipv6"
end
end
function OpenTracingHandler:initialise_request(conf, ctx)
local tracer = self:get_tracer(conf)
local wire_context = tracer:extract("http_headers", ngx.req.get_headers()) -- could be nil
local request_span = tracer:start_span("kong.request", {
child_of = wire_context;
start_timestamp = ngx.req.start_time(),
tags = {
component = "kong";
["span.kind"] = "server";
["http.method"] = ngx.req.get_method();
["http.url"] = ngx.var.scheme .. "://" .. ngx.var.host .. ":" .. ngx.var.server_port .. ngx.var.request_uri;
[ip_tag(ngx.var.remote_addr)] = ngx.var.remote_addr;
["peer.ipv6"] = nil;
["peer.port"] = tonumber(ngx.var.remote_port, 10);
}
})
ctx.opentracing = {
tracer = tracer;
wire_context = wire_context;
request_span = request_span;
rewrite_span = nil;
access_span = nil;
proxy_span = nil;
header_filter_span = nil;
header_filter_finished = false;
body_filter_span = nil;
}
end
function OpenTracingHandler:get_context(conf, ctx)
local opentracing = ctx.opentracing
if not opentracing then
self:initialise_request(conf, ctx)
opentracing = ctx.opentracing
end
return opentracing
end
function OpenTracingHandler:access(conf)
OpenTracingHandler.super.access(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
opentracing.proxy_span = opentracing.request_span:start_child_span(
"kong.proxy",
ctx.KONG_ACCESS_START / 1000
)
opentracing.access_span = opentracing.proxy_span:start_child_span(
"kong.access",
ctx.KONG_ACCESS_START / 1000
)
-- Want to send headers to upstream
local outgoing_headers = {}
opentracing.tracer:inject(opentracing.proxy_span, "http_headers", outgoing_headers)
for k, v in pairs(outgoing_headers) do
ngx_set_header(k, v)
end
end
function OpenTracingHandler:header_filter(conf)
OpenTracingHandler.super.header_filter(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
local header_started = ctx.KONG_HEADER_FILTER_STARTED_AT and ctx.KONG_HEADER_FILTER_STARTED_AT / 1000 or ngx.now()
if not opentracing.proxy_span then
opentracing.proxy_span = opentracing.request_span:start_child_span(
"kong.proxy",
header_started
)
end
opentracing.header_filter_span = opentracing.proxy_span:start_child_span(
"kong.header_filter",
header_started
)
end
function OpenTracingHandler:body_filter(conf)
OpenTracingHandler.super.body_filter(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
-- Finish header filter when body filter starts
if not opentracing.header_filter_finished then
local now = ngx.now()
opentracing.header_filter_span:finish(now)
opentracing.header_filter_finished = true
opentracing.body_filter_span = opentracing.proxy_span:start_child_span("kong.body_filter", now)
end
end
function OpenTracingHandler:log(conf)
local now = ngx.now()
OpenTracingHandler.super.log(self, conf)
local ctx = ngx.ctx
local opentracing = self:get_context(conf, ctx)
local request_span = opentracing.request_span
local proxy_span = opentracing.proxy_span
if not proxy_span then
proxy_span = request_span:start_child_span("kong.proxy", now)
opentracing.proxy_span = proxy_span
end
proxy_span:set_tag("span.kind", "client")
local proxy_end = ctx.KONG_BODY_FILTER_ENDED_AT and ctx.KONG_BODY_FILTER_ENDED_AT/1000 or now
-- We'd run this in rewrite phase, but then we wouldn't have per-service configuration of this plugin
if ctx.KONG_REWRITE_TIME then
opentracing.rewrite_span = opentracing.request_span:start_child_span(
"kong.rewrite",
ctx.KONG_REWRITE_START / 1000
):finish((ctx.KONG_REWRITE_START + ctx.KONG_REWRITE_TIME) / 1000)
end
if opentracing.access_span then
opentracing.access_span:finish(ctx.KONG_ACCESS_ENDED_AT / 1000)
end
local balancer_address = ctx.balancer_address
if balancer_address then
local balancer_tries = balancer_address.tries
for i=1, balancer_address.try_count do
local try = balancer_tries[i]
local span = proxy_span:start_child_span("kong.balancer", try.balancer_start / 1000)
span:set_tag(ip_tag(try.ip), try.ip)
span:set_tag("peer.port", try.port)
span:set_tag("kong.balancer.try", i)
if i < balancer_address.try_count then
span:set_tag("error", true)
span:set_tag("kong.balancer.state", try.state)
span:set_tag("kong.balancer.code", try.code)
end
span:finish((try.balancer_start + try.balancer_latency) / 1000)
end
proxy_span:set_tag("peer.hostname", balancer_address.hostname) -- could be nil
proxy_span:set_tag(ip_tag(balancer_address.ip), balancer_address.ip)
proxy_span:set_tag("peer.port", balancer_address.port)
end
if not opentracing.header_filter_finished and opentracing.header_filter_span then
opentracing.header_filter_span:finish(now)
opentracing.header_filter_finished = true
end
if opentracing.body_filter_span then
opentracing.body_filter_span:finish(proxy_end)
end
request_span:set_tag("http.status_code", ngx.status)
if ctx.authenticated_consumer then
request_span:set_tag("kong.consumer", ctx.authenticated_consumer.id)
end
if ctx.authenticated_credentials then
request_span:set_tag("kong.credential", ctx.authenticated_credentials.id)
end
if ctx.service and ctx.service.id then
proxy_span:set_tag("kong.service", ctx.service.id)
if ctx.route and ctx.route.id then
proxy_span:set_tag("kong.route", ctx.route.id)
end
if ctx.service.name ~= ngx.null then
proxy_span:set_tag("peer.service", ctx.service.name)
end
end
proxy_span:finish(proxy_end)
request_span:finish(now)
end
return OpenTracingHandler
|
kong/plugins/zipkin/opentracing.lua: Check that .id field exists before using service or route
|
kong/plugins/zipkin/opentracing.lua: Check that .id field exists before using service or route
Fixes #19
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
be7fc528d892eb4593ea3cf2ed00af2c2893b3fd
|
Makefile.lua
|
Makefile.lua
|
CFLAGS+=-Ilibuv/include -g -I/usr/local/include \
-DLUV_STACK_CHECK -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 \
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
uname_S=$(shell uname -s)
ifeq (Darwin, $(uname_S))
LDFLAGS+=-bundle -bundle_loader /usr/local/bin/lua \
-framework CoreServices \
-L/usr/local/lib/
else
LDFLAGS+=-shared -lrt
endif
SOURCE_FILES=\
src/luv.c \
src/loop.c \
src/dns.c \
src/fs.c \
src/handle.c \
src/luv.h \
src/misc.c \
src/pipe.c \
src/process.c \
src/stream.c \
src/tcp.c \
src/timer.c \
src/prepare.c \
src/check.c \
src/idle.c \
src/tty.c \
src/util.c
all: luv.so
libuv/out/Release/libuv.a:
cd libuv && ./gyp_uv.py && BUILDTYPE=Release ${MAKE} -C out && cd ..
libuv/out/Debug/libuv.a:
cd libuv && ./gyp_uv.py && BUILDTYPE=Debug ${MAKE} -C out && cd ..
luv.o: ${SOURCE_FILES}
$(CC) -c $< ${CFLAGS} -o $@
luv.so: luv.o libuv/out/Release/libuv.a
$(CC) $^ ${LDFLAGS} -o $@
clean:
rm -f luv.so *.o
|
CFLAGS+=-Ilibuv/include -g -I/usr/local/include \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 \
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
uname_S=$(shell uname -s)
ifeq (Darwin, $(uname_S))
LDFLAGS+=-bundle -bundle_loader /usr/local/bin/lua \
-framework CoreServices \
-L/usr/local/lib/
else
CFLAGS+= -fPIC
LDFLAGS+=-shared -lrt
endif
SOURCE_FILES=\
src/luv.c \
src/loop.c \
src/dns.c \
src/fs.c \
src/handle.c \
src/luv.h \
src/misc.c \
src/pipe.c \
src/process.c \
src/stream.c \
src/tcp.c \
src/timer.c \
src/prepare.c \
src/check.c \
src/idle.c \
src/tty.c \
src/util.c
all: luv.so
libuv/out/Release/libuv.a:
cd libuv && ./gyp_uv.py && BUILDTYPE=Release CFLAGS=-fPIC ${MAKE} -C out && cd ..
libuv/out/Debug/libuv.a:
cd libuv && ./gyp_uv.py && BUILDTYPE=Debug CFLAGS=-fPIC ${MAKE} -C out && cd ..
luv.o: ${SOURCE_FILES}
$(CC) -c $< ${CFLAGS} -o $@
luv.so: luv.o libuv/out/Release/libuv.a
$(CC) $^ ${LDFLAGS} -o $@
clean:
rm -f luv.so *.o
|
Fix Makefile.lua for linux
|
Fix Makefile.lua for linux
|
Lua
|
apache-2.0
|
daurnimator/luv,daurnimator/luv,luvit/luv,kidaa/luv,joerg-krause/luv,daurnimator/luv,zhaozg/luv,zhaozg/luv,luvit/luv,RomeroMalaquias/luv,NanXiao/luv,mkschreder/luv,joerg-krause/luv,xpol/luv,brimworks/luv,mkschreder/luv,kidaa/luv,brimworks/luv,leecrest/luv,NanXiao/luv,leecrest/luv,RomeroMalaquias/luv,DBarney/luv,RomeroMalaquias/luv,xpol/luv,DBarney/luv
|
6aa264748c87a5343b7d05061a0f3a3463987cc7
|
util/sasl.lua
|
util/sasl.lua
|
-- sasl.lua v0.4
-- Copyright (C) 2008-2009 Tobias Markmann
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local md5 = require "util.hashes".md5;
local log = require "util.logger".init("sasl");
local tostring = tostring;
local st = require "util.stanza";
local generate_uuid = require "util.uuid".generate;
local t_insert, t_concat = table.insert, table.concat;
local to_byte, to_char = string.byte, string.char;
local to_unicode = require "util.encodings".idna.to_unicode;
local s_match = string.match;
local gmatch = string.gmatch
local string = string
local math = require "math"
local type = type
local error = error
local print = print
local setmetatable = setmetatable;
local assert = assert;
module "sasl"
local method = {}
local mechanisms = {};
local backend_mechanism = {};
-- register a new SASL mechanims
local function registerMechanism(name, backends, f)
assert(type(name) == "string", "Parameter name MUST be a string.");
assert(type(backends) == "string" or type(backends) == "table", "Parameter backends MUST be either a string or a table.");
assert(type(f) == "function", "Parameter f MUST be a function.");
mechanism[name] = f
for _, backend_name in ipairs(backend)
end
-- create a new SASL object which can be used to authenticate clients
function new(realm, profile)
sasl_i = {};
return setmetatable(sasl_i, method);
end
-- get a list of possible SASL mechanims to use
function method:mechanisms()
end
-- select a mechanism to use
function method.select( mechanism )
end
return _M;
|
-- sasl.lua v0.4
-- Copyright (C) 2008-2009 Tobias Markmann
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local md5 = require "util.hashes".md5;
local log = require "util.logger".init("sasl");
local tostring = tostring;
local st = require "util.stanza";
local generate_uuid = require "util.uuid".generate;
local pairs, ipairs = pairs, ipairs;
local t_insert, t_concat = table.insert, table.concat;
local to_byte, to_char = string.byte, string.char;
local to_unicode = require "util.encodings".idna.to_unicode;
local s_match = string.match;
local gmatch = string.gmatch
local string = string
local math = require "math"
local type = type
local error = error
local print = print
local setmetatable = setmetatable;
local assert = assert;
require "util.iterators"
local keys = keys
local array = require "util.array"
module "sasl"
local method = {};
method.__index = method;
local mechanisms = {};
local backend_mechanism = {};
-- register a new SASL mechanims
local function registerMechanism(name, backends, f)
assert(type(name) == "string", "Parameter name MUST be a string.");
assert(type(backends) == "string" or type(backends) == "table", "Parameter backends MUST be either a string or a table.");
assert(type(f) == "function", "Parameter f MUST be a function.");
mechanisms[name] = f
for _, backend_name in ipairs(backends) do
if backend_mechanism[backend_name] == nil then backend_mechanism[backend_name] = {}; end
t_insert(backend_mechanism[backend_name], name);
end
end
-- create a new SASL object which can be used to authenticate clients
function new(realm, profile)
sasl_i = {profile = profile};
return setmetatable(sasl_i, method);
end
-- get a list of possible SASL mechanims to use
function method:mechanisms()
local mechanisms = {}
for backend, f in pairs(self.profile) do
print(backend)
if backend_mechanism[backend] then
for _, mechanism in ipairs(backend_mechanism[backend]) do
mechanisms[mechanism] = true;
end
end
end
return array.collect(keys(mechanisms));
end
-- select a mechanism to use
function method:select(mechanism)
end
-- feed new messages to process into the library
function method:process(message)
end
--=========================
--SASL PLAIN
local function sasl_mechanism_plain(realm, credentials_handler)
local object = { mechanism = "PLAIN", realm = realm, credentials_handler = credentials_handler}
function object.feed(self, message)
if message == "" or message == nil then return "failure", "malformed-request" end
local response = message
local authorization = s_match(response, "([^&%z]+)")
local authentication = s_match(response, "%z([^&%z]+)%z")
local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
if authentication == nil or password == nil then return "failure", "malformed-request" end
self.username = authentication
local auth_success = self.credentials_handler("PLAIN", self.username, self.realm, password)
if auth_success then
return "success"
elseif auth_success == nil then
return "failure", "account-disabled"
else
return "failure", "not-authorized"
end
end
return object
end
registerMechanism("PLAIN", {"plain", "plain_test"}, sasl_mechanism_plain);
return _M;
|
Mostly making the code run; includes fixing typos and so on.
|
Mostly making the code run; includes fixing typos and so on.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
9f86901f5f91f88e2dfe11e4c5f46d74b6d5ad34
|
modules/textadept/run.lua
|
modules/textadept/run.lua
|
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local L = _G.locale.localize
---
-- Module for running/executing source files.
-- Typically, language-specific modules populate the 'compile_command',
-- 'run_command', and 'error_detail' tables for a particular language's file
-- extension.
module('_m.textadept.run', package.seeall)
---
-- Executes the command line parameter and prints the output to Textadept.
-- @param command The command line string.
-- It can have the following macros:
-- * %(filepath) The full path of the current file.
-- * %(filedir) The current file's directory path.
-- * %(filename) The name of the file including extension.
-- * %(filename_noext) The name of the file excluding extension.
function execute(command)
local filepath = buffer.filename:iconv(_CHARSET, 'UTF-8')
local filedir, filename
if filepath:find('[/\\]') then
filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$')
else
filedir, filename = '', filepath
end
local filename_noext = filename:match('^(.+)%.')
command = command:gsub('%%%b()', {
['%(filepath)'] = filepath,
['%(filedir)'] = filedir,
['%(filename)'] = filename,
['%(filename_noext)'] = filename_noext,
})
local current_dir = lfs.currentdir()
lfs.chdir(filedir)
local p = io.popen(command..' 2>&1')
local out = p:read('*all')
p:close()
lfs.chdir(current_dir)
gui.print(('> '..command..'\n'..out):iconv('UTF-8', _CHARSET))
buffer:goto_pos(buffer.length)
end
---
-- File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a either a command line string to
-- execute or a function returning one.
-- This table is typically populated by language-specific modules.
-- @class table
-- @name compile_command
compile_command = {}
---
-- Compiles the file as specified by its extension in the compile_command
-- table.
-- @see compile_command
function compile()
if not buffer.filename then return end
buffer:save()
local action = compile_command[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is either a command line string to
-- execute or a function returning one.
-- This table is typically populated by language-specific modules.
-- @class table
-- @name run_command
run_command = {}
---
-- Runs/executes the file as specified by its extension in the run_command
-- table.
-- @see run_command
function run()
if not buffer.filename then return end
buffer:save()
local action = run_command[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- This table is usually populated by language-specific modules.
-- @class table
-- @name error_detail
error_detail = {}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_detail
function goto_error(pos, line_num)
local type = buffer._type
if type == L('[Message Buffer]') or type == L('[Error Buffer]') then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_detail) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
local lfs = require 'lfs'
local utf8_filename = captures[error_detail.filename]
local filename = utf8_filename:iconv(_CHARSET, 'UTF-8')
if lfs.attributes(filename) then
io.open_file(utf8_filename)
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
else
error(string.format('"%s" %s', L('does not exist'), utf8_filename))
end
break
end
end
end
end
events.connect('double_click', goto_error)
|
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local L = _G.locale.localize
---
-- Module for running/executing source files.
-- Typically, language-specific modules populate the 'compile_command',
-- 'run_command', and 'error_detail' tables for a particular language's file
-- extension.
module('_m.textadept.run', package.seeall)
---
-- Executes the command line parameter and prints the output to Textadept.
-- @param command The command line string.
-- It can have the following macros:
-- * %(filepath) The full path of the current file.
-- * %(filedir) The current file's directory path.
-- * %(filename) The name of the file including extension.
-- * %(filename_noext) The name of the file excluding extension.
function execute(command)
local filepath = buffer.filename:iconv(_CHARSET, 'UTF-8')
local filedir, filename
if filepath:find('[/\\]') then
filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$')
else
filedir, filename = '', filepath
end
local filename_noext = filename:match('^(.+)%.')
command = command:gsub('%%%b()', {
['%(filepath)'] = filepath,
['%(filedir)'] = filedir,
['%(filename)'] = filename,
['%(filename_noext)'] = filename_noext,
})
local current_dir = lfs.currentdir()
lfs.chdir(filedir)
local p = io.popen(command..' 2>&1')
local out = p:read('*all')
p:close()
lfs.chdir(current_dir)
gui.print(('> '..command..'\n'..out):iconv('UTF-8', _CHARSET))
buffer:goto_pos(buffer.length)
end
---
-- File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a either a command line string to
-- execute or a function returning one.
-- This table is typically populated by language-specific modules.
-- @class table
-- @name compile_command
compile_command = {}
---
-- Compiles the file as specified by its extension in the compile_command
-- table.
-- @see compile_command
function compile()
if not buffer.filename then return end
buffer:save()
local action = compile_command[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is either a command line string to
-- execute or a function returning one.
-- This table is typically populated by language-specific modules.
-- @class table
-- @name run_command
run_command = {}
---
-- Runs/executes the file as specified by its extension in the run_command
-- table.
-- @see run_command
function run()
if not buffer.filename then return end
buffer:save()
local action = run_command[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- This table is usually populated by language-specific modules.
-- @class table
-- @name error_detail
error_detail = {}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_detail
function goto_error(pos, line_num)
local type = buffer._type
if type == L('[Message Buffer]') or type == L('[Error Buffer]') then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_detail) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
local lfs = require 'lfs'
local utf8_filename = captures[error_detail.filename]
local filename = utf8_filename:iconv(_CHARSET, 'UTF-8')
if lfs.attributes(filename) then
io.open_file(utf8_filename)
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
else
error(string.format('"%s" %s', utf8_filename, L('does not exist'))
end
break
end
end
end
end
events.connect('double_click', goto_error)
|
Fixed bug in modules/textadept/run.lua from localization changes.
|
Fixed bug in modules/textadept/run.lua from localization changes.
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
ebf1f199e66dc86348c671c24f96990a2025b5a6
|
src/nova/object.lua
|
src/nova/object.lua
|
--- LuaNova's object module.
-- This module is used to create objects from prototypes, through the use of
-- the nova.object:new() method. It also defines a reference to a nil object,
-- which may be acquired with nova.object.nilref().
module ("nova.object", package.seeall) do
--- Local instance of the "nil object".
local nilref_ = {}
--- Returns the representation of the nil object.
-- @return An object reference to the nil object.
function nilref()
return nilref_
end
-- Recursive initialization.
local function init (obj)
if obj then
init(obj.__super)
if obj.__init then obj:__init() end
end
end
--- Method. Creates a new object from a prototype.
-- @param prototype A table containing the object's methods and the default
-- values of its attributes.
function nova.object:new (prototype)
prototype = prototype or {}
self.__index = rawget(self, "__index") or self
setmetatable(prototype, self)
prototype.__super = self
init(prototype)
return prototype;
end
--- Makes a class module inherit from a table.
-- This function is to be used only when declaring modules, like this:
-- <p><code>
-- module ("my.module", nova.object.inherit(some_table))
-- </code></p>
-- This essentially makes the module inherit everything indexable from the
-- given table. It also turns the module into an object.
-- @param super A table from which the module will inherit.
function inherit (super)
return function (class)
class.__index = super
nova.object:new(class)
end
end
end
|
--- LuaNova's object module.
-- This module is used to create objects from prototypes, through the use of
-- the nova.object:new() method. It also defines a reference to a nil object,
-- which may be acquired with nova.object.nilref().
module ("nova.object", package.seeall) do
--- Local instance of the "nil object".
local nilref_ = {}
--- Returns the representation of the nil object.
-- @return An object reference to the nil object.
function nilref()
return nilref_
end
-- Recursive initialization.
local function init (obj)
if obj then
init(obj:super())
if obj.__init then obj:__init() end
end
end
--- Method. Creates a new object from a prototype.
-- @param prototype A table containing the object's methods and the default
-- values of its attributes.
function nova.object:new (prototype)
prototype = prototype or {}
self.__index = rawget(self, "__index") or self
setmetatable(prototype, self)
init(prototype)
return prototype;
end
--- Method. Returns the super class of an object.
-- @return The super class of an object.
function nova.object:super ()
return self == nova.object and self or getmetatable(self)
end
--- Makes a class module inherit from a table.
-- This function is to be used only when declaring modules, like this:
-- <p><code>
-- module ("my.module", nova.object.inherit(some_table))
-- </code></p>
-- This essentially makes the module inherit everything indexable from the
-- given table. It also turns the module into an object.
-- @param super A table from which the module will inherit.
function inherit (super)
return function (class)
class.__index = super
nova.object:new(class)
end
end
end
|
Fixed super class getter.
|
Fixed super class getter.
|
Lua
|
mit
|
Kazuo256/luxproject
|
af8bb1ebedca7d3a7f94b7cdaf04c51770f01546
|
ardivink.lua
|
ardivink.lua
|
bootstrap = require("bootstrap")
bootstrap.init()
ci = require("ci")
--godi = require("godi")
oasis = require("oasis")
git = require("git")
ci.init()
-- godi.init()
git.init()
oasis.init()
--godi.bootstrap("3.12")
--godi.update()
--godi.upgrade()
--godi.build_many(
-- {"godi-findlib",
-- "godi-ocaml-fileutils",
-- "godi-ocaml-data-notation",
-- "godi-ocaml-expect",
-- "godi-ounit",
-- "apps-ocamlmod",
-- "apps-ocamlify"})
oasis.std_process("--enable-tests")
git.create_tag(oasis.package_version())
|
ci = require("ci")
--godi = require("godi")
oasis = require("oasis")
git = require("git")
ci.init()
-- godi.init()
git.init()
oasis.init()
--godi.bootstrap("3.12")
--godi.update()
--godi.upgrade()
--godi.build_many(
-- {"godi-findlib",
-- "godi-ocaml-fileutils",
-- "godi-ocaml-data-notation",
-- "godi-ocaml-expect",
-- "godi-ounit",
-- "apps-ocamlmod",
-- "apps-ocamlify"})
oasis.std_process("--enable-tests")
git.create_tag(oasis.package_version())
|
Fix missing bootstrap.lua.
|
Fix missing bootstrap.lua.
|
Lua
|
lgpl-2.1
|
diml/oasis,gerdstolpmann/oasis,jpdeplaix/oasis,jpdeplaix/oasis,Chris00/oasis,gerdstolpmann/oasis,RadicalZephyr/oasis,madroach/oasis,gerdstolpmann/oasis,jpdeplaix/oasis,RadicalZephyr/oasis,Chris00/oasis,madroach/oasis,Chris00/oasis,diml/oasis
|
4bd2c0e087279f66aa312ad3fab03cfa583f554f
|
src/bidi/LinkedList.lua
|
src/bidi/LinkedList.lua
|
----------------------------------------------------------------
-- Doubly-linked List
--
-- @classmod LinkedList
-- @author [email protected]
-- @usage
-- dll = LinkedList.new()
-- dll:pushBack("Some data")
-- print(dll:popBack())
----------------------------------------------------------------
local Node = require('bidi.LNode')
local LinkedList = {}
LinkedList.__index = LinkedList
----------------------------------------------------------------
-- Creates a new Doubly-linked List
-- @constructor
--
-- @return **(LinkedList)** New LinkedList
----------------------------------------------------------------
function LinkedList.new()
local self = {}
self.head = nil
self.tail = nil
self.count = 0
setmetatable(self, LinkedList)
return self
end
-- Removes a node from the list
local function removeNode(list, node)
local prevN = node.prev
local nextN = node.next
if(prevN ~= nil) then
prevN.next = nextN
else
-- The node was at the head
list.head = nextN
end
if(nextN ~= nil) then
nextN.prev = prevN
else
-- The node was at the tail
list.tail = prevN
end
node.prev = nil
node.next = nil
node:setData(nil)
list.count = list.count - 1
end
----------------------------------------------------------------
-- Returns the last node
--
-- @return **(LNode)** The last node or nil
----------------------------------------------------------------
function LinkedList:getTail()
return self.tail
end
----------------------------------------------------------------
-- Returns the number of items in the list
--
-- @return **(num)** The number of items on the list
----------------------------------------------------------------
function LinkedList:getCount()
return self.count
end
----------------------------------------------------------------
-- Pushes the data to the back of the list inside a new Node
--
-- @param data **(any)** Any data to store in the list
----------------------------------------------------------------
function LinkedList:pushBack(data)
local node = Node.new(data)
if(self.head == nil) then
self.head = node
self.tail = node
else
self.tail.next = node
node.prev = self.tail
self.tail = node
end
self.count = self.count + 1
end
----------------------------------------------------------------
-- Pushes the data to the front of the list inside a new node
--
-- @param data **(any)** The data to store
----------------------------------------------------------------
function LinkedList:pushFront(data)
local node = Node.new(data)
if(self.head == nil)then
self.head = node
self.tail = node
else
self.head.prev = node
node.next = self.head
self.head = node
end
self.count = self.count + 1
end
----------------------------------------------------------------
-- Deletas all the nodes and data references in the list
----------------------------------------------------------------
function LinkedList:deleteAll()
if(self.head == nil) then return end
local n = self.head
repeat
local nextNode = n.next
n:setData(nil)
n.next = nil
n.prev = nil
self.count = self.count -1
n = nextNode
until(n == nil)
self.head = nil
self.tail = nil
end
----------------------------------------------------------------
-- Pops the first element's data. Removes it from the list
--
-- @return **(data)** The first data stored in the list
----------------------------------------------------------------
function LinkedList:popFront()
if(self.head == nil) then return nil end
local wasHead = self.head
if(wasHead.next ~= nil) then
self.head = wasHead.next
self.head.prev = nil
end
self.count = self.count - 1
return wasHead:getData()
end
----------------------------------------------------------------
-- Removes and returns the last data in the list
--
-- @return **(data)** The last item's data
----------------------------------------------------------------
function LinkedList:popBack()
if(self.head == nil) then return nil end
local wasTail = self.tail
if(wasTail.prev ~= nil) then
self.tail = wasTail.prev
self.tail.next = nil
end
self.count = self.count - 1
return wasTail:getData()
end
----------------------------------------------------------------
-- Returns all the data inside the list as an array. Uses '[nil]' for nil data
--
-- return **({arr})** An array with the data.
----------------------------------------------------------------
function LinkedList:getDataArray()
local dataArray = {}
local node = self.head
while node ~= nil do
if(node:getData() ~= nil) then
table.insert(dataArray, node:getData())
else
table.insert(dataArray, "[nil]")
end
node = node.next
end
return dataArray
end
----------------------------------------------------------------
-- Same as above but backwards ordered
--
-- @return **({arr})** An array with the data reversed.
----------------------------------------------------------------
function LinkedList:getDataArrayBackwards()
local dataArray = {}
local node = self.tail
while (node ~= nil) do
if(node:getData() ~= nil) then
table.insert(dataArray, node:getData())
else
table.insert(dataArray, "[nil]")
end
node = node.prev
end
return dataArray
end
----------------------------------------------------------------
-- Removes the last item on the list
----------------------------------------------------------------
function LinkedList:removeLast()
if(self.tail == nil) then return end
-- Remove the tail
removeNode(self, self.tail)
end
----------------------------------------------------------------
-- Removes the first item on the list
----------------------------------------------------------------
function LinkedList:removeFirst()
if(self.head == nil) then return end
-- Remove the head
removeNode(self, self.head)
end
return LinkedList
|
----------------------------------------------------------------
-- Doubly-linked List
--
-- @classmod LinkedList
-- @author [email protected]
-- @usage
-- dll = LinkedList.new()
-- dll:pushBack("Some data")
-- print(dll:popBack())
----------------------------------------------------------------
local Node = require('bidi.LNode')
local LinkedList = {}
LinkedList.__index = LinkedList
----------------------------------------------------------------
-- Creates a new Doubly-linked List
-- @constructor
--
-- @return **(LinkedList)** New LinkedList
----------------------------------------------------------------
function LinkedList.new()
local self = {}
self.head = nil
self.tail = nil
self.count = 0
setmetatable(self, LinkedList)
return self
end
-- Removes a node from the list
local function removeNode(list, node)
local prevN = node.prev
local nextN = node.next
if(prevN ~= nil) then
prevN.next = nextN
else
-- The node was at the head
list.head = nextN
end
if(nextN ~= nil) then
nextN.prev = prevN
else
-- The node was at the tail
list.tail = prevN
end
node.prev = nil
node.next = nil
node:setData(nil)
list.count = list.count - 1
end
----------------------------------------------------------------
-- Returns the list's first node
--
-- @return **(LNode)** The first node or nil
----------------------------------------------------------------
function LinkedList:getHead()
return self.head
end
----------------------------------------------------------------
-- Returns the last node
--
-- @return **(LNode)** The last node or nil
----------------------------------------------------------------
function LinkedList:getTail()
return self.tail
end
----------------------------------------------------------------
-- Returns the number of items in the list
--
-- @return **(num)** The number of items on the list
----------------------------------------------------------------
function LinkedList:getCount()
return self.count
end
----------------------------------------------------------------
-- Pushes the data to the back of the list inside a new Node
--
-- @param data **(any)** Any data to store in the list
----------------------------------------------------------------
function LinkedList:pushBack(data)
local node = Node.new(data)
if(self.head == nil) then
self.head = node
self.tail = node
else
self.tail.next = node
node.prev = self.tail
self.tail = node
end
self.count = self.count + 1
end
----------------------------------------------------------------
-- Pushes the data to the front of the list inside a new node
--
-- @param data **(any)** The data to store
----------------------------------------------------------------
function LinkedList:pushFront(data)
local node = Node.new(data)
if(self.head == nil)then
self.head = node
self.tail = node
else
self.head.prev = node
node.next = self.head
self.head = node
end
self.count = self.count + 1
end
----------------------------------------------------------------
-- Deletas all the nodes and data references in the list
----------------------------------------------------------------
function LinkedList:deleteAll()
if(self.head == nil) then return end
local n = self.head
repeat
local nextNode = n.next
n:setData(nil)
n.next = nil
n.prev = nil
self.count = self.count -1
n = nextNode
until(n == nil)
self.head = nil
self.tail = nil
end
----------------------------------------------------------------
-- Pops the first element's data. Removes it from the list
--
-- @return **(data)** The first data stored in the list
----------------------------------------------------------------
function LinkedList:popFront()
if(self.head == nil) then return nil end
local wasHead = self.head
if(wasHead.next ~= nil) then
self.head = wasHead.next
self.head.prev = nil
end
self.count = self.count - 1
return wasHead:getData()
end
----------------------------------------------------------------
-- Removes and returns the last data in the list
--
-- @return **(data)** The last item's data
----------------------------------------------------------------
function LinkedList:popBack()
if(self.head == nil) then return nil end
local wasTail = self.tail
if(wasTail.prev ~= nil) then
self.tail = wasTail.prev
self.tail.next = nil
end
self.count = self.count - 1
return wasTail:getData()
end
----------------------------------------------------------------
-- Returns all the data inside the list as an array. Uses '[nil]' for nil data
--
-- return **({arr})** An array with the data.
----------------------------------------------------------------
function LinkedList:getDataArray()
local dataArray = {}
local node = self.head
while node ~= nil do
if(node:getData() ~= nil) then
table.insert(dataArray, node:getData())
else
table.insert(dataArray, "[nil]")
end
node = node.next
end
return dataArray
end
----------------------------------------------------------------
-- Same as above but backwards ordered
--
-- @return **({arr})** An array with the data reversed.
----------------------------------------------------------------
function LinkedList:getDataArrayBackwards()
local dataArray = {}
local node = self.tail
while (node ~= nil) do
if(node:getData() ~= nil) then
table.insert(dataArray, node:getData())
else
table.insert(dataArray, "[nil]")
end
node = node.prev
end
return dataArray
end
----------------------------------------------------------------
-- Removes the last item on the list
----------------------------------------------------------------
function LinkedList:removeLast()
if(self.tail == nil) then return end
-- Remove the tail
removeNode(self, self.tail)
end
----------------------------------------------------------------
-- Removes the first item on the list
----------------------------------------------------------------
function LinkedList:removeFirst()
if(self.head == nil) then return end
-- Remove the head
removeNode(self, self.head)
end
return LinkedList
|
Fix method removed in error
|
Fix method removed in error
|
Lua
|
mit
|
ufyTeX/luabidi
|
41d4204c491037730908ffbc8818e0b4657a50fd
|
init.lua
|
init.lua
|
require 'action'
require 'hotkey_modal'
require 'profile'
----------------------------------------------------------------------------------------------------
-- Settings
----------------------------------------------------------------------------------------------------
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}, {
["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)},
["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),
Action.EnsureIsInScreenBounds(),
Action.PositionBottomRight()
},
["TextMate"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
})
----------------------------------------------------------------------------------------------------
Profile.new('Work', {2077750397, 188898833, 188898834, 188898835, 188898836, 188915586}, {
["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()},
["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),
Action.EnsureIsInScreenBounds(),
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()}
})
----------------------------------------------------------------------------------------------------
-- Hotkey Bindings
----------------------------------------------------------------------------------------------------
local mash = {'ctrl', 'alt'}
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() utils.snapAll() end)
hs.hotkey.bind(mash, 'H', function() hs.hints.windowHints() end)
hs.hotkey.bind(mash, 'G', function() hs.grid.toggleShow() end)
hs.hotkey.bind(mash, '^', function() Profile.activateActiveProfile() end)
local position = HotkeyModal.new('Position', mash, '1')
position:bind({}, 'UP', function() Action.PositionBottomLeft()(focusedWin()) end)
position:bind({}, 'DOWN', function() Action.PositionBottomRight()(focusedWin()) end)
position:bind({}, 'LEFT', function() Action.PositionTopLeft()(focusedWin()) end)
position:bind({}, 'RIGHT', function() Action.PositionTopRight()(focusedWin()) end)
position:bind({}, 'RETURN', function() position:exit() end)
local resize = HotkeyModal.new('Resize', mash, '2')
resize:bind({}, 'UP', function() hs.grid.resizeWindowShorter() end)
resize:bind({}, 'DOWN', function() hs.grid.resizeWindowTaller() end)
resize:bind({}, 'LEFT', function() hs.grid.resizeWindowThinner() end)
resize:bind({}, 'RIGHT', function() hs.grid.resizeWindowWider() end)
resize:bind({}, 'RETURN', function() resize:exit() end)
local move = HotkeyModal.new('Move', mash, '3')
move:bind({}, 'UP', function() hs.grid.pushWindowUp() end)
move:bind({}, 'DOWN', function() hs.grid.pushWindowDown() end)
move:bind({}, 'LEFT', function() hs.grid.pushWindowLeft() end)
move:bind({}, 'RIGHT', function() hs.grid.pushWindowRight() end)
move:bind({}, 'RETURN', function() move:exit() end)
local appShortcuts = {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['d'] = 'Dash',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'Tower',
['m'] = 'iTunes',
['p'] = 'Parallels Desktop',
['t'] = 'Terminal',
['x'] = 'Xcode',
}
for shortcut, appName in pairs(appShortcuts) do
hs.hotkey.bind({'alt', 'cmd'}, shortcut, function() hs.application.launchOrFocus(appName) end)
end
----------------------------------------------------------------------------------------------------
-- Watcher
----------------------------------------------------------------------------------------------------
function appEvent(appName, event) if event == hs.application.watcher.launched then Profile.activateForApp(appName) end end
function pathEvent(files) hs.reload() end
function screenEvent() Profile.activateActiveProfile() end
hs.application.watcher.new(appEvent):start()
hs.pathwatcher.new(hs.configdir, pathEvent):start()
hs.screen.watcher.new(screenEvent):start()
screenEvent()
|
require 'action'
require 'hotkey_modal'
require 'profile'
----------------------------------------------------------------------------------------------------
-- Settings
----------------------------------------------------------------------------------------------------
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
----------------------------------------------------------------------------------------------------
function handleTerminalWindow(win)
hs.timer.doAfter(hs.window.animationDuration,
function()
Action.EnsureIsInScreenBounds()(win)
hs.timer.doAfter(hs.window.animationDuration, function() Action.PositionBottomRight()(win) end)
end)
end
Profile.new('Home', {69671680}, {
["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)},
["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), handleTerminalWindow},
["TextMate"] = {Action.MoveToScreen(1), Action.MoveToUnit(0.5, 0.0, 0.5, 1.0)},
["Xcode"] = {Action.MoveToScreen(1), Action.Maximize()},
["_"] = {Action.Snap()}
})
----------------------------------------------------------------------------------------------------
Profile.new('Work', {2077750397, 188898833, 188898834, 188898835, 188898836, 188915586}, {
["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()},
["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), handleTerminalWindow},
["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()}
})
----------------------------------------------------------------------------------------------------
-- Hotkey Bindings
----------------------------------------------------------------------------------------------------
local mash = {'ctrl', 'alt'}
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() utils.snapAll() end)
hs.hotkey.bind(mash, 'H', function() hs.hints.windowHints() end)
hs.hotkey.bind(mash, 'G', function() hs.grid.toggleShow() end)
hs.hotkey.bind(mash, '^', function() Profile.activateActiveProfile() end)
local position = HotkeyModal.new('Position', mash, '1')
position:bind({}, 'UP', function() Action.PositionBottomLeft()(focusedWin()) end)
position:bind({}, 'DOWN', function() Action.PositionBottomRight()(focusedWin()) end)
position:bind({}, 'LEFT', function() Action.PositionTopLeft()(focusedWin()) end)
position:bind({}, 'RIGHT', function() Action.PositionTopRight()(focusedWin()) end)
position:bind({}, 'RETURN', function() position:exit() end)
local resize = HotkeyModal.new('Resize', mash, '2')
resize:bind({}, 'UP', function() hs.grid.resizeWindowShorter() end)
resize:bind({}, 'DOWN', function() hs.grid.resizeWindowTaller() end)
resize:bind({}, 'LEFT', function() hs.grid.resizeWindowThinner() end)
resize:bind({}, 'RIGHT', function() hs.grid.resizeWindowWider() end)
resize:bind({}, 'RETURN', function() resize:exit() end)
local move = HotkeyModal.new('Move', mash, '3')
move:bind({}, 'UP', function() hs.grid.pushWindowUp() end)
move:bind({}, 'DOWN', function() hs.grid.pushWindowDown() end)
move:bind({}, 'LEFT', function() hs.grid.pushWindowLeft() end)
move:bind({}, 'RIGHT', function() hs.grid.pushWindowRight() end)
move:bind({}, 'RETURN', function() move:exit() end)
local appShortcuts = {
['a'] = 'Atom',
['c'] = 'Google Chrome',
['d'] = 'Dash',
['e'] = 'TextMate',
['f'] = 'Finder',
['g'] = 'Tower',
['m'] = 'iTunes',
['p'] = 'Parallels Desktop',
['t'] = 'Terminal',
['x'] = 'Xcode',
}
for shortcut, appName in pairs(appShortcuts) do
hs.hotkey.bind({'alt', 'cmd'}, shortcut, function() hs.application.launchOrFocus(appName) end)
end
----------------------------------------------------------------------------------------------------
-- Watcher
----------------------------------------------------------------------------------------------------
function appEvent(appName, event) if event == hs.application.watcher.launched then Profile.activateForApp(appName) end end
function pathEvent(files) hs.reload() end
function screenEvent() Profile.activateActiveProfile() end
hs.application.watcher.new(appEvent):start()
hs.pathwatcher.new(hs.configdir, pathEvent):start()
hs.screen.watcher.new(screenEvent):start()
screenEvent()
|
Fix Terminal window handling again
|
Fix Terminal window handling again
|
Lua
|
mit
|
mgee/hammerspoon-config
|
f4c67d996571566fc3d8432c07c7fd13ae010564
|
layout-app.lua
|
layout-app.lua
|
local book = SILE.require("classes/book");
book:defineMaster({ id = "right", firstContentFrame = "content", frames = {
content = {left = "2mm", right = "100%pw-2mm", top = "12mm", bottom = "100%ph-2mm" },
runningHead = {left = "left(content)", right = "right(content)", top = "top(content)-10mm", bottom = "top(content)-2mm" },
footnotes = {left = "left(content)", right = "right(content)", top = "0", height = "0" },
}})
book:defineMaster({ id = "left", firstContentFrame = "content", frames = {}})
book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" });
book:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", {id="right"})
SILE.registerCommand("imprint:font", function(options, content)
SILE.call("font", { family="Libertinus Serif", size="6.5pt", language="und" }, content)
end)
SILE.registerCommand("meta:distribution", function(options, content)
SILE.call("font", { weight=600, style="Bold" }, {"Yayın: "})
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function(options, content)
end)
SILE.require("packages/background")
SILE.call("background", { color="#e9d8ba" })
local inkColor = SILE.colorparser("#5a4129")
SILE.outputter:pushColor(inkColor)
|
local book=SILE.require("classes/book");
book:defineMaster({ id="right", firstContentFrame="content", frames={
content={ left="2mm", right="100%pw-2mm", top="12mm", bottom="top(footnotes)" },
runningHead= {left="left(content)", right="right(content)", top="top(content)-10mm", bottom="top(content)-2mm" },
footnotes={ left="left(content)", right="right(content)", bottom="100%ph-2mm", height="0" },
}})
book:defineMaster({ id="left", firstContentFrame="content", frames={}})
book:loadPackage("twoside", { oddPageMaster="right", evenPageMaster="left" });
book:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", {id="right"})
SILE.registerCommand("imprint:font", function(options, content)
SILE.call("font", { family="Libertinus Serif", size="6.5pt", language="und" }, content)
end)
SILE.registerCommand("meta:distribution", function(options, content)
SILE.call("font", { weight=600, style="Bold" }, {"Yayın: "})
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function(options, content)
end)
SILE.require("packages/background")
SILE.call("background", { color="#e9d8ba" })
local inkColor = SILE.colorparser("#5a4129")
SILE.outputter:pushColor(inkColor)
|
Attach footnote frame to page bottom instead of top
|
Attach footnote frame to page bottom instead of top
Fixes viachristus/mujdeyi_kurtarmak#96
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
73f4dc82b707a0e369ed208a4ae0b4a1401a7ae1
|
core/engine.lua
|
core/engine.lua
|
Engine = class("Engine")
function Engine:__init()
self.entities = {}
self.requirements = {}
self.entityLists = {}
self.allSystems = {}
self.logicSystems = {}
self.drawSystems = {}
self.freeIds = {}
end
function Engine:addEntity(entity)
if #self.freeIds == 0 then
table.insert(self.entities, entity)
entity.id = #self.entities
else
entity.id = self.freeIds[#self.freeIds]
self.entities[entity.id] = entity
table.remove(self.freeIds, #self.freeIds)
end
for index, component in pairs(entity.components) do
-- Adding Entity to specific Entitylist
self.entityLists[component.__name] = self.entityLists[component.__name] or {}
self.entityLists[component.__name][entity.id] = entity
-- Adding Entity to System if all requirements are granted
if self.requirements[component.__name] then
for index2, system in pairs(self.requirements[component.__name]) do
local meetsRequirements = true
for index3, requirement in pairs(system:getRequiredComponents()) do
if meetsRequirements == true then
for index4, component in pairs(entity.components) do
if component.__name == requirement then
meetsRequirements = true
break
else
meetsRequirements = false
end
end
else
break
end
end
if meetsRequirements == true then
system:addEntity(entity)
end
end
end
end
end
function Engine:removeEntity(entity)
if self.entities[entity.id] == entity then
-- Stashing the id of the removed Entity in self.freeIds
table.insert(self.freeIds, entity.id)
-- Removing the Entity from all Systems and engine
for i, component in pairs(entity.components) do
if self.requirements[component.__name] then
for i2, system in pairs(self.requirements[component.__name]) do
system:removeEntity(entity)
end
end
end
-- Deleting the Entity from the specific entity lists
for index, component in pairs(entity.components) do
if self.entityLists[component.__name] then
self.entityLists[component.__name][entity.id] = nil
end
end
self.entities[entity.id] = nil
end
end
function Engine:addSystem(system, type)
-- Adding System to draw or logic table
if type == "draw" then
table.insert(self.drawSystems, system)
elseif type == "logic" then
table.insert(self.logicSystems, system)
end
table.insert(self.allSystems, system)
-- Registering the systems requirements and saving them in a special table for fast access
for index, value in pairs(system:getRequiredComponents()) do
self.requirements[value] = self.requirements[value] or {}
table.insert(self.requirements[value], system)
end
return system
end
function Engine:update(dt)
for index, system in ipairs(self.logicSystems) do
system:update(dt)
end
end
function Engine:draw()
for index, system in ipairs(self.drawSystems) do
system:draw()
end
-- Enable to get white boxes around Bodies with polygonshapes
--[[
for key, entity in pairs(self:getEntitylist("PhysicsComponent")) do
x1, y1, x2, y2 = entity:getComponent("PhysicsComponent").fixture:getBoundingBox()
if entity:getComponent("PhysicsComponent").shape.getPoints then
love.graphics.polygon("fill", entity:getComponent("PhysicsComponent").body:getWorldPoints(entity:getComponent("PhysicsComponent").shape:getPoints()))
end
end
--]]--
end
function Engine:componentRemoved(entity, removed)
if removed then
for i, component in pairs(removed) do
-- Removing Entity from Entitylists
self.entityLists[component][entity.id] = nil
-- Removing Entity from old systems
if self.requirements[component] then
for i2, system in pairs(self.requirements[component]) do
system:removeEntity(entity)
end
end
end
end
end
function Engine:componentAdded(entity, added)
for i, component in pairs(added) do
-- Adding the Entity to Entitylist
if self.entityLists[component] then
table.insert(self.entityLists[component], entity)
else
self.entityLists[component] = {}
table.insert(self.entityLists[component], entity)
end
-- Adding the Entity to the requiring systems
if self.requirements[component] then
for i2, system in pairs(self.requirements[component]) do
local add = true
for i3, req in pairs(system.getRequiredComponents()) do
for i3, comp in pairs(entity.components) do
if comp.__name == req then
add = true
break
else
add = false
end
end
end
if add == true then
system:addEntity(entity)
end
end
end
end
end
-- Returns an Entitylist for a specific component. If the Entitylist doesn't exists yet it'll be created and returned.
function Engine:getEntitylist(component)
if self.entityLists[component] then
return self.entityLists[component]
else
self.entityLists[component] = {}
return self.entityLists[component]
end
end
|
Engine = class("Engine")
function Engine:__init()
self.entities = {}
self.requirements = {}
self.entityLists = {}
self.allSystems = {}
self.logicSystems = {}
self.drawSystems = {}
self.freeIds = {}
end
function Engine:addEntity(entity)
if #self.freeIds == 0 then
table.insert(self.entities, entity)
entity.id = #self.entities
else
entity.id = self.freeIds[#self.freeIds]
self.entities[entity.id] = entity
table.remove(self.freeIds, #self.freeIds)
end
for index, component in pairs(entity.components) do
-- Adding Entity to specific Entitylist
self.entityLists[component.__name] = self.entityLists[component.__name] or {}
self.entityLists[component.__name][entity.id] = entity
-- Adding Entity to System if all requirements are granted
if self.requirements[component.__name] then
for index2, system in pairs(self.requirements[component.__name]) do
local meetsRequirements = true
for index3, requirement in pairs(system:getRequiredComponents()) do
if meetsRequirements == true then
for index4, component in pairs(entity.components) do
if component.__name == requirement then
meetsRequirements = true
break
else
meetsRequirements = false
end
end
else
break
end
end
if meetsRequirements == true then
system:addEntity(entity)
end
end
end
end
end
function Engine:removeEntity(entity)
if self.entities[entity.id] == entity then
-- Stashing the id of the removed Entity in self.freeIds
table.insert(self.freeIds, entity.id)
-- Removing the Entity from all Systems and engine
for i, component in pairs(entity.components) do
if self.requirements[component.__name] then
for i2, system in pairs(self.requirements[component.__name]) do
system:removeEntity(entity)
end
end
end
-- Deleting the Entity from the specific entity lists
for index, component in pairs(entity.components) do
if self.entityLists[component.__name] then
self.entityLists[component.__name][entity.id] = nil
end
end
self.entities[entity.id] = nil
end
end
function Engine:addSystem(system, type)
-- Adding System to draw or logic table
if type == "draw" then
table.insert(self.drawSystems, system)
elseif type == "logic" then
table.insert(self.logicSystems, system)
end
table.insert(self.allSystems, system)
-- Registering the systems requirements and saving them in a special table for fast access
for index, value in pairs(system:getRequiredComponents()) do
self.requirements[value] = self.requirements[value] or {}
table.insert(self.requirements[value], system)
end
return system
end
function Engine:update(dt)
for index, system in ipairs(self.logicSystems) do
system:update(dt)
end
end
function Engine:draw()
for index, system in ipairs(self.drawSystems) do
system:draw()
end
-- Enable to get white boxes around Bodies with polygonshapes
--[[
for key, entity in pairs(self:getEntitylist("PhysicsComponent")) do
x1, y1, x2, y2 = entity:getComponent("PhysicsComponent").fixture:getBoundingBox()
if entity:getComponent("PhysicsComponent").shape.getPoints then
love.graphics.polygon("fill", entity:getComponent("PhysicsComponent").body:getWorldPoints(entity:getComponent("PhysicsComponent").shape:getPoints()))
end
end
--]]--
end
function Engine:componentRemoved(entity, removed)
if removed then
for i, component in pairs(removed) do
-- Removing Entity from Entitylists
self.entityLists[component][entity.id] = nil
-- Removing Entity from old systems
if self.requirements[component] then
for i2, system in pairs(self.requirements[component]) do
system:removeEntity(entity)
end
end
end
end
end
function Engine:componentAdded(entity, added)
for i, component in pairs(added) do
-- Adding the Entity to Entitylist
if self.entityLists[component] then
self.entityLists[component][entity.id] = entity
else
self.entityLists[component] = {}
self.entityLists[component][entity.id] = entity
end
-- Adding the Entity to the requiring systems
if self.requirements[component] then
for i2, system in pairs(self.requirements[component]) do
local add = true
for i3, req in pairs(system.getRequiredComponents()) do
for i3, comp in pairs(entity.components) do
if comp.__name == req then
add = true
break
else
add = false
end
end
end
if add == true then
system:addEntity(entity)
end
end
end
end
end
-- Returns an Entitylist for a specific component. If the Entitylist doesn't exists yet it'll be created and returned.
function Engine:getEntitylist(component)
if self.entityLists[component] then
return self.entityLists[component]
else
self.entityLists[component] = {}
return self.entityLists[component]
end
end
|
Bug fixed
|
Bug fixed
- componentAdded in Engine added Entities with wrong index into entitieLists
|
Lua
|
mit
|
takaaptech/lovetoys,xpol/lovetoys
|
89ede95aef19c2efa52ec329e5ef2e40fdd33494
|
core/rostermanager.lua
|
core/rostermanager.lua
|
local mainlog = log;
local function log(type, message)
mainlog(type, "rostermanager", message);
end
local setmetatable = setmetatable;
local format = string.format;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
require "util.datamanager"
local datamanager = datamanager;
module "rostermanager"
--[[function getroster(username, host)
return {
["mattj@localhost"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
}
--return datamanager.load(username, host, "roster") or {};
end]]
function add_to_roster(roster, jid, item)
roster[jid] = item;
-- TODO implement
end
function remove_from_roster(roster, jid)
roster[jid] = nil;
-- TODO implement
end
function load_roster(host, username)
if hosts[host] and hosts[host].sessions[username] then
local roster = hosts[host].sessions[username].roster;
if not roster then
return hosts[host].sessions[username].roster = datamanger.load(username, host, "roster") or {};
end
return roster;
end
error("Attempt to load roster for non-loaded user"); --return nil;
end
function save_roster(host, username)
if hosts[host] and hosts[host].sessions[username] and hosts[host].sessions[username].roster then
return datamanager.save(username, host, "roster", hosts[host].sessions[username].roster);
end
return nil;
end
return _M;
|
local mainlog = log;
local function log(type, message)
mainlog(type, "rostermanager", message);
end
local setmetatable = setmetatable;
local format = string.format;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local hosts = hosts;
require "util.datamanager"
local datamanager = datamanager;
module "rostermanager"
--[[function getroster(username, host)
return {
["mattj@localhost"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
["[email protected]"] = true,
}
--return datamanager.load(username, host, "roster") or {};
end]]
function add_to_roster(roster, jid, item)
roster[jid] = item;
-- TODO implement
end
function remove_from_roster(roster, jid)
roster[jid] = nil;
-- TODO implement
end
function load_roster(username, host)
if hosts[host] and hosts[host].sessions[username] then
local roster = hosts[host].sessions[username].roster;
if not roster then
roster = datamanager.load(username, host, "roster") or {};
hosts[host].sessions[username].roster = roster;
end
return roster;
end
error("Attempt to load roster for non-loaded user"); --return nil;
end
function save_roster(username, host)
if hosts[host] and hosts[host].sessions[username] and hosts[host].sessions[username].roster then
return datamanager.save(username, host, "roster", hosts[host].sessions[username].roster);
end
return nil;
end
return _M;
|
Fixed: Typos caused by lack of sleep. Learned: Lua variable assignments are not expressions.
|
Fixed: Typos caused by lack of sleep.
Learned: Lua variable assignments are not expressions.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
f82ead2b39ef0a91ac384863103bf8e318302d10
|
datastorage.lua
|
datastorage.lua
|
-- need low-level mechnism to detect android to avoid recursive dependency
local isAndroid, android = pcall(require, "android")
local lfs = require("libs/libkoreader-lfs")
local DataStorage = {}
local data_dir
local full_data_dir
function DataStorage:getDataDir()
if data_dir then return data_dir end
if isAndroid then
data_dir = android.getExternalStoragePath() .. "/koreader"
elseif os.getenv("UBUNTU_APPLICATION_ISOLATION") then
local app_id = os.getenv("APP_ID")
local package_name = app_id:match("^(.-)_")
-- confined ubuntu app has write access to this dir
data_dir = string.format("%s/%s", os.getenv("XDG_DATA_HOME"), package_name)
elseif os.getenv("APPIMAGE") or os.getenv("KO_MULTIUSER") then
local user_rw = jit.os == "OSX" and "Library/Application Support" or ".config"
data_dir = string.format("%s/%s/%s", os.getenv("HOME"), user_rw, "koreader")
else
data_dir = "."
end
if lfs.attributes(data_dir, "mode") ~= "directory" then
lfs.mkdir(data_dir)
end
return data_dir
end
function DataStorage:getHistoryDir()
return self:getDataDir() .. "/history"
end
function DataStorage:getSettingsDir()
return self:getDataDir() .. "/settings"
end
function DataStorage:getFullDataDir()
if full_data_dir then return full_data_dir end
if string.sub(self:getDataDir(), 1, 1) == "/" then
full_data_dir = self:getDataDir()
elseif self:getDataDir() == "." then
full_data_dir = lfs.currentdir()
end
return full_data_dir
end
local function initDataDir()
local sub_data_dirs = {
"cache", "clipboard",
"data", "data/dict", "data/tessdata",
"history", "ota", "plugins",
"screenshots", "settings", "styletweaks",
}
for _, dir in ipairs(sub_data_dirs) do
local sub_data_dir = string.format("%s/%s", DataStorage:getDataDir(), dir)
if lfs.attributes(sub_data_dir, "mode") ~= "directory" then
lfs.mkdir(sub_data_dir)
end
end
end
initDataDir()
return DataStorage
|
-- need low-level mechnism to detect android to avoid recursive dependency
local isAndroid, android = pcall(require, "android")
local lfs = require("libs/libkoreader-lfs")
local DataStorage = {}
local data_dir
local full_data_dir
function DataStorage:getDataDir()
if data_dir then return data_dir end
if isAndroid then
data_dir = android.getExternalStoragePath() .. "/koreader"
elseif os.getenv("UBUNTU_APPLICATION_ISOLATION") then
local app_id = os.getenv("APP_ID")
local package_name = app_id:match("^(.-)_")
-- confined ubuntu app has write access to this dir
data_dir = string.format("%s/%s", os.getenv("XDG_DATA_HOME"), package_name)
elseif os.getenv("APPIMAGE") or os.getenv("KO_MULTIUSER") then
if os.getenv("XDG_CONFIG_HOME") then
data_dir = string.format("%s/%s", os.getenv("XDG_CONFIG_HOME"), "koreader")
else
local user_rw = jit.os == "OSX" and "Library/Application Support" or ".config"
data_dir = string.format("%s/%s/%s", os.getenv("HOME"), user_rw, "koreader")
end
else
data_dir = "."
end
if lfs.attributes(data_dir, "mode") ~= "directory" then
lfs.mkdir(data_dir)
end
return data_dir
end
function DataStorage:getHistoryDir()
return self:getDataDir() .. "/history"
end
function DataStorage:getSettingsDir()
return self:getDataDir() .. "/settings"
end
function DataStorage:getFullDataDir()
if full_data_dir then return full_data_dir end
if string.sub(self:getDataDir(), 1, 1) == "/" then
full_data_dir = self:getDataDir()
elseif self:getDataDir() == "." then
full_data_dir = lfs.currentdir()
end
return full_data_dir
end
local function initDataDir()
local sub_data_dirs = {
"cache", "clipboard",
"data", "data/dict", "data/tessdata",
"history", "ota", "plugins",
"screenshots", "settings", "styletweaks",
}
for _, dir in ipairs(sub_data_dirs) do
local sub_data_dir = string.format("%s/%s", DataStorage:getDataDir(), dir)
if lfs.attributes(sub_data_dir, "mode") ~= "directory" then
lfs.mkdir(sub_data_dir)
end
end
end
initDataDir()
return DataStorage
|
Fix koreader not using XDG_CONFIG_HOME on linux (#8507)
|
Fix koreader not using XDG_CONFIG_HOME on linux (#8507)
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,koreader/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader
|
c970f33bc26683e675000c39dc205f5d0e58ab17
|
kong/db/strategies/cassandra/plugins.lua
|
kong/db/strategies/cassandra/plugins.lua
|
local cassandra = require "cassandra"
local split = require("pl.stringx").split
local cjson = require("cjson")
local insert = table.insert
local fmt = string.format
local Plugins = {}
-- Emulate the `select_by_cache_key` operation
-- using the `plugins` table of a 0.14 database.
-- @tparam string key a 0.15+ plugin cache_key
-- @treturn table|nil,err the row for this unique cache_key
-- or nil and an error object.
function Plugins:select_by_cache_key_migrating(key)
-- unpack cache_key
local parts = split(key, ":")
-- build query and args
local qbuild = { "SELECT * FROM %s WHERE name = ?" }
local args = { cassandra.text(parts[2]) }
for i, field in ipairs({
"route_id",
"service_id",
"consumer_id",
"api_id",
}) do
local id = parts[i + 2]
if id ~= "" then
insert(qbuild, field .. " = ?")
insert(args, cassandra.uuid(id))
else
parts[i + 2] = nil
end
end
local query = table.concat(qbuild, " AND ") .. " ALLOW FILTERING"
-- perform query, trying both temp and old table
local errs = 0
local last_err
for _, tbl in ipairs({ "plugins_temp", "plugins" }) do
for rows, err in self.connector.cluster:iterate(fmt(query, tbl), args) do
if err then
-- some errors here may happen depending of migration stage
errs = errs + 1
last_err = err
break
end
for i = 1, #rows do
local row = rows[i]
if row then
if row.route_id == parts[3] and
row.service_id == parts[4] and
row.consumer_id == parts[5] and
row.api_id == parts[6] then
row.config = cjson.decode(row.config)
row.cache_key = nil
return row
end
end
end
end
end
-- not found
return nil, errs == 2 and last_err
end
return Plugins
|
local cassandra = require "cassandra"
local split = require("pl.stringx").split
local cjson = require("cjson")
local insert = table.insert
local fmt = string.format
local Plugins = {}
-- Emulate the `select_by_cache_key` operation
-- using the `plugins` table of a 0.14 database.
-- @tparam string key a 0.15+ plugin cache_key
-- @treturn table|nil,err the row for this unique cache_key
-- or nil and an error object.
function Plugins:select_by_cache_key_migrating(key)
-- unpack cache_key
local parts = split(key, ":")
local c3 = self.connector.major_version >= 3
-- build query and args
local qbuild = {}
local args = {}
for i, field in ipairs({
"route_id",
"service_id",
"consumer_id",
"api_id",
}) do
local id = parts[i + 2]
if id ~= "" then
if c3 or #args == 0 then
insert(qbuild, field .. " = ?")
insert(args, cassandra.uuid(id))
end
else
parts[i + 2] = nil
end
end
if c3 or #args == 0 then
insert(qbuild, "name = ?")
insert(args, cassandra.text(parts[2]))
end
local query = "SELECT * FROM %s WHERE " ..
table.concat(qbuild, " AND ") ..
" ALLOW FILTERING"
-- perform query, trying both temp and old table
local errs = 0
local last_err
for _, tbl in ipairs({ "plugins_temp", "plugins" }) do
for rows, err in self.connector.cluster:iterate(fmt(query, tbl), args) do
if err then
-- some errors here may happen depending of migration stage
errs = errs + 1
last_err = err
break
end
for i = 1, #rows do
local row = rows[i]
if row then
if row.name == parts[2] and
row.route_id == parts[3] and
row.service_id == parts[4] and
row.consumer_id == parts[5] and
row.api_id == parts[6] then
row.config = cjson.decode(row.config)
row.cache_key = nil
return row
end
end
end
end
end
-- not found
return nil, errs == 2 and last_err
end
return Plugins
|
hotfix(db) fix Plugins cache_key translation function for C* 2.x
|
hotfix(db) fix Plugins cache_key translation function for C* 2.x
Complex queries (even with `ALLOW FILTERING`) can cause a Java exception in
Cassandra 2. This commit simplifies the query when using Cassandra 2 to only
filter by a single non-null entry -- either one of the ids set, or the plugin
name as a fallback -- and then filter the results in Lua.
From #3893
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
c8a3c4b755bf08e4cef431d98a0a2b9994db978d
|
scripts/entity_system.lua
|
scripts/entity_system.lua
|
entity_system = inherits_from ()
function entity_system:constructor(deletes_caller)
self.deletes_caller = deletes_caller
self.all_systems = {}
self.messages = {}
self.message_groups = {}
self.callbacks = {}
self.to_be_removed = {}
self.cpp_entity = cpp_entity_system:create()
self:register_systems( { ["cpp_entity"] = self.cpp_entity } )
end
function entity_system:register_messages(msgs)
for k, v in pairs(msgs) do
if self.messages[v] == nil then self.messages[v] = {} end
end
self:flush_messages()
end
function entity_system:register_callbacks(callbacks)
self.callbacks = callbacks
end
function entity_system:register_message_group(group_name, msgs)
self.message_groups[group_name] = msgs
self:flush_messages()
end
function entity_system:flush_messages()
for k, v in pairs(self.messages) do
self.messages[k] = {}
end
for group_name, messages_in_group in pairs(self.message_groups) do
self.messages[group_name] = {}
for ind, msg_name in pairs(messages_in_group) do
-- point message name to its group
self.messages[msg_name] = self.messages[group_name]
end
end
end
function entity_system:post(name, msg_table)
self:post_table(name, _G[name]:create(msg_table))
end
GLOBAL_MESSAGE_ID = 0
function entity_system:post_table(name, msg_table)
msg_table.name = name
--if name == "item_wielder_change" then
-- GLOBAL_MESSAGE_ID = GLOBAL_MESSAGE_ID + 1
-- msg_table._MESSAGE_ID = GLOBAL_MESSAGE_ID
----
-- --local out = debug.traceback()
-- global_logfile:write("\nMESSAGE ID: \n" .. GLOBAL_MESSAGE_ID .. "\n\n")
-- global_logfile:write(debug.traceback())
--end
if self.callbacks[name] then
self.callbacks[name](msg_table)
else
table.insert(self.messages[name], msg_table)
end
end
function entity_system:register_systems(new_systems)
for k, v in pairs(new_systems) do
v.owner_entity_system = self
self.all_systems[k] = v
end
end
function entity_system:post_remove(removed_entity)
self.to_be_removed[removed_entity] = true
end
function entity_system:handle_removed_entities()
for k, v in pairs (self.to_be_removed) do
self:remove_entity(k)
end
self.to_be_removed = {}
self.deletes_caller()
end
function entity_system:for_all_matching_systems(component_set, callback)
for k, v in pairs(self.all_systems) do
local required_components = v:get_required_components()
if required_components ~= nil then
local matches = true
for j=1, #required_components do
if component_set[required_components[j]] == nil then
matches = false
break
end
end
if matches then
callback(v)
end
end
end
end
function entity_system:add_entity(new_entity)
new_entity.owner_entity_system = self
self:for_all_matching_systems(new_entity, function(matching_system) matching_system:add_entity(new_entity) end)
return new_entity
end
function entity_system:remove_entity(to_be_removed)
self:for_all_matching_systems(to_be_removed, function(matching_system) matching_system:remove_entity(to_be_removed) end)
end
processing_system = inherits_from ()
function processing_system:constructor()
self.targets = {}
end
function processing_system:get_required_components()
return nil
end
function processing_system:add_entity(new_entity)
table.insert(self.targets, new_entity)
end
function processing_system:remove_entity(to_be_removed)
table.erase(self.targets, to_be_removed)
end
-- convenience table
components = {}
local function position_getter(tab, key)
if key == "pos" then
return tab.cpp_entity.transform.current.pos
elseif key == "vel" then
return to_pixels(tab.cpp_entity.physics.body:GetLinearVelocity())
elseif key == "veln" then
return to_pixels(tab.cpp_entity.physics.body:GetLinearVelocity()):normalize()
elseif key == "rot" then
return tab.cpp_entity.transform.current.pos
end
end
components.create_components = function(entry)
local output = {}
setmetatable(output, { __index = position_getter })
for k, v in pairs(entry) do
if type(v) == "table" then
output[k] = components[k]:create(v)
else
output[k] = v
end
end
return output
end
-- convenience processing_system for entities from cpp framework
cpp_entity_system = inherits_from (processing_system)
function cpp_entity_system:get_required_components()
return { "cpp_entity" }
end
function cpp_entity_system:add_entity(new_entity)
-- don't store anything
new_entity.cpp_entity.script = new_entity
end
function cpp_entity_system:remove_entity(removed_entity)
-- get world object owning that entity and delete it
local owner_world = removed_entity.cpp_entity.owner_world
--global_logfile:write(table.inspect(removed_entity))
--
--print ("removing..")
--print (removed_entity)
removed_entity.cpp_entity.script = nil
owner_world:post_message(destroy_message(removed_entity.cpp_entity, nil))
end
|
entity_system = inherits_from ()
function entity_system:constructor(deletes_caller)
self.deletes_caller = deletes_caller
self.all_systems = {}
self.messages = {}
self.message_groups = {}
self.callbacks = {}
self.to_be_removed = {}
self.cpp_entity = cpp_entity_system:create()
self:register_systems( { ["cpp_entity"] = self.cpp_entity } )
end
function entity_system:register_messages(msgs)
for k, v in pairs(msgs) do
if self.messages[v] == nil then self.messages[v] = {} end
end
self:flush_messages()
end
function entity_system:register_callbacks(callbacks)
self.callbacks = callbacks
end
function entity_system:register_message_group(group_name, msgs)
self.message_groups[group_name] = msgs
self:flush_messages()
end
function entity_system:flush_messages()
for k, v in pairs(self.messages) do
self.messages[k] = {}
end
for group_name, messages_in_group in pairs(self.message_groups) do
self.messages[group_name] = {}
for ind, msg_name in pairs(messages_in_group) do
-- point message name to its group
self.messages[msg_name] = self.messages[group_name]
end
end
end
function entity_system:post(name, msg_table)
self:post_table(name, _G[name]:create(msg_table))
end
GLOBAL_MESSAGE_ID = 0
function entity_system:post_table(name, msg_table)
msg_table.name = name
--if name == "item_wielder_change" then
-- GLOBAL_MESSAGE_ID = GLOBAL_MESSAGE_ID + 1
-- msg_table._MESSAGE_ID = GLOBAL_MESSAGE_ID
----
-- --local out = debug.traceback()
-- global_logfile:write("\nMESSAGE ID: \n" .. GLOBAL_MESSAGE_ID .. "\n\n")
-- global_logfile:write(debug.traceback())
--end
if self.callbacks[name] then
self.callbacks[name](msg_table)
else
table.insert(self.messages[name], msg_table)
end
end
function entity_system:register_systems(new_systems)
for k, v in pairs(new_systems) do
v.owner_entity_system = self
self.all_systems[k] = v
end
end
function entity_system:post_remove(removed_entity)
self.to_be_removed[removed_entity] = true
end
function entity_system:handle_removed_entities()
for k, v in pairs (self.to_be_removed) do
self:remove_entity(k)
end
self.to_be_removed = {}
self.deletes_caller()
end
function entity_system:for_all_matching_systems(component_set, callback)
for k, v in pairs(self.all_systems) do
local required_components = v:get_required_components()
if required_components ~= nil then
local matches = true
for j=1, #required_components do
if component_set[required_components[j]] == nil then
matches = false
break
end
end
if matches then
callback(v)
end
end
end
end
function entity_system:add_entity(new_entity)
new_entity.owner_entity_system = self
self:for_all_matching_systems(new_entity, function(matching_system) matching_system:add_entity(new_entity) end)
return new_entity
end
function entity_system:remove_entity(to_be_removed)
self:for_all_matching_systems(to_be_removed, function(matching_system) matching_system:remove_entity(to_be_removed) end)
end
processing_system = inherits_from ()
function processing_system:constructor()
self.targets = {}
end
function processing_system:get_required_components()
return nil
end
function processing_system:add_entity(new_entity)
table.insert(self.targets, new_entity)
end
function processing_system:remove_entity(to_be_removed)
table.erase(self.targets, to_be_removed)
end
-- convenience table
components = {}
local function position_getter(tab, key)
if key == "pos" then
return tab.cpp_entity.transform.current.pos
elseif key == "vel" then
return to_pixels(tab.cpp_entity.physics.body:GetLinearVelocity())
elseif key == "veln" then
return to_pixels(tab.cpp_entity.physics.body:GetLinearVelocity()):normalize()
elseif key == "rot" then
return tab.cpp_entity.transform.current.pos
end
end
components.create_components = function(entry)
local output = {}
setmetatable(output, { __index = position_getter })
for k, v in pairs(entry) do
if type(v) == "table" then
output[k] = components[k]:create(v)
else
output[k] = v
end
end
return output
end
-- convenience processing_system for entities from cpp framework
cpp_entity_system = inherits_from (processing_system)
function cpp_entity_system:get_required_components()
return { "cpp_entity" }
end
function cpp_entity_system:add_entity(new_entity)
-- don't store anything
local old_content = {}
if new_entity.cpp_entity.script ~= nil then
rewrite(old_content, new_entity.cpp_entity.script)
end
rewrite(new_entity, old_content)
new_entity.cpp_entity.script = new_entity
end
function cpp_entity_system:remove_entity(removed_entity)
-- get world object owning that entity and delete it
local owner_world = removed_entity.cpp_entity.owner_world
--global_logfile:write(table.inspect(removed_entity))
--
--print ("removing..")
--print (removed_entity)
removed_entity.cpp_entity.script = nil
owner_world:post_message(destroy_message(removed_entity.cpp_entity, nil))
end
|
bug correction (this is to refactor) #219
|
bug correction (this is to refactor) #219
|
Lua
|
agpl-3.0
|
TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Augmentations,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations
|
16c79d80030684edd91e8b664c033a850e3db3be
|
premake4.lua
|
premake4.lua
|
function copy(src, dst, always)
local action = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\""
src = "\"" .. src .. "\""
dst = "\"" .. dst .. "\""
cwd = "\"" .. os.getcwd() .. "\""
postbuildcommands { action .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) }
end
function resource(src, dst, always)
if always == nil then
always = false
else
always = true
end
copy(src, path.join("build", dst), always)
copy(src, path.join("bin", dst), always)
end
function windows_libdir(basePath)
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { arch, conf, plat }
libdirs { path.join(basePath, confpath) }
end
end
end
configuration "*"
end
function windows_binary(basePath, dllName)
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { arch, conf, plat }
resource(path.join(path.join(basePath, confpath), dllName), dllName, true)
end
end
end
configuration "*"
end
newaction {
trigger = 'clean',
description = 'Cleans up the project.',
shortname = "clean",
execute = function()
os.rmdir("bin")
os.rmdir("build")
end
}
solution "blowmorph"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location "build"
targetdir "bin"
flags { "FatalWarnings", "NoRTTI" }
configuration { "linux" }
flags { "NoExceptions" }
configuration { "windows" }
defines { "WIN32", "_WIN32" }
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" }
configuration { "debug" }
defines { "DEBUG" }
flags { "Symbols" }
configuration { "release" }
defines { "NDEBUG" }
flags { "Optimize" }
project "client"
kind "ConsoleApp"
language "C++"
includedirs { "include/", "src/" }
files { "src/client/**.cpp",
"src/client/**.hpp" }
links { "bm-base" }
links { "bm-enet" }
links { "interpolator" }
configuration "linux"
includedirs {
"/usr/include/freetype2",
"ext-libs/glm/include"
}
links {
"SDLmain",
"SDL",
"freeimage",
"GLEW",
"freetype"
}
configuration "windows"
includedirs {
"ext-libs/SDL1.2/include",
"ext-libs/glew/include",
"ext-libs/glm/include",
"ext-libs/FreeImage/include",
"ext-libs/freetype2/include"
}
links {
"SDLmain",
"SDL",
"freeimage",
"opengl32",
"glu32",
"glew32",
"freetype"
}
windows_libdir("ext-libs/SDL1.2/bin")
windows_libdir("ext-libs/glew/bin")
windows_libdir("ext-libs/FreeImage/bin")
windows_libdir("ext-libs/freetype2/bin")
includedirs { "ext-libs/pugixml/include" }
windows_libdir("ext-libs/pugixml/bin")
links { "pugixml" }
windows_binary("ext-libs/SDL1.2/bin", "SDL.dll")
windows_binary("ext-libs/glew/bin", "glew32.dll")
windows_binary("ext-libs/FreeImage/bin", "FreeImage.dll")
windows_binary("ext-libs/freetype2/bin", "freetype.dll")
resource("data", "data")
project "bm-base"
kind "SharedLib"
language "C++"
defines { "BM_BASE_DLL" }
includedirs { "include/", "src/" }
files { "src/base/**.cpp",
"src/base/**.hpp" }
project "bm-enet"
kind "SharedLib"
language "C++"
defines { "BM_ENET_DLL" }
includedirs { "include/", "src/" }
files { "src/enet-wrapper/**.cpp",
"src/enet-wrapper/**.hpp" }
links { "bm-base" }
includedirs { "ext-libs/enet/include" }
links { "enet" }
windows_libdir("ext-libs/enet/bin")
configuration "windows"
links {
"ws2_32",
"winmm"
}
project "interpolator"
kind "StaticLib"
language "C++"
includedirs { "include/", "src/" }
files { "src/interpolator/**.cpp",
"src/interpolator/**.hpp" }
project "server"
kind "ConsoleApp"
language "C++"
includedirs { "include/", "src/" }
files { "src/server/**.cpp",
"src/server/**.hpp" }
links { "bm-base" }
links { "bm-enet" }
includedirs { "ext-libs/pugixml/include" }
windows_libdir("ext-libs/pugixml/bin")
links { "pugixml" }
resource("data", "data")
project "sample-server"
kind "ConsoleApp"
language "C++"
includedirs { "include/", "src/" }
files { "src/enet-sample/server.cpp" }
links { "bm-base" }
links { "bm-enet" }
project "sample-client"
kind "ConsoleApp"
language "C++"
includedirs { "include/", "src/" }
files { "src/enet-sample/client.cpp" }
links { "bm-base" }
links { "bm-enet" }
|
function copy(src, dst, always)
local action = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\""
src = "\"" .. src .. "\""
dst = "\"" .. dst .. "\""
cwd = "\"" .. os.getcwd() .. "\""
postbuildcommands { action .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) }
end
function resource(src, dst, always)
if always == nil then
always = false
else
always = true
end
copy(src, path.join("build", dst), always)
copy(src, path.join("bin", dst), always)
end
function windows_libdir(basePath)
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { arch, conf, plat }
libdirs { path.join(basePath, confpath) }
end
end
end
configuration "*"
end
function windows_binary(basePath, dllName)
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { arch, conf, plat }
resource(path.join(path.join(basePath, confpath), dllName), dllName, true)
end
end
end
configuration "*"
end
newaction {
trigger = 'clean',
description = 'Cleans up the project.',
shortname = "clean",
execute = function()
os.rmdir("bin")
os.rmdir("build")
end
}
solution "blowmorph"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location "build"
targetdir "bin"
flags { "FatalWarnings", "NoRTTI" }
configuration { "linux" }
flags { "NoExceptions" }
configuration { "windows" }
defines { "WIN32", "_WIN32" }
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" }
configuration { "debug" }
defines { "DEBUG" }
flags { "Symbols" }
configuration { "release" }
defines { "NDEBUG" }
flags { "Optimize" }
project "client"
kind "ConsoleApp"
language "C++"
includedirs { "src/" }
files { "src/client/**.cpp",
"src/client/**.hpp" }
links { "bm-base" }
links { "bm-enet" }
links { "interpolator" }
configuration "linux"
includedirs {
"/usr/include/freetype2",
"ext-libs/glm/include"
}
links {
"SDLmain",
"SDL",
"freeimage",
"GLEW",
"freetype"
}
configuration "windows"
includedirs {
"ext-libs/SDL1.2/include",
"ext-libs/glew/include",
"ext-libs/glm/include",
"ext-libs/FreeImage/include",
"ext-libs/freetype2/include"
}
links {
"SDLmain",
"SDL",
"freeimage",
"opengl32",
"glu32",
"glew32",
"freetype"
}
windows_libdir("ext-libs/SDL1.2/bin")
windows_libdir("ext-libs/glew/bin")
windows_libdir("ext-libs/FreeImage/bin")
windows_libdir("ext-libs/freetype2/bin")
includedirs { "ext-libs/pugixml/include" }
windows_libdir("ext-libs/pugixml/bin")
links { "pugixml" }
windows_binary("ext-libs/SDL1.2/bin", "SDL.dll")
windows_binary("ext-libs/glew/bin", "glew32.dll")
windows_binary("ext-libs/FreeImage/bin", "FreeImage.dll")
windows_binary("ext-libs/freetype2/bin", "freetype.dll")
resource("data", "data")
project "bm-base"
kind "SharedLib"
language "C++"
defines { "BM_BASE_DLL" }
includedirs { "src/" }
files { "src/base/**.cpp",
"src/base/**.hpp" }
project "bm-enet"
kind "SharedLib"
language "C++"
defines { "BM_ENET_DLL" }
includedirs { "src/" }
files { "src/enet-wrapper/**.cpp",
"src/enet-wrapper/**.hpp" }
links { "bm-base" }
includedirs { "ext-libs/enet/include" }
windows_libdir("ext-libs/enet/bin")
links { "enet" }
configuration "windows"
links {
"ws2_32",
"winmm"
}
project "interpolator"
kind "StaticLib"
language "C++"
includedirs { "src/" }
files { "src/interpolator/**.cpp",
"src/interpolator/**.hpp" }
project "server"
kind "ConsoleApp"
language "C++"
includedirs { "src/" }
files { "src/server/**.cpp",
"src/server/**.hpp" }
links { "bm-base" }
links { "bm-enet" }
includedirs { "ext-libs/pugixml/include" }
windows_libdir("ext-libs/pugixml/bin")
links { "pugixml" }
resource("data", "data")
project "sample-server"
kind "ConsoleApp"
language "C++"
includedirs { "src/" }
files { "src/enet-sample/server.cpp" }
links { "bm-base" }
links { "bm-enet" }
project "sample-client"
kind "ConsoleApp"
language "C++"
includedirs { "src/" }
files { "src/enet-sample/client.cpp" }
links { "bm-base" }
links { "bm-enet" }
|
Minor fixes in premake4.lua
|
Minor fixes in premake4.lua
|
Lua
|
bsd-3-clause
|
bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph
|
12bf282ef290340e7b9a668854e749042d2816a7
|
graphics.lua
|
graphics.lua
|
--[[
Draw a border
@x: start position in x axis
@y: start position in y axis
@w: width of the border
@h: height of the border
@bw: line width of the border
@c: color for loading bar
@r: radius of for border's corner (nil or 0 means right corner border)
--]]
function blitbuffer.paintBorder(bb, x, y, w, h, bw, c, r)
if not r or r == 0 then
bb:paintRect(x, y, w, bw, c)
bb:paintRect(x, y+h-bw, w, bw, c)
bb:paintRect(x, y+bw, bw, h - 2*bw, c)
bb:paintRect(x+w-bw, y+bw, bw, h - 2*bw, c)
else
if h < 2*r then r = math.floor(h/2) end
if w < 2*r then r = math.floor(w/2) end
bb:paintRoundedCorner(x, y, w, h, bw, r, c)
bb:paintRect(r+x, y, w-2*r, bw, c)
bb:paintRect(r+x, y+h-bw, w-2*r, bw, c)
bb:paintRect(x, r+y, bw, h-2*r, c)
bb:paintRect(x+w-bw, r+y, bw, h-2*r, c)
end
end
--[[
Fill a rounded corner rectangular area
@x: start position in x axis
@y: start position in y axis
@w: width of the area
@h: height of the area
@c: color used to fill the area
@r: radius of for four corners
--]]
function blitbuffer.paintRoundedRect(bb, x, y, w, h, c, r)
if not r or r == 0 then
bb:paintRect(x, y, w, h, c)
else
if h < 2*r then r = math.floor(h/2) end
if w < 2*r then r = math.floor(w/2) end
bb:paintBorder(x, y, w, h, r, c, r)
bb:paintRect(x+r, y+r, w-2*r, h-2*r, c)
end
end
--[[
Draw a progress bar according to following args:
@x: start position in x axis
@y: start position in y axis
@w: width for progress bar
@h: height for progress bar
@load_m_w: width margin for loading bar
@load_m_h: height margin for loading bar
@load_percent: progress in percent
@c: color for loading bar
--]]
function blitbuffer.progressBar(bb, x, y, w, h,
load_m_w, load_m_h, load_percent, c)
if load_m_h*2 > h then
load_m_h = h/2
end
blitbuffer.paintBorder(fb.bb, x, y, w, h, 2, 15)
fb.bb:paintRect(x+load_m_w, y+load_m_h,
(w-2*load_m_w)*load_percent, (h-2*load_m_h), c)
end
------------------------------------------------
-- Start of Cursor class
------------------------------------------------
Cursor = {
x_pos = 0,
y_pos = 0,
--color = 15,
h = 10,
w = nil,
line_w = nil,
is_cleared = true,
}
function Cursor:new(o)
o = o or {}
o.x_pos = o.x_pos or self.x_pos
o.y_pos = o.y_pos or self.y_pos
o.line_width_factor = o.line_width_factor or 10
setmetatable(o, self)
self.__index = self
o:setHeight(o.h or self.h)
return o
end
function Cursor:setHeight(h)
self.h = h
self.w = self.h / 3
self.line_w = math.floor(self.h / self.line_width_factor)
end
function Cursor:_draw(x, y)
local up_down_width = math.floor(self.line_w / 2)
local body_h = self.h - (up_down_width * 2)
-- paint upper horizontal line
fb.bb:invertRect(x, y, self.w, up_down_width)
-- paint middle vertical line
fb.bb:invertRect(x + (self.w / 2) - up_down_width, y + up_down_width,
self.line_w, body_h)
-- paint lower horizontal line
fb.bb:invertRect(x, y + body_h + up_down_width, self.w, up_down_width)
end
function Cursor:draw()
if self.is_cleared then
self.is_cleared = false
self:_draw(self.x_pos, self.y_pos)
end
end
function Cursor:clear()
if not self.is_cleared then
self.is_cleared = true
self:_draw(self.x_pos, self.y_pos)
end
end
function Cursor:move(x_off, y_off)
self.x_pos = self.x_pos + x_off
self.y_pos = self.y_pos + y_off
end
function Cursor:moveHorizontal(x_off)
self.x_pos = self.x_pos + x_off
end
function Cursor:moveVertical(x_off)
self.y_pos = self.y_pos + y_off
end
function Cursor:moveAndDraw(x_off, y_off)
self:clear()
self:move(x_off, y_off)
self:draw()
end
function Cursor:moveTo(x_pos, y_pos)
self.x_pos = x_pos
self.y_pos = y_pos
end
function Cursor:moveToAndDraw(x_pos, y_pos)
self:clear()
self.x_pos = x_pos
self.y_pos = y_pos
self:draw()
end
function Cursor:moveHorizontalAndDraw(x_off)
self:clear()
self:move(x_off, 0)
self:draw()
end
function Cursor:moveVerticalAndDraw(y_off)
self:clear()
self:move(0, y_off)
self:draw()
end
|
--[[
Draw a border
@x: start position in x axis
@y: start position in y axis
@w: width of the border
@h: height of the border
@bw: line width of the border
@c: color for loading bar
@r: radius of for border's corner (nil or 0 means right corner border)
--]]
function blitbuffer.paintBorder(bb, x, y, w, h, bw, c, r)
x, y = math.ceil(x), math.ceil(y)
h, w = math.ceil(h), math.ceil(w)
if not r or r == 0 then
bb:paintRect(x, y, w, bw, c)
bb:paintRect(x, y+h-bw, w, bw, c)
bb:paintRect(x, y+bw, bw, h - 2*bw, c)
bb:paintRect(x+w-bw, y+bw, bw, h - 2*bw, c)
else
if h < 2*r then r = math.floor(h/2) end
if w < 2*r then r = math.floor(w/2) end
bb:paintRoundedCorner(x, y, w, h, bw, r, c)
bb:paintRect(r+x, y, w-2*r, bw, c)
bb:paintRect(r+x, y+h-bw, w-2*r, bw, c)
bb:paintRect(x, r+y, bw, h-2*r, c)
bb:paintRect(x+w-bw, r+y, bw, h-2*r, c)
end
end
--[[
Fill a rounded corner rectangular area
@x: start position in x axis
@y: start position in y axis
@w: width of the area
@h: height of the area
@c: color used to fill the area
@r: radius of for four corners
--]]
function blitbuffer.paintRoundedRect(bb, x, y, w, h, c, r)
x, y = math.ceil(x), math.ceil(y)
h, w = math.ceil(h), math.ceil(w)
if not r or r == 0 then
bb:paintRect(x, y, w, h, c)
else
if h < 2*r then r = math.floor(h/2) end
if w < 2*r then r = math.floor(w/2) end
bb:paintBorder(x, y, w, h, r, c, r)
bb:paintRect(x+r, y+r, w-2*r, h-2*r, c)
end
end
--[[
Draw a progress bar according to following args:
@x: start position in x axis
@y: start position in y axis
@w: width for progress bar
@h: height for progress bar
@load_m_w: width margin for loading bar
@load_m_h: height margin for loading bar
@load_percent: progress in percent
@c: color for loading bar
--]]
function blitbuffer.progressBar(bb, x, y, w, h,
load_m_w, load_m_h, load_percent, c)
if load_m_h*2 > h then
load_m_h = h/2
end
blitbuffer.paintBorder(fb.bb, x, y, w, h, 2, 15)
fb.bb:paintRect(x+load_m_w, y+load_m_h,
(w-2*load_m_w)*load_percent, (h-2*load_m_h), c)
end
------------------------------------------------
-- Start of Cursor class
------------------------------------------------
Cursor = {
x_pos = 0,
y_pos = 0,
--color = 15,
h = 10,
w = nil,
line_w = nil,
is_cleared = true,
}
function Cursor:new(o)
o = o or {}
o.x_pos = o.x_pos or self.x_pos
o.y_pos = o.y_pos or self.y_pos
o.line_width_factor = o.line_width_factor or 10
setmetatable(o, self)
self.__index = self
o:setHeight(o.h or self.h)
return o
end
function Cursor:setHeight(h)
self.h = h
self.w = self.h / 3
self.line_w = math.floor(self.h / self.line_width_factor)
end
function Cursor:_draw(x, y)
local up_down_width = math.floor(self.line_w / 2)
local body_h = self.h - (up_down_width * 2)
-- paint upper horizontal line
fb.bb:invertRect(x, y, self.w, up_down_width)
-- paint middle vertical line
fb.bb:invertRect(x + (self.w / 2) - up_down_width, y + up_down_width,
self.line_w, body_h)
-- paint lower horizontal line
fb.bb:invertRect(x, y + body_h + up_down_width, self.w, up_down_width)
end
function Cursor:draw()
if self.is_cleared then
self.is_cleared = false
self:_draw(self.x_pos, self.y_pos)
end
end
function Cursor:clear()
if not self.is_cleared then
self.is_cleared = true
self:_draw(self.x_pos, self.y_pos)
end
end
function Cursor:move(x_off, y_off)
self.x_pos = self.x_pos + x_off
self.y_pos = self.y_pos + y_off
end
function Cursor:moveHorizontal(x_off)
self.x_pos = self.x_pos + x_off
end
function Cursor:moveVertical(x_off)
self.y_pos = self.y_pos + y_off
end
function Cursor:moveAndDraw(x_off, y_off)
self:clear()
self:move(x_off, y_off)
self:draw()
end
function Cursor:moveTo(x_pos, y_pos)
self.x_pos = x_pos
self.y_pos = y_pos
end
function Cursor:moveToAndDraw(x_pos, y_pos)
self:clear()
self.x_pos = x_pos
self.y_pos = y_pos
self:draw()
end
function Cursor:moveHorizontalAndDraw(x_off)
self:clear()
self:move(x_off, 0)
self:draw()
end
function Cursor:moveVerticalAndDraw(y_off)
self:clear()
self:move(0, y_off)
self:draw()
end
|
fix bug in paintRoundedRect
|
fix bug in paintRoundedRect
rounded up decimal leads to wrong claculation
for bottom corners
|
Lua
|
agpl-3.0
|
koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,robert00s/koreader,koreader/koreader-base,lgeek/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,NiLuJe/koreader,Frenzie/koreader-base,Frenzie/koreader-base,apletnev/koreader,Frenzie/koreader,houqp/koreader-base,NiLuJe/koreader-base,houqp/koreader,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader-base,koreader/koreader,ashang/koreader,houqp/koreader-base,frankyifei/koreader,NickSavage/koreader,mwoz123/koreader,apletnev/koreader-base,frankyifei/koreader-base,chrox/koreader,Frenzie/koreader-base,NiLuJe/koreader,noname007/koreader,NiLuJe/koreader-base,poire-z/koreader,Markismus/koreader,frankyifei/koreader-base,ashhher3/koreader,mihailim/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,pazos/koreader,frankyifei/koreader-base,poire-z/koreader,chihyang/koreader,apletnev/koreader-base,koreader/koreader,Frenzie/koreader,koreader/koreader-base
|
bd6a32ea04e45fc821cdf8ac8eb5ae9039360a80
|
files/init.lua
|
files/init.lua
|
HYPER = {"cmd", "alt", "ctrl", "shift"}
DEBUG = true
NUMBERS = {
["1"]=true,
["2"]=true,
["3"]=true,
["4"]=true,
["5"]=true,
["6"]=true,
["7"]=true,
["8"]=true,
["9"]=true
}
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
function run_resizer_tap(axis, edge)
local vertical = axis == "vertical"
local leading = edge == "leading"
local win = hs.window.focusedWindow()
local screen = win:screen()
tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event)
if DEBUG then
print("event tap debug got event:")
print(hs.inspect.inspect(event:getRawEventData()))
end
local characters = event:getCharacters()
if string.len(characters) == 1 and NUMBERS[characters] == true then
local num = tonumber(characters)
local ratio = num / 10.0
resize_to_ratio(ratio, screen, win, vertical, leading)
if DEBUG then
print("Resizing to " .. ratio)
end
else
hs.alert.show("Please press a number between 1 and 9")
end
tap:stop()
return true
end)
tap:start()
hs.timer.doAfter(2, function()
if tap:isEnabled() then
tap:stop()
if DEBUG then
print("Stopping tap")
end
end
end)
end
function resize_to_ratio(ratio, screen, win, vertical, leading)
local screen_frame = screen:frame()
local frame = screen:frame()
if vertical then
height = frame.h * ratio
frame.h = height
if leading then
frame.y = 0
else
frame.y = screen_frame.h - height
end
else
width = frame.w * ratio
frame.w = width
if leading then
frame.x = 0
else
frame.x = screen_frame.w - width
end
end
win:setFrame(frame)
end
-- Movement
hs.hotkey.bind(HYPER, "I", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame = max
win:setFrame(frame)
end)
-- Right Half, Full Height
hs.hotkey.bind(HYPER, "L", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame.x = max.x + (max.w / 2)
frame.y = max.y
frame.w = max.w / 2
frame.h = max.h
win:setFrame(frame)
end)
-- Left Half, Full Height
hs.hotkey.bind(HYPER, "H", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame.x = max.x
frame.y = max.y
frame.w = max.w / 2
frame.h = max.h
win:setFrame(frame)
end)
-- Top Half, Full Width
hs.hotkey.bind(HYPER, "K", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w
local newFrameHeight = max.h / 2
frame.x = max.x
frame.y = max.y
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Bottom Half, Full Width
hs.hotkey.bind(HYPER, "J", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w
local newFrameHeight = max.h / 2
frame.x = max.x
frame.y = max.y + newFrameHeight
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Center of screen
hs.hotkey.bind(HYPER, "P", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w / 2
local newFrameHeight = max.h / 2
frame.x = max.x + (max.w / 2) - (newFrameWidth / 2)
frame.y = max.y + (max.h / 2) - (newFrameHeight / 2)
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Ratio based resizing.
-- These binds facilitate resizing to ratios based on tenths
-- either vertically or horizontally and anchored either on the
-- leading or trailing edge of the axis.
--
-- To use them:
-- 1. Focus the window to resize
-- 2. Invoke the hotkey
-- 3. Press a number between 1 and 9
hs.hotkey.bind(HYPER, "W", function ()
run_resizer_tap("vertical", "leading")
end)
hs.hotkey.bind(HYPER, "S", function ()
run_resizer_tap("vertical", "trailing")
end)
hs.hotkey.bind(HYPER, "A", function ()
run_resizer_tap("horizontal", "leading")
end)
hs.hotkey.bind(HYPER, "D", function ()
run_resizer_tap("horizontal", "trailing")
end)
-- Moving between screens
function defineScrenThrow(screenIndex)
hs.hotkey.bind(HYPER, tostring(screenIndex), function ()
local win = hs.window.focusedWindow()
if tablelength(hs.screen.allScreens()) < screenIndex then
return
end
local screen = hs.screen.allScreens()[screenIndex]
local screnFrame = screen:frame()
win:setFrame(screnFrame)
end)
end
defineScrenThrow(1)
defineScrenThrow(2)
defineScrenThrow(3)
defineScrenThrow(4)
-- Misc
hs.hotkey.bind(HYPER, "Z", function ()
hs.reload()
end)
hs.alert.show("Config loaded")
|
HYPER = {"cmd", "alt", "ctrl", "shift"}
DEBUG = true
NUMBERS = {
["1"]=true,
["2"]=true,
["3"]=true,
["4"]=true,
["5"]=true,
["6"]=true,
["7"]=true,
["8"]=true,
["9"]=true
}
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
function run_resizer_tap(axis, edge)
local vertical = axis == "vertical"
local leading = edge == "leading"
local win = hs.window.focusedWindow()
local screen = win:screen()
tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event)
if DEBUG then
print("event tap debug got event:")
print(hs.inspect.inspect(event:getRawEventData()))
end
local characters = event:getCharacters()
if string.len(characters) == 1 and NUMBERS[characters] == true then
local num = tonumber(characters)
local ratio = num / 10.0
resize_to_ratio(ratio, screen, win, vertical, leading)
if DEBUG then
print("Resizing to " .. ratio)
end
else
hs.alert.show("Please press a number between 1 and 9")
end
tap:stop()
return true
end)
tap:start()
hs.timer.doAfter(2, function()
if tap:isEnabled() then
tap:stop()
if DEBUG then
print("Stopping tap")
end
end
end)
end
function resize_to_ratio(ratio, screen, win, vertical, leading)
local screen_frame = screen:frame()
local frame = screen:frame()
if vertical then
height = frame.h * ratio
frame.h = height
if leading then
frame.y = 0
else
frame.y = screen_frame.h - height
end
else
width = frame.w * ratio
frame.w = width
if leading then
frame.x = screen_frame.x
else
frame.x = screen_frame.x + screen_frame.w - width
end
end
win:setFrame(frame)
end
-- Movement
hs.hotkey.bind(HYPER, "I", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame = max
win:setFrame(frame)
end)
-- Right Half, Full Height
hs.hotkey.bind(HYPER, "L", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame.x = max.x + (max.w / 2)
frame.y = max.y
frame.w = max.w / 2
frame.h = max.h
win:setFrame(frame)
end)
-- Left Half, Full Height
hs.hotkey.bind(HYPER, "H", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
frame.x = max.x
frame.y = max.y
frame.w = max.w / 2
frame.h = max.h
win:setFrame(frame)
end)
-- Top Half, Full Width
hs.hotkey.bind(HYPER, "K", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w
local newFrameHeight = max.h / 2
frame.x = max.x
frame.y = max.y
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Bottom Half, Full Width
hs.hotkey.bind(HYPER, "J", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w
local newFrameHeight = max.h / 2
frame.x = max.x
frame.y = max.y + newFrameHeight
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Center of screen
hs.hotkey.bind(HYPER, "P", function ()
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local newFrameWidth = max.w / 2
local newFrameHeight = max.h / 2
frame.x = max.x + (max.w / 2) - (newFrameWidth / 2)
frame.y = max.y + (max.h / 2) - (newFrameHeight / 2)
frame.w = newFrameWidth
frame.h = newFrameHeight
win:setFrame(frame)
end)
-- Ratio based resizing.
-- These binds facilitate resizing to ratios based on tenths
-- either vertically or horizontally and anchored either on the
-- leading or trailing edge of the axis.
--
-- To use them:
-- 1. Focus the window to resize
-- 2. Invoke the hotkey
-- 3. Press a number between 1 and 9
hs.hotkey.bind(HYPER, "W", function ()
run_resizer_tap("vertical", "leading")
end)
hs.hotkey.bind(HYPER, "S", function ()
run_resizer_tap("vertical", "trailing")
end)
hs.hotkey.bind(HYPER, "A", function ()
run_resizer_tap("horizontal", "leading")
end)
hs.hotkey.bind(HYPER, "D", function ()
run_resizer_tap("horizontal", "trailing")
end)
-- Moving between screens
function defineScrenThrow(screenIndex)
hs.hotkey.bind(HYPER, tostring(screenIndex), function ()
local win = hs.window.focusedWindow()
if tablelength(hs.screen.allScreens()) < screenIndex then
return
end
local screen = hs.screen.allScreens()[screenIndex]
local screnFrame = screen:frame()
win:setFrame(screnFrame)
end)
end
defineScrenThrow(1)
defineScrenThrow(2)
defineScrenThrow(3)
defineScrenThrow(4)
-- Misc
hs.hotkey.bind(HYPER, "Z", function ()
hs.reload()
end)
hs.alert.show("Config loaded")
|
[Hammerspoon] Fix A/D on multi monitor
|
[Hammerspoon] Fix A/D on multi monitor
|
Lua
|
mit
|
k0nserv/dotfiles,k0nserv/dotfiles,k0nserv/dotfiles
|
8cbd6df093ca06f98092b979a27e74628ba698cc
|
hikyuu_pywrap/xmake_on_load.lua
|
hikyuu_pywrap/xmake_on_load.lua
|
import("lib.detect.find_tool")
function main(target)
if is_plat("windows") then
-- detect installed python3
local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0")
assert(python.version > "3", "python version must > 3.0, please use python3.0 or later!")
-- find python include and libs directory
local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"")
pydir = path.directory(pydir)
target:add("includedirs", pydir .. "/include")
target:add("linkdirs", pydir .. "/libs")
return
end
-- detect installed python3
local python3 = assert(find_tool("python3", {version = true}), "python3 not found, please install it first!")
target:add("rpathdirs", "$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib")
if is_plat("macosx") then
local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib"
target:add("linkdirs", libdir)
local ver = python.version
local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10))
target:add("links", python_lib)
end
-- get python include directory.
local pydir = os.iorun("python3-config --includes"):trim()
target:add("cxflags", pydir)
-- get suffix configure for link libboost_pythonX.so
local suffix = get_config("boost-python-suffix")
if suffix == nil then
raise("You need to config --boost-python-suffix specify libboost_python suffix")
end
suffix = string.upper(suffix)
if suffix == "3X" then
local ver = python.version
local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10)
target:add("links", boost_python_lib)
else
target:add("links", "boost_python"..suffix)
end
end
|
import("lib.detect.find_tool")
function main(target)
if is_plat("windows") then
-- detect installed python3
local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0")
assert(python.version > "3", "python version must > 3.0, please use python3.0 or later!")
-- find python include and libs directory
local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"")
pydir = path.directory(pydir)
target:add("includedirs", pydir .. "/include")
target:add("linkdirs", pydir .. "/libs")
return
end
target:add("rpathdirs", "$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib")
if is_plat("macosx") then
local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib"
target:add("linkdirs", libdir)
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10))
target:add("links", python_lib)
end
-- get python include directory.
local pydir = os.iorun("python3-config --includes"):trim()
target:add("cxflags", pydir)
-- get suffix configure for link libboost_pythonX.so
local suffix = get_config("boost-python-suffix")
if suffix == nil then
raise("You need to config --boost-python-suffix specify libboost_python suffix")
end
suffix = string.upper(suffix)
if suffix == "3X" then
local out, err = os.iorun("python3 --version")
local ver = (out .. err):trim()
local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10)
target:add("links", boost_python_lib)
else
target:add("links", "boost_python"..suffix)
end
end
|
fix defect python on unit-like
|
fix defect python on unit-like
|
Lua
|
mit
|
fasiondog/hikyuu
|
51b3a697e2ea947757e7319a9d51f9d9265c9bbf
|
pud/util.lua
|
pud/util.lua
|
local select, type, tostring = select, type, tostring
local pairs, error, setmetatable = pairs, error, setmetatable
local format, io_stderr = string.format, io.stderr
-- pud namespace
pud = {}
--[[--
UTILITIES
--]]--
-----------------
-- fast assert --
-----------------
do
local oldassert, format, select = assert, string.format, select
assert = function(condition, ...)
if condition then return condition end
if select('#', ...) > 0 then
oldassert(condition, format(...))
else
oldassert(condition)
end
end
end
local vector = require 'lib.hump.vector'
-- assert helpers
function verify(theType, ...)
for i=1,select('#', ...) do
local x = select(i, ...)
local xType = type(x)
if theType == 'vector' then
assert(vector.isvector(x), 'vector expected (was %s)', xType)
else
assert(xType == theType, '%s expected (was %s)', theType, xType)
end
end
return true
end
function verifyClass(className, ...)
verify('string', className)
for i=1,select('#', ...) do
local obj = select(i, ...)
assert(pud.isClass(className, obj),
'expected %s (was %s, %s)', className, type(obj), tostring(obj))
end
return true
end
--------------------------
-- handy switch statement --
--------------------------
function switch(x)
return function (of)
local what = of[x] or of.default
if type(what) == "function" then
return what()
end
return what
end
end
------------------------------
-- get nearest power of two --
------------------------------
function nearestPO2(x)
local po2 = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
assert(x <= po2[#po2], 'higher than %d is not supported', po2[#po2])
for i=#po2-1,1,-1 do
if x > po2[i] then return po2[i+1] end
end
return 2
end
-------------
-- warning --
-------------
function warning(msg, ...)
msg = msg or 'unknown warning'
msg = 'Warning: '..msg..'\n'
io_stderr:write(format(msg, ...))
end
-------------------
-- class helpers --
-------------------
local _pudPath = ';pud/?.lua'
local pudfiles = love.filesystem.enumerate('pud')
for _,file in pairs(pudfiles) do
if love.filesystem.isDirectory(file) then
_pudPath = _pudPath..';pud/'..file..'/?.lua'
end
end
local _classCache = {}
local _verifyCache = {}
local _mt = {__mode = 'k'}
-- cache class objects (even though Lua does this).
-- this also avoids weird loop errors with require.
function pud.getClass(className)
verify('string', className)
local theClass = _classCache[className]
if nil == theClass then
local oldPath = package.path
package.path = package.path.._pudPath
local ok,theClass = pcall(require, className)
if not ok then error(theClass) end
package.path = oldPath
_classCache[className] = theClass
end
return theClass
end
-- convenience function to get a new object of className
function pud.new(className, ...)
local theClass = pud.getClass(className)
return theClass.new(...)
end
function pud.isClass(className, obj)
verify('string', className)
if obj == nil then return false end
_verifyCache[className] = _verifyCache[className] or setmetatable({}, _mt)
local is = _verifyCache[className][obj]
if nil == is then
local theClass = pud.getClass(className)
is = type(obj) == 'table' and obj.is_a and type(obj.is_a) == 'function'
and obj:is_a(theClass)
_verifyCache[className][obj] = is
end
return is
end
--[[--
LÖVE UTILITIES
--]]--
---------------------------
-- loaders for resources --
---------------------------
local function Proxy(loader)
return setmetatable({}, {__index = function(self, k)
local v = loader(k)
rawset(self, k, v)
return v
end})
end
State = Proxy(function(k)
return assert(love.filesystem.load('state/'..k..'.lua'))()
end)
Font = Proxy(function(k)
return love.graphics.newFont('font/dejavu.ttf', k)
end)
Image = Proxy(function(k)
local img = love.graphics.newImage('image/'..k..'.png')
img:setFilter('nearest', 'nearest')
return img
end)
Sound = Proxy(function(k)
return love.audio.newSource(
love.sound.newSoundData('sound/'..k..'.ogg'),
'static')
end)
-----------------------------
-- float values for colors --
-----------------------------
do
local type, setmetatable, table_concat = type, setmetatable, table.concat
local sc = love.graphics.setColor
local sbg = love.graphics.setBackgroundColor
local _colorCache = setmetatable({}, {__mode='v'})
local function color(r, g, b, a)
local col = type(r) == 'table' and r or {r,g,b,a}
local key = table_concat(col, '-')
local c = _colorCache[key]
if c == nil then
if col[1] <= 1 and col[1] >= 0
and col[2] <= 1 and col[2] >= 0
and col[3] <= 1 and col[3] >= 0
and (not col[4] or (col[4] <= 1 and col[4] >= 0))
then
c = {255*col[1], 255*col[2], 255*col[3], 255*(col[4] or 1)}
else
c = {col[1], col[2], col[3], (col[4] or 1)}
end
_colorCache[key] = c
end
return c[1], c[2], c[3], c[4]
end
function love.graphics.setColor(r,g,b,a) sc(color(r,g,b,a)) end
function love.graphics.setBackgroundColor(r,g,b,a) sbg(color(r,g,b,a)) end
end
-------------------
-- resize screen --
-------------------
function resizeScreen(width, height)
local modes = love.graphics.getModes()
local w, h
for i=1,#modes do
w = modes[i].width
h = modes[i].height
if w <= width and h <= height then break end
end
if w ~= love.graphics.getWidth() and h ~= love.graphics.getHeight() then
assert(love.graphics.setMode(w, h))
end
-- global screen width/height
WIDTH, HEIGHT = love.graphics.getWidth(), love.graphics.getHeight()
end
--[[--
AUDIO MANAGER
--]]--
do
-- will hold the currently playing sources
local sources = {}
local pairs, ipairs, type = pairs, ipairs, type
-- check for sources that finished playing and remove them
function love.audio.update()
local remove = {}
for _,s in pairs(sources) do
if s:isStopped() then
remove[#remove + 1] = s
end
end
for i,s in ipairs(remove) do
sources[s] = nil
end
end
-- overwrite love.audio.play to create and register source if needed
local play = love.audio.play
function love.audio.play(what, how, loop)
local src = what
if type(what) ~= "userdata" or not what:typeOf("Source") then
src = love.audio.newSource(what, how)
src:setLooping(loop or false)
end
play(src)
sources[src] = src
return src
end
-- stops a source
local stop = love.audio.stop
function love.audio.stop(src)
if not src then return end
stop(src)
sources[src] = nil
end
end
|
local select, type, tostring = select, type, tostring
local pairs, error, setmetatable = pairs, error, setmetatable
local format, io_stderr = string.format, io.stderr
-- pud namespace
pud = {}
--[[--
UTILITIES
--]]--
-----------------
-- fast assert --
-----------------
do
local oldassert, format, select = assert, string.format, select
assert = function(condition, ...)
if condition then return condition end
if select('#', ...) > 0 then
oldassert(condition, format(...))
else
oldassert(condition)
end
end
end
local vector = require 'lib.hump.vector'
-- assert helpers
function verify(theType, ...)
for i=1,select('#', ...) do
local x = select(i, ...)
local xType = type(x)
if theType == 'vector' then
assert(vector.isvector(x), 'vector expected (was %s)', xType)
else
assert(xType == theType, '%s expected (was %s)', theType, xType)
end
end
return true
end
function verifyClass(className, ...)
verify('string', className)
for i=1,select('#', ...) do
local obj = select(i, ...)
assert(pud.isClass(className, obj),
'expected %s (was %s, %s)', className, type(obj), tostring(obj))
end
return true
end
--------------------------
-- handy switch statement --
--------------------------
function switch(x)
return function (of)
local what = of[x] or of.default
if type(what) == "function" then
return what()
end
return what
end
end
------------------------------
-- get nearest power of two --
------------------------------
function nearestPO2(x)
local po2 = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
assert(x <= po2[#po2], 'higher than %d is not supported', po2[#po2])
for i=#po2-1,1,-1 do
if x > po2[i] then return po2[i+1] end
end
return 2
end
-------------
-- warning --
-------------
function warning(msg, ...)
msg = msg or 'unknown warning'
msg = 'Warning: '..msg..'\n'
io_stderr:write(format(msg, ...))
end
-------------------
-- class helpers --
-------------------
local _pudPath = ';./pud/?.lua'
local pudfiles = love.filesystem.enumerate('pud')
for _,file in pairs(pudfiles) do
file = 'pud/'..file
if love.filesystem.isDirectory(file) then
_pudPath = _pudPath..';./'..file..'/?.lua'
else
end
end
local _classCache = {}
local _verifyCache = {}
local _mt = {__mode = 'k'}
-- cache class objects (even though Lua does this).
-- this also helps to avoid weird loop errors with require, by printing the
-- entire stack trace.
function pud.getClass(className)
verify('string', className)
local theClass = _classCache[className]
if nil == theClass then
local oldPath = package.path
package.path = package.path.._pudPath
local ok,res = xpcall(function()
return require(className)
end, debug.traceback)
if not ok then error(res) end
package.path = oldPath
theClass = res
_classCache[className] = theClass
end
return theClass
end
-- convenience function to get a new object of className
function pud.new(className, ...)
local theClass = pud.getClass(className)
return theClass.new(...)
end
function pud.isClass(className, obj)
verify('string', className)
if obj == nil then return false end
_verifyCache[className] = _verifyCache[className] or setmetatable({}, _mt)
local is = _verifyCache[className][obj]
if nil == is then
local theClass = pud.getClass(className)
is = type(obj) == 'table' and obj.is_a and type(obj.is_a) == 'function'
and obj:is_a(theClass)
_verifyCache[className][obj] = is
end
return is
end
--[[--
LÖVE UTILITIES
--]]--
---------------------------
-- loaders for resources --
---------------------------
local function Proxy(loader)
return setmetatable({}, {__index = function(self, k)
local v = loader(k)
rawset(self, k, v)
return v
end})
end
State = Proxy(function(k)
return assert(love.filesystem.load('state/'..k..'.lua'))()
end)
Font = Proxy(function(k)
return love.graphics.newFont('font/dejavu.ttf', k)
end)
Image = Proxy(function(k)
local img = love.graphics.newImage('image/'..k..'.png')
img:setFilter('nearest', 'nearest')
return img
end)
Sound = Proxy(function(k)
return love.audio.newSource(
love.sound.newSoundData('sound/'..k..'.ogg'),
'static')
end)
-----------------------------
-- float values for colors --
-----------------------------
do
local type, setmetatable, table_concat = type, setmetatable, table.concat
local sc = love.graphics.setColor
local sbg = love.graphics.setBackgroundColor
local _colorCache = setmetatable({}, {__mode='v'})
local function color(r, g, b, a)
local col = type(r) == 'table' and r or {r,g,b,a}
local key = table_concat(col, '-')
local c = _colorCache[key]
if c == nil then
if col[1] <= 1 and col[1] >= 0
and col[2] <= 1 and col[2] >= 0
and col[3] <= 1 and col[3] >= 0
and (not col[4] or (col[4] <= 1 and col[4] >= 0))
then
c = {255*col[1], 255*col[2], 255*col[3], 255*(col[4] or 1)}
else
c = {col[1], col[2], col[3], (col[4] or 1)}
end
_colorCache[key] = c
end
return c[1], c[2], c[3], c[4]
end
function love.graphics.setColor(r,g,b,a) sc(color(r,g,b,a)) end
function love.graphics.setBackgroundColor(r,g,b,a) sbg(color(r,g,b,a)) end
end
-------------------
-- resize screen --
-------------------
function resizeScreen(width, height)
local modes = love.graphics.getModes()
local w, h
for i=1,#modes do
w = modes[i].width
h = modes[i].height
if w <= width and h <= height then break end
end
if w ~= love.graphics.getWidth() and h ~= love.graphics.getHeight() then
assert(love.graphics.setMode(w, h))
end
-- global screen width/height
WIDTH, HEIGHT = love.graphics.getWidth(), love.graphics.getHeight()
end
--[[--
AUDIO MANAGER
--]]--
do
-- will hold the currently playing sources
local sources = {}
local pairs, ipairs, type = pairs, ipairs, type
-- check for sources that finished playing and remove them
function love.audio.update()
local remove = {}
for _,s in pairs(sources) do
if s:isStopped() then
remove[#remove + 1] = s
end
end
for i,s in ipairs(remove) do
sources[s] = nil
end
end
-- overwrite love.audio.play to create and register source if needed
local play = love.audio.play
function love.audio.play(what, how, loop)
local src = what
if type(what) ~= "userdata" or not what:typeOf("Source") then
src = love.audio.newSource(what, how)
src:setLooping(loop or false)
end
play(src)
sources[src] = src
return src
end
-- stops a source
local stop = love.audio.stop
function love.audio.stop(src)
if not src then return end
stop(src)
sources[src] = nil
end
end
|
fix pudPaths and call require with xpcall
|
fix pudPaths and call require with xpcall
|
Lua
|
mit
|
scottcs/wyx
|
1147cd325a6dbcdbcfd514f41f782bf6c4870a49
|
kong/plugins/session/schema.lua
|
kong/plugins/session/schema.lua
|
local utils = require("kong.tools.utils")
return {
no_consumer = true,
fields = {
secret = {
type = "string",
required = false,
default = utils.random_string,
},
cookie_name = { type = "string", default = "session" },
cookie_lifetime = { type = "number", default = 3600 },
cookie_renew = { type = "number", default = 600 },
cookie_path = { type = "string", default = "/" },
cookie_domain = { type = "string" },
cookie_samesite = {
type = "string",
default = "Strict",
one_of = { "Strict", "Lax", "off" }
},
cookie_httponly = { type = "boolean", default = true },
cookie_secure = { type = "boolean", default = true },
cookie_discard = { type = "number", default = 10 },
storage = {
required = false,
type = "string",
enum = {
"cookie",
"kong",
},
default = "cookie",
},
logout_methods = {
type = "array",
enum = { "POST", "GET", "DELETE" },
default = { "POST", "DELETE" }
},
logout_query_arg = {
required = false,
type = "string",
default = "session_logout",
},
logout_post_arg = {
required = false,
type = "string",
default = "session_logout",
},
}
}
|
local utils = require("kong.tools.utils")
local char = string.char
local rand = math.random
local encode_base64 = ngx.encode_base64
-- kong.utils.random_string with number of bytes config
local function random_string(n_bytes)
return encode_base64(get_rand_bytes(n_bytes or 32, true))
:gsub("/", char(rand(48, 57))) -- 0 - 10
:gsub("+", char(rand(65, 90))) -- A - Z
:gsub("=", char(rand(97, 122))) -- a - z
end
return {
no_consumer = true,
fields = {
secret = {
type = "string",
required = false,
default = random_string,
},
cookie_name = { type = "string", default = "session" },
cookie_lifetime = { type = "number", default = 3600 },
cookie_renew = { type = "number", default = 600 },
cookie_path = { type = "string", default = "/" },
cookie_domain = { type = "string" },
cookie_samesite = {
type = "string",
default = "Strict",
one_of = { "Strict", "Lax", "off" }
},
cookie_httponly = { type = "boolean", default = true },
cookie_secure = { type = "boolean", default = true },
cookie_discard = { type = "number", default = 10 },
storage = {
required = false,
type = "string",
enum = {
"cookie",
"kong",
},
default = "cookie",
},
logout_methods = {
type = "array",
enum = { "POST", "GET", "DELETE" },
default = { "POST", "DELETE" }
},
logout_query_arg = {
required = false,
type = "string",
default = "session_logout",
},
logout_post_arg = {
required = false,
type = "string",
default = "session_logout",
},
}
}
|
fix(session) make random bytes 32, not 24 for sid
|
fix(session) make random bytes 32, not 24 for sid
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
3b15f029afecc75f951eea9d931d5cc1b42323e9
|
luaforth.lua
|
luaforth.lua
|
-- LuaForth.
-- Simplistic Forth for Lua interaction.
-- Based on parts of MiniForth
-- The MIT License (MIT)
--
-- Copyright (c) 2016 Adrian Pistol
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
local luaforth = {}
-- Version
luaforth.version = "0.3"
-- Word structure:
-- env[name] = {
-- _fn = func -- function that runs the logic
-- _fnret = ["pushtostack", "newstack"] -- wether the function's return values should be added to the stack or _be_ the stack. Defaults to pushtostack.
-- _args = n -- number of arguments which are pop'd from the stack, defaults to 0
-- _parse = ["line"|"word"|"endsign"|"pattern"] -- optional advanced parsing, line passes the whole line to the word, word only the next word, pattern parses given pattern, endsign until...
-- _endsign = string -- the given endsign appears.
-- _pattern = pattern -- pattern for parse option
-- }
-- Method caching, should be a little faster because no global lookup.
local unpack = table.unpack or unpack
local tremove = table.remove
local smatch = string.match
local type, error = type, error
function luaforth.eval(src, env, stack, startpos)
if src == "" then -- Short cut in case of src being empty
return stack, startpos
end
-- Small fix.
src = src .. "\n"
local pos = startpos or 1
-- Stack
stack = stack or {}
local function pop()
if #stack == 0 then error("Stack underflow!") end
return tremove(stack)
end
local function push(x)
stack[#stack + 1] = x
end
-- Patterns and stuff for the parser
local genpattparse = function(pat)
return function()
local capture, newpos = smatch(src, pat, pos)
if newpos then
pos = newpos
return capture
end
end
end
local pattparse = function(pat)
local capture, newpos = smatch(src, pat, pos)
if newpos then
pos = newpos
return capture
end
end
local parse_spaces = genpattparse("^([ \t]*)()")
local parse_word = genpattparse("^([^ \t\r\n]+)()")
local parse_eol = genpattparse("^(.-)[\r\n]+()")
while src ~= "" do -- Main loop
parse_spaces()
local word_name = parse_word()
if word_name then
local word_value = env[word_name]
if word_value then -- if the word is in the env
local word_type = type(word_value)
if word_type == "table" then -- word
local f = word_value._fn
if type(f) == "function" then
local argn = word_value._args or 0
local args = {stack, env}
local pt = word_value._parse
if pt then -- not just plain word
parse_spaces()
local extra
if pt == "line" then
extra = parse_eol()
elseif pt == "word" then
extra = parse_word()
elseif pt == "pattern" then
extra = pattparse("^"..word_value._pattern.."()")
elseif pt == "endsign" then
extra = pattparse("^(.-)"..word_value._endsign:gsub(".", "%%%1").."()")
end
args[#args + 1] = extra
end
for i=1, argn, 1 do
args[i+2] = pop()
end
local rt = word_value._fnret
local ra = {f(unpack(args))}
if rt == "newstack" then
stack = ra[1]
local nenv = ra[2]
if nenv then
env = nenv
end
else
for i=1, #ra, 1 do
local e = ra[i]
if e then
push(e)
end
end
end
else
push(word_value)
end
else
push(word_value)
end
else
local tonword = tonumber(word_name) -- fallback for numbers.
if tonword then
push(tonword)
else
error("No such word: "..word_name, 0)
end
end
else
return stack, env
end
end
return stack, env
end
-- Example env that has %L to evaluate the line and [L L] pairs to evalute a small block of lua code.
luaforth.simple_env = {
["%L"] = { -- line of lua source
_fn=function(stack, env, str)
local f, err = loadstring("return " .. str)
if err then
f, err = loadstring(str)
if err then
error(err, 0)
end
end
return f(stack, env)
end,
_parse = "line"
},
["[L"] = { -- same as above, but not the whole line
_fn=function(stack, env, str)
local f, err = loadstring("return " .. str)
if err then
f, err = loadstring(str)
if err then
error(err, 0)
end
end
return f(stack, env)
end,
_parse = "endsign",
_endsign = "L]"
},
["("] = { -- Comment.
_fn=function() end, -- Do... Nothing!
_parse = "endsign",
_endsign = ")"
},
["\\"] = {
_fn=function() end, -- Do nothing once again. Man, I wish I could be as lazy as that function.
_parse = "line"
},
["source"] = { -- source file
_fn=function(stack, env, loc)
local f, err = io.open(loc, "r")
if err then
error(err, 0)
end
local src = f:read("*all")
f:close()
return luaforth.eval(src, env, stack)
end,
_args = 1,
_fnret = "newstack"
},
["%source"] = { -- shortcut. allows "%source bla.fs\n" syntax.
_fn=function(stack, env, loc)
local f, err = io.open(loc, "r")
if err then
error(err, 0)
end
local src = f:read("*all")
f:close()
return luaforth.eval(src, env, stack)
end,
_fnret = "newstack",
_parse = "line"
}
}
-- Function creation.
luaforth.simple_env[":"] = { -- word definiton, arguebly the most interesting part of this env.
_fn = function(_, _, fn)
local nme, prg = string.match(fn, "^(.-) (.-)$")
luaforth.simple_env[nme] = {
_fn = function(stack, env)
return luaforth.eval(prg, env, stack)
end,
_fnret = "newstack"
}
end,
_parse = "endsign",
_endsign = ";"
}
luaforth.simple_env[":[L"] = { -- word definition using lua!
_fn = function(stack, env, fn)
local nme, argno, prg = string.match(fn, "^(.-) (%d-) (.-)$")
local f, err = loadstring("return " .. prg) -- this is to get the "invisible return" action going.
if err then
f, err = loadstring(prg)
if err then
error(err, 0)
end
end
env[nme] = {
_fn=function(_, _, ...)
return f(...)
end,
_args=tonumber(argno)
}
return stack, env
end,
_parse = "endsign",
_endsign = "L];",
_fnret = "newstack" -- to switch out stack and more importantly env
}
return luaforth
|
-- LuaForth.
-- Simplistic Forth for Lua interaction.
-- Based on parts of MiniForth
-- The MIT License (MIT)
--
-- Copyright (c) 2016 Adrian Pistol
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
local luaforth = {}
-- Version
luaforth.version = "0.3"
-- Word structure:
-- env[name] = {
-- _fn = func -- function that runs the logic
-- _fnret = ["pushtostack", "newstack"] -- wether the function's return values should be added to the stack or _be_ the stack. Defaults to pushtostack.
-- _args = n -- number of arguments which are pop'd from the stack, defaults to 0
-- _parse = ["line"|"word"|"endsign"|"pattern"] -- optional advanced parsing, line passes the whole line to the word, word only the next word, pattern parses given pattern, endsign until...
-- _endsign = string -- the given endsign appears.
-- _pattern = pattern -- pattern for parse option
-- }
-- Method caching, should be a little faster because no global lookup.
local unpack = table.unpack or unpack
local tremove = table.remove
local smatch = string.match
local type, error = type, error
local load = loadstring or load
function luaforth.eval(src, env, stack, startpos)
if src == "" then -- Short cut in case of src being empty
return stack, startpos
end
-- Small fix.
src = src .. "\n"
local pos = startpos or 1
-- Stack
stack = stack or {}
local function pop()
if #stack == 0 then error("Stack underflow!") end
return tremove(stack)
end
local function push(x)
stack[#stack + 1] = x
end
-- Patterns and stuff for the parser
local genpattparse = function(pat)
return function()
local capture, newpos = smatch(src, pat, pos)
if newpos then
pos = newpos
return capture
end
end
end
local pattparse = function(pat)
local capture, newpos = smatch(src, pat, pos)
if newpos then
pos = newpos
return capture
end
end
local parse_spaces = genpattparse("^([ \t]*)()")
local parse_word = genpattparse("^([^ \t\r\n]+)()")
local parse_eol = genpattparse("^(.-)[\r\n]+()")
while src ~= "" do -- Main loop
parse_spaces()
local word_name = parse_word()
if word_name then
local word_value = env[word_name]
if word_value then -- if the word is in the env
local word_type = type(word_value)
if word_type == "table" then -- word
local f = word_value._fn
if type(f) == "function" then
local argn = word_value._args or 0
local args = {stack, env}
local pt = word_value._parse
if pt then -- not just plain word
parse_spaces()
local extra
if pt == "line" then
extra = parse_eol()
elseif pt == "word" then
extra = parse_word()
elseif pt == "pattern" then
extra = pattparse("^"..word_value._pattern.."()")
elseif pt == "endsign" then
extra = pattparse("^(.-)"..word_value._endsign:gsub(".", "%%%1").."()")
end
args[#args + 1] = extra
end
for i=1, argn, 1 do
args[i+2] = pop()
end
local rt = word_value._fnret
local ra = {f(unpack(args))}
if rt == "newstack" then
stack = ra[1]
local nenv = ra[2]
if nenv then
env = nenv
end
else
for i=1, #ra, 1 do
local e = ra[i]
if e then
push(e)
end
end
end
else
push(word_value)
end
else
push(word_value)
end
else
local tonword = tonumber(word_name) -- fallback for numbers.
if tonword then
push(tonword)
else
error("No such word: "..word_name, 0)
end
end
else
return stack, env
end
end
return stack, env
end
-- Example env that has %L to evaluate the line and [L L] pairs to evalute a small block of lua code.
luaforth.simple_env = {
["%L"] = { -- line of lua source
_fn=function(stack, env, str)
local f, err = load("return " .. str)
if err then
f, err = load(str)
if err then
error(err, 0)
end
end
return f(stack, env)
end,
_parse = "line"
},
["[L"] = { -- same as above, but not the whole line
_fn=function(stack, env, str)
local f, err = load("return " .. str)
if err then
f, err = load(str)
if err then
error(err, 0)
end
end
return f(stack, env)
end,
_parse = "endsign",
_endsign = "L]"
},
["("] = { -- Comment.
_fn=function() end, -- Do... Nothing!
_parse = "endsign",
_endsign = ")"
},
["\\"] = {
_fn=function() end, -- Do nothing once again. Man, I wish I could be as lazy as that function.
_parse = "line"
},
["source"] = { -- source file
_fn=function(stack, env, loc)
local f, err = io.open(loc, "r")
if err then
error(err, 0)
end
local src = f:read("*all")
f:close()
return luaforth.eval(src, env, stack)
end,
_args = 1,
_fnret = "newstack"
},
["%source"] = { -- shortcut. allows "%source bla.fs\n" syntax.
_fn=function(stack, env, loc)
local f, err = io.open(loc, "r")
if err then
error(err, 0)
end
local src = f:read("*all")
f:close()
return luaforth.eval(src, env, stack)
end,
_fnret = "newstack",
_parse = "line"
}
}
-- Function creation.
luaforth.simple_env[":"] = { -- word definiton, arguebly the most interesting part of this env.
_fn = function(_, _, fn)
local nme, prg = string.match(fn, "^(.-) (.-)$")
luaforth.simple_env[nme] = {
_fn = function(stack, env)
return luaforth.eval(prg, env, stack)
end,
_fnret = "newstack"
}
end,
_parse = "endsign",
_endsign = ";"
}
luaforth.simple_env[":[L"] = { -- word definition using lua!
_fn = function(stack, env, fn)
local nme, argno, prg = string.match(fn, "^(.-) (%d-) (.-)$")
local f, err = load("return " .. prg) -- this is to get the "invisible return" action going.
if err then
f, err = load(prg)
if err then
error(err, 0)
end
end
env[nme] = {
_fn=function(_, _, ...)
return f(...)
end,
_args=tonumber(argno)
}
return stack, env
end,
_parse = "endsign",
_endsign = "L];",
_fnret = "newstack" -- to switch out stack and more importantly env
}
return luaforth
|
Hoping to fix lua 5.3 support.
|
Hoping to fix lua 5.3 support.
|
Lua
|
mit
|
vifino/luaforth
|
ce0fe525a7a2cc5d4fb7d810125fc7a5f43cee7e
|
UCDvehicleShops/client.lua
|
UCDvehicleShops/client.lua
|
local markerInfo = {}
local sX, sY = guiGetScreenSize()
GUI = {
gridlist = {},
window = {},
button = {}
}
GUI.window = GuiWindow(1085, 205, 281, 361, "UCD | Vehicle Shop - Low End", false)
GUI.window.sizable = false
GUI.window.visible = false
GUI.window.alpha = 255
GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Vehicle", 0.6)
guiGridListAddColumn(GUI.gridlist, "Price", 0.3)
GUI.button["buy"] = GuiButton(10, 318, 80, 30, "Buy", false, GUI.window)
GUI.button["colour"] = GuiButton(101, 318, 80, 30, "Colour", false, GUI.window)
GUI.button["close"] = GuiButton(191, 318, 80, 30, "Close", false, GUI.window)
function onHitShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
if (localPlayer.position.z < source.position.z + 1.5 and localPlayer.position.z > source.position.z - 1.5) then
exports.UCDdx:add("Press Z: Buy Vehicle", 255, 255, 0)
bindKey("z", "down", openGUI, source)
end
end
end
function onLeaveShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
exports.UCDdx:del("Press Z: Buy Vehicle")
unbindKey("z", "down", closeGUI)
closeGUI()
end
end
for i, info in ipairs(markers) do
local m = Marker(info.x, info.y, info.z - 1, "cylinder", 2, 255, 255, 180, 170)
-- Custom blips
if (type(blips[info.t]) == "string") then
local b = exports.UCDblips:createCustomBlip(info.x, info.y, 16, 16, blips[info.t], 300)
exports.UCDblips:setCustomBlipStreamRadius(b, 50)
else
Blip.createAttachedTo(m, blips[info.t], 2, 0, 0, 0, 0, 0, 300)
end
addEventHandler("onClientMarkerHit", m, onHitShopMarker)
addEventHandler("onClientMarkerLeave", m, onLeaveShopMarker)
markerInfo[m] = {info.t, i}
end
function openGUI(_, _, m)
if (GUI.visible) then return end
if (m and isElement(m)) then
if (getDistanceBetweenPoints3D(localPlayer.position, m.position) > 1.5) then
return
end
GUI.window.text = "UCD | Vehicle Shop - "..tostring(markerInfo[m][1])
populateGridList(markerInfo[m][1])
end
GUI.window.visible = true
GUI.window:setPosition(sX - 281, sY / 2 - (361 / 2), false)
showCursor(true)
exports.UCDdx:del("Press Z: Buy Vehicle")
unbindKey("z", "down", closeGUI)
_markerInfo = markerInfo[m]
end
function closeGUI()
if (not GUI.window.visible) then return end
GUI.gridlist:clear()
GUI.window.visible = false
showCursor(false)
exports.UCDdx:del("Press Z: Buy Vehicle")
unbindKey("z", "down", closeGUI)
if (Camera.target ~= localPlayer) then
Camera.target = localPlayer
end
_markerInfo = nil
if (veh and isElement(veh)) then
veh:destroy()
end
veh = nil
end
addEventHandler("onClientGUIClick", GUI.button["close"], closeGUI, false)
function populateGridList(var)
GUI.gridlist:clear()
for k, v in ipairs(vehicles[var] or {}) do
local name = getVehicleNameFromModel(v)
local price = prices[name]
local row = guiGridListAddRow(GUI.gridlist)
guiGridListSetItemText(GUI.gridlist, row, 1, tostring(name), false, false)
guiGridListSetItemText(GUI.gridlist, row, 2, tostring(exports.UCDutil:tocomma(price)), false, false)
if (price ~= nil and price <= localPlayer:getMoney()) then
guiGridListSetItemColor(GUI.gridlist, row, 1, 0, 255, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 0, 255, 0)
else
guiGridListSetItemColor(GUI.gridlist, row, 1, 255, 0, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 255, 0, 0)
end
end
end
function onClickVehicle()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and _markerInfo) then
if (veh and isElement(veh)) then
veh:destroy()
veh = nil
end
local i = _markerInfo[2]
local p = markers[i].p
veh = Vehicle(id, p)
veh.rotation = Vector3(0, 0, markers[i].r)
Camera.setMatrix(markers[i].c, p, 0, 180)
end
end
end
addEventHandler("onClientGUIClick", GUI.gridlist, onClickVehicle, false)
function onClickBuy()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and veh and isElement(veh)) then
triggerServerEvent("UCDvehicleShops.purchase", localPlayer, id, {veh:getColor(true)}, _markerInfo[2])
closeGUI()
end
end
end
addEventHandler("onClientGUIClick", GUI.button["buy"], onClickBuy, false)
function onClickColour()
if (veh and isElement(veh)) then
GUI.window.visible = false
colorPicker.openSelect()
addEventHandler("onClientRender", root, updateColor)
end
end
addEventHandler("onClientGUIClick", GUI.button["colour"], onClickColour, false)
function updateColor()
if (not colorPicker.isSelectOpen) then return end
local r, g, b = colorPicker.updateTempColors()
if (veh and isElement(veh)) then
local r1, g1, b1, r2, g2, b2 = getVehicleColor(veh, true)
if (guiCheckBoxGetSelected(checkColor1)) then
r1, g1, b1 = r, g, b
end
if (guiCheckBoxGetSelected(checkColor2)) then
r2, g2, b2 = r, g, b
end
--if (guiCheckBoxGetSelected(checkColor3)) then
-- setVehicleHeadLightColor(localPlayer.vehicle, r, g, b)
--end
setVehicleColor(veh, r1, g1, b1, r2, g2, b2)
tempColors = {r1, g1, b1, r2, g2, b2}
end
end
|
local markerInfo = {}
local sX, sY = guiGetScreenSize()
GUI = {
gridlist = {},
window = {},
button = {}
}
GUI.window = GuiWindow(1085, 205, 281, 361, "UCD | Vehicle Shop - Low End", false)
GUI.window.sizable = false
GUI.window.visible = false
GUI.window.alpha = 255
GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Vehicle", 0.6)
guiGridListAddColumn(GUI.gridlist, "Price", 0.3)
GUI.button["buy"] = GuiButton(10, 318, 80, 30, "Buy", false, GUI.window)
GUI.button["colour"] = GuiButton(101, 318, 80, 30, "Colour", false, GUI.window)
GUI.button["close"] = GuiButton(191, 318, 80, 30, "Close", false, GUI.window)
function onHitShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
if (localPlayer.position.z < source.position.z + 1.5 and localPlayer.position.z > source.position.z - 1.5) then
exports.UCDdx:add("vehicleshop", "Press Z: Buy Vehicle", 255, 255, 0)
bindKey("z", "down", openGUI, source)
end
end
end
function onLeaveShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
closeGUI()
end
end
for i, info in ipairs(markers) do
local m = Marker(info.x, info.y, info.z - 1, "cylinder", 2, 255, 255, 180, 170)
-- Custom blips
if (type(blips[info.t]) == "string") then
local b = exports.UCDblips:createCustomBlip(info.x, info.y, 16, 16, blips[info.t], 300)
exports.UCDblips:setCustomBlipStreamRadius(b, 50)
else
Blip.createAttachedTo(m, blips[info.t], 2, 0, 0, 0, 0, 0, 300)
end
addEventHandler("onClientMarkerHit", m, onHitShopMarker)
addEventHandler("onClientMarkerLeave", m, onLeaveShopMarker)
markerInfo[m] = {info.t, i}
end
function openGUI(_, _, m)
if (GUI.visible) then return end
if (m and isElement(m)) then
if (getDistanceBetweenPoints3D(localPlayer.position, m.position) > 1.5) then
return
end
GUI.window.text = "UCD | Vehicle Shop - "..tostring(markerInfo[m][1])
populateGridList(markerInfo[m][1])
end
GUI.window.visible = true
GUI.window:setPosition(sX - 281, sY / 2 - (361 / 2), false)
showCursor(true)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
_markerInfo = markerInfo[m]
end
function closeGUI()
if (not GUI.window.visible) then return end
GUI.gridlist:clear()
GUI.window.visible = false
showCursor(false)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
if (Camera.target ~= localPlayer) then
Camera.target = localPlayer
end
_markerInfo = nil
if (veh and isElement(veh)) then
veh:destroy()
end
veh = nil
end
addEventHandler("onClientGUIClick", GUI.button["close"], closeGUI, false)
function populateGridList(var)
GUI.gridlist:clear()
for k, v in ipairs(vehicles[var] or {}) do
local name = getVehicleNameFromModel(v)
local price = prices[name]
local row = guiGridListAddRow(GUI.gridlist)
guiGridListSetItemText(GUI.gridlist, row, 1, tostring(name), false, false)
guiGridListSetItemText(GUI.gridlist, row, 2, tostring(exports.UCDutil:tocomma(price)), false, false)
if (price ~= nil and price <= localPlayer:getMoney()) then
guiGridListSetItemColor(GUI.gridlist, row, 1, 0, 255, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 0, 255, 0)
else
guiGridListSetItemColor(GUI.gridlist, row, 1, 255, 0, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 255, 0, 0)
end
end
end
function onClickVehicle()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and _markerInfo) then
if (veh and isElement(veh)) then
veh:destroy()
veh = nil
end
local i = _markerInfo[2]
local p = markers[i].p
veh = Vehicle(id, p)
veh.rotation = Vector3(0, 0, markers[i].r)
Camera.setMatrix(markers[i].c, p, 0, 180)
end
end
end
addEventHandler("onClientGUIClick", GUI.gridlist, onClickVehicle, false)
function onClickBuy()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and veh and isElement(veh)) then
triggerServerEvent("UCDvehicleShops.purchase", localPlayer, id, {veh:getColor(true)}, _markerInfo[2])
closeGUI()
end
end
end
addEventHandler("onClientGUIClick", GUI.button["buy"], onClickBuy, false)
function onClickColour()
if (veh and isElement(veh)) then
GUI.window.visible = false
colorPicker.openSelect()
addEventHandler("onClientRender", root, updateColor)
end
end
addEventHandler("onClientGUIClick", GUI.button["colour"], onClickColour, false)
function updateColor()
if (not colorPicker.isSelectOpen) then return end
local r, g, b = colorPicker.updateTempColors()
if (veh and isElement(veh)) then
local r1, g1, b1, r2, g2, b2 = getVehicleColor(veh, true)
if (guiCheckBoxGetSelected(checkColor1)) then
r1, g1, b1 = r, g, b
end
if (guiCheckBoxGetSelected(checkColor2)) then
r2, g2, b2 = r, g, b
end
--if (guiCheckBoxGetSelected(checkColor3)) then
-- setVehicleHeadLightColor(localPlayer.vehicle, r, g, b)
--end
setVehicleColor(veh, r1, g1, b1, r2, g2, b2)
tempColors = {r1, g1, b1, r2, g2, b2}
end
end
|
UCDvehicleShops
|
UCDvehicleShops
- Fixed to work with new dx side bar.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
c48123dca7deb4900e1e5b5bb75c4deda674623c
|
kong/cmd/hybrid.lua
|
kong/cmd/hybrid.lua
|
local log = require("kong.cmd.utils.log")
local pkey = require("resty.openssl.pkey")
local x509 = require("resty.openssl.x509")
local name = require("resty.openssl.x509.name")
local pl_file = require("pl.file")
local pl_path = require("pl.path")
local assert = assert
local tonumber = tonumber
local CERT_FILENAME = "./cluster.crt"
local KEY_FILENAME = "./cluster.key"
local DEFAULT_DURATION = 3 * 365 * 86400
local function generate_cert(duration, cert_file, key_file)
if pl_file.access_time(cert_file) then
error(cert_file .. " already exists.\nWill not overwrite it.")
end
if pl_file.access_time(key_file) then
error(key_file .. " already exists.\nWill not overwrite it.")
end
local key = assert(pkey.new({
type = "EC",
curve = "secp384r1",
}))
local crt = assert(x509.new())
assert(crt:set_pubkey(key))
local time = ngx.time()
assert(crt:set_not_before(time))
assert(crt:set_not_after(time + duration))
local cn = assert(name.new())
assert(cn:add("CN", "kong_clustering"))
assert(crt:set_subject_name(cn))
assert(crt:set_issuer_name(cn))
assert(crt:sign(key))
pl_file.write(cert_file, crt:to_PEM())
pl_file.write(key_file, key:to_PEM("private"))
os.execute("chmod 644 " .. cert_file)
os.execute("chmod 600 " .. key_file)
log("Successfully generated certificate/key pairs, " ..
"they have been written to: '" .. cert_file .. "' and '" ..
key_file .. "'.")
end
local function execute(args)
if args.command == "gen_cert" then
local day = args.d or args.days
if #args ~= 0 and #args ~= 2 then
error("both cert and key path needs to be provided")
end
local cert_file = args[1] or CERT_FILENAME
local key_file = args[2] or KEY_FILENAME
generate_cert(day and tonumber(day) * 86400 or DEFAULT_DURATION,
pl_path.abspath(cert_file),
pl_path.abspath(key_file))
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong hybrid COMMAND [OPTIONS]
Hybrid mode utilities for Kong.
The available commands are:
gen_cert [<cert> <key>] Generate a certificate/key pair that is suitable
for use in hybrid mode deployment.
Cert and key will be written to
']] .. CERT_FILENAME .. [[' and ']] ..
KEY_FILENAME .. [[' inside
the current directory unless filenames are given.
Options:
-d,--days (optional number) Override certificate validity duration.
Default: 1095 days (3 years)
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
gen_cert = true,
},
}
|
local log = require("kong.cmd.utils.log")
local pkey = require("resty.openssl.pkey")
local x509 = require("resty.openssl.x509")
local name = require("resty.openssl.x509.name")
local pl_file = require("pl.file")
local pl_path = require("pl.path")
local assert = assert
local tonumber = tonumber
local CERT_FILENAME = "./cluster.crt"
local KEY_FILENAME = "./cluster.key"
local DEFAULT_DURATION = 3 * 365 * 86400
local function generate_cert(duration, cert_file, key_file)
if pl_file.access_time(cert_file) then
error(cert_file .. " already exists.\nWill not overwrite it.")
end
if pl_file.access_time(key_file) then
error(key_file .. " already exists.\nWill not overwrite it.")
end
local key = assert(pkey.new({
type = "EC",
curve = "secp384r1",
}))
local crt = assert(x509.new())
assert(crt:set_pubkey(key))
local time = ngx.time()
assert(crt:set_not_before(time))
assert(crt:set_not_after(time + duration))
local cn = assert(name.new())
assert(cn:add("CN", "kong_clustering"))
assert(crt:set_subject_name(cn))
assert(crt:set_issuer_name(cn))
assert(crt:sign(key))
assert(pl_file.write(cert_file, crt:to_PEM()))
assert(pl_file.write(key_file, key:to_PEM("private")))
assert(os.execute("chmod 644 " .. cert_file))
assert(os.execute("chmod 600 " .. key_file))
log("Successfully generated certificate/key pairs, " ..
"they have been written to: '" .. cert_file .. "' and '" ..
key_file .. "'.")
end
local function execute(args)
if args.command == "gen_cert" then
local day = args.d or args.days
if #args ~= 0 and #args ~= 2 then
error("both cert and key path needs to be provided")
end
local cert_file = args[1] or CERT_FILENAME
local key_file = args[2] or KEY_FILENAME
generate_cert(day and tonumber(day) * 86400 or DEFAULT_DURATION,
pl_path.abspath(cert_file),
pl_path.abspath(key_file))
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong hybrid COMMAND [OPTIONS]
Hybrid mode utilities for Kong.
The available commands are:
gen_cert [<cert> <key>] Generate a certificate/key pair that is suitable
for use in hybrid mode deployment.
Cert and key will be written to
']] .. CERT_FILENAME .. [[' and ']] ..
KEY_FILENAME .. [[' inside
the current directory unless filenames are given.
Options:
-d,--days (optional number) Override certificate validity duration.
Default: 1095 days (3 years)
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
gen_cert = true,
},
}
|
fix(cmd) kong hybrid gen_cert errors on permissions issues (#6368)
|
fix(cmd) kong hybrid gen_cert errors on permissions issues (#6368)
### Summary
It was reported by @hishamhm on #6365 that we give indication of success
even when we fail writing a certificate. This commit changes that to error
on such cases.
Fix #6365
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
28d765d9f8bdb2e19fbdf39a38ac6d90ad8f2f72
|
net/http/parser.lua
|
net/http/parser.lua
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "net.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
chunked = have_body and headers["transfer-encoding"] == "chunked";
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
if not first_line then error = true; return error_cb("invalid-status-line"); end
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url;
if path:byte() == 47 then -- starts with /
local _path, _query = path:match("([^?]*).?(.*)");
if _query == "" then _query = nil; end
parsed_url = { path = _path, query = _query };
else
parsed_url = url_parse(path);
end
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
local index = buf:find("\r\n", nil, true);
if not index then return; end -- not enough data
local chunk_size = buf:match("^%x+");
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
chunk_size = tonumber(chunk_size, 16);
index = index + 2;
if chunk_size == 0 then
state = nil; success_cb(packet);
elseif #buf - index + 1 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(index, index + chunk_size - 1);
buf = buf:sub(index + chunk_size);
end
error("trailers"); -- FIXME MUST read trailers
elseif len and #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "net.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
chunked = have_body and headers["transfer-encoding"] == "chunked";
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
if not first_line then error = true; return error_cb("invalid-status-line"); end
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url;
if path:byte() == 47 then -- starts with /
local _path, _query = path:match("([^?]*).?(.*)");
if _query == "" then _query = nil; end
parsed_url = { path = _path, query = _query };
else
parsed_url = url_parse(path);
if not parsed_url then error = true; return error_cb("invalid-url"); end
end
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
local index = buf:find("\r\n", nil, true);
if not index then return; end -- not enough data
local chunk_size = buf:match("^%x+");
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
chunk_size = tonumber(chunk_size, 16);
index = index + 2;
if chunk_size == 0 then
state = nil; success_cb(packet);
elseif #buf - index + 1 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(index, index + chunk_size - 1);
buf = buf:sub(index + chunk_size);
end
error("trailers"); -- FIXME MUST read trailers
elseif len and #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
net.http.parser: Fix traceback on invalid URL in status line.
|
net.http.parser: Fix traceback on invalid URL in status line.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
0bed2a92c19ee9343cb907c375c6e40e07f0cd21
|
mem.lua
|
mem.lua
|
_MEM = {
cls = {}, -- offsets for fixed fields inside classes
evt_off = 0, -- max event index among all classes
code_clss = nil,
}
function alloc (mem, n, al)
local al = al or n
--DBG(mem.off, n, _TP.align(mem.off,n))
mem.off = _TP.align(mem.off,al)
local cur = mem.off
mem.off = cur + n
mem.max = MAX(mem.max, mem.off)
--DBG(mem, n, mem.max)
return cur
end
function pred_sort (v1, v2)
return v1.len > v2.len
end
F = {
Root = function (me)
ASR(_MEM.evt_off+#_ENV.exts < 255, me, 'too many events')
me.mem = _MAIN.mem
-- cls/ifc accessors
local code = {}
for _,cls in ipairs(_ENV.clss) do
local pre = (cls.is_ifc and 'IFC') or 'CLS'
code[#code+1] = [[
typedef struct {
char data[]]..cls.mem.max..[[];
} ]]..pre..'_'..cls.id..[[;
]]
-- TODO: separate vars/ints in two ifcs? (ifcs_vars/ifcs_ints)
for _, var in ipairs(cls.blk_ifc.vars) do
local off
if cls.is_ifc then
-- off = IFC[org.cls][var.n]
off = 'CEU.ifcs['
..'(*PTR_org(tceu_ncls*,org,'.._MEM.cls.idx_cls..'))'
..']['
.._ENV.ifcs[var.id_ifc]
..']'
else
off = var.off
end
if var.isEvt then
val = nil
elseif var.cls or var.arr then
val = 'PTR_org('.._TP.c(var.tp)..',org,'..off..')'
else
val = '(*PTR_org('.._TP.c(var.tp..'*')..',org,'..off..'))'
end
local id = pre..'_'..cls.id..'_'..var.id
code[#code+1] = '#define '..id..'_off(org) '..off
if val then
code[#code+1] = '#define '..id..'(org) '..val
end
end
end
_MEM.code_clss = table.concat(code,'\n')
end,
Dcl_cls_pre = function (me)
me.mem = { off=0, max=0 }
if _PROPS.has_ifcs then
local off = alloc(me.mem, _ENV.c.tceu_ncls.len) -- cls N
_MEM.cls.idx_cls = off -- same off for all orgs
DBG('', string.format('%8s','cls'), off, _ENV.c.tceu_ncls.len)
end
--if _PROPS.has_orgs then
me.mem.trail0 = alloc(me.mem, me.ns.trails*_ENV.c.tceu_trail.len,
_ENV.c.tceu_trail.len)
_MEM.cls.idx_trail0 = me.mem.trail0 -- same off for all orgs
DBG('', string.format('%8s','trl0'), me.mem.trail0,
me.ns.trails*_ENV.c.tceu_trail.len)
--end
if _PROPS.has_wclocks then
me.mem.wclock0 = alloc(me.mem, me.ns.wclocks*4)
DBG('', string.format('%8s','clk0'), me.mem.wclock0, me.ns.wclocks*4)
end
end,
Dcl_cls = function (me)
DBG('===', me.id)
DBG('', 'mem', me.mem.max)
DBG('', 'trl', me.ns.trails)
DBG('', 'clk', me.ns.wclocks)
DBG('======================')
--[[
local glb = {}
for i,v in ipairs(me.aw.t) do
local ID = v[1].evt
glb[#glb+1] = ID.id
end
DBG('', 'glb', '{'..table.concat(glb,',')..'}')
]]
end,
Block_pre = function (me)
local cls = CLS()
if cls.is_ifc then
cls.mem.off = 0
cls.mem.max = 0
me.max = 0
return
end
local mem = cls.mem
me.off = mem.off
-- TODO: bitmap?
me.off_fins = alloc(CLS().mem, (me.fins and #me.fins) or 0)
for _, var in ipairs(me.vars) do
local len
if var.isTmp or var.isEvt then
--if var.isTmp then
len = 0
--elseif var.isEvt then
--len = 1
elseif var.cls then
len = (var.arr or 1) * var.cls.mem.max
elseif var.arr then
local _tp = _TP.deref(var.tp)
len = var.arr * (_TP.deref(_tp) and _ENV.c.pointer.len
or (_ENV.c[_tp] and _ENV.c[_tp].len))
elseif _TP.deref(var.tp) then
len = _ENV.c.pointer.len
else
len = _ENV.c[var.tp].len
end
var.len = len
end
-- sort offsets in descending order to optimize alignment
-- TODO: previous org metadata
local sorted = { unpack(me.vars) }
table.sort(sorted, pred_sort)
for _, var in ipairs(sorted) do
--
if not var.isEvt then
var.off = alloc(mem, var.len)
DBG('', string.format('%8s',var.id), var.off,
var.isTmp and '*' or var.len)
end
--
end
--_MEM.evt_off = MAX(_MEM.evt_off, mem.off)
-- events fill the gaps between variables
-- we use offsets for events because of interfaces
local off = 0
local i = 1
local var = sorted[i]
local function nextOff ()
if var and (var.isEvt or off==var.off) then
i = i + 1
var = sorted[i]
return nextOff()
end
off = off + 1
_MEM.evt_off = MAX(_MEM.evt_off, off)
return off
end
for _, var in ipairs(sorted) do
if var.isEvt then
var.off = nextOff()
DBG('', string.format('%8s',var.id), var.off, var.len)
end
end
--[[
]]
me.max = mem.off
end,
Block = function (me)
local mem = CLS().mem
for blk in _AST.iter'Block' do
blk.max = MAX(blk.max, mem.off)
end
mem.off = me.off
end,
ParEver_aft = function (me, sub)
me.lst = sub.max
end,
ParEver_bef = function (me, sub)
local mem = CLS().mem
mem.off = me.lst or mem.off
end,
ParOr_aft = 'ParEver_aft',
ParOr_bef = 'ParEver_bef',
ParAnd_aft = 'ParEver_aft',
ParAnd_bef = 'ParEver_bef',
ParAnd_pre = function (me)
me.off = alloc(CLS().mem, #me) -- TODO: bitmap?
end,
ParAnd = 'Block',
}
_AST.visit(F)
|
_MEM = {
cls = {}, -- offsets for fixed fields inside classes
evt_off = 0, -- max event index among all classes
code_clss = nil,
}
function alloc (mem, n, al)
local al = al or n
--DBG(mem.off, n, _TP.align(mem.off,n))
mem.off = _TP.align(mem.off,al)
local cur = mem.off
mem.off = cur + n
mem.max = MAX(mem.max, mem.off)
--DBG(mem, n, mem.max)
return cur
end
function pred_sort (v1, v2)
return v1.len > v2.len
end
F = {
Root = function (me)
ASR(_MEM.evt_off+#_ENV.exts < 255, me, 'too many events')
me.mem = _MAIN.mem
-- cls/ifc accessors
local code = {}
for _,cls in ipairs(_ENV.clss) do
local pre = (cls.is_ifc and 'IFC') or 'CLS'
code[#code+1] = [[
typedef struct {
char data[]]..cls.mem.max..[[];
} ]]..pre..'_'..cls.id..[[;
]]
-- TODO: separate vars/ints in two ifcs? (ifcs_vars/ifcs_ints)
for _, var in ipairs(cls.blk_ifc.vars) do
local off
if cls.is_ifc then
-- off = IFC[org.cls][var.n]
off = 'CEU.ifcs['
..'(*PTR_org(tceu_ncls*,org,'.._MEM.cls.idx_cls..'))'
..']['
.._ENV.ifcs[var.id_ifc]
..']'
else
off = var.off
end
if var.isEvt then
val = nil
elseif var.cls or var.arr then
val = 'PTR_org('.._TP.c(var.tp)..',org,'..off..')'
else
val = '(*PTR_org('.._TP.c(var.tp..'*')..',org,'..off..'))'
end
local id = pre..'_'..cls.id..'_'..var.id
code[#code+1] = '#define '..id..'_off(org) '..off
if val then
code[#code+1] = '#define '..id..'(org) '..val
end
end
end
_MEM.code_clss = table.concat(code,'\n')
end,
Dcl_cls_pre = function (me)
me.mem = { off=0, max=0 }
if _PROPS.has_ifcs then
local off = alloc(me.mem, _ENV.c.tceu_ncls.len) -- cls N
_MEM.cls.idx_cls = off -- same off for all orgs
DBG('', string.format('%8s','cls'), off, _ENV.c.tceu_ncls.len)
end
--if _PROPS.has_orgs then
me.mem.trail0 = alloc(me.mem, me.ns.trails*_ENV.c.tceu_trail.len,
_ENV.c.tceu_trail.len)
_MEM.cls.idx_trail0 = me.mem.trail0 -- same off for all orgs
DBG('', string.format('%8s','trl0'), me.mem.trail0,
me.ns.trails*_ENV.c.tceu_trail.len)
--end
if _PROPS.has_wclocks then
me.mem.wclock0 = alloc(me.mem, me.ns.wclocks*4)
DBG('', string.format('%8s','clk0'), me.mem.wclock0, me.ns.wclocks*4)
end
end,
Dcl_cls = function (me)
DBG('===', me.id)
DBG('', 'mem', me.mem.max)
DBG('', 'trl', me.ns.trails)
DBG('', 'clk', me.ns.wclocks)
DBG('======================')
--[[
local glb = {}
for i,v in ipairs(me.aw.t) do
local ID = v[1].evt
glb[#glb+1] = ID.id
end
DBG('', 'glb', '{'..table.concat(glb,',')..'}')
]]
end,
Block_pre = function (me)
local cls = CLS()
if cls.is_ifc then
cls.mem.off = 0
cls.mem.max = 0
me.max = 0
return
end
local mem = cls.mem
me.off = mem.off
-- TODO: bitmap?
me.off_fins = alloc(CLS().mem, (me.fins and #me.fins) or 0)
for _, var in ipairs(me.vars) do
local len
--if var.isTmp or var.isEvt then
--
if var.isTmp then
len = 0
--
elseif var.isEvt then
--
len = 1
elseif var.cls then
len = (var.arr or 1) * var.cls.mem.max
elseif var.arr then
local _tp = _TP.deref(var.tp)
len = var.arr * (_TP.deref(_tp) and _ENV.c.pointer.len
or (_ENV.c[_tp] and _ENV.c[_tp].len))
elseif _TP.deref(var.tp) then
len = _ENV.c.pointer.len
else
len = _ENV.c[var.tp].len
end
var.len = len
end
-- sort offsets in descending order to optimize alignment
-- TODO: previous org metadata
local sorted = { unpack(me.vars) }
table.sort(sorted, pred_sort)
for _, var in ipairs(sorted) do
--
--if not var.isEvt then
var.off = alloc(mem, var.len)
DBG('', string.format('%8s',var.id), var.off,
var.isTmp and '*' or var.len)
--end
--
end
--
_MEM.evt_off = MAX(_MEM.evt_off, mem.off)
-- events fill the gaps between variables
-- we use offsets for events because of interfaces
--[[
local off = 0
local i = 1
local var = sorted[i]
local function nextOff ()
if var and (var.isEvt or off==var.off) then
i = i + 1
var = sorted[i]
return nextOff()
end
off = off + 1
_MEM.evt_off = MAX(_MEM.evt_off, off)
return off
end
for _, var in ipairs(sorted) do
if var.isEvt then
var.off = nextOff()
DBG('', string.format('%8s',var.id), var.off, var.len)
end
end
]]
me.max = mem.off
end,
Block = function (me)
local mem = CLS().mem
for blk in _AST.iter'Block' do
blk.max = MAX(blk.max, mem.off)
end
mem.off = me.off
end,
ParEver_aft = function (me, sub)
me.lst = sub.max
end,
ParEver_bef = function (me, sub)
local mem = CLS().mem
mem.off = me.lst or mem.off
end,
ParOr_aft = 'ParEver_aft',
ParOr_bef = 'ParEver_bef',
ParAnd_aft = 'ParEver_aft',
ParAnd_bef = 'ParEver_bef',
ParAnd_pre = function (me)
me.off = alloc(CLS().mem, #me) -- TODO: bitmap?
end,
ParAnd = 'Block',
}
_AST.visit(F)
|
(*) TODO: ints are using 1 byte (bug in CC2420)
|
(*) TODO: ints are using 1 byte (bug in CC2420)
|
Lua
|
mit
|
Johnicholas/ceu,Johnicholas/ceu
|
62610734569539eecab6c8cf3fc064c8cad371d4
|
lua/entities/gmod_wire_adv_emarker.lua
|
lua/entities/gmod_wire_adv_emarker.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Adv Wire Entity Marker"
ENT.Author = "Divran"
ENT.WireDebugName = "Adv EMarker"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Marks = {}
local outputs = {"Entities [ARRAY]", "Nr"}
for i=3,12 do
outputs[i] = "Entity" .. (i-2) .. " [ENTITY]"
end
self.Inputs = WireLib.CreateInputs( self, { "Entity [ENTITY]", "Add Entity", "Remove Entity", "Clear Entities" } )
self.Outputs = WireLib.CreateOutputs( self, outputs )
self:SetOverlayText( "Number of entities linked: 0" )
end
function ENT:TriggerInput( name, value )
if (name == "Entity") then
if IsValid(value) then
self.Target = value
end
elseif (name == "Add Entity") then
if IsValid(self.Target) then
if (value != 0) then
local bool, index = self:CheckEnt( self.Target )
if (!bool) then
self:LinkEnt( self.Target )
end
end
end
elseif (name == "Remove Entity") then
if IsValid(self.Target) then
if (value != 0) then
local bool, index = self:CheckEnt( self.Target )
if (bool) then
self:UnlinkEnt( self.Target )
end
end
end
elseif (name == "Clear Entities") then
self:ClearEntities()
end
end
function ENT:UpdateOutputs()
-- Trigger regular outputs
WireLib.TriggerOutput( self, "Entities", self.Marks )
WireLib.TriggerOutput( self, "Nr", #self.Marks )
-- Trigger special outputs
for i=3,12 do
WireLib.TriggerOutput( self, "Entity" .. (i-2), self.Marks[i-2] )
end
-- Overlay text
self:SetOverlayText( "Number of entities linked: " .. #self.Marks )
-- Yellow lines information
WireLib.SendMarks(self)
end
function ENT:CheckEnt( ent )
for index, e in pairs( self.Marks ) do
if (e == ent) then return true, index end
end
return false, 0
end
function ENT:LinkEnt( ent )
if (self:CheckEnt( ent )) then return false end
self.Marks[#self.Marks+1] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
self:UnlinkEnt(ent)
end)
self:UpdateOutputs()
return true
end
function ENT:UnlinkEnt( ent )
local bool, index = self:CheckEnt( ent )
if (bool) then
table.remove( self.Marks, index )
self:UpdateOutputs()
end
return bool
end
function ENT:ClearEntities()
for i=1,#self.Marks do
self.Marks[i]:RemoveCallOnRemove( "AdvEMarker.Unlink" )
end
self.Marks = {}
self:UpdateOutputs()
end
function ENT:OnRemove()
self:ClearEntities()
end
duplicator.RegisterEntityClass( "gmod_wire_adv_emarker", WireLib.MakeWireEnt, "Data" )
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if next(self.Marks) then
local tbl = {}
for index, e in pairs( self.Marks ) do
tbl[index] = e:EntIndex()
end
info.marks = tbl
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
if (info.marks) then
self.Marks = self.Marks or {}
for index, entid in pairs(info.marks) do
local ent = GetEntByID(entid)
self.Marks[index] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
if IsValid(self) then self:UnlinkEnt(ent) end
end)
end
self:UpdateOutputs()
end
end
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Adv Wire Entity Marker"
ENT.Author = "Divran"
ENT.WireDebugName = "Adv EMarker"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Marks = {}
local outputs = {"Entities [ARRAY]", "Nr"}
for i=3,12 do
outputs[i] = "Entity" .. (i-2) .. " [ENTITY]"
end
self.Inputs = WireLib.CreateInputs( self, { "Entity [ENTITY]", "Add Entity", "Remove Entity", "Clear Entities" } )
self.Outputs = WireLib.CreateOutputs( self, outputs )
self:SetOverlayText( "Number of entities linked: 0" )
end
function ENT:TriggerInput( name, value )
if (name == "Entity") then
if IsValid(value) then
self.Target = value
end
elseif (name == "Add Entity") then
if IsValid(self.Target) then
if (value != 0) then
local bool, index = self:CheckEnt( self.Target )
if (!bool) then
self:LinkEnt( self.Target )
end
end
end
elseif (name == "Remove Entity") then
if IsValid(self.Target) then
if (value != 0) then
local bool, index = self:CheckEnt( self.Target )
if (bool) then
self:UnlinkEnt( self.Target )
end
end
end
elseif (name == "Clear Entities") then
self:ClearEntities()
end
end
function ENT:UpdateOutputs()
-- Trigger regular outputs
WireLib.TriggerOutput( self, "Entities", self.Marks )
WireLib.TriggerOutput( self, "Nr", #self.Marks )
-- Trigger special outputs
for i=3,12 do
WireLib.TriggerOutput( self, "Entity" .. (i-2), self.Marks[i-2] )
end
-- Overlay text
self:SetOverlayText( "Number of entities linked: " .. #self.Marks )
-- Yellow lines information
WireLib.SendMarks(self)
end
function ENT:CheckEnt( ent )
for index, e in pairs( self.Marks ) do
if (e == ent) then return true, index end
end
return false, 0
end
function ENT:LinkEnt( ent )
if (self:CheckEnt( ent )) then return false end
self.Marks[#self.Marks+1] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
self:UnlinkEnt(ent)
end)
self:UpdateOutputs()
return true
end
function ENT:UnlinkEnt( ent )
local bool, index = self:CheckEnt( ent )
if (bool) then
table.remove( self.Marks, index )
self:UpdateOutputs()
end
return bool
end
function ENT:ClearEntities()
for i=1,#self.Marks do
if self.Marks[i]:IsValid() then
self.Marks[i]:RemoveCallOnRemove( "AdvEMarker.Unlink" )
end
end
self.Marks = {}
self:UpdateOutputs()
end
function ENT:OnRemove()
self:ClearEntities()
end
duplicator.RegisterEntityClass( "gmod_wire_adv_emarker", WireLib.MakeWireEnt, "Data" )
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if next(self.Marks) then
local tbl = {}
for index, e in pairs( self.Marks ) do
tbl[index] = e:EntIndex()
end
info.marks = tbl
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
if (info.marks) then
self.Marks = self.Marks or {}
for index, entid in pairs(info.marks) do
local ent = GetEntByID(entid)
self.Marks[index] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
if IsValid(self) then self:UnlinkEnt(ent) end
end)
end
self:UpdateOutputs()
end
end
|
Fixed lua error in adv_emarker
|
Fixed lua error in adv_emarker
|
Lua
|
apache-2.0
|
garrysmodlua/wire,Grocel/wire,dvdvideo1234/wire,NezzKryptic/Wire,wiremod/wire,sammyt291/wire
|
c517abf7bf62269d1f523ec32ebe5b43eaf27f45
|
packages/footnotes.lua
|
packages/footnotes.lua
|
-- Footnotes class
-- Exports: The \footnote command
-- outputInsertions (call this in endPage)
SILE.require("packages/counters")
SILE.require("packages/raiselower")
local insertions = SILE.require("packages/insertions")
SILE.scratch.counters.footnote = { value= 1, display= "arabic" };
SILE.registerCommand("footnotemark", function(options, content)
SILE.Commands["raise"]({height = "0.7ex"}, function()
SILE.Commands["font"]({ size = "1.5ex" }, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote))
end)
end)
end)
SILE.registerCommand("footnote", function(options, content)
SILE.call("footnotemark")
-- XXX We need to vbox the material in the context of the frame it's going to
-- be inserted into, not in the frame it's coming from; e.g. when a two-column
-- layout has a full-width footnotes frame. This does so for the width, but by
-- being too familiar with the workings of insertions.
local opts = SILE.scratch.insertions.classes.footnote
local f = SILE.getFrame(opts["insertInto"])
local fwidth = SILE.length.new({length=f:width()})
insertions.exports:insert("footnote", SILE.Commands["vbox"]({width = fwidth}, function()
SILE.Commands["font"]({size = "9pt"}, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote)..".")
SILE.call("qquad")
SILE.process(content)
end)
end
))
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
return {
init = function (class, args)
insertions.exports:initInsertionClass("footnote", {
insertInto = args.insertInto,
stealFrom = args.stealFrom,
maxHeight = SILE.length.new({length = SILE.toPoints("25", "%","h") }),
topSkip = SILE.length.parse("2ex"),
interInsertionSkip = SILE.length.parse("1ex"),
})
end,
exports = {
outputInsertions = insertions.exports.outputInsertions
}
}
|
-- Footnotes class
-- Exports: The \footnote command
-- outputInsertions (call this in endPage)
SILE.require("packages/counters")
SILE.require("packages/raiselower")
local insertions = SILE.require("packages/insertions")
SILE.scratch.counters.footnote = { value= 1, display= "arabic" };
SILE.registerCommand("footnotemark", function(options, content)
SILE.Commands["raise"]({height = "0.7ex"}, function()
SILE.Commands["font"]({ size = "1.5ex" }, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote))
end)
end)
end)
SILE.registerCommand("footnote", function(options, content)
SILE.call("footnotemark")
local opts = SILE.scratch.insertions.classes.footnote
local f = SILE.getFrame(opts["insertInto"])
local oldF = SILE.typesetter.frame
SILE.typesetter.frame = f
SILE.typesetter:pushState()
SILE.typesetter:initFrame(f)
insertions.exports:insert("footnote", SILE.Commands["vbox"]({}, function()
SILE.Commands["font"]({size = "9pt"}, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote)..".")
SILE.call("qquad")
SILE.process(content)
end)
end
))
SILE.typesetter:popState()
SILE.typesetter.frame = oldF
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
return {
init = function (class, args)
insertions.exports:initInsertionClass("footnote", {
insertInto = args.insertInto,
stealFrom = args.stealFrom,
maxHeight = SILE.length.new({length = SILE.toPoints("25", "%","h") }),
topSkip = SILE.length.parse("2ex"),
interInsertionSkip = SILE.length.parse("1ex"),
})
end,
exports = {
outputInsertions = insertions.exports.outputInsertions
}
}
|
Switch frames when setting footnotes. (Fixes a bad interaction with grid.)
|
Switch frames when setting footnotes. (Fixes a bad interaction with grid.)
|
Lua
|
mit
|
alerque/sile,alerque/sile,shirat74/sile,WAKAMAZU/sile_fe,anthrotype/sile,neofob/sile,neofob/sile,simoncozens/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,neofob/sile,alerque/sile,WAKAMAZU/sile_fe,anthrotype/sile,anthrotype/sile,simoncozens/sile,anthrotype/sile,simoncozens/sile,shirat74/sile,alerque/sile,shirat74/sile,simoncozens/sile,shirat74/sile,neofob/sile
|
bedd133daa5e9fab819bdd6ed0266bf6692b7ea3
|
hydro/eqn/euler-lingr.lua
|
hydro/eqn/euler-lingr.lua
|
--[[
Euler fluid equations (rho, v^i, P) <-> (rho, m^i, ETotal)
with additional GEM (phi_g, A_g)
so that means no need for op/selfgrav because it's now built in as (phi, A)
--]]
local class = require 'ext.class'
local table = require 'ext.table'
local Euler = require 'hydro.eqn.euler'
local EulerLinGR = class(Euler)
EulerLinGR.name = 'euler_lingr'
EulerLinGR.solverCodeFile = 'hydro/eqn/euler-lingr.cl'
function EulerLinGR:buildVars(args)
EulerLinGR.super.buildVars(self, args)
for _,t in ipairs{self.primVars, self.consVars} do
local i = assert(t:find(nil, function(v) return v.name == 'ePot' end))
t:remove(i)
-- TODO behaviors of eqn's ... just apply behavior to this and to twofluid-emhd
t:append{
{name='D_g', type='real3', units='kg/m^2', variance='l'}, -- (D_g)_i
{name='B_g', type='real3', units='1/s', variance='l'}, -- (B_g)_i
{name='phi_g', type='real', units='kg/m^2', variance=''}, -- div D_g potential
{name='psi_g', type='real', units='1/s', variance=''}, -- div B_g potential
}
end
end
function EulerLinGR:buildSelfGrav()
-- no self-grav. that's now done through the lingr
end
function EulerLinGR:createInitState()
EulerLinGR.super.createInitState(self)
local speedOfLight = 1
local gravitationalConstant = 1e-3
self:addGuiVars(table{
{name='divPsiWavespeed_g', value=speedOfLight, units='m/s'},
{name='divPhiWavespeed_g', value=speedOfLight, units='m/s'},
{name='speedOfLight', value=speedOfLight, units='m/s'},
{name='sqrt_G', value=math.sqrt(gravitationalConstant), units='(m^3/(kg*s^2))^.5'},
})
end
--[=[
function EulerLinGR:postComputeFluxCode()
return self:template[[
//// MODULE_DEPENDS: <?=coord_sqrt_det_g?> <?=coord_lower?>
//flux is computed raised via Levi-Civita upper
//so here we lower it
real _1_sqrt_det_g = 1. / coord_sqrt_det_g(x);
flux.D = real3_real_mul(coord_lower(flux.D, x), _1_sqrt_det_g);
flux.B = real3_real_mul(coord_lower(flux.B, x), _1_sqrt_det_g);
flux.D_g = real3_real_mul(coord_lower(flux.D_g, x), _1_sqrt_det_g);
flux.B_g = real3_real_mul(coord_lower(flux.B_g, x), _1_sqrt_det_g);
]]
end
--]=]
-- don't use default
function EulerLinGR:initCodeModule_fluxFromCons() end
function EulerLinGR:initCodeModule_consFromPrim_primFromCons() end
function EulerLinGR:getDisplayVars()
local vars = EulerLinGR.super.getDisplayVars(self)
local i = assert(vars:find(nil, function(v) return v.name == 'EPot' end))
vars:remove(i)
return vars
end
local eigenVars = table()
eigenVars:append{
-- Roe-averaged vars
{name='rho', type='real', units='kg/m^3'},
{name='v', type='real3', units='m/s'},
{name='hTotal', type='real', units='m^2/s^2'},
-- derived vars
{name='vSq', type='real', units='m^2/s^2'},
{name='vL', type='real3', units='m/s'},
{name='Cs', type='real', units='m/s'},
}
EulerLinGR.eigenVars = eigenVars
function EulerLinGR:eigenWaveCodePrefix(n, eig, x)
return self:template([[
real const Cs_nLen = <?=eig?>->Cs * normal_len(n);
real const v_n = normal_vecDotN1(n, <?=eig?>->v);
]], {
x = x,
eig = '('..eig..')',
n = n,
})
end
function EulerLinGR:eigenWaveCode(n, eig, x, waveIndex)
if waveIndex == 0 then
return 'v_n - Cs_nLen'
elseif waveIndex >= 1 and waveIndex <= 3 then
return 'v_n'
elseif waveIndex == 4 then
return 'v_n + Cs_nLen'
end
if waveIndex >= 5 and waveIndex < 5+8 then
return ({
'-solver->divPhiWavespeed_g / unit_m_per_s',
'-solver->divPsiWavespeed_g / unit_m_per_s',
'-solver->speedOfLight / unit_m_per_s',
'-solver->speedOfLight / unit_m_per_s',
'solver->speedOfLight / unit_m_per_s',
'solver->speedOfLight / unit_m_per_s',
'solver->divPsiWavespeed_g / unit_m_per_s',
'solver->divPhiWavespeed_g / unit_m_per_s',
})[waveIndex - 5 - 8 + 1]
end
error('got a bad waveIndex: '..waveIndex)
end
--TODO timestep restriction
-- 2014 Abgrall, Kumar eqn 2.25
-- dt < sqrt( E_alpha,i / rho_alpha,i) * |lHat_r,alpha| sqrt(2) / |E_i + v_alpha,i x B_i|
function EulerLinGR:consWaveCodePrefix(n, U, x)
return self:template([[
<?=prim_t?> W;
<?=primFromCons?>(&W, solver, <?=U?>, <?=x?>);
<?if true then -- using the EM wavespeed ?>
real consWaveCode_lambdaMax = max(
max(
max(solver->divPsiWavespeed, solver->divPhiWavespeed),
max(solver->divPsiWavespeed_g, solver->divPhiWavespeed_g)
),
solver->speedOfLight
) / unit_m_per_s;
<? else -- ignoring it ?>
real consWaveCode_lambdaMax = INFINITY;
<? end ?>
real consWaveCode_lambdaMin = -consWaveCode_lambdaMax;
real const Cs = calc_Cs(solver, &W);
real const Cs_nLen = Cs * normal_len(n);
consWaveCode_lambdaMin = min(consWaveCode_lambdaMin, normal_vecDotN1(n, W.v) - Cs_nLen);
consWaveCode_lambdaMax = max(consWaveCode_lambdaMax, normal_vecDotN1(n, W.v) + Cs_nLen);
]], {
n = n,
U = '('..U..')',
x = x,
})
end
function EulerLinGR:consMinWaveCode(n, U, x)
return 'consWaveCode_lambdaMin'
end
function EulerLinGR:consMaxWaveCode(n, U, x)
return 'consWaveCode_lambdaMax'
end
return EulerLinGR
|
--[[
Euler fluid equations (rho, v^i, P) <-> (rho, m^i, ETotal)
with additional GEM (phi_g, A_g)
so that means no need for op/selfgrav because it's now built in as (phi, A)
--]]
local class = require 'ext.class'
local table = require 'ext.table'
local Euler = require 'hydro.eqn.euler'
local EulerLinGR = class(Euler)
EulerLinGR.numWaves = nil
EulerLinGR.numIntStates = nil
EulerLinGR.name = 'euler_lingr'
EulerLinGR.solverCodeFile = 'hydro/eqn/euler-lingr.cl'
function EulerLinGR:buildVars(args)
EulerLinGR.super.buildVars(self, args)
for _,t in ipairs{self.primVars, self.consVars} do
local i = assert(t:find(nil, function(v) return v.name == 'ePot' end))
t:remove(i)
-- TODO behaviors of eqn's ... just apply behavior to this and to twofluid-emhd
t:append{
{name='D_g', type='real3', units='kg/m^2', variance='l'}, -- (D_g)_i
{name='B_g', type='real3', units='1/s', variance='l'}, -- (B_g)_i
{name='phi_g', type='real', units='kg/m^2', variance=''}, -- div D_g potential
{name='psi_g', type='real', units='1/s', variance=''}, -- div B_g potential
}
end
end
function EulerLinGR:buildSelfGrav()
-- no self-grav. that's now done through the lingr
end
function EulerLinGR:createInitState()
EulerLinGR.super.createInitState(self)
local speedOfLight = 1
local gravitationalConstant = 1e-3
self:addGuiVars(table{
{name='divPsiWavespeed_g', value=speedOfLight, units='m/s'},
{name='divPhiWavespeed_g', value=speedOfLight, units='m/s'},
{name='speedOfLight', value=speedOfLight, units='m/s'},
{name='sqrt_G', value=math.sqrt(gravitationalConstant), units='(m^3/(kg*s^2))^.5'},
})
end
--[=[
function EulerLinGR:postComputeFluxCode()
return self:template[[
//// MODULE_DEPENDS: <?=coord_sqrt_det_g?> <?=coord_lower?>
//flux is computed raised via Levi-Civita upper
//so here we lower it
real _1_sqrt_det_g = 1. / coord_sqrt_det_g(x);
flux.D = real3_real_mul(coord_lower(flux.D, x), _1_sqrt_det_g);
flux.B = real3_real_mul(coord_lower(flux.B, x), _1_sqrt_det_g);
flux.D_g = real3_real_mul(coord_lower(flux.D_g, x), _1_sqrt_det_g);
flux.B_g = real3_real_mul(coord_lower(flux.B_g, x), _1_sqrt_det_g);
]]
end
--]=]
-- don't use default
function EulerLinGR:initCodeModule_fluxFromCons() end
function EulerLinGR:initCodeModule_consFromPrim_primFromCons() end
function EulerLinGR:getDisplayVars()
local vars = EulerLinGR.super.getDisplayVars(self)
local i = assert(vars:find(nil, function(v) return v.name == 'EPot' end))
vars:remove(i)
return vars
end
local eigenVars = table()
eigenVars:append{
-- Roe-averaged vars
{name='rho', type='real', units='kg/m^3'},
{name='v', type='real3', units='m/s'},
{name='hTotal', type='real', units='m^2/s^2'},
-- derived vars
{name='vSq', type='real', units='m^2/s^2'},
{name='vL', type='real3', units='m/s'},
{name='Cs', type='real', units='m/s'},
}
EulerLinGR.eigenVars = eigenVars
function EulerLinGR:eigenWaveCodePrefix(n, eig, x)
return self:template([[
real const Cs_nLen = <?=eig?>->Cs * normal_len(n);
real const v_n = normal_vecDotN1(n, <?=eig?>->v);
]], {
x = x,
eig = '('..eig..')',
n = n,
})
end
function EulerLinGR:eigenWaveCode(n, eig, x, waveIndex)
if waveIndex == 0 then
return 'v_n - Cs_nLen'
elseif waveIndex >= 1 and waveIndex <= 3 then
return 'v_n'
elseif waveIndex == 4 then
return 'v_n + Cs_nLen'
end
if waveIndex >= 5 and waveIndex < 5+8 then
return ({
'-solver->divPhiWavespeed_g / unit_m_per_s',
'-solver->divPsiWavespeed_g / unit_m_per_s',
'-solver->speedOfLight / unit_m_per_s',
'-solver->speedOfLight / unit_m_per_s',
'solver->speedOfLight / unit_m_per_s',
'solver->speedOfLight / unit_m_per_s',
'solver->divPsiWavespeed_g / unit_m_per_s',
'solver->divPhiWavespeed_g / unit_m_per_s',
})[waveIndex - 5 + 1]
end
error('got a bad waveIndex: '..waveIndex)
end
--TODO timestep restriction
-- 2014 Abgrall, Kumar eqn 2.25
-- dt < sqrt( E_alpha,i / rho_alpha,i) * |lHat_r,alpha| sqrt(2) / |E_i + v_alpha,i x B_i|
function EulerLinGR:consWaveCodePrefix(n, U, x)
return self:template([[
<?=prim_t?> W;
<?=primFromCons?>(&W, solver, <?=U?>, <?=x?>);
<?if true then -- using the EM wavespeed ?>
real consWaveCode_lambdaMax = max(
max(
max(solver->divPsiWavespeed, solver->divPhiWavespeed),
max(solver->divPsiWavespeed_g, solver->divPhiWavespeed_g)
),
solver->speedOfLight
) / unit_m_per_s;
<? else -- ignoring it ?>
real consWaveCode_lambdaMax = INFINITY;
<? end ?>
real consWaveCode_lambdaMin = -consWaveCode_lambdaMax;
real const Cs = calc_Cs(solver, &W);
real const Cs_nLen = Cs * normal_len(n);
consWaveCode_lambdaMin = min(consWaveCode_lambdaMin, normal_vecDotN1(n, W.v) - Cs_nLen);
consWaveCode_lambdaMax = max(consWaveCode_lambdaMax, normal_vecDotN1(n, W.v) + Cs_nLen);
]], {
n = n,
U = '('..U..')',
x = x,
})
end
function EulerLinGR:consMinWaveCode(n, U, x)
return 'consWaveCode_lambdaMin'
end
function EulerLinGR:consMaxWaveCode(n, U, x)
return 'consWaveCode_lambdaMax'
end
return EulerLinGR
|
ok fixed warnings, but now GEM force is wrong
|
ok fixed warnings, but now GEM force is wrong
|
Lua
|
mit
|
thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua
|
55f0cddb0895db085429052562a1c42b997bd90b
|
deviceloaders/joystick.lua
|
deviceloaders/joystick.lua
|
--- Library for accesing a joystick.
-- This library allows to read data from a joystick,
-- such as it's coordinates and button presses.
-- The device will be named something like "joystick:/dev/input/js0", module "joystick".
-- @module joystick
-- @alias device
--https://www.kernel.org/doc/Documentation/input/joystick-api.txt
local M = {}
--- Initialize and starts the module.
-- This is called automatically by toribio if the _load_ attribute for the module in the configuration file is set to
-- true.
-- @param conf the configuration table (see @{conf}).
M.init = function(conf)
local toribio = require 'toribio'
local selector = require 'lumen.tasks.selector'
local sched = require 'lumen.sched'
local filename = conf.filename or '/dev/input/js0'
local devicename = 'joystick:'..filename
local evmove, evbutton = {}, {} --events
local axes = {} --holds reading
local device = {}
--- Name of the device (something like 'joystick:/dev/input/js0').
device.name=devicename
--- Module name (in this case, 'joystick').
device.module='joystick'
--- Device file of the joystick.
-- For example, '/dev/input/js0'
device.filename=filename
--- Events emitted by this device.
-- @field button Button operated. First parameter is the button number,
-- followed by _true_ for pressed or _false_ for released.
-- @field move Joystick moved. Parameters are the axis readings.
-- @table events
device.events={
move = evmove,
button = evbutton,
}
device.start = function ()
if device.fd then device.fd:close()
device.fd = assert(selector.new_fd(filename, {'rdonly', 'sync'}, 8, function(_, data)
local value = data:byte(5) + 256*data:byte(6)--2 bytes
if value>32768 then value=value-0xFFFF end
local vtype = data:byte(7)
local vaxis = data:byte(8)
if vtype == 0x02 then --#define JS_EVENT_AXIS /* joystick moved */
axes[vaxis] = value
--print('AXES', unpack(axes, 0))
sched.signal(evmove, unpack(axes, 0))
elseif vtype == 0x01 then --#define JS_EVENT_BUTTON /* button pressed/released */
sched.signal(evbutton, vaxis, value == 1 )
elseif vtype > 0x80 then --#define JS_EVENT_INIT /* initial state of device */
vtype = vtype - 0x80
if vtype == 0x02 then
axes[vaxis] = value
elseif vtype == 0x01 then
sched.signal(evbutton, vaxis, value == 1 )
end
end
return true
end))
end
device.stop = function ()
device.fd:close()
device.fd = nil
end
toribio.add_device(device)
end
return M
--- Configuration Table.
-- When the start is done automatically (trough configuration),
-- this table points to the modules section in the global configuration table loaded from the configuration file.
-- @table conf
-- @field load whether toribio should start this module automatically at startup.
-- @field filename the device file for the joystick (defaults to ''/dev/input/js0'').
|
--- Library for accesing a joystick.
-- This library allows to read data from a joystick,
-- such as it's coordinates and button presses.
-- The device will be named something like "joystick:/dev/input/js0", module "joystick".
-- @module joystick
-- @alias device
--https://www.kernel.org/doc/Documentation/input/joystick-api.txt
local M = {}
--- Initialize and starts the module.
-- This is called automatically by toribio if the _load_ attribute for the module in the configuration file is set to
-- true.
-- @param conf the configuration table (see @{conf}).
M.init = function(conf)
local toribio = require 'toribio'
local selector = require 'lumen.tasks.selector'
local sched = require 'lumen.sched'
local filename = conf.filename or '/dev/input/js0'
local devicename = 'joystick:'..filename
local evmove, evbutton = {}, {} --events
local axes = {} --holds reading
local device = {}
--- Name of the device (something like 'joystick:/dev/input/js0').
device.name=devicename
--- Module name (in this case, 'joystick').
device.module='joystick'
--- Device file of the joystick.
-- For example, '/dev/input/js0'
device.filename=filename
--- Events emitted by this device.
-- @field button Button operated. First parameter is the button number,
-- followed by _true_ for pressed or _false_ for released.
-- @field move Joystick moved. Parameters are the axis readings.
-- @table events
device.events={
move = evmove,
button = evbutton,
}
device.start = function ()
if device.fd then device.fd:close() end
device.fd = assert(selector.new_fd(filename, {'rdonly', 'sync'}, 8, function(_, data)
local value = data:byte(5) + 256*data:byte(6)--2 bytes
if value>32768 then value=value-0xFFFF end
local vtype = data:byte(7)
local vaxis = data:byte(8)
if vtype == 0x02 then --#define JS_EVENT_AXIS /* joystick moved */
axes[vaxis] = value
--print('AXES', unpack(axes, 0))
sched.signal(evmove, unpack(axes, 0))
elseif vtype == 0x01 then --#define JS_EVENT_BUTTON /* button pressed/released */
sched.signal(evbutton, vaxis, value == 1 )
elseif vtype > 0x80 then --#define JS_EVENT_INIT /* initial state of device */
vtype = vtype - 0x80
if vtype == 0x02 then
axes[vaxis] = value
elseif vtype == 0x01 then
sched.signal(evbutton, vaxis, value == 1 )
end
end
return true
end))
end
device.stop = function ()
device.fd:close()
device.fd = nil
end
toribio.add_device(device)
end
return M
--- Configuration Table.
-- When the start is done automatically (trough configuration),
-- this table points to the modules section in the global configuration table loaded from the configuration file.
-- @table conf
-- @field load whether toribio should start this module automatically at startup.
-- @field filename the device file for the joystick (defaults to ''/dev/input/js0'').
|
fix breakage
|
fix breakage
|
Lua
|
mit
|
xopxe/Toribio,xopxe/Toribio,xopxe/Toribio
|
55406487260440e78e4eb4e97f7f926d5672195c
|
src/program/snabbnfv/traffic/traffic.lua
|
src/program/snabbnfv/traffic/traffic.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local nfvconfig = require("program.snabbnfv.nfvconfig")
local usage = require("program.snabbnfv.traffic.README_inc")
local ffi = require("ffi")
local C = ffi.C
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor")
local counter = require("core.counter")
local long_opts = {
benchmark = "B",
help = "h",
["link-report-interval"] = "k",
["load-report-interval"] = "l",
["debug-report-interval"] = "D",
["busy"] = "b",
["long-help"] = "H"
}
function run (args)
local opt = {}
local benchpackets
local linkreportinterval = 0
local loadreportinterval = 1
local debugreportinterval = 0
function opt.B (arg) benchpackets = tonumber(arg) end
function opt.h (arg) print(short_usage()) main.exit(1) end
function opt.H (arg) print(long_usage()) main.exit(1) end
function opt.k (arg) linkreportinterval = tonumber(arg) end
function opt.l (arg) loadreportinterval = tonumber(arg) end
function opt.D (arg) debugreportinterval = tonumber(arg) end
function opt.b (arg) engine.busywait = true end
args = lib.dogetopt(args, opt, "hHB:k:l:D:b", long_opts)
if #args == 3 then
local pciaddr, confpath, sockpath = unpack(args)
local ok, info = pcall(pci.device_info, pciaddr)
if not ok then
print("Error: device not found " .. pciaddr)
os.exit(1)
end
if not info.driver then
print("Error: no driver for device " .. pciaddr)
os.exit(1)
end
if loadreportinterval > 0 then
local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating')
timer.activate(t)
end
if linkreportinterval > 0 then
local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating')
timer.activate(t)
end
if debugreportinterval > 0 then
local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating')
timer.activate(t)
end
if benchpackets then
print("snabbnfv traffic starting (benchmark mode)")
bench(pciaddr, confpath, sockpath, benchpackets)
else
print("snabbnfv traffic starting")
traffic(pciaddr, confpath, sockpath)
end
else
print("Wrong number of arguments: " .. tonumber(#args))
print()
print(short_usage())
main.exit(1)
end
end
function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end
function long_usage () return usage end
-- Run in real traffic mode.
function traffic (pciaddr, confpath, sockpath)
engine.log = true
local mtime = 0
if C.stat_mtime(confpath) == 0 then
print(("WARNING: File '%s' does not exist."):format(confpath))
end
timer.activate(ingress_drop_monitor.new({action='warn'}):timer())
while true do
local mtime2 = C.stat_mtime(confpath)
if mtime2 ~= mtime then
print("Loading " .. confpath)
engine.configure(nfvconfig.load(confpath, pciaddr, sockpath))
mtime = mtime2
end
engine.main({duration=1, no_report=true})
-- Flush buffered log messages every 1s
io.flush()
end
end
-- Run in benchmark mode.
function bench (pciaddr, confpath, sockpath, npackets)
npackets = tonumber(npackets)
local ports = dofile(confpath)
local nic = (nfvconfig.port_name(ports[1])).."_NIC"
engine.log = true
engine.Hz = false
print("Loading " .. confpath)
engine.configure(nfvconfig.load(confpath, pciaddr, sockpath))
-- From designs/nfv
local start, packets, bytes = 0, 0, 0
local done = function ()
local input = link.stats(engine.app_table[nic].input.rx)
if start == 0 and input.rxpackets > 0 then
-- started receiving, record time and packet count
packets = input.rxpackets
bytes = input.rxbytes
start = C.get_monotonic_time()
if os.getenv("NFV_PROF") then
require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE"))
else
print("No LuaJIT profiling enabled ($NFV_PROF unset).")
end
if os.getenv("NFV_DUMP") then
require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE"))
main.dumping = true
else
print("No LuaJIT dump enabled ($NFV_DUMP unset).")
end
end
return input.rxpackets - packets >= npackets
end
engine.main({done = done, no_report = true})
local finish = C.get_monotonic_time()
local runtime = finish - start
local breaths = tonumber(counter.read(engine.breaths))
local input = link.stats(engine.app_table[nic].input.rx)
packets = input.rxpackets - packets
bytes = input.rxbytes - bytes
engine.report()
print()
print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime))
print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6))
print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6))
require("jit.p").stop()
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local nfvconfig = require("program.snabbnfv.nfvconfig")
local usage = require("program.snabbnfv.traffic.README_inc")
local ffi = require("ffi")
local C = ffi.C
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor")
local counter = require("core.counter")
local long_opts = {
benchmark = "B",
help = "h",
["link-report-interval"] = "k",
["load-report-interval"] = "l",
["debug-report-interval"] = "D",
["busy"] = "b",
["long-help"] = "H"
}
function run (args)
local opt = {}
local benchpackets
local linkreportinterval = 0
local loadreportinterval = 1
local debugreportinterval = 0
function opt.B (arg) benchpackets = tonumber(arg) end
function opt.h (arg) print(short_usage()) main.exit(1) end
function opt.H (arg) print(long_usage()) main.exit(1) end
function opt.k (arg) linkreportinterval = tonumber(arg) end
function opt.l (arg) loadreportinterval = tonumber(arg) end
function opt.D (arg) debugreportinterval = tonumber(arg) end
function opt.b (arg) engine.busywait = true end
args = lib.dogetopt(args, opt, "hHB:k:l:D:b", long_opts)
if #args == 3 then
local pciaddr, confpath, sockpath = unpack(args)
local ok, info = pcall(pci.device_info, pciaddr)
if not ok then
print("Error: device not found " .. pciaddr)
os.exit(1)
end
if not info.driver then
print("Error: no driver for device " .. pciaddr)
os.exit(1)
end
if loadreportinterval > 0 then
local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating')
timer.activate(t)
end
if linkreportinterval > 0 then
local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating')
timer.activate(t)
end
if debugreportinterval > 0 then
local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating')
timer.activate(t)
end
if benchpackets then
print("snabbnfv traffic starting (benchmark mode)")
bench(pciaddr, confpath, sockpath, benchpackets)
else
print("snabbnfv traffic starting")
traffic(pciaddr, confpath, sockpath)
end
else
print("Wrong number of arguments: " .. tonumber(#args))
print()
print(short_usage())
main.exit(1)
end
end
function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end
function long_usage () return usage end
-- Run in real traffic mode.
function traffic (pciaddr, confpath, sockpath)
engine.log = true
local mtime = 0
local needs_reconfigure = true
function check_for_reconfigure()
needs_reconfigure = C.stat_mtime(confpath) ~= mtime
end
timer.activate(ingress_drop_monitor.new({action='warn'}):timer())
timer.activate(timer.new("reconf", check_for_reconfigure, 1e9, 'repeating'))
-- Flush logs every second.
timer.activate(timer.new("flush", io.flush, 1e9, 'repeating'))
while true do
needs_reconfigure = false
print("Loading " .. confpath)
mtime = C.stat_mtime(confpath)
if mtime == 0 then
print(("WARNING: File '%s' does not exist."):format(confpath))
end
engine.configure(nfvconfig.load(confpath, pciaddr, sockpath))
engine.main({done=function() return needs_reconfigure end})
end
end
-- Run in benchmark mode.
function bench (pciaddr, confpath, sockpath, npackets)
npackets = tonumber(npackets)
local ports = dofile(confpath)
local nic = (nfvconfig.port_name(ports[1])).."_NIC"
engine.log = true
engine.Hz = false
print("Loading " .. confpath)
engine.configure(nfvconfig.load(confpath, pciaddr, sockpath))
-- From designs/nfv
local start, packets, bytes = 0, 0, 0
local done = function ()
local input = link.stats(engine.app_table[nic].input.rx)
if start == 0 and input.rxpackets > 0 then
-- started receiving, record time and packet count
packets = input.rxpackets
bytes = input.rxbytes
start = C.get_monotonic_time()
if os.getenv("NFV_PROF") then
require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE"))
else
print("No LuaJIT profiling enabled ($NFV_PROF unset).")
end
if os.getenv("NFV_DUMP") then
require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE"))
main.dumping = true
else
print("No LuaJIT dump enabled ($NFV_DUMP unset).")
end
end
return input.rxpackets - packets >= npackets
end
engine.main({done = done, no_report = true})
local finish = C.get_monotonic_time()
local runtime = finish - start
local breaths = tonumber(counter.read(engine.breaths))
local input = link.stats(engine.app_table[nic].input.rx)
packets = input.rxpackets - packets
bytes = input.rxbytes - bytes
engine.report()
print()
print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime))
print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6))
print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6))
require("jit.p").stop()
end
|
snabbnfv traffic: Only re-start engine when configuration changes
|
snabbnfv traffic: Only re-start engine when configuration changes
Before, snabbnfv would run the engine for one-second intervals, checking
for restart every second and restarting the engine. However this
interacts poorly with the latency-tracking mechanism, which expects to
be able to call non-performant functions like ffi.typeof() at setup,
because it's just setup. With this fix we have less trace creation and
interpreter bailout at run-time.
|
Lua
|
apache-2.0
|
Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,heryii/snabb,snabbco/snabb,heryii/snabb,kbara/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,Igalia/snabb,kbara/snabb,eugeneia/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,heryii/snabb,alexandergall/snabbswitch,dpino/snabbswitch,snabbco/snabb,mixflowtech/logsensor,Igalia/snabb,kbara/snabb,kbara/snabb,heryii/snabb,dpino/snabb,snabbco/snabb,mixflowtech/logsensor,mixflowtech/logsensor,Igalia/snabb,Igalia/snabb,snabbco/snabb,kbara/snabb,dpino/snabb,alexandergall/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,Igalia/snabbswitch,eugeneia/snabb,heryii/snabb,dpino/snabb,snabbco/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,kbara/snabb,dpino/snabb,dpino/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,heryii/snabb,eugeneia/snabbswitch,dpino/snabb,Igalia/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,Igalia/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,eugeneia/snabb
|
1474a1f1efd13de47b0fd7468c64f1e79845c930
|
mod_auth_ldap/mod_auth_ldap.lua
|
mod_auth_ldap/mod_auth_ldap.lua
|
local new_sasl = require "util.sasl".new;
local log = require "util.logger".init("auth_ldap");
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)");
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local lualdap = require "lualdap";
local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls));
module.unload = function() ld:close(); end
local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
return ld:search({
base = ldap_base;
scope = ldap_scope;
filter = ldap_filter:format(ldap_filter_escape(username));
})();
end
local provider = {};
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.password ~= password then
ld:modify(dn, { '=', userPassword = password });
end
return true
end
function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
module:provides("auth", provider);
|
local new_sasl = require "util.sasl".new;
local log = require "util.logger".init("auth_ldap");
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)");
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local lualdap = require "lualdap";
local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls));
module.unload = function() ld:close(); end
local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
return ld:search({
base = ldap_base;
scope = ldap_scope;
filter = ldap_filter:format(ldap_filter_escape(username));
})();
end
local provider = {};
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.userPassword == password then return true end
return ld:modify(dn, { '=', userPassword = password })();
end
function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
module:provides("auth", provider);
|
mod_auth_ldap: Fix set_password
|
mod_auth_ldap: Fix set_password
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
6803bda16dd64d3003d8bdd2457171a7b1065c7e
|
libs/core/luasrc/model/network/wireless.lua
|
libs/core/luasrc/model/network/wireless.lua
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(iface.dev.wifi.mode or "Client"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
elseif m == "wds" then m = "WDS"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
libs/core: i18n fixes for wds mode
|
libs/core: i18n fixes for wds mode
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5513 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
stephank/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,projectbismark/luci-bismark,Canaan-Creative/luci,stephank/luci,Flexibity/luci,ch3n2k/luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,vhpham80/luci,yeewang/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,vhpham80/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,stephank/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,stephank/luci,zwhfly/openwrt-luci,gwlim/luci,freifunk-gluon/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,8devices/carambola2-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,vhpham80/luci,saraedum/luci-packages-old,jschmidlapp/luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,Flexibity/luci,jschmidlapp/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,stephank/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,gwlim/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,gwlim/luci,Canaan-Creative/luci,ch3n2k/luci,phi-psi/luci,projectbismark/luci-bismark,freifunk-gluon/luci,saraedum/luci-packages-old,phi-psi/luci,ch3n2k/luci,phi-psi/luci,freifunk-gluon/luci,phi-psi/luci,Flexibity/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,stephank/luci,jschmidlapp/luci,Flexibity/luci,projectbismark/luci-bismark,freifunk-gluon/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,jschmidlapp/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,phi-psi/luci,freifunk-gluon/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,ThingMesh/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,saraedum/luci-packages-old,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci
|
e268052a8bc56803772eadcfb5f4399bcf8ba919
|
ffi/framebuffer_linux.lua
|
ffi/framebuffer_linux.lua
|
local ffi = require("ffi")
local bit = require("bit")
local BB = require("ffi/blitbuffer")
local dummy = require("ffi/linux_fb_h")
local dummy = require("ffi/posix_h")
local framebuffer = {}
local framebuffer_mt = {__index={}}
local function einkfb_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct update_area_t[1]")
refarea[0].x1 = x or 0
refarea[0].y1 = y or 0
refarea[0].x2 = x + (w or (fb.vinfo.xres-x))
refarea[0].y2 = y + (h or (fb.vinfo.yres-y))
refarea[0].buffer = nil
if refreshtype == 1 then
refarea[0].which_fx = ffi.C.fx_update_partial
else
refarea[0].which_fx = ffi.C.fx_update_full
end
ioctl(fb.fd, ffi.C.FBIO_EINK_UPDATE_DISPLAY_AREA, refarea);
end
local function mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
refarea[0].update_mode = refreshtype or 1
refarea[0].waveform_mode = waveform_mode or 2
refarea[0].update_region.left = x or 0
refarea[0].update_region.top = y or 0
refarea[0].update_region.width = w or fb.vinfo.xres
refarea[0].update_region.height = h or fb.vinfo.yres
refarea[0].update_marker = 1
refarea[0].temp = 0x1000
-- TODO make the flag configurable from UI,
-- this flag invert all the pixels on display 09.01 2013 (houqp)
refarea[0].flags = 0
refarea[0].alt_buffer_data.phys_addr = 0
refarea[0].alt_buffer_data.width = 0
refarea[0].alt_buffer_data.height = 0
refarea[0].alt_buffer_data.alt_update_region.top = 0
refarea[0].alt_buffer_data.alt_update_region.left = 0
refarea[0].alt_buffer_data.alt_update_region.width = 0
refarea[0].alt_buffer_data.alt_update_region.height = 0
ffi.C.ioctl(fb.fd, ffi.C.MXCFB_SEND_UPDATE, refarea)
end
local function k51_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct mxcfb_update_data[1]")
-- only for Amazon's driver:
refarea[0].hist_bw_waveform_mode = 0
refarea[0].hist_gray_waveform_mode = 0
return mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
end
local function kobo_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct mxcfb_update_data_kobo[1]")
-- only for Kobo driver:
refarea[0].alt_buffer_data.virt_addr = nil
return mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
end
function framebuffer.open(device)
local fb = {
fd = -1,
finfo = ffi.new("struct fb_fix_screeninfo"),
vinfo = ffi.new("struct fb_var_screeninfo"),
fb_size = -1,
einkUpdateFunc = nil,
bb = nil,
data = nil
}
setmetatable(fb, framebuffer_mt)
fb.fd = ffi.C.open(device, ffi.C.O_RDWR)
assert(fb.fd ~= -1, "cannot open framebuffer")
-- Get fixed screen information
assert(ffi.C.ioctl(fb.fd, ffi.C.FBIOGET_FSCREENINFO, fb.finfo) == 0,
"cannot get screen info")
assert(ffi.C.ioctl(fb.fd, ffi.C.FBIOGET_VSCREENINFO, fb.vinfo) == 0,
"cannot get variable screen info")
assert(fb.finfo.type == ffi.C.FB_TYPE_PACKED_PIXELS,
"video type not supported")
--Kindle Paperwhite doesn't set this properly?
--assert(fb.vinfo.grayscale == 0, "only grayscale is supported but framebuffer says it isn't")
assert(fb.vinfo.xres_virtual > 0 and fb.vinfo.yres_virtual > 0, "invalid framebuffer resolution")
-- it seems that fb.finfo.smem_len is unreliable on kobo
-- Figure out the size of the screen in bytes
fb.fb_size = fb.vinfo.xres_virtual * fb.vinfo.yres_virtual * fb.vinfo.bits_per_pixel / 8
fb.data = ffi.C.mmap(nil, fb.fb_size, bit.bor(ffi.C.PROT_READ, ffi.C.PROT_WRITE), ffi.C.MAP_SHARED, fb.fd, 0)
assert(fb.data ~= ffi.C.MAP_FAILED, "can not mmap() framebuffer")
if ffi.string(fb.finfo.id, 11) == "mxc_epdc_fb" then
-- TODO: check for Kobo
-- Kindle PaperWhite and KT with 5.1 or later firmware
fb.einkUpdateFunc = k51_update
if fb.vinfo.bits_per_pixel == 16 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB16, fb.data, fb.finfo.line_length)
fb.bb:invert()
elseif fb.vinfo.bits_per_pixel == 8 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB8, fb.data, fb.finfo.line_length)
fb.bb:invert()
else
error("unknown bpp value for the mxc eink driver")
end
elseif ffi.string(fb.finfo.id, 7) == "eink_fb" then
fb.einkUpdateFunc = einkfb_update
if fb.vinfo.bits_per_pixel == 8 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB8, fb.data, fb.finfo.line_length)
elseif fb.vinfo.bits_per_pixel == 4 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB4, fb.data, fb.finfo.line_length)
else
error("unknown bpp value for the classic eink driver")
end
else
error("eink model not supported");
end
return fb
end
function framebuffer_mt:getOrientation()
local mode = ffi.new("int[1]")
ffi.C.ioctl(self.fd, ffi.C.FBIO_EINK_GET_DISPLAY_ORIENTATION, mode)
-- adjust ioctl's rotate mode definition to KPV's
-- refer to screen.lua
if mode == 2 then
return 1
elseif mode == 1 then
return 2
end
return mode
end
function framebuffer_mt:setOrientation(mode)
mode = ffi.cast("int", mode or 0)
if mode < 0 or mode > 3 then
error("Wrong rotation mode given!")
end
--[[
ioctl has a different definition for rotation mode.
1
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 2
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
if mode == 1 then
mode = 2
elseif mode == 2 then
mode = 1
end
ffi.C.ioctl(self.fd, ffi.C.FBIO_EINK_SET_DISPLAY_ORIENTATION, mode)
end
function framebuffer_mt.__index:refresh(refreshtype, waveform_mode, x, y, w, h)
w, x = BB.checkBounds(w or self.bb:getWidth(), x or 0, 0, self.bb:getWidth(), 0xFFFF)
h, y = BB.checkBounds(h or self.bb:getHeight(), y or 0, 0, self.bb:getHeight(), 0xFFFF)
local px, py = self.bb:getPhysicalRect(x, y, w, h)
self:einkUpdateFunc(refreshtype, waveform_mode, px, py, w, h)
end
function framebuffer_mt.__index:getSize()
return self.bb:getWidth(), self.bb:getHeight()
end
function framebuffer_mt.__index:getPitch()
return self.bb.pitch
end
function framebuffer_mt.__index:close()
ffi.C.munmap(self.data, self.fb_size)
ffi.C.close(self.fd)
self.fd = -1
self.data = nil
self.bb = nil
end
return framebuffer
|
local ffi = require("ffi")
local bit = require("bit")
local BB = require("ffi/blitbuffer")
local dummy = require("ffi/linux_fb_h")
local dummy = require("ffi/posix_h")
local framebuffer = {}
local framebuffer_mt = {__index={}}
local function einkfb_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct update_area_t[1]")
refarea[0].x1 = x or 0
refarea[0].y1 = y or 0
refarea[0].x2 = x + (w or (fb.vinfo.xres-x))
refarea[0].y2 = y + (h or (fb.vinfo.yres-y))
refarea[0].buffer = nil
if refreshtype == 1 then
refarea[0].which_fx = ffi.C.fx_update_partial
else
refarea[0].which_fx = ffi.C.fx_update_full
end
ioctl(fb.fd, ffi.C.FBIO_EINK_UPDATE_DISPLAY_AREA, refarea);
end
local function mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
refarea[0].update_mode = refreshtype or 1
refarea[0].waveform_mode = waveform_mode or 2
refarea[0].update_region.left = x or 0
refarea[0].update_region.top = y or 0
refarea[0].update_region.width = w or fb.vinfo.xres
refarea[0].update_region.height = h or fb.vinfo.yres
refarea[0].update_marker = 1
refarea[0].temp = 0x1000
-- TODO make the flag configurable from UI,
-- this flag invert all the pixels on display 09.01 2013 (houqp)
refarea[0].flags = 0
refarea[0].alt_buffer_data.phys_addr = 0
refarea[0].alt_buffer_data.width = 0
refarea[0].alt_buffer_data.height = 0
refarea[0].alt_buffer_data.alt_update_region.top = 0
refarea[0].alt_buffer_data.alt_update_region.left = 0
refarea[0].alt_buffer_data.alt_update_region.width = 0
refarea[0].alt_buffer_data.alt_update_region.height = 0
ffi.C.ioctl(fb.fd, ffi.C.MXCFB_SEND_UPDATE, refarea)
end
local function k51_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct mxcfb_update_data[1]")
-- only for Amazon's driver:
refarea[0].hist_bw_waveform_mode = 0
refarea[0].hist_gray_waveform_mode = 0
return mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
end
local function kobo_update(fb, refreshtype, waveform_mode, x, y, w, h)
local refarea = ffi.new("struct mxcfb_update_data_kobo[1]")
-- only for Kobo driver:
refarea[0].alt_buffer_data.virt_addr = nil
return mxc_update(fb, refarea, refreshtype, waveform_mode, x, y, w, h)
end
function framebuffer.open(device)
local fb = {
fd = -1,
finfo = ffi.new("struct fb_fix_screeninfo"),
vinfo = ffi.new("struct fb_var_screeninfo"),
fb_size = -1,
einkUpdateFunc = nil,
bb = nil,
data = nil
}
setmetatable(fb, framebuffer_mt)
fb.fd = ffi.C.open(device, ffi.C.O_RDWR)
assert(fb.fd ~= -1, "cannot open framebuffer")
-- Get fixed screen information
assert(ffi.C.ioctl(fb.fd, ffi.C.FBIOGET_FSCREENINFO, fb.finfo) == 0,
"cannot get screen info")
assert(ffi.C.ioctl(fb.fd, ffi.C.FBIOGET_VSCREENINFO, fb.vinfo) == 0,
"cannot get variable screen info")
assert(fb.finfo.type == ffi.C.FB_TYPE_PACKED_PIXELS,
"video type not supported")
--Kindle Paperwhite doesn't set this properly?
--assert(fb.vinfo.grayscale == 0, "only grayscale is supported but framebuffer says it isn't")
assert(fb.vinfo.xres_virtual > 0 and fb.vinfo.yres_virtual > 0, "invalid framebuffer resolution")
-- it seems that fb.finfo.smem_len is unreliable on kobo
-- Figure out the size of the screen in bytes
fb.fb_size = fb.vinfo.xres_virtual * fb.vinfo.yres_virtual * fb.vinfo.bits_per_pixel / 8
fb.data = ffi.C.mmap(nil, fb.fb_size, bit.bor(ffi.C.PROT_READ, ffi.C.PROT_WRITE), ffi.C.MAP_SHARED, fb.fd, 0)
assert(fb.data ~= ffi.C.MAP_FAILED, "can not mmap() framebuffer")
if ffi.string(fb.finfo.id, 11) == "mxc_epdc_fb" then
-- TODO: implement a better check for Kobo
if fb.vinfo.bits_per_pixel == 16 then
-- this ought to be a Kobo
fb.einkUpdateFunc = kobo_update
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB16, fb.data, fb.finfo.line_length)
fb.bb:invert()
elseif fb.vinfo.bits_per_pixel == 8 then
-- Kindle PaperWhite and KT with 5.1 or later firmware
fb.einkUpdateFunc = k51_update
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB8, fb.data, fb.finfo.line_length)
fb.bb:invert()
else
error("unknown bpp value for the mxc eink driver")
end
elseif ffi.string(fb.finfo.id, 7) == "eink_fb" then
fb.einkUpdateFunc = einkfb_update
if fb.vinfo.bits_per_pixel == 8 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB8, fb.data, fb.finfo.line_length)
elseif fb.vinfo.bits_per_pixel == 4 then
fb.bb = BB.new(fb.vinfo.xres, fb.vinfo.yres, BB.TYPE_BB4, fb.data, fb.finfo.line_length)
else
error("unknown bpp value for the classic eink driver")
end
else
error("eink model not supported");
end
return fb
end
function framebuffer_mt:getOrientation()
local mode = ffi.new("int[1]")
ffi.C.ioctl(self.fd, ffi.C.FBIO_EINK_GET_DISPLAY_ORIENTATION, mode)
-- adjust ioctl's rotate mode definition to KPV's
-- refer to screen.lua
if mode == 2 then
return 1
elseif mode == 1 then
return 2
end
return mode
end
function framebuffer_mt:setOrientation(mode)
mode = ffi.cast("int", mode or 0)
if mode < 0 or mode > 3 then
error("Wrong rotation mode given!")
end
--[[
ioctl has a different definition for rotation mode.
1
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 2
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
if mode == 1 then
mode = 2
elseif mode == 2 then
mode = 1
end
ffi.C.ioctl(self.fd, ffi.C.FBIO_EINK_SET_DISPLAY_ORIENTATION, mode)
end
function framebuffer_mt.__index:refresh(refreshtype, waveform_mode, x, y, w, h)
w, x = BB.checkBounds(w or self.bb:getWidth(), x or 0, 0, self.bb:getWidth(), 0xFFFF)
h, y = BB.checkBounds(h or self.bb:getHeight(), y or 0, 0, self.bb:getHeight(), 0xFFFF)
local px, py = self.bb:getPhysicalRect(x, y, w, h)
self:einkUpdateFunc(refreshtype, waveform_mode, px, py, w, h)
end
function framebuffer_mt.__index:getSize()
return self.bb:getWidth(), self.bb:getHeight()
end
function framebuffer_mt.__index:getPitch()
return self.bb.pitch
end
function framebuffer_mt.__index:close()
ffi.C.munmap(self.data, self.fb_size)
ffi.C.close(self.fd)
self.fd = -1
self.data = nil
self.bb = nil
end
return framebuffer
|
fixes in device/framebuffer recognition
|
fixes in device/framebuffer recognition
we assume that 16bpp framebuffers are Kobo devices
|
Lua
|
agpl-3.0
|
koreader/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,houqp/koreader-base,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,frankyifei/koreader-base,koreader/koreader-base,frankyifei/koreader-base
|
4a9431ae1309025c7b46063cf17f3d56bd5f0ab1
|
otouto/plugins/heise.lua
|
otouto/plugins/heise.lua
|
local heise = {}
heise.triggers = {
"heise.de/newsticker/meldung/(.*).html$"
}
function heise:get_heise_article(article)
local url = 'https://query.yahooapis.com/v1/public/yql?q=select%20content,src,strong%20from%20html%20where%20url=%22http://www.heise.de/newsticker/meldung/'..article..'.html%22%20and%20xpath=%22//div[@id=%27mitte_news%27]/article/header/h2|//div[@id=%27mitte_news%27]/article/div/p[1]/strong|//div[@id=%27mitte_news%27]/article/div/figure/img%22&format=json'
local res,code = https.request(url)
local data = json.decode(res).query.results
if code ~= 200 then return "HTTP-Fehler" end
local title = data.h2
if data.strong then
teaser = '\n'..data.strong
else
teaser = ''
end
if data.img then
image_url = 'https:'..data.img.src
end
local text = '*'..title..'*'..teaser
if data.img then
return text, image_url
else
return text
end
end
function heise:action(msg, config, matches)
local article = URL.escape(matches[1])
local text, image_url = heise:get_heise_article(article)
if image_url then
utilities.send_typing(msg.chat.id, 'upload_photo')
local file = download_to_file(image_url, 'heise_teaser.jpg')
utilities.send_photo(msg.chat.id, file, nil, msg.message_id)
end
utilities.send_reply(msg, text, true)
end
return heise
|
local heise = {}
heise.triggers = {
"heise.de/newsticker/meldung/(.*).html$"
}
function heise:get_heise_article(article)
local url = 'https://query.yahooapis.com/v1/public/yql?q=select%20content,src,strong%20from%20html%20where%20url=%22http://www.heise.de/newsticker/meldung/'..article..'.html%22%20and%20xpath=%22//div[@id=%27mitte_news%27]/article/header/h2|//div[@id=%27mitte_news%27]/article/div/p[1]/strong|//div[@id=%27mitte_news%27]/article/div/figure/img%22&format=json'
local res, code = https.request(url)
if code ~= 200 then return nil end
local data = json.decode(res).query.results
local title = data.h2
if data.strong then
teaser = '\n'..data.strong
else
teaser = ''
end
if data.img then
image_url = 'https:'..data.img.src
end
local text = '*'..title..'*'..teaser
if data.img then
return text, image_url
else
return text
end
end
function heise:action(msg, config, matches)
local article = URL.escape(matches[1])
local text, image_url = heise:get_heise_article(article)
if not text then return end
if image_url then
utilities.send_typing(msg.chat.id, 'upload_photo')
local file = download_to_file(image_url, 'heise_teaser.jpg')
utilities.send_photo(msg.chat.id, file, nil, msg.message_id)
end
utilities.send_reply(msg, text, true)
end
return heise
|
Heise: Fix
|
Heise: Fix
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
2990b9f06f2c57c79643aa384b5a58027cdd73bc
|
xmake/actions/require/impl/environment.lua
|
xmake/actions/require/impl/environment.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 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("package")
-- enter the package environments
function _enter_package(package_name, envs, installdir)
-- save the old environments
_g._OLDENVS = _g._OLDENVS or {}
local oldenvs = _g._OLDENVS[package_name]
if not oldenvs then
oldenvs = {}
_g._OLDENVS[package_name] = oldenvs
end
-- add the new environments
oldenvs.PATH = os.getenv("PATH")
for name, values in pairs(envs) do
oldenvs[name] = oldenvs[name] or os.getenv(name)
if name == "PATH" then
if path.is_absolute(value) then
os.addenv(name, value)
else
os.addenv(name, path.join(installdir, value))
end
else
os.addenv(name, unpack(values))
end
end
end
-- leave the package environments
function _leave_package(package_name)
_g._OLDENVS = _g._OLDENVS or {}
local oldenvs = _g._OLDENVS[package_name]
if oldenvs then
for name, values in pairs(oldenvs) do
os.setenv(name, values)
end
_g._OLDENVS[package_name] = nil
end
end
-- enter environment of the given binary packages, git, 7z, ..
function _enter_packages(...)
for _, name in ipairs({...}) do
for _, manifest_file in ipairs(os.files(path.join(core_package.installdir(), name:sub(1, 1), name, "*", "*", "manifest.txt"))) do
local manifest = io.load(manifest_file)
if manifest and manifest.plat == os.host() and manifest.arch == os.arch() then
_enter_package(name, manifest.envs, path.directory(manifest_file))
end
end
end
end
-- leave environment of the given binary packages, git, 7z, ..
function _leave_packages(...)
for _, name in ipairs({...}) do
_leave_package(name)
end
end
-- enter environment
--
-- ensure that we can find some basic tools: git, unzip, ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search pathes of toolchains
environment.enter("toolchains")
-- unzip is necessary
if not find_tool("unzip") then
raise("unzip not found! we need install it first")
end
-- enter the environments of git and 7z
_enter_packages("git", "7z")
-- git not found? install it first
local packages = {}
if not find_tool("git") then
table.join2(packages, package.install_packages("git"))
end
-- missing the necessary unarchivers for *.gz, *.7z? install them first, e.g. gzip, 7z, tar ..
if not ((find_tool("gzip") and find_tool("tar")) or find_tool("7z")) then
table.join2(packages, package.install_packages("7z"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
_g._PACKAGES = packages
end
-- leave environment
function leave()
-- leave the environments of installed packages
for _, instance in irpairs(_g._PACKAGES) do
instance:envs_leave()
end
_g._PACKAGES = nil
-- leave the environments of git and 7z
_leave_packages("7z", "git")
-- restore search pathes of toolchains
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 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("package")
-- enter the package environments
function _enter_package(package_name, envs, installdir)
-- save the old environments
_g._OLDENVS = _g._OLDENVS or {}
local oldenvs = _g._OLDENVS[package_name]
if not oldenvs then
oldenvs = {}
_g._OLDENVS[package_name] = oldenvs
end
-- add the new environments
oldenvs.PATH = os.getenv("PATH")
for name, values in pairs(envs) do
oldenvs[name] = oldenvs[name] or os.getenv(name)
if name == "PATH" then
for _, value in ipairs(values) do
if path.is_absolute(value) then
os.addenv(name, value)
else
os.addenv(name, path.join(installdir, value))
end
end
else
os.addenv(name, unpack(values))
end
end
end
-- leave the package environments
function _leave_package(package_name)
_g._OLDENVS = _g._OLDENVS or {}
local oldenvs = _g._OLDENVS[package_name]
if oldenvs then
for name, values in pairs(oldenvs) do
os.setenv(name, values)
end
_g._OLDENVS[package_name] = nil
end
end
-- enter environment of the given binary packages, git, 7z, ..
function _enter_packages(...)
for _, name in ipairs({...}) do
for _, manifest_file in ipairs(os.files(path.join(core_package.installdir(), name:sub(1, 1), name, "*", "*", "manifest.txt"))) do
local manifest = io.load(manifest_file)
if manifest and manifest.plat == os.host() and manifest.arch == os.arch() then
_enter_package(name, manifest.envs, path.directory(manifest_file))
end
end
end
end
-- leave environment of the given binary packages, git, 7z, ..
function _leave_packages(...)
for _, name in ipairs({...}) do
_leave_package(name)
end
end
-- enter environment
--
-- ensure that we can find some basic tools: git, unzip, ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search pathes of toolchains
environment.enter("toolchains")
-- unzip is necessary
if not find_tool("unzip") then
raise("unzip not found! we need install it first")
end
-- enter the environments of git and 7z
_enter_packages("git", "7z")
-- git not found? install it first
local packages = {}
if not find_tool("git") then
table.join2(packages, package.install_packages("git"))
end
-- missing the necessary unarchivers for *.gz, *.7z? install them first, e.g. gzip, 7z, tar ..
if not ((find_tool("gzip") and find_tool("tar")) or find_tool("7z")) then
table.join2(packages, package.install_packages("7z"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
_g._PACKAGES = packages
end
-- leave environment
function leave()
-- leave the environments of installed packages
for _, instance in irpairs(_g._PACKAGES) do
instance:envs_leave()
end
_g._PACKAGES = nil
-- leave the environments of git and 7z
_leave_packages("7z", "git")
-- restore search pathes of toolchains
environment.leave("toolchains")
end
|
fix package envs
|
fix package envs
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
|
e310da1376a4d4861091ccc914d82d414490807e
|
samples/gtkbuilder.lua
|
samples/gtkbuilder.lua
|
#! /usr/bin/env lua
-- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and
-- is probably covered by its appropriate license.
-- Import lgi and get Gtk package.
local lgi = require 'lgi'
local Gtk = lgi.Gtk
-- There are two ways to access Gtk.Builder; using standard Gtk API's
-- get_object() and get_objects(), or LGI override shortcuts. Both
-- can be used, as demonstrated below.
local window
if gtk_builder_use_standard_api then
-- Instantiate Gtk.Builder and load resources from ui file.
local builder = Gtk.Builder()
assert(builder:add_from_file('demo.ui'))
-- Get top-level window from the builder.
window = builder:get_object('window1')
-- Connect 'Quit' and 'About' actions.
builder:get_object('Quit').on_activate = function(action)
window:destroy()
end
builder:get_object('About').on_activate =
function(action)
local about_dlg = builder:get_object('aboutdialog1')
about_dlg:run()
about_dlg:hide()
end
else
-- Instantiate builder and load objects.
local ui = assert(Gtk.Builder.new_from_file('demo.ui')).objects
-- Get top-level window from the builder.
window = ui.window1
-- Connect 'Quit' and 'About' actions.
function ui.Quit:on_activate() window:destroy() end
function ui.About:on_activate()
ui.aboutdialog1:run()
ui.aboutdialog1:hide()
end
end
-- Connect 'destroy' signal of the main window, terminates the main loop.
window.on_destroy = Gtk.main_quit
-- Make sure that main window is visible.
window:show_all()
-- Start the loop.
Gtk.main()
|
#! /usr/bin/env lua
-- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and
-- is probably covered by its appropriate license.
-- Import lgi and get Gtk package.
local lgi = require 'lgi'
local Gtk = lgi.Gtk
-- There are two ways to access Gtk.Builder; using standard Gtk API's
-- get_object() and get_objects(), or LGI override shortcuts. Both
-- can be used, as demonstrated below.
local window
if gtk_builder_use_standard_api then
-- Instantiate Gtk.Builder and load resources from ui file.
local builder = Gtk.Builder()
assert(builder:add_from_file('demo.ui'))
-- Get top-level window from the builder.
window = builder:get_object('window1')
-- Connect 'Quit' and 'About' actions.
builder:get_object('Quit').on_activate = function(action)
window:destroy()
end
builder:get_object('About').on_activate =
function(action)
local about_dlg = builder:get_object('aboutdialog1')
about_dlg:run()
about_dlg:hide()
end
else
-- Instantiate builder and load objects.
local builder = Gtk.Builder()
local ui = assert(builder:add_from_file('demo.ui')).objects
-- Get top-level window from the builder.
window = ui.window1
-- Connect 'Quit' and 'About' actions.
function ui.Quit:on_activate() window:destroy() end
function ui.About:on_activate()
ui.aboutdialog1:run()
ui.aboutdialog1:hide()
end
end
-- Connect 'destroy' signal of the main window, terminates the main loop.
window.on_destroy = Gtk.main_quit
-- Make sure that main window is visible.
window:show_all()
-- Start the loop.
Gtk.main()
|
Fix builder sample, do not use removed new_from_file method
|
Fix builder sample, do not use removed new_from_file method
|
Lua
|
mit
|
psychon/lgi,zevv/lgi,pavouk/lgi
|
63abe7c4d062a637ceb14ead079b49a54b008282
|
boss.lua
|
boss.lua
|
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.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",
}
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)
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() and IsRLorML() 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")
if DBM then
EPGP:Print(L["Using DBM for boss kill tracking"])
DBM:RegisterCallback("kill",
function (mod)
BossKilled("kill", mod.combatInfo.name)
end)
else
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
self:RegisterMessage("BossKilled", BossKilled)
end
end
|
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.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",
}
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)
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)
-- 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", 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")
if DBM then
EPGP:Print(L["Using DBM for boss kill tracking"])
DBM:RegisterCallback("kill",
function (mod)
BossKilled("kill", mod.combatInfo.name)
end)
else
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
self:RegisterMessage("BossKilled", BossKilled)
end
end
|
Temporary fix to allow disabling/enabling the automatic boss kill module if it is hooked on DBM detection.
|
Temporary fix to allow disabling/enabling the automatic boss kill module if it is hooked on DBM detection.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,sheldon/epgp
|
e05f5016e88c716a36d59b1103b7a868052292fe
|
item/id_359_firefield.lua
|
item/id_359_firefield.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.id_359_firefield' where itm_id=359;
local common = require("base.common")
local monstermagic = require("monster.base.spells.base")
local character = require("base.character")
local M = {}
local flameImmuneMonsters = {}
function M.setFlameImmunity(monsterId)
flameImmuneMonsters[monsterId] = true
end
local function checkFlameImmunity(monsterId)
return flameImmuneMonsters[monsterId]
end
local function DeleteFlame(User, FlameItem)
local field = world:getField(User.pos);
local count = field:countItems();
local currentitem;
local items = { };
for i=0, count-1 do
currentitem = world:getItemOnField(User.pos);
world:erase(currentitem, currentitem.number);
if(currentitem.id ~= FlameItem.id) then
table.insert(items, currentitem);
end
end
for i,item in pairs(items) do
world:createItemFromItem(item, User.pos, true);
end
end
local golems = {}
golems[301]=true --Stone Golem/Fighter/Plate/Blunt
golems[302]=true --Son of the Mountains/Fighter/Plate/Blunt
golems[303]=true --Clay Golem/Fighter/Plate/Blunt
golems[304]=true --Lava Golem/Fighter/Plate/Blunt
golems[305]=true --Silver Golem/Fighter/Plate/Blunt
golems[306]=true --Diamond Golem/Fighter/Plate/Blunt
golems[561]=true --Iron Golem/Fighter/Plate/Blunt
golems[562]=true --Steel Golem/Fighter/Plate/Blunt
golems[563]=true --Merinium Golem/Fighter/Plate/Blunt
golems[564]=true --Gold Golem/Fighter/Plate/Blunt
function M.CharacterOnField(User)
-- dont harm dead chars anymore
if (User:increaseAttrib("hitpoints", 0) == 0) then
return
end
-- dont harm NPCs
if User:getType() == Character.npc then
return
end
-- Search for the falme on the field
-- !!There might be some issues with multiple flames on the same field!!
local Items = common.GetItemsOnField(User.pos)
local FieldItem
for _, item in pairs(Items) do
if(item.id == 359) then
FieldItem = item
break
end
end
-- immune
if not character.IsPlayer(User) then
if checkFlameImmunity(User:getMonsterType()) then
return
elseif golems[User:getMonsterType()] and FieldItem:getData("meteroitFlame") == "true" then --Golems are immune to special flames
return
end
end
if (FieldItem.quality > 100) and User.pos.z ~= 40 then --no harmful flames in the working camp
local resist = monstermagic.getSpellResistence(User) * 10
if resist < FieldItem.quality then
local foundEffect = User.effects:find(110); -- firefield lte
if not foundEffect then
local myEffect = LongTimeEffect(110, 50) --5sec
myEffect:addValue("quality", FieldItem.quality);
User.effects:addEffect(myEffect)
end
else
DeleteFlame(User, FieldItem)
end
else
DeleteFlame(User, FieldItem);
User:inform("Die Feuerflamme war nur eine Illusion und verpufft.",
"The fireflame was just an illusion and disappears.")
end
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.id_359_firefield' where itm_id=359;
local common = require("base.common")
local monstermagic = require("monster.base.spells.base")
local character = require("base.character")
local M = {}
local flameImmuneMonsters = {}
function M.setFlameImmunity(monsterId)
flameImmuneMonsters[monsterId] = true
end
local function checkFlameImmunity(monsterId)
return flameImmuneMonsters[monsterId]
end
local function DeleteFlame(User, FlameItem)
local field = world:getField(User.pos);
local count = field:countItems();
local currentitem;
local items = { };
for i=0, count-1 do
currentitem = world:getItemOnField(User.pos);
world:erase(currentitem, currentitem.number);
if(currentitem.id ~= FlameItem.id) then
table.insert(items, currentitem);
end
end
for i,item in pairs(items) do
world:createItemFromItem(item, User.pos, true);
end
end
local golems = {}
golems[301]=true --Stone Golem/Fighter/Plate/Blunt
golems[302]=true --Son of the Mountains/Fighter/Plate/Blunt
golems[303]=true --Clay Golem/Fighter/Plate/Blunt
golems[304]=true --Lava Golem/Fighter/Plate/Blunt
golems[305]=true --Silver Golem/Fighter/Plate/Blunt
golems[306]=true --Diamond Golem/Fighter/Plate/Blunt
golems[561]=true --Iron Golem/Fighter/Plate/Blunt
golems[562]=true --Steel Golem/Fighter/Plate/Blunt
golems[563]=true --Merinium Golem/Fighter/Plate/Blunt
golems[564]=true --Gold Golem/Fighter/Plate/Blunt
function M.CharacterOnField(User)
-- dont harm dead chars anymore
if (User:increaseAttrib("hitpoints", 0) == 0) then
return
end
-- dont harm NPCs
if User:getType() == Character.npc then
return
end
-- Search for the falme on the field
-- !!There might be some issues with multiple flames on the same field!!
local Items = common.GetItemsOnField(User.pos)
local FieldItem
for _, item in pairs(Items) do
if(item.id == 359) then
FieldItem = item
break
end
end
if not FieldItem then -- the flame doesn't exist anymore
return
end
-- immune
if not character.IsPlayer(User) then
if checkFlameImmunity(User:getMonsterType()) then
return
elseif golems[User:getMonsterType()] and FieldItem:getData("meteroitFlame") == "true" then --Golems are immune to special flames
return
end
end
if (FieldItem.quality > 100) and User.pos.z ~= 40 then --no harmful flames in the working camp
local resist = monstermagic.getSpellResistence(User) * 10
if resist < FieldItem.quality then
local foundEffect = User.effects:find(110); -- firefield lte
if not foundEffect then
local myEffect = LongTimeEffect(110, 50) --5sec
myEffect:addValue("quality", FieldItem.quality);
User.effects:addEffect(myEffect)
end
else
DeleteFlame(User, FieldItem)
end
else
DeleteFlame(User, FieldItem);
User:inform("Die Feuerflamme war nur eine Illusion und verpufft.",
"The fireflame was just an illusion and disappears.")
end
end
return M
|
fix script error in rare case that flame disappears upon character stepping on it
|
fix script error in rare case that flame disappears upon character stepping on it
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content
|
936f810ca8110b052dd62d29162057f9145ad160
|
src/lgix/GObject-Value.lua
|
src/lgix/GObject-Value.lua
|
------------------------------------------------------------------------------
--
-- LGI GObject.Value support.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local assert, pairs = assert, pairs
local lgi = require 'lgi'
local core = require 'lgi._core'
local repo = core.repo
local gi = core.gi
local Type = repo.GObject.Type
-- Value is constructible from any kind of source Lua value, and the
-- type of the value can be hinted by type name.
local Value = repo.GObject.Value
local value_info = gi.GObject.Value
local log = lgi.log.domain('Lgi')
-- Workaround for incorrect annotations - g_value_set_xxx are missing
-- (allow-none) annotations in glib < 2.30.
for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do
if not value_info.methods[name].args[1].optional then
log.message("g_value_%s() is missing (allow-none)", name)
local setter = Value[name]
Value._method[name] =
function(value, val)
if not val then Value.reset(value) else setter(value, val) end
end
end
end
-- Do not allow direct access to fields.
local value_field_gtype = Value._field.g_type
Value._field = nil
-- 'type' property controls gtype of the property.
Value._attribute = { gtype = {} }
function Value._attribute.gtype.get(value)
return core.record.field(value, value_field_gtype)
end
function Value._attribute.gtype.set(value, newtype)
local gtype = core.record.field(value, value_field_gtype)
if gtype then
if newtype then
-- Try converting old value to new one.
local dest = core.record.new(value_info)
Value.init(dest, newtype)
if not Value.transform(value, dest) then
error(("GObject.Value: cannot convert `%s' to `%s'"):format(
gtype, core.record.field(dest, value_field_gtype)))
end
Value.unset(value)
Value.init(value, newtype)
Value.copy(dest, value)
else
Value.unset(value)
end
elseif newtype then
-- No value was set and some is requested, so set it.
Value.init(value, newtype)
end
end
local value_marshallers = {}
for name, gtype in pairs(Type) do
local get = Value._method['get_' .. name:lower()]
local set = Value._method['set_' .. name:lower()]
if get and set then
value_marshallers[gtype] =
function(value, params, ...)
return (select('#', ...) > 0 and set or get)(value, ...)
end
end
end
-- Interface marshaller is the same as object marshallers.
value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT]
-- Override 'boxed' marshaller, default one marshalls to gpointer
-- instead of target boxed type.
value_marshallers[Type.BOXED] =
function(value, params, ...)
local gtype = core.record.field(value, value_field_gtype)
if select('#', ...) > 0 then
Value.set_boxed(value, core.record.query((...), 'addr', gtype))
else
return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value))
end
end
-- Create GStrv marshaller, implement it using typeinfo marshaller
-- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from
-- g_shell_parse_argv().
value_marshallers[Type.STRV] = core.marshal.container(
gi.GLib.shell_parse_argv.args[3].typeinfo)
-- Finds marshaller closure which can marshal type described either by
-- gtype or typeinfo/transfer combo.
function Value._method.find_marshaller(gtype, typeinfo, transfer)
-- Check whether we can have marshaller for typeinfo.
local marshaller
if typeinfo then
marshaller = core.marshal.container(typeinfo, transfer)
if marshaller then return marshaller end
end
local gt = gtype
-- Special marshaller, allowing only 'nil'.
if not gt then return function() end end
-- Find marshaller according to gtype of the value.
while gt do
-- Check simple and/or fundamental marshallers.
marshaller = value_marshallers[gt] or core.marshal.fundamental(gt)
if marshaller then return marshaller end
gt = Type.parent(gt)
end
error(("GValue marshaller for `%s' not found"):format(tostring(gtype)))
end
-- Value 'value' property provides access to GValue's embedded data.
function Value._attribute:value(...)
local marshaller = Value._method.find_marshaller(
core.record.field(self, value_field_gtype))
return marshaller(self, nil, ...)
end
-- Implement custom 'constructor', taking optionally two values (type
-- and value). The reason why it is overriden is that the order of
-- initialization is important, and standard record intializer cannot
-- enforce the order.
function Value:_new(gtype, value)
local v = core.record.new(value_info)
if gtype then v.gtype = gtype end
if value then v.value = value end
return v
end
|
------------------------------------------------------------------------------
--
-- LGI GObject.Value support.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local assert, pairs = assert, pairs
local lgi = require 'lgi'
local core = require 'lgi._core'
local repo = core.repo
local gi = core.gi
local Type = repo.GObject.Type
-- Value is constructible from any kind of source Lua value, and the
-- type of the value can be hinted by type name.
local Value = repo.GObject.Value
local value_info = gi.GObject.Value
local log = lgi.log.domain('Lgi')
-- Workaround for incorrect annotations - g_value_set_xxx are missing
-- (allow-none) annotations in glib < 2.30.
for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do
if not value_info.methods[name].args[1].optional then
log.message("g_value_%s() is missing (allow-none)", name)
local setter = Value[name]
Value._method[name] =
function(value, val)
if not val then Value.reset(value) else setter(value, val) end
end
end
end
-- Do not allow direct access to fields.
local value_field_gtype = Value._field.g_type
Value._field = nil
-- 'type' property controls gtype of the property.
Value._attribute = { gtype = {} }
function Value._attribute.gtype.get(value)
return core.record.field(value, value_field_gtype)
end
function Value._attribute.gtype.set(value, newtype)
local gtype = core.record.field(value, value_field_gtype)
if gtype then
if newtype then
-- Try converting old value to new one.
local dest = core.record.new(value_info)
Value.init(dest, newtype)
if not Value.transform(value, dest) then
error(("GObject.Value: cannot convert `%s' to `%s'"):format(
gtype, core.record.field(dest, value_field_gtype)))
end
Value.unset(value)
Value.init(value, newtype)
Value.copy(dest, value)
else
Value.unset(value)
end
elseif newtype then
-- No value was set and some is requested, so set it.
Value.init(value, newtype)
end
end
local value_marshallers = {}
for name, gtype in pairs(Type) do
local get = Value._method['get_' .. name:lower()]
local set = Value._method['set_' .. name:lower()]
if get and set then
value_marshallers[gtype] =
function(value, params, ...)
return (select('#', ...) > 0 and set or get)(value, ...)
end
end
end
-- Interface marshaller is the same as object marshallers.
value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT]
-- Override 'boxed' marshaller, default one marshalls to gpointer
-- instead of target boxed type.
value_marshallers[Type.BOXED] =
function(value, params, ...)
local gtype = core.record.field(value, value_field_gtype)
if select('#', ...) > 0 then
Value.set_boxed(value, core.record.query((...), 'addr', gtype))
else
return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value))
end
end
-- Create GStrv marshaller, implement it using typeinfo marshaller
-- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from
-- g_shell_parse_argv().
value_marshallers[Type.STRV] = core.marshal.container(
gi.GLib.shell_parse_argv.args[3].typeinfo)
-- Finds marshaller closure which can marshal type described either by
-- gtype or typeinfo/transfer combo.
function Value._method.find_marshaller(gtype, typeinfo, transfer)
-- Check whether we can have marshaller for typeinfo.
local marshaller
if typeinfo then
marshaller = core.marshal.container(typeinfo, transfer)
if marshaller then return marshaller end
end
local gt = gtype
if type(gt) == 'number' then gt = Type.name(gt) end
-- Special marshaller, allowing only 'nil'.
if not gt then return function() end end
-- Find marshaller according to gtype of the value.
while gt do
-- Check simple and/or fundamental marshallers.
marshaller = value_marshallers[gt] or core.marshal.fundamental(gt)
if marshaller then return marshaller end
gt = Type.parent(gt)
end
error(("GValue marshaller for `%s' not found"):format(tostring(gtype)))
end
-- Value 'value' property provides access to GValue's embedded data.
function Value._attribute:value(...)
local marshaller = Value._method.find_marshaller(
core.record.field(self, value_field_gtype))
return marshaller(self, nil, ...)
end
-- Implement custom 'constructor', taking optionally two values (type
-- and value). The reason why it is overriden is that the order of
-- initialization is important, and standard record intializer cannot
-- enforce the order.
function Value:_new(gtype, value)
local v = core.record.new(value_info)
if gtype then v.gtype = gtype end
if value then v.value = value end
return v
end
|
Fix Value marshalling even for numeric gtypes
|
Fix Value marshalling even for numeric gtypes
|
Lua
|
mit
|
pavouk/lgi,psychon/lgi,zevv/lgi
|
518bef7c326d890dbcd5666c17d65f5c0f88de99
|
plugins/welcome.lua
|
plugins/welcome.lua
|
local function set_welcome(msg, welcome)
local data = load_data(_config.moderation.data)
local data_cat = 'welcome'
data[tostring(msg.to.id)][data_cat] = welcome
save_data(_config.moderation.data, data)
return lang_text('newWelcome') .. welcome
end
local function get_welcome(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'welcome'
if not data[tostring(msg.to.id)][data_cat] then
return ''
end
local welcome = data[tostring(msg.to.id)][data_cat]
return welcome
end
local function set_memberswelcome(msg, value)
local data = load_data(_config.moderation.data)
local data_cat = 'welcomemembers'
data[tostring(msg.to.id)][data_cat] = value
save_data(_config.moderation.data, data)
return string.gsub(lang_text('newWelcomeNumber'), 'X', tostring(value))
end
local function get_memberswelcome(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'welcomemembers'
if not data[tostring(msg.to.id)][data_cat] then
return lang_text('noSetValue')
end
local value = data[tostring(msg.to.id)][data_cat]
return value
end
local function get_rules(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return lang_text('noRules')
end
local rules = data[tostring(msg.to.id)][data_cat]
return rules
end
local function run(msg, matches)
if matches[1]:lower() == 'getwelcome' then
if tonumber(msg.to.id) == 1026492373 then
if is_momod(msg) then
-- moderatore del canile abusivo usa getwelcome allora ok altrimenti return
return get_welcome(msg)
else
return
end
else
return get_welcome(msg)
end
end
if matches[1]:lower() == 'setwelcome' and is_owner(msg) then
return set_welcome(msg, matches[2])
end
if matches[1]:lower() == 'setmemberswelcome' and is_owner(msg) then
return set_memberswelcome(msg, matches[2])
end
if matches[1]:lower() == 'getmemberswelcome' and is_owner(msg) then
return get_memberswelcome(msg)
end
if msg.action.type == "chat_add_user" or msg.action.type == "chat_add_user_link" then
local hash
if msg.to.type == 'channel' then
hash = 'channel:welcome' .. msg.to.id
end
if msg.to.type == 'chat' then
hash = 'chat:welcome' .. msg.to.id
end
redis:incr(hash)
local hashonredis = redis:get(hash)
if hashonredis then
if tonumber(hashonredis) >= tonumber(get_memberswelcome(msg)) then
send_large_msg(get_receiver(msg), get_welcome(msg) .. '\n' .. get_rules(msg), ok_cb, false)
redis:getset(hash, 0)
end
else
redis:set(hash, 0)
end
end
end
return {
description = "WELCOME",
usage =
{
"#setwelcome <text>: Sasha imposta <text> come benvenuto.",
"#getwelcome: Sasha manda il benvenuto.",
"#setmemberswelcome <value>: Sasha dopo <value> membri manderà il benvenuto con le regole.",
"#getmemberswelcome: Sasha manda il numero di membri entrati dopo i quali invia il benvenuto.",
},
patterns =
{
"^[#!/]([Ss][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee])$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Mm][Bb][Ee][Rr][Ss][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Mm][Ee][Mm][Bb][Ee][Rr][Ss][Ww][Ee][Ll][Cc][Oo][Mm][Ee])$",
"^!!tgservice (.+)$",
},
run = run,
min_rank = 0
}
|
local function set_welcome(msg, welcome)
local data = load_data(_config.moderation.data)
local data_cat = 'welcome'
data[tostring(msg.to.id)][data_cat] = welcome
save_data(_config.moderation.data, data)
return lang_text('newWelcome') .. welcome
end
local function get_welcome(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'welcome'
if not data[tostring(msg.to.id)][data_cat] then
return ''
end
local welcome = data[tostring(msg.to.id)][data_cat]
return welcome
end
local function set_memberswelcome(msg, value)
local data = load_data(_config.moderation.data)
local data_cat = 'welcomemembers'
data[tostring(msg.to.id)][data_cat] = value
save_data(_config.moderation.data, data)
return string.gsub(lang_text('newWelcomeNumber'), 'X', tostring(value))
end
local function get_memberswelcome(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'welcomemembers'
if not data[tostring(msg.to.id)][data_cat] then
return lang_text('noSetValue')
end
local value = data[tostring(msg.to.id)][data_cat]
return value
end
local function get_rules(msg)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return lang_text('noRules')
end
local rules = data[tostring(msg.to.id)][data_cat]
return rules
end
local function run(msg, matches)
if matches[1]:lower() == 'getwelcome' then
if tonumber(msg.to.id) == 1026492373 then
if is_momod(msg) then
-- moderatore del canile abusivo usa getwelcome allora ok altrimenti return
return get_welcome(msg)
else
return
end
else
return get_welcome(msg)
end
end
if matches[1]:lower() == 'setwelcome' and is_owner(msg) then
return set_welcome(msg, matches[2])
end
if matches[1]:lower() == 'setmemberswelcome' and is_owner(msg) then
return set_memberswelcome(msg, matches[2])
end
if matches[1]:lower() == 'getmemberswelcome' and is_owner(msg) then
return get_memberswelcome(msg)
end
if msg.action.type == "chat_add_user" or msg.action.type == "chat_add_user_link" and get_mamberswelcome(msg) ~= lang_text('noSetValue') then
local hash
if msg.to.type == 'channel' then
hash = 'channel:welcome' .. msg.to.id
end
if msg.to.type == 'chat' then
hash = 'chat:welcome' .. msg.to.id
end
redis:incr(hash)
local hashonredis = redis:get(hash)
if hashonredis then
if tonumber(hashonredis) >= tonumber(get_memberswelcome(msg)) then
send_large_msg(get_receiver(msg), get_welcome(msg) .. '\n' .. get_rules(msg), ok_cb, false)
redis:getset(hash, 0)
end
else
redis:set(hash, 0)
end
end
end
return {
description = "WELCOME",
usage =
{
"#setwelcome <text>: Sasha imposta <text> come benvenuto.",
"#getwelcome: Sasha manda il benvenuto.",
"#setmemberswelcome <value>: Sasha dopo <value> membri manderà il benvenuto con le regole.",
"#getmemberswelcome: Sasha manda il numero di membri entrati dopo i quali invia il benvenuto.",
},
patterns =
{
"^[#!/]([Ss][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee])$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Mm][Bb][Ee][Rr][Ss][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Mm][Ee][Mm][Bb][Ee][Rr][Ss][Ww][Ee][Ll][Cc][Oo][Mm][Ee])$",
"^!!tgservice (.+)$",
},
run = run,
min_rank = 0
}
|
fix nil values
|
fix nil values
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
a8c8a632262a7464b6e7b3a196e204c97125797b
|
tests/test-json.lua
|
tests/test-json.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 JSON = require('json')
local deepEqual = require('deep-equal')
require('tap')(function(test)
test('smoke', function()
assert(JSON.stringify({a = 'a'}) == '{"a":"a"}')
assert(deepEqual({a = 'a'}, JSON.parse('{"a":"a"}')))
end)
test('parse invalid json', function()
for _, x in ipairs({ '', ' ', '{', '[', '{"f":', '{"f":1', '{"f":1', }) do
local status, pos, result = pcall(JSON.parse, x)
assert(status)
assert(result)
end
for _, x in ipairs({ '{]', '[}', }) do
local status, pos, result = pcall(JSON.parse, x)
assert(status)
assert(result)
end
end)
test('parse valid json', function()
for _, x in ipairs({ '[]', '{}', }) do
local status, result = pcall(JSON.parse, x)
assert(type(result) == 'table')
end
end)
test('stringify', function()
assert(JSON.stringify() == 'null')
for _, x in ipairs({ {}, {1, 2, 3}, {a = 'a'}, 'string', 0, 0.1, 3.1415926, true, false, }) do
local status, result = pcall(JSON.stringify, x)
assert(status)
assert(type(result) == 'string')
end
end)
test('edge cases', function()
assert(JSON.stringify({}) == '[]')
-- escaped strings
assert(JSON.stringify('a"b\tc\nd') == '"a\\"b\\tc\\nd"')
assert(JSON.parse('"a\\"b\\tc\\nd"') == 'a"b\tc\nd')
-- booleans
assert(JSON.stringify(true) == 'true')
assert(JSON.stringify(false) == 'false')
assert(JSON.parse('true') == true)
assert(JSON.parse('false') == false)
end)
test('strict', function()
for _, x in ipairs({ '{f:1}', "{'f':1}", }) do
local status, _, msg = pcall(JSON.parse, x)
assert(status)
end
end)
end)
|
--[[
Copyright 2015 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 JSON = require('json')
local deepEqual = require('deep-equal')
require('tap')(function(test)
test('smoke', function()
assert(JSON.stringify({a = 'a'}) == '{"a":"a"}')
assert(deepEqual({a = 'a'}, JSON.parse('{"a":"a"}')))
end)
test('parse invalid json', function()
for _, x in ipairs({ '', ' ', '{', '[', '{"f":', '{"f":1', '{"f":1', }) do
local status, _, result = pcall(JSON.parse, x)
assert(status)
assert(result)
end
for _, x in ipairs({ '{]', '[}', }) do
local status, _, result = pcall(JSON.parse, x)
assert(status)
assert(result)
end
end)
test('parse valid json', function()
for _, x in ipairs({ '[]', '{}', }) do
local _, result = pcall(JSON.parse, x)
assert(type(result) == 'table')
end
end)
test('stringify', function()
assert(JSON.stringify() == 'null')
for _, x in ipairs({ {}, {1, 2, 3}, {a = 'a'}, 'string', 0, 0.1, 3.1415926, true, false, }) do
local status, result = pcall(JSON.stringify, x)
assert(status)
assert(type(result) == 'string')
end
end)
test('edge cases', function()
assert(JSON.stringify({}) == '[]')
-- escaped strings
assert(JSON.stringify('a"b\tc\nd') == '"a\\"b\\tc\\nd"')
assert(JSON.parse('"a\\"b\\tc\\nd"') == 'a"b\tc\nd')
-- booleans
assert(JSON.stringify(true) == 'true')
assert(JSON.stringify(false) == 'false')
assert(JSON.parse('true') == true)
assert(JSON.parse('false') == false)
end)
test('strict', function()
for _, x in ipairs({ '{f:1}', "{'f':1}", }) do
local status, _, _ = pcall(JSON.parse, x)
assert(status)
end
end)
test('unicode', function()
local s = "{\"f\":\"こんにちは 世界\"}"
local obj = JSON.parse(s)
assert(obj.f)
end)
end)
|
lint + add unicode json test
|
lint + add unicode json test
fixes #506
|
Lua
|
apache-2.0
|
kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,bsn069/luvit,rjeli/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,rjeli/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,kaustavha/luvit,rjeli/luvit,zhaozg/luvit
|
1cf4504109a4f36b939a6e659b5c59a63660efab
|
src_trunk/resources/tow-system/s_backup.lua
|
src_trunk/resources/tow-system/s_backup.lua
|
backupBlip = nil
backupPlayer = nil
function removeBackup(thePlayer, commandName)
if (exports.global:isPlayerAdmin(thePlayer)) then
if (backupPlayer~=nil) then
destroyElement(backupBlip)
removeEventHandler("onPlayerQuit", backupPlayer, destroyBlip)
removeEventHandler("savePlayer", backupPlayer, destroyBlip)
backupPlayer = nil
backupBlip = nil
outputChatBox("Backup system reset!", thePlayer, 255, 194, 14)
else
outputChatBox("Backup system did not need reset.", thePlayer, 255, 194, 14)
end
end
end
--addCommandHandler("resettowbackup", removeBackup, false, false)
function towtruck(thePlayer, commandName)
local theTeam = getTeamFromName("McJones Towing")
local thePlayerTeam = getPlayerTeam(thePlayer)
local factionType = getElementData(thePlayerTeam, "type")
--if (factionType==3 or getTeamName(thePlayerTeam) == "McJones Towing") then--Leaving this in in case of abuse.
if (backupBlip) and (backupPlayer~=thePlayer) then -- in use
outputChatBox("There is already a TowTruck request beacon in use.", thePlayer, 255, 194, 14)
elseif not (backupBlip) then -- make backup blip
backupPlayer = thePlayer
local x, y, z = getElementPosition(thePlayer)
backupBlip = createBlip(x, y, z, 0, 3, 255, 0, 0, 255, 255, 32767)
exports.pool:allocateElement(backupBlip)
attachElements(backupBlip, thePlayer)
addEventHandler("onPlayerQuit", thePlayer, destroyBlip)
addEventHandler("savePlayer", thePlayer, destroyBlip)
setElementVisibleTo(backupBlip, getRootElement(), false)
for key, value in ipairs(getPlayersInTeam(theTeam)) do
outputChatBox("A player requires a Tow Truck. Please respond ASAP!", value, 255, 194, 14)
setElementVisibleTo(backupBlip, value, true)
end
for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do
if (getPlayerTeam(value)~=theTeam) then
setElementVisibleTo(backupBlip, value, false)
end
end
elseif (backupBlip) and (backupPlayer==thePlayer) then -- in use by this player
for key, value in ipairs(getPlayersInTeam(theTeam)) do
outputChatBox("The player no longer requires a Tow Truck. Resume normal patrol", value, 255, 194, 14)
end
destroyElement(backupBlip)
removeEventHandler("onPlayerQuit", thePlayer, destroyBlip)
removeEventHandler("savePlayer", thePlayer, destroyBlip)
backupPlayer = nil
backupBlip = nil
end
--end
end
--addCommandHandler("towtruck", towtruck, false, false)
function destroyBlip()
local theTeam = getPlayerTeam(source)
for key, value in ipairs(getPlayersInTeam(theTeam)) do
outputChatBox("The Officer no longer requires a Tow Truck. Resume normal patrol", value, 255, 194, 14)
end
destroyElement(backupBlip)
removeEventHandler("onPlayerQuit", thePlayer, destroyBlip)
removeEventHandler("savePlayer", thePlayer, destroyBlip)
backupPlayer = nil
backupBlip = nil
end
|
backupBlip = false
backupPlayer = nil
function removeBackup(thePlayer, commandName)
if (exports.global:isPlayerAdmin(thePlayer)) then
if (backupPlayer~=nil) then
for k,v in ipairs(getPlayersInTeam ( getTeamFromName("McJones Towing") )) do
triggerClientEvent(v, "destroyBackupBlip", backupBlip)
end
removeEventHandler("onPlayerQuit", backupPlayer, destroyBlip)
removeEventHandler("savePlayer", backupPlayer, destroyBlip)
backupPlayer = nil
backupBlip = false
outputChatBox("Backup system reset!", thePlayer, 255, 194, 14)
else
outputChatBox("Backup system did not need reset.", thePlayer, 255, 194, 14)
end
end
end
addCommandHandler("resettowbackup", removeBackup, false, false)
function backup(thePlayer, commandName)
local duty = tonumber(getElementData(thePlayer, "duty"))
local theTeam = getPlayerTeam(thePlayer)
local factionType = getElementData(theTeam, "type")
--if (factionType==3 or getTeamName(thePlayerTeam) == "McJones Towing") then--Leaving this in in case of abuse.
if (backupBlip == true) and (backupPlayer~=thePlayer) then -- in use
outputChatBox("There is already a backup beacon in use.", thePlayer, 255, 194, 14)
elseif (backupBlip == false) then -- make backup blip
backupBlip = true
backupPlayer = thePlayer
for k,v in ipairs(getPlayersInTeam (theTeam)) do
triggerClientEvent(v, "createBackupBlip", thePlayer)
outputChatBox("A player requires a Tow Truck. Please respond ASAP!", v, 255, 194, 14)
end
addEventHandler("onPlayerQuit", thePlayer, destroyBlip)
addEventHandler("savePlayer", thePlayer, destroyBlip)
elseif (backupBlip == true) and (backupPlayer==thePlayer) then -- in use by this player
for key, v in ipairs(getPlayersInTeam(theTeam)) do
triggerClientEvent(v, "destroyBackupBlip", getRootElement())
outputChatBox("The player no longer requires a Tow Truck. Resume normal patrol", v, 255, 194, 14)
end
removeEventHandler("onPlayerQuit", thePlayer, destroyBlip)
removeEventHandler("savePlayer", thePlayer, destroyBlip)
backupPlayer = nil
backupBlip = false
end
--end
end
addCommandHandler("towtruck", backup, false, false)
function destroyBlip()
local theTeam = getPlayerTeam(source)
for key, value in ipairs(getPlayersInTeam(theTeam)) do
outputChatBox("The unit no longer requires assistance. Resume normal patrol", value, 255, 194, 14)
end
for k,v in ipairs(getPlayersInTeam ( getTeamFromName("McJones Towing") )) do
triggerClientEvent(v, "destroyBackupBlip", backupBlip)
end
removeEventHandler("onPlayerQuit", thePlayer, destroyBlip)
removeEventHandler("savePlayer", thePlayer, destroyBlip)
backupPlayer = nil
backupBlip = false
end
|
Fixed tow truck backup
|
Fixed tow truck backup
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1124 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
dd78a8eca99ee5408055ed8b3d293c6013f077c3
|
packages/verseindex.lua
|
packages/verseindex.lua
|
SILE.scratch.tableofverses = {}
local orig_href = SILE.Commands["href"]
local loadstring = loadstring or load
local writeTov = function (self)
local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses)
local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w")
if not tovfile then return SU.error(err) end
tovfile:write(contents)
end
local moveNodes = function (self)
local node = SILE.scratch.info.thispage.tov
if node then
for i = 1, #node do
node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio)
SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i]
end
end
end
local init = function (self)
self:loadPackage("infonode")
self:loadPackage("leaders")
local inpair = nil
local defaultparskip = SILE.settings.get("typesetter.parfillskip")
local continuepair = function (args)
if not args then return end
if inpair and (args.frame.id == "content") then
SILE.typesetter:pushState()
SILE.call("tableofverses:book", { }, { inpair })
SILE.typesetter:popState()
end
end
local pushBack = SILE.typesetter.pushBack
SILE.typesetter.pushBack = function(self)
continuepair(self)
pushBack(self)
end
local startpair = function (pair)
SILE.call("makecolumns", { gutter = "4%pw" })
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
inpair = pair
end
local endpair = function (seq)
inpair = nil
SILE.call("mergecolumns")
SILE.settings.set("typesetter.parfillskip", defaultparskip)
end
SILE.registerCommand("href", function (options, content)
SILE.call("markverse", options, content)
return orig_href(options, content)
end)
SILE.registerCommand("tableofverses:book", function (options, content)
SILE.call("requireSpace", { height = "4em" })
SILE.settings.set("typesetter.parfillskip", defaultparskip)
SILE.call("hbox")
SILE.call("skip", { height = "1ex" })
SILE.call("section", { numbering = false, skiptoc = true }, content)
SILE.call("breakframevertical")
startpair(content[1])
end)
SILE.registerCommand("tableofverses:reference", function (options, content)
if #options.pages < 1 then
SU.warn("Verse in index doesn't have page marker")
SU.debug("casile", content)
pages = { "0" }
end
SILE.process(content)
SILE.call("noindent")
SILE.call("font", { size = ".5em" }, function ()
SILE.call("dotfill")
end)
local first = true
for _, pageno in pairs(options.pages) do
if not first then
SILE.typesetter:typeset(", ")
end
SILE.typesetter:typeset(pageno)
first = false
end
SILE.call("par")
end)
SILE.registerCommand("markverse", function (options, content)
SILE.typesetter:typeset("") -- Protect hbox location from getting discarded
SILE.call("info", {
category = "tov",
value = {
label = options.title and { options.title } or content
}
})
end)
SILE.registerCommand("tableofverses", function (options, content)
SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" })
SILE.call("cabook:seriffont", { size = "0.95em" })
local origmethod = SILE.settings.get("linespacing.method")
local origleader = SILE.settings.get("linespacing.fixed.baselinedistance")
local origparskip = SILE.settings.get("document.parskip")
SILE.settings.set("linespacing.method", "fixed")
SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length.parse("1.1em"))
SILE.settings.set("document.parskip", SILE.nodefactory.newVglue({}))
local refshash = {}
local lastbook = nil
local seq = 1
for i, ref in pairs(CASILE.verses) do
if not refshash[ref.osis] then
refshash[ref.osis] = true
if not(lastbook == ref.b) then
if inpair then endpair(seq) end
SILE.call("tableofverses:book", { }, { ref.b })
seq = 1
lastbook = inpair
end
local label = ref.reformat:match(".* (.*)")
local pages = {}
local pageshash = {}
local bk = ref.b == "Mezmurlar" and "Mezmur" or ref.b
for _, link in pairs(SILE.scratch.tableofverses) do
if link.label[1]:match(bk .. "[ ]" .. label) then
local pageno = link.pageno
if not pageshash[pageno] then
pages[#pages+1] = pageno
pageshash[pageno] = true
end
end
end
SILE.call("tableofverses:reference", { pages = pages }, { label })
seq = seq + 1
end
end
if inpair then endpair(seq) end
inpair = nil
SILE.settings.set("linespacing.fixed.baselinedistance", origleader)
SILE.settings.set("linespacing.method", origmethod)
SILE.settings.set("document.parskip", origparskip)
end)
end
return {
exports = {
writeTov = writeTov,
moveTovNodes = moveNodes
},
init = init
}
|
SILE.scratch.tableofverses = {}
local orig_href = SILE.Commands["href"]
local loadstring = loadstring or load
local writeTov = function (self)
local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses)
local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w")
if not tovfile then return SU.error(err) end
tovfile:write(contents)
end
local moveNodes = function (self)
local node = SILE.scratch.info.thispage.tov
if node then
for i = 1, #node do
node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio)
SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i]
end
end
end
local init = function (self)
self:loadPackage("infonode")
self:loadPackage("leaders")
local inpair = nil
local repairbreak = function () end
local defaultparskip = SILE.settings.get("typesetter.parfillskip")
local continuepair = function (args)
if not args then return end
if inpair and (args.frame.id == "content") then
repairbreak = function () SILE.call("break"); repairbreak = function() end end
SILE.typesetter:pushState()
SILE.call("tableofverses:book", { }, { inpair })
SILE.typesetter:popState()
end
end
local pushBack = SILE.typesetter.pushBack
SILE.typesetter.pushBack = function(self)
continuepair(self)
pushBack(self)
repairbreak()
end
local startpair = function (pair)
SILE.call("makecolumns", { gutter = "4%pw" })
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
inpair = pair
end
local endpair = function (seq)
inpair = nil
SILE.call("mergecolumns")
SILE.settings.set("typesetter.parfillskip", defaultparskip)
end
SILE.registerCommand("href", function (options, content)
SILE.call("markverse", options, content)
return orig_href(options, content)
end)
SILE.registerCommand("tableofverses:book", function (options, content)
SILE.call("requireSpace", { height = "4em" })
SILE.settings.set("typesetter.parfillskip", defaultparskip)
SILE.call("hbox")
SILE.call("skip", { height = "1ex" })
SILE.call("section", { numbering = false, skiptoc = true }, content)
SILE.call("breakframevertical")
startpair(content[1])
end)
SILE.registerCommand("tableofverses:reference", function (options, content)
if #options.pages < 1 then
SU.warn("Verse in index doesn't have page marker")
SU.debug("casile", content)
pages = { "0" }
end
SILE.process(content)
SILE.call("noindent")
SILE.call("font", { size = ".5em" }, function ()
SILE.call("dotfill")
end)
local first = true
for _, pageno in pairs(options.pages) do
if not first then
SILE.typesetter:typeset(", ")
end
SILE.typesetter:typeset(pageno)
first = false
end
SILE.call("par")
end)
SILE.registerCommand("markverse", function (options, content)
SILE.typesetter:typeset("") -- Protect hbox location from getting discarded
SILE.call("info", {
category = "tov",
value = {
label = options.title and { options.title } or content
}
})
end)
SILE.registerCommand("tableofverses", function (options, content)
SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" })
SILE.call("cabook:seriffont", { size = "0.95em" })
local origmethod = SILE.settings.get("linespacing.method")
local origleader = SILE.settings.get("linespacing.fixed.baselinedistance")
local origparskip = SILE.settings.get("document.parskip")
SILE.settings.set("linespacing.method", "fixed")
SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length.parse("1.1em"))
SILE.settings.set("document.parskip", SILE.nodefactory.newVglue({}))
local refshash = {}
local lastbook = nil
local seq = 1
for i, ref in pairs(CASILE.verses) do
if not refshash[ref.osis] then
refshash[ref.osis] = true
if not(lastbook == ref.b) then
if inpair then endpair(seq) end
SILE.call("tableofverses:book", { }, { ref.b })
seq = 1
lastbook = inpair
end
local label = ref.reformat:match(".* (.*)")
local pages = {}
local pageshash = {}
local bk = ref.b == "Mezmurlar" and "Mezmur" or ref.b
for _, link in pairs(SILE.scratch.tableofverses) do
if link.label[1]:match(bk .. "[ ]" .. label) then
local pageno = link.pageno
if not pageshash[pageno] then
pages[#pages+1] = pageno
pageshash[pageno] = true
end
end
end
SILE.call("tableofverses:reference", { pages = pages }, { label })
seq = seq + 1
end
end
if inpair then endpair(seq) end
inpair = nil
SILE.settings.set("linespacing.fixed.baselinedistance", origleader)
SILE.settings.set("linespacing.method", origmethod)
SILE.settings.set("document.parskip", origparskip)
end)
end
return {
exports = {
writeTov = writeTov,
moveTovNodes = moveNodes
},
init = init
}
|
Hack in breaks after section splits, fixes viachristus/kurtarici_kitaplar#51
|
Hack in breaks after section splits, fixes viachristus/kurtarici_kitaplar#51
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
29f210ac0033b72e5d82ee0bc0dd295d52ad6bad
|
lib/resty/chash/server.lua
|
lib/resty/chash/server.lua
|
local jchash = require "resty.chash.jchash"
local ok, new_table = pcall(require, "table.new")
if not ok then
new_table = function (narr, nrec) return {} end
end
local function svname(server)
-- @server: {addr, port, id}
-- @return: concat the addr and port with ":" as seperator
return string.format("%s:%s#%s", tostring(server[1]), tostring(server[2]), tostring(server[3]))
end
local function init_name2index(servers)
-- map server name to index
local map = {}
for index, s in ipairs(servers) do
-- name is just the concat of addr , port and inner id
map[ svname(s) ] = index
end
return map
end
local function expand_servers(servers)
-- expand servers list of {addr, port, weight} into a list of {addr, port, id}
local total_weight = 0
for _, s in ipairs(servers) do
total_weight = total_weight + (s[3] or 1)
end
local expanded_servers = new_table(total_weight, 0)
local weight
for _, s in ipairs(servers) do
weight = s[3] or 1
for id = 1, weight do
expanded_servers[#expanded_servers + 1] = {s[1], s[2], id}
end
end
assert(#expanded_servers == total_weight, "expand_servers size not match")
return expanded_servers
end
local function update_name2index(old_servers, new_servers)
-- new servers may have some servers of the same name in the old ones.
-- we could assign the same index(if in range) to the server of same name,
-- and as to new servers whose name are new will be assigned to indexs that're
-- not occupied
local old_name2index = init_name2index(old_servers)
local new_name2index = init_name2index(new_servers)
local new_size = #new_servers -- new_size is also the maxmuim index
local old_size = #old_servers
local unused_indexs = {}
for old_index, old_sv in ipairs(old_servers) do
if old_index <= new_size then
local old_sv_name = svname(old_sv)
if new_name2index[ old_sv_name ] then
-- restore the old_index
new_name2index[ old_sv_name ] = old_index
else
-- old_index can be recycled
unused_indexs[#unused_indexs + 1] = old_index
end
else
-- index that exceed maxmium index is of no use, we should mark it nil.
-- the next next loop (assigning unused_indexs) will make use of this mark
old_name2index[ svname(old_sv) ] = nil
end
end
for i = old_size + 1, new_size do -- only loop when old_size < new_size
unused_indexs[#unused_indexs + 1] = i
end
-- assign the unused_indexs to the real new servers
local index = 1
for _, new_sv in ipairs(new_servers) do
local new_sv_name = svname(new_sv)
if not old_name2index[ new_sv_name ] then
-- it's a new server, or an old server whose old index is too big
assert(index <= #unused_indexs, "no enough indexs for new server")
new_name2index[ new_sv_name ] = unused_indexs[index]
index = index + 1
end
end
assert(index == #unused_indexs + 1, "recycled indexs are not exhausted")
return new_name2index
end
local _M = {}
local mt = { __index = _M }
function _M.new(servers)
assert(servers, "nil servers")
return setmetatable({servers = expand_servers(servers)}, mt)
end
-- instance methods
function _M.lookup(self, key)
-- @key: user defined string, eg. uri
-- @return: {addr, port, id}
-- the `id` is a number in [1, weight], to identify server of same addr and port,
if #self.servers == 0 then
return nil
end
local index = jchash.hash_short_str(key, #self.servers)
return self.servers[index]
end
function _M.update_servers(self, new_servers)
-- @new_servers: remove all old servers, and use the new servers
-- but we would keep the server whose name is not changed
-- in the same `id` slot, so consistence is maintained.
assert(new_servers, "nil new_servers")
local old_servers = self.servers
local new_servers = expand_servers(new_servers)
local name2index = update_name2index(old_servers, new_servers)
self.servers = new_table(#new_servers, 0)
for _, s in ipairs(new_servers) do
self.servers[name2index[ svname(s) ]] = s
end
end
function _M.debug(self)
print("* Instance Info *")
print("* size: " .. tostring(#self.servers))
print("* servers -> id ")
for id, s in ipairs(self.servers) do
print(svname(s) .. " -> " .. tostring(id))
end
print("\n")
end
function _M.dump(self)
-- @return: deepcopy a self.servers
-- this can be use to save the server list to a file or something
-- and restore it back some time later. eg. nginx restart/reload
--
-- please NOTE: the data being dumped is not the same as the data we
-- use to do _M.new or _M.update_servers, though it looks the same, the third
-- field in the {addr, port, id} is an `id`, NOT a `weight`
local servers = {}
for index, sv in ipairs(self.servers) do
servers[index] = {sv[1], sv[2], sv[3]} -- {addr, port, id}
end
return servers
end
function _M.restore(self, servers)
assert(servers, "nil servers")
-- restore servers from dump (deepcopy the servers)
self.servers = {}
for index, sv in ipairs(servers) do
self.servers[index] = {sv[1], sv[2], sv[3]}
end
end
_M._VERSION = "0.1.1"
return _M
|
local jchash = require "resty.chash.jchash"
local ok, new_table = pcall(require, "table.new")
if not ok then
new_table = function (narr, nrec) return {} end
end
local function svname(server)
-- @server: {addr, port, id}
-- @return: concat the addr and port with ":" as seperator
return string.format("%s:%s#%s", tostring(server[1]), tostring(server[2]), tostring(server[3]))
end
local function init_name2index(servers)
-- map server name to index
local map = {}
for index, s in ipairs(servers) do
-- name is just the concat of addr , port and inner id
map[ svname(s) ] = index
end
return map
end
local function expand_servers(servers)
-- expand servers list of {addr, port, weight} into a list of {addr, port, id}
local total_weight = 0
for _, s in ipairs(servers) do
total_weight = total_weight + (s[3] or 1)
end
local expanded_servers = new_table(total_weight, 0)
local weight
for _, s in ipairs(servers) do
weight = s[3] or 1
for id = 1, weight do
expanded_servers[#expanded_servers + 1] = {s[1], s[2], id}
end
end
assert(#expanded_servers == total_weight, "expand_servers size not match")
return expanded_servers
end
local function update_name2index(old_servers, new_servers)
-- new servers may have some servers of the same name in the old ones.
-- we could assign the same index(if in range) to the server of same name,
-- and as to new servers whose name are new will be assigned to indexs that're
-- not occupied
local old_name2index = init_name2index(old_servers)
local new_name2index = init_name2index(new_servers)
local new_size = #new_servers -- new_size is also the maxmuim index
local old_size = #old_servers
local unused_indexs = {}
for old_index, old_sv in ipairs(old_servers) do
if old_index <= new_size then
local old_sv_name = svname(old_sv)
if new_name2index[ old_sv_name ] then
-- restore the old_index
new_name2index[ old_sv_name ] = old_index
else
-- old_index can be recycled
unused_indexs[#unused_indexs + 1] = old_index
end
else
-- index that exceed maxmium index is of no use, we should mark it nil.
-- the next next loop (assigning unused_indexs) will make use of this mark
old_name2index[ svname(old_sv) ] = nil
end
end
for i = old_size + 1, new_size do -- only loop when old_size < new_size
unused_indexs[#unused_indexs + 1] = i
end
-- assign the unused_indexs to the real new servers
local index = 1
for _, new_sv in ipairs(new_servers) do
local new_sv_name = svname(new_sv)
if not old_name2index[ new_sv_name ] then
-- it's a new server, or an old server whose old index is too big
assert(index <= #unused_indexs, "no enough indexs for new server")
new_name2index[ new_sv_name ] = unused_indexs[index]
index = index + 1
end
end
return new_name2index
end
local _M = {}
local mt = { __index = _M }
function _M.new(servers)
assert(servers, "nil servers")
return setmetatable({servers = expand_servers(servers)}, mt)
end
-- instance methods
function _M.lookup(self, key)
-- @key: user defined string, eg. uri
-- @return: {addr, port, id}
-- the `id` is a number in [1, weight], to identify server of same addr and port,
if #self.servers == 0 then
return nil
end
local index = jchash.hash_short_str(key, #self.servers)
return self.servers[index]
end
function _M.update_servers(self, new_servers)
-- @new_servers: remove all old servers, and use the new servers
-- but we would keep the server whose name is not changed
-- in the same `id` slot, so consistence is maintained.
assert(new_servers, "nil new_servers")
local old_servers = self.servers
local new_servers = expand_servers(new_servers)
local name2index = update_name2index(old_servers, new_servers)
self.servers = new_table(#new_servers, 0)
for _, s in ipairs(new_servers) do
self.servers[name2index[ svname(s) ]] = s
end
end
function _M.debug(self)
print("* Instance Info *")
print("* size: " .. tostring(#self.servers))
print("* servers -> id ")
for id, s in ipairs(self.servers) do
print(svname(s) .. " -> " .. tostring(id))
end
print("\n")
end
function _M.dump(self)
-- @return: deepcopy a self.servers
-- this can be use to save the server list to a file or something
-- and restore it back some time later. eg. nginx restart/reload
--
-- please NOTE: the data being dumped is not the same as the data we
-- use to do _M.new or _M.update_servers, though it looks the same, the third
-- field in the {addr, port, id} is an `id`, NOT a `weight`
local servers = {}
for index, sv in ipairs(self.servers) do
servers[index] = {sv[1], sv[2], sv[3]} -- {addr, port, id}
end
return servers
end
function _M.restore(self, servers)
assert(servers, "nil servers")
-- restore servers from dump (deepcopy the servers)
self.servers = {}
for index, sv in ipairs(servers) do
self.servers[index] = {sv[1], sv[2], sv[3]}
end
end
_M._VERSION = "0.1.1"
return _M
|
fix: assertion would fail if servers privided have duplicated items
|
fix: assertion would fail if servers privided have duplicated items
|
Lua
|
mit
|
ruoshan/lua-resty-jump-consistent-hash,ruoshan/lua-resty-jump-consistent-hash
|
ab4341e18c607a6250a4fb33b7991148e6e06616
|
premake4.lua
|
premake4.lua
|
--[[
DAGON
An Adventure Game Engine
This is a fairly basic Premake configuration that generates project files for
your preferred build system. Premake may be downloaded from the following
site:
http://industriousone.com/premake
Usage is as simple as typing 'premake4 [action]'. Please, do note that this
configuration targets the native architecture of the host computer and will
attempt to link dynamically. Also, the Windows configuration only builds as
a console.
Because this Premake file is primarily intended for building from source and
contributing to Dagon, we strongly suggest that you download the official binary
releases for deploying your games:
https://github.com/Senscape/Dagon/releases
Copyright (c) 2011-2013 Senscape s.r.l. All rights reserved.
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/.
--]]
--[[
BUILD INSTRUCTIONS
Dagon requires the following dependencies: FreeType, GLEW, Lua 5.1, Ogg, OpenAL,
Theora, Vorbis, SDL2.
Linux:
We suggest installing the following packages via apt-get: libfreetype6-dev,
libglew-dev, liblua5.1-0-dev, libogg-dev, libopenal-dev, libvorbis-dev,
libtheora-dev.
SDL2 was not available in default repos as of this writing and had to be built
from scratch.
Mac OS X:
We strongly encourage using Homebrew to install packages: http://brew.sh
Suggested Homebrew formulas are: freetype, glew, lua, libogg, libvorbis,
theora, sdl2.
Windows:
We provide the following binaries packages for your convenience:
http://www.senscape.net/files/dagon-0.6.0-libs-win-x86.zip
http://www.senscape.net/files/dagon-0.6.0-libs-win-x64.zip
]]--
-- Base solution
solution "Dagon"
configurations { "Release", "Debug" }
platforms { "native" } -- Default to native architecture
location "Build"
configuration { "Release" }
defines { "NDEBUG" }
flags { "Optimize" }
targetdir "Build/Release"
configuration { "Debug" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
targetdir "Build/Debug"
-- Clean up if required and exit
if _ACTION == "clean" then
os.rmdir("Build")
os.exit()
end
-- The main Dagon project
project "Dagon"
targetname "dagon"
-- GLEW_STATIC only applies to Windows, but there's no harm done if defined
-- on other systems.
defines { "GLEW_STATIC", "OV_EXCLUDE_STATIC_CALLBACKS" }
location "Build"
objdir "Build/Objects"
-- Note that we always build as a console app, even on Windows.
kind "ConsoleApp"
language "C++"
files { "Source/**.h", "Source/**.c", "Source/**.cpp" }
libraries = {}
-- Libraries required for Unix-based systems
libs_unix = { "freetype", "GLEW", "ogg", "SDL2",
"vorbis", "vorbisfile", "theoradec" }
-- Libraries required for Windows, preferring static binaries
libs_win = { "freetype", "glew32s", "libogg_static",
"libtheora_static", "libvorbis_static",
"libvorbisfile_static", "lua", "OpenAL32",
"SDL2", "SDL2main", "opengl32", "glu32" }
-- Attempt to look for Lua library with most commonly used names
local lua_lib_names = { "lua-5.1", "lua5.1", "lua" }
local lua_lib = { name = nil, dir = nil }
for i = 1, #lua_lib_names do
lua_lib.name = lua_lib_names[i]
lua_lib.dir = os.findlib(lua_lib.name)
if(lua_lib.dir ~= nil) then
break
end
end
-- Build the libraries table according to the host system
if os.is("linux") then
libraries = libs_unix
table.insert(libraries, "GL")
table.insert(libraries, "GLU")
table.insert(libraries, "openal")
table.insert(libraries, lua_lib.name)
elseif os.is("macosx") then
libraries = libs_unix
table.insert(libraries, lua_lib.name)
elseif os.is("windows") then
libraries = libs_win
table.insert(libraries, lua_lib.name)
else
print "Attempting to build on unsupported system."
print "Aborting..."
os.exit()
end
-- Confirm that all the required libraries are present
for i = 1, #libraries do
local lib = libraries[i]
if os.findlib(lib) == nil then
print ("Library not found:", lib)
print "Aborting..."
os.exit()
end
end
-- Final configuration, includes and links according to the host system
configuration "linux"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { libraries }
configuration "macosx"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { "OpenAL.framework", "OpenGL.framework" }
links { libraries }
configuration "windows"
links { libraries }
|
--[[
DAGON
An Adventure Game Engine
This is a fairly basic Premake configuration that generates project files for
your preferred build system. Premake may be downloaded from the following
site:
http://industriousone.com/premake
Usage is as simple as typing 'premake4 [action]'. Please, do note that this
configuration targets the native architecture of the host computer and will
attempt to link dynamically. Also, the Windows configuration only builds as
a console.
Because this Premake file is primarily intended for building from source and
contributing to Dagon, we strongly suggest that you download the official binary
releases for deploying your games:
https://github.com/Senscape/Dagon/releases
Copyright (c) 2011-2013 Senscape s.r.l. All rights reserved.
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/.
--]]
--[[
BUILD INSTRUCTIONS
Dagon requires the following dependencies: FreeType, GLEW, Lua 5.1, Ogg, OpenAL,
Theora, Vorbis, SDL2.
Linux:
We suggest installing the following packages via apt-get: libfreetype6-dev,
libglew-dev, liblua5.1-0-dev, libogg-dev, libopenal-dev, libvorbis-dev,
libtheora-dev.
SDL2 was not available in default repos as of this writing and had to be built
from scratch.
Mac OS X:
We strongly encourage using Homebrew to install packages: http://brew.sh
Suggested Homebrew formulas are: freetype, glew, lua, libogg, libvorbis,
theora, sdl2.
Windows:
We provide the following Visual Studio binaries for your convenience:
http://www.senscape.net/files/dagon-0.6.0-libs-win-x86.zip
http://www.senscape.net/files/dagon-0.6.0-libs-win-x64.zip
Please note that on Visual Studio you may need to specify the target platform
as well as includes and libraries folders.
]]--
-- Base solution
solution "Dagon"
configurations { "Release", "Debug" }
platforms { "native", "x32", "x64" }
location "Build"
configuration { "Release" }
defines { "NDEBUG" }
flags { "Optimize" }
targetdir "Build/Release"
configuration { "Debug" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
targetdir "Build/Debug"
-- Clean up if required and exit
if _ACTION == "clean" then
os.rmdir("Build")
os.exit()
end
-- The main Dagon project
project "Dagon"
targetname "dagon"
-- GLEW_STATIC only applies to Windows, but there's no harm done if defined
-- on other systems.
defines { "GLEW_STATIC", "OV_EXCLUDE_STATIC_CALLBACKS" }
location "Build"
objdir "Build/Objects"
-- Note that we always build as a console app, even on Windows.
kind "ConsoleApp"
language "C++"
files { "Source/**.h", "Source/**.c", "Source/**.cpp" }
libraries = {}
-- Libraries required for Unix-based systems
libs_unix = { "freetype", "GLEW", "ogg", "SDL2",
"vorbis", "vorbisfile", "theoradec" }
-- Libraries required for Windows, preferring static binaries
libs_win = { "freetype", "glew32s", "libogg_static",
"libtheora_static", "libvorbis_static",
"libvorbisfile_static", "lua", "OpenAL32",
"SDL2", "SDL2main", "opengl32", "glu32"
"Imm32", "version", "winmm" }
-- Attempt to look for Lua library with most commonly used names
local lua_lib_names = { "lua-5.1", "lua5.1", "lua" }
local lua_lib = { name = nil, dir = nil }
for i = 1, #lua_lib_names do
lua_lib.name = lua_lib_names[i]
lua_lib.dir = os.findlib(lua_lib.name)
if(lua_lib.dir ~= nil) then
break
end
end
-- Build the libraries table according to the host system
if os.is("linux") then
libraries = libs_unix
table.insert(libraries, "GL")
table.insert(libraries, "GLU")
table.insert(libraries, "openal")
table.insert(libraries, lua_lib.name)
elseif os.is("macosx") then
libraries = libs_unix
table.insert(libraries, lua_lib.name)
elseif os.is("windows") then
libraries = libs_win
table.insert(libraries, lua_lib.name)
else
print "Attempting to build on unsupported system."
print "Aborting..."
os.exit()
end
-- Confirm that all the required libraries are present
-- (not working well on Windows)
if os.is("linux") or os.is("macosx") then
for i = 1, #libraries do
local lib = libraries[i]
if os.findlib(lib) == nil then
print ("Library not found:", lib)
print "Aborting..."
os.exit()
end
end
end
-- Final configuration, includes and links according to the host system
configuration "linux"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { libraries }
configuration "macosx"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { "OpenAL.framework", "OpenGL.framework" }
links { libraries }
configuration "windows"
links { libraries }
|
Fixes for building on Windows.
|
Fixes for building on Windows.
|
Lua
|
mpl-2.0
|
Senscape/Dagon,Senscape/Dagon
|
0c7fe29215c9c32adfbef1d5c2ec93c9f660ced3
|
premake5.lua
|
premake5.lua
|
local build_dir = "build/" .. _ACTION
--------------------------------------------------------------------------------
solution "Format"
configurations { "release", "debug" }
architecture "x64"
location (build_dir)
objdir (build_dir .. "/obj")
warnings "Extra"
exceptionhandling "Off"
rtti "Off"
configuration { "debug" }
targetdir (build_dir .. "/bin/debug")
configuration { "release" }
targetdir (build_dir .. "/bin/release")
configuration { "debug" }
defines { "_DEBUG" }
symbols "On"
configuration { "release" }
defines { "NDEBUG" }
symbols "On"
optimize "Full"
-- On ==> -O2
-- Full ==> -O3
configuration { "gmake" }
buildoptions {
"-march=native",
"-std=c++11",
"-Wformat",
-- "-Wsign-compare",
-- "-Wsign-conversion",
-- "-pedantic",
-- "-fvisibility=hidden",
-- "-fno-omit-frame-pointer",
-- "-ftime-report",
}
-- configuration { "gmake", "debug", "linux" }
-- buildoptions {
-- "-fno-omit-frame-pointer",
-- "-fsanitize=undefined",
-- "-fsanitize=address",
---- "-fsanitize=memory",
---- "-fsanitize-memory-track-origins",
-- }
-- linkoptions {
-- "-fsanitize=undefined",
-- "-fsanitize=address",
---- "-fsanitize=memory",
-- }
configuration { "vs*" }
buildoptions {
-- "/std:c++latest",
-- "/arch:AVX2",
-- "/GR-",
}
-- defines {
-- "_CRT_SECURE_NO_WARNINGS=1",
-- "_SCL_SECURE_NO_WARNINGS=1",
-- }
configuration { "windows" }
characterset "Unicode"
--------------------------------------------------------------------------------
group "Libs"
project "fmtxx"
language "C++"
kind "SharedLib"
files {
"src/**.h",
"src/**.cc",
}
defines {
"FMTXX_SHARED=1",
"FMTXX_EXPORT=1",
}
includedirs {
"src/",
}
configuration { "gmake" }
buildoptions {
"-Wsign-compare",
"-Wsign-conversion",
"-Wold-style-cast",
"-pedantic",
"-fvisibility=hidden",
}
project "gtest"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/*.cc",
"test/ext/googletest/googletest/src/*.h",
}
excludes {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/",
"test/ext/googletest/googletest/include/",
}
project "gtest_main"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/include/",
}
links {
"gtest",
}
-- project "fmt"
-- language "C++"
-- kind "SharedLib"
-- files {
-- "ext/fmt/**.h",
-- "ext/fmt/**.cc",
-- }
-- defines {
-- "FMT_SHARED=1",
-- "FMT_EXPORT=1",
-- }
-- includedirs {
-- "ext/",
-- }
--------------------------------------------------------------------------------
group "Tests"
project "Test"
language "C++"
kind "ConsoleApp"
files {
"test/Test.cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
"test/ext/googletest/googletest/include/",
}
links {
"fmtxx",
"gtest",
"gtest_main",
}
function AddExampleProject(name)
project (name)
language "C++"
kind "ConsoleApp"
files {
"test/" .. name .. ".cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
}
links {
"fmtxx",
}
end
AddExampleProject("Example1")
AddExampleProject("Example2")
AddExampleProject("Example3")
AddExampleProject("Example4")
AddExampleProject("Example5")
-- Doesn't work with MinGW (std::condition_variable not implemented...)
-- project "Benchmark"
-- language "C++"
-- kind "ConsoleApp"
-- files {
-- "test/Bench.cc",
-- "test/ext/benchmark/include/benchmark/*.h",
-- "test/ext/benchmark/src/*.cc",
-- }
-- defines {
-- "HAVE_STD_REGEX=1",
-- "FMTXX_SHARED=1",
-- }
-- includedirs {
-- "src/",
-- "test/ext/",
-- "test/ext/benchmark/include/",
-- }
-- links {
-- "fmtxx",
-- }
-- configuration { "vs*" }
-- links {
-- "shlwapi",
-- }
-- configuration { "not vs*" }
-- links {
-- "pthread",
-- }
|
local build_dir = "build/" .. _ACTION
--------------------------------------------------------------------------------
solution "Format"
configurations { "release", "debug" }
architecture "x64"
location (build_dir)
objdir (build_dir .. "/obj")
warnings "Extra"
exceptionhandling "Off"
rtti "Off"
configuration { "debug" }
targetdir (build_dir .. "/bin/debug")
configuration { "release" }
targetdir (build_dir .. "/bin/release")
configuration { "debug" }
defines { "_DEBUG" }
symbols "On"
configuration { "release" }
defines { "NDEBUG" }
symbols "On"
optimize "Full"
-- On ==> -O2
-- Full ==> -O3
configuration { "gmake" }
buildoptions {
"-march=native",
"-std=c++11",
"-Wformat",
-- "-Wsign-compare",
-- "-Wsign-conversion",
-- "-pedantic",
-- "-fvisibility=hidden",
-- "-fno-omit-frame-pointer",
-- "-ftime-report",
}
-- configuration { "gmake", "debug", "linux" }
-- buildoptions {
-- "-fno-omit-frame-pointer",
-- "-fsanitize=undefined",
-- "-fsanitize=address",
---- "-fsanitize=memory",
---- "-fsanitize-memory-track-origins",
-- }
-- linkoptions {
-- "-fsanitize=undefined",
-- "-fsanitize=address",
---- "-fsanitize=memory",
-- }
configuration { "vs*" }
buildoptions {
-- "/std:c++latest",
"/EHsc",
-- "/arch:AVX2",
-- "/GR-",
}
defines {
-- "_CRT_SECURE_NO_WARNINGS=1",
-- "_SCL_SECURE_NO_WARNINGS=1",
"_HAS_EXCEPTIONS=0",
}
configuration { "windows" }
characterset "Unicode"
--------------------------------------------------------------------------------
group "Libs"
project "fmtxx"
language "C++"
kind "SharedLib"
files {
"src/**.h",
"src/**.cc",
}
defines {
"FMTXX_SHARED=1",
"FMTXX_EXPORT=1",
}
includedirs {
"src/",
}
configuration { "gmake" }
buildoptions {
"-Wsign-compare",
"-Wsign-conversion",
"-Wold-style-cast",
"-pedantic",
"-fvisibility=hidden",
}
project "gtest"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/*.cc",
"test/ext/googletest/googletest/src/*.h",
}
excludes {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/",
"test/ext/googletest/googletest/include/",
}
project "gtest_main"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/include/",
}
links {
"gtest",
}
-- project "fmt"
-- language "C++"
-- kind "SharedLib"
-- files {
-- "ext/fmt/**.h",
-- "ext/fmt/**.cc",
-- }
-- defines {
-- "FMT_SHARED=1",
-- "FMT_EXPORT=1",
-- }
-- includedirs {
-- "ext/",
-- }
--------------------------------------------------------------------------------
group "Tests"
project "Test"
language "C++"
kind "ConsoleApp"
files {
"test/Test.cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
"test/ext/googletest/googletest/include/",
}
links {
"fmtxx",
"gtest",
"gtest_main",
}
function AddExampleProject(name)
project (name)
language "C++"
kind "ConsoleApp"
files {
"test/" .. name .. ".cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
}
links {
"fmtxx",
}
end
AddExampleProject("Example1")
AddExampleProject("Example2")
AddExampleProject("Example3")
AddExampleProject("Example4")
AddExampleProject("Example5")
-- Doesn't work with MinGW (std::condition_variable not implemented...)
-- project "Benchmark"
-- language "C++"
-- kind "ConsoleApp"
-- files {
-- "test/Bench.cc",
-- "test/ext/benchmark/include/benchmark/*.h",
-- "test/ext/benchmark/src/*.cc",
-- }
-- defines {
-- "HAVE_STD_REGEX=1",
-- "FMTXX_SHARED=1",
-- }
-- includedirs {
-- "src/",
-- "test/ext/",
-- "test/ext/benchmark/include/",
-- }
-- links {
-- "fmtxx",
-- }
-- configuration { "vs*" }
-- links {
-- "shlwapi",
-- }
-- configuration { "not vs*" }
-- links {
-- "pthread",
-- }
|
Fix warnings
|
Fix warnings
|
Lua
|
mit
|
abolz/Format
|
b7db402b47e4c1bc50c1d356bb6b37af01ebf2ff
|
lib/lua/checkStalledJobs.lua
|
lib/lua/checkStalledJobs.lua
|
--[[
key 1 -> bq:name:stallBlock
key 2 -> bq:name:stalling
key 3 -> bq:name:waiting
key 4 -> bq:name:active
arg 1 -> ms stallInterval
returns {resetJobId1, resetJobId2, ...}
workers are responsible for removing their jobId from the stalling set every stallInterval ms
if a jobId is not removed from the stalling set within a stallInterval window,
we assume the job has stalled and should be reset (moved from active back to waiting)
--]]
-- try to update the stallBlock key
if not redis.call("set", KEYS[1], "1", "PX", tonumber(ARGV[1]), "NX") then
-- hasn't been long enough (stallInterval) since last check
return {}
end
-- reset any stalling jobs by moving from active to waiting
local stalling, stalled = redis.call("smembers", KEYS[2]), {}
if next(stalling) ~= nil then
-- not worth optimizing - this should be a rare occurrence, better to keep it straightforward
local nextIndex = 1
for i, jobId in ipairs(stalling) do
local removed = redis.call("lrem", KEYS[4], 0, jobId)
-- we only restart stalled jobs if we can find them in the active list - otherwise, the stalled
-- lrem may have been delayed, or may not have run after the last checkStalledJobs call despite
-- having ended. this can cause problems with static ids, and cause jobs to run again
if removed > 0 then
stalled[nextIndex] = jobId
nextIndex = nextIndex + 1
end
end
-- don't lpush zero jobs (the redis command will fail)
if nextIndex > 1 then
redis.call("lpush", KEYS[3], unpack(stalled))
end
redis.call("del", KEYS[2])
end
-- copy currently active jobs into stalling set
local actives = redis.call("lrange", KEYS[4], 0, -1)
if next(actives) ~= nil then
redis.call("sadd", KEYS[2], unpack(actives))
end
return stalled
|
--[[
key 1 -> bq:name:stallBlock
key 2 -> bq:name:stalling
key 3 -> bq:name:waiting
key 4 -> bq:name:active
arg 1 -> ms stallInterval
returns {resetJobId1, resetJobId2, ...}
workers are responsible for removing their jobId from the stalling set every stallInterval ms
if a jobId is not removed from the stalling set within a stallInterval window,
we assume the job has stalled and should be reset (moved from active back to waiting)
--]]
-- try to update the stallBlock key
if not redis.call("set", KEYS[1], "1", "PX", tonumber(ARGV[1]), "NX") then
-- hasn't been long enough (stallInterval) since last check
return {}
end
-- reset any stalling jobs by moving from active to waiting
local stalling, stalled = redis.call("smembers", KEYS[2]), {}
if next(stalling) ~= nil then
-- not worth optimizing - this should be a rare occurrence, better to keep it straightforward
local nextIndex = 1
for i, jobId in ipairs(stalling) do
local removed = redis.call("lrem", KEYS[4], 0, jobId)
-- safety belts: we only restart stalled jobs if we can find them in the active list
-- the only place we add jobs to the stalling set is in this script, and the two places we
-- remove jobs from the active list are in this script, and in the MULTI after the job finishes
if removed > 0 then
stalled[nextIndex] = jobId
nextIndex = nextIndex + 1
end
end
-- don't lpush zero jobs (the redis command will fail)
if nextIndex > 1 then
redis.call("lpush", KEYS[3], unpack(stalled))
end
redis.call("del", KEYS[2])
end
-- copy currently active jobs into stalling set
local actives = redis.call("lrange", KEYS[4], 0, -1)
if next(actives) ~= nil then
redis.call("sadd", KEYS[2], unpack(actives))
end
return stalled
|
Fix comment
|
Fix comment
|
Lua
|
mit
|
LewisJEllis/bee-queue
|
4b26f70657a4fa23d10a6493f93ea409b597e172
|
src/python.lua
|
src/python.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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
--]]
Python = newclass "Python"
function Python:init(loader)
self.loader = loader
end
function Python:yaml2json(yaml)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml))
end
function Python:prettifyJSON(json)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json))
end
function Python:update()
self:conda("config --set always_yes yes --set changeps1 no")
self:conda("update --all --yes")
end
function Python:__call(command)
return os.outputoff("%s %s", self:_getPythonExe(), command)
end
function Python:conda(command)
local conda = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("conda"))
os.executef("%s %s", conda, command)
end
function Python:pip(command)
local pip = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("pip"))
os.executef("%s %s", pip, command)
end
function Python:_getDirectory()
return path.join(zpm.env.getDataDirectory(), "conda")
end
function Python:_getPythonExe()
return path.join(self:_getDirectory(), zpm.util.getExecutable(iif(os.is("windows"), "python", "python3")))
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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
--]]
Python = newclass "Python"
function Python:init(loader)
self.loader = loader
end
function Python:yaml2json(yaml)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml))
end
function Python:prettifyJSON(json)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json))
end
function Python:update()
self:conda("config --set always_yes yes --set changeps1 no")
self:conda("update --all --yes")
end
function Python:__call(command)
return os.outputoff("%s %s", self:_getPythonExe(), command)
end
function Python:conda(command)
local conda = path.join(self:_getBinDirectory(), zpm.util.getExecutable("conda"))
self:_execute("%s %s", conda, command)
end
function Python:pip(command)
local pip = path.join(self:_getBinDirectory(), zpm.util.getExecutable("pip"))
self:_execute("%s %s", pip, command)
end
function Python:_getBinDirectory()
return path.join(self:_getDirectory(), iif(os.is("windows"), "Scripts", "bin"))
end
function Python:_getDirectory()
return path.join(zpm.env.getDataDirectory(), "conda")
end
function Python:_execute(command)
os.executef("%s/activate && %s", self:_getDirectory(), command)
end
function Python:_getPythonExe()
return path.join(self:_getDirectory(), zpm.util.getExecutable(iif(os.is("windows"), "python", "python3")))
end
|
Fix python execution
|
Fix python execution
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
62c09d33590c76d7618fb6c4edd7779c9ea0dd88
|
plugins/mod_selftests.lua
|
plugins/mod_selftests.lua
|
local st = require "util.stanza";
local register_component = require "core.componentmanager".register_component;
local core_route_stanza = core_route_stanza;
local socket = require "socket";
local open_pings = {};
local t_insert = table.insert;
local log = require "util.logger".init("mod_selftests");
local tests_jid, host; "[email protected]";
local host = "getjabber.ath.cx";
if not (tests_jid and host) then
for currhost in pairs(host) do
if currhost ~= "localhost" then
tests_jid, host = "self_tests@"..currhost, currhost;
end
end
end
if tests_jid and host then
local bot = register_component(tests_jid, function(origin, stanza, ourhost)
local time = open_pings[stanza.attr.id];
if time then
log("info", "Ping reply from %s in %fs", tostring(stanza.attr.from), socket.gettime() - time);
else
log("info", "Unexpected reply: %s", stanza:pretty_print());
end
end);
local our_origin = hosts[host];
add_event_hook("server-started",
function ()
local id = st.new_id();
local ping_attr = { xmlns = 'urn:xmpp:ping' };
local function send_ping(to)
log("info", "Sending ping to %s", to);
core_route_stanza(our_origin, st.iq{ to = to, from = tests_jid, id = id, type = "get" }:tag("ping", ping_attr));
open_pings[id] = socket.gettime();
end
send_ping "matthewwild.co.uk"
send_ping "snikket.com"
send_ping "gmail.com"
send_ping "isode.com"
send_ping "jabber.org"
send_ping "chrome.pl"
send_ping "swissjabber.ch"
send_ping "soapbox.net"
send_ping "jabber.ccc.de"
end);
end
|
local st = require "util.stanza";
local register_component = require "core.componentmanager".register_component;
local core_route_stanza = core_route_stanza;
local socket = require "socket";
local config = require "core.configmanager";
local ping_hosts = config.get("*", "mod_selftests", "ping_hosts") or { "jabber.org" };
local open_pings = {};
local t_insert = table.insert;
local log = require "util.logger".init("mod_selftests");
local tests_jid = "[email protected]";
local host = "getjabber.ath.cx";
if not (tests_jid and host) then
for currhost in pairs(host) do
if currhost ~= "localhost" then
tests_jid, host = "self_tests@"..currhost, currhost;
end
end
end
if tests_jid and host then
local bot = register_component(tests_jid, function(origin, stanza, ourhost)
local time = open_pings[stanza.attr.id];
if time then
log("info", "Ping reply from %s in %fs", tostring(stanza.attr.from), socket.gettime() - time);
else
log("info", "Unexpected reply: %s", stanza:pretty_print());
end
end);
local our_origin = hosts[host];
add_event_hook("server-started",
function ()
local id = st.new_id();
local ping_attr = { xmlns = 'urn:xmpp:ping' };
local function send_ping(to)
log("info", "Sending ping to %s", to);
core_route_stanza(our_origin, st.iq{ to = to, from = tests_jid, id = id, type = "get" }:tag("ping", ping_attr));
open_pings[id] = socket.gettime();
end
for _, host in ipairs(ping_hosts) do
send_ping(host);
end
end);
end
|
Fix mod_selftests syntax, and switch it to use config
|
Fix mod_selftests syntax, and switch it to use config
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2dda43a379d24b2bef3a4f469db41035d9a531ad
|
src/lua/smtp/smtp_io.lua
|
src/lua/smtp/smtp_io.lua
|
local smtp_io = {}
smtp_io.__index = smtp_io
-- {{{ smtp_io.new()
function smtp_io.new(socket)
local self = {}
setmetatable(self, smtp_io)
self.socket = socket
self.send_buffer = {}
self.recv_buffer = ""
return self
end
-- }}}
-- {{{ smtp_io:close()
function smtp_io:close()
local enc = self.socket:get_encryption()
if enc then
enc:shutdown()
end
return self.socket:close()
end
-- }}}
-- {{{ smtp_io:buffered_recv()
function smtp_io:buffered_recv()
local received = self.socket:recv()
if received == "" then
local err = ratchet.error.new("Connection closed.", "ECONNCLOSED", "ratchet.smtp.io.recv()")
error(err)
end
self.recv_buffer = self.recv_buffer .. received
return self.recv_buffer
end
-- }}}
-- {{{ smtp_io:buffered_send()
function smtp_io:buffered_send(data)
table.insert(self.send_buffer, data)
end
-- }}}
-- {{{ smtp_io:flush_send()
function smtp_io:flush_send()
local send_buffer = table.concat(self.send_buffer)
self.send_buffer = {}
repeat
send_buffer = self.socket:send(send_buffer)
until not send_buffer
end
-- }}}
-- {{{ smtp_io:recv_reply()
function smtp_io:recv_reply()
local pattern
local code, message_lines = nil, {}
local bad_line_pattern = "^(.-)%\r?%\n()"
local incomplete = true
local input = self.recv_buffer
while incomplete do
-- Build the full reply pattern once we know the code.
if not pattern then
code = input:match("^%d%d%d")
if code then
pattern = "^" .. code .. "([% %\t%-])(.-)%\r?%\n()"
else
local bad_line, end_i = input:match(bad_line_pattern)
if bad_line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return nil, bad_line
end
end
end
-- Check for lines that match the pattern.
if pattern then
local start_i = 1
repeat
local splitter, line, end_i = input:match(pattern, start_i)
if line then
table.insert(message_lines, line)
self.recv_buffer = self.recv_buffer:sub(end_i)
if splitter ~= "-" then
incomplete = false
start_i = nil
else
start_i = end_i
end
else
local bad_line, end_i = input:match(bad_line_pattern)
if bad_line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return nil, bad_line
else
start_i = nil
end
end
until not start_i
end
-- Check if we need to receive more data.
if incomplete then
input = self:buffered_recv()
end
end
return code, table.concat(message_lines, "\r\n")
end
-- }}}
-- {{{ smtp_io:recv_line()
function smtp_io:recv_line()
local input = self.recv_buffer
while true do
local line, end_i = input:match("^(.-)%\r?%\n()")
if line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return line
end
input = self:buffered_recv()
end
end
-- }}}
-- {{{ smtp_io:recv_command()
function smtp_io:recv_command()
local line = self:recv_line()
local command, extra = line:match("^(%a+)%s*(.-)%s*$")
if command then
return command:upper(), extra
else
return line
end
end
-- }}}
-- {{{ smtp_io:send_reply()
function smtp_io:send_reply(code, message)
local lines = {}
message = message .. "\r\n"
for line in message:gmatch("(.-)%\r?%\n") do
table.insert(lines, line)
end
local num_lines = #lines
if num_lines == 0 then
local to_send = code .. " " .. message .. "\r\n"
return self:buffered_send(to_send)
else
local to_send = ""
for i=1,(num_lines-1) do
to_send = to_send .. code .. "-" .. lines[i] .. "\r\n"
end
to_send = to_send .. code .. " " .. lines[num_lines] .. "\r\n"
return self:buffered_send(to_send)
end
end
-- }}}
-- {{{ smtp_io:send_command()
function smtp_io:send_command(command)
return self:buffered_send(command.."\r\n")
end
-- }}}
return smtp_io
-- vim:foldmethod=marker:sw=4:ts=4:sts=4:et:
|
local smtp_io = {}
smtp_io.__index = smtp_io
-- {{{ smtp_io.new()
function smtp_io.new(socket)
local self = {}
setmetatable(self, smtp_io)
self.socket = socket
self.send_buffer = {}
self.recv_buffer = ""
return self
end
-- }}}
-- {{{ smtp_io:close()
function smtp_io:close()
local enc = self.socket:get_encryption()
if enc then
enc:shutdown()
end
return self.socket:close()
end
-- }}}
-- {{{ smtp_io:buffered_recv()
function smtp_io:buffered_recv()
local received = self.socket:recv()
if received == "" then
local err = ratchet.error.new("Connection closed.", "ECONNCLOSED", "ratchet.smtp.io.recv()")
error(err)
end
self.recv_buffer = self.recv_buffer .. received
return self.recv_buffer
end
-- }}}
-- {{{ smtp_io:buffered_send()
function smtp_io:buffered_send(data)
table.insert(self.send_buffer, data)
end
-- }}}
-- {{{ smtp_io:flush_send()
function smtp_io:flush_send()
if not self.send_buffer[1] then
-- Don't try to send nothing.
return
end
local send_buffer = table.concat(self.send_buffer)
self.send_buffer = {}
repeat
send_buffer = self.socket:send(send_buffer)
until not send_buffer
end
-- }}}
-- {{{ smtp_io:recv_reply()
function smtp_io:recv_reply()
local pattern
local code, message_lines = nil, {}
local bad_line_pattern = "^(.-)%\r?%\n()"
local incomplete = true
local input = self.recv_buffer
while incomplete do
-- Build the full reply pattern once we know the code.
if not pattern then
code = input:match("^%d%d%d")
if code then
pattern = "^" .. code .. "([% %\t%-])(.-)%\r?%\n()"
else
local bad_line, end_i = input:match(bad_line_pattern)
if bad_line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return nil, bad_line
end
end
end
-- Check for lines that match the pattern.
if pattern then
local start_i = 1
repeat
local splitter, line, end_i = input:match(pattern, start_i)
if line then
table.insert(message_lines, line)
self.recv_buffer = self.recv_buffer:sub(end_i)
if splitter ~= "-" then
incomplete = false
start_i = nil
else
start_i = end_i
end
else
local bad_line, end_i = input:match(bad_line_pattern)
if bad_line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return nil, bad_line
else
start_i = nil
end
end
until not start_i
end
-- Check if we need to receive more data.
if incomplete then
input = self:buffered_recv()
end
end
return code, table.concat(message_lines, "\r\n")
end
-- }}}
-- {{{ smtp_io:recv_line()
function smtp_io:recv_line()
local input = self.recv_buffer
while true do
local line, end_i = input:match("^(.-)%\r?%\n()")
if line then
self.recv_buffer = self.recv_buffer:sub(end_i)
return line
end
input = self:buffered_recv()
end
end
-- }}}
-- {{{ smtp_io:recv_command()
function smtp_io:recv_command()
local line = self:recv_line()
local command, extra = line:match("^(%a+)%s*(.-)%s*$")
if command then
return command:upper(), extra
else
return line
end
end
-- }}}
-- {{{ smtp_io:send_reply()
function smtp_io:send_reply(code, message)
local lines = {}
message = message .. "\r\n"
for line in message:gmatch("(.-)%\r?%\n") do
table.insert(lines, line)
end
local num_lines = #lines
if num_lines == 0 then
local to_send = code .. " " .. message .. "\r\n"
return self:buffered_send(to_send)
else
local to_send = ""
for i=1,(num_lines-1) do
to_send = to_send .. code .. "-" .. lines[i] .. "\r\n"
end
to_send = to_send .. code .. " " .. lines[num_lines] .. "\r\n"
return self:buffered_send(to_send)
end
end
-- }}}
-- {{{ smtp_io:send_command()
function smtp_io:send_command(command)
return self:buffered_send(command.."\r\n")
end
-- }}}
return smtp_io
-- vim:foldmethod=marker:sw=4:ts=4:sts=4:et:
|
fixed bug with SSL'ed
|
fixed bug with SSL'ed
|
Lua
|
mit
|
icgood/ratchet
|
344ddf1b3fcccbf2f66d983beeb36abb06fa5c2c
|
main.lua
|
main.lua
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local ScreenManager = require('lib.screenmanager.ScreenManager');
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local showDebug = false;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Check if the hardware supports certain features.
--
local function checkSupport()
print("\n---- SUPPORTED ---- ");
print("Canvas: " .. tostring(love.graphics.isSupported('canvas')));
print("PO2: " .. tostring(love.graphics.isSupported('npot')));
print("Subtractive BM: " .. tostring(love.graphics.isSupported('subtractive')));
print("Shaders: " .. tostring(love.graphics.isSupported('shader')));
print("HDR Canvas: " .. tostring(love.graphics.isSupported('hdrcanvas')));
print("Multicanvas: " .. tostring(love.graphics.isSupported('multicanvas')));
print("Mipmaps: " .. tostring(love.graphics.isSupported('mipmap')));
print("DXT: " .. tostring(love.graphics.isSupported('dxt')));
print("BC5: " .. tostring(love.graphics.isSupported('bc5')));
print("SRGB: " .. tostring(love.graphics.isSupported('srgb')));
print("\n---- RENDERER ---- ");
local name, version, vendor, device = love.graphics.getRendererInfo()
print(string.format("Name: %s \nVersion: %s \nVendor: %s \nDevice: %s", name, version, vendor, device));
print("\n---- SYSTEM ---- ");
print(love.system.getOS());
end
local function drawStats()
love.graphics.setColor(100, 100, 100, 255);
love.graphics.rectangle('fill', 5, love.window.getHeight() - 185, 200, 200);
love.graphics.setColor(255, 255, 255, 255);
love.graphics.print(string.format("FT: %.3f ms", 1000 * love.timer.getAverageDelta()), 10, love.window.getHeight() - 180);
love.graphics.print(string.format("FPS: %.3f fps", love.timer.getFPS()), 10, love.window.getHeight() - 160);
love.graphics.print(string.format("MEM: %.3f kb", collectgarbage("count")), 10, love.window.getHeight() - 140);
local stats = love.graphics.getStats();
love.graphics.print(string.format("Drawcalls: %d", stats.drawcalls), 10, love.window.getHeight() - 120);
love.graphics.print(string.format("Canvas Switches: %d", stats.canvasswitches), 10, love.window.getHeight() - 100);
love.graphics.print(string.format("TextureMemory: %.2f kb", stats.texturememory / 1024), 10, love.window.getHeight() - 80);
love.graphics.print(string.format("Images: %d", stats.images), 10, love.window.getHeight() - 60);
love.graphics.print(string.format("Canvases: %d", stats.canvases), 10, love.window.getHeight() - 40);
love.graphics.print(string.format("Fonts: %d", stats.fonts), 10, love.window.getHeight() - 20);
end
-- ------------------------------------------------
-- Callbacks
-- ------------------------------------------------
function love.load()
print("===================")
print(string.format("Title: '%s'", getTitle()));
print(string.format("Version: %.4d", getVersion()));
print(string.format("LOVE Version: %d.%d.%d (%s)", love.getVersion()));
print(string.format("Resolution: %dx%d", love.window.getDimensions()));
-- Check the user's hardware.
checkSupport();
print("===================")
print(os.date('%c', os.time()));
print("===================")
local screens = {
selection = require('src.screens.SelectionScreen');
main = require('src.screens.MainScreen');
};
ScreenManager.init(screens, 'selection');
end
function love.draw()
ScreenManager.draw();
if showDebug then
drawStats();
end
end
function love.update(dt)
ScreenManager.update(dt);
end
function love.quit(q)
ScreenManager.quit(q);
end
function love.resize(x, y)
ScreenManager.resize(x, y);
end
function love.keypressed(key)
if key == 'f1' then
showDebug = not showDebug;
end
ScreenManager.keypressed(key);
end
function love.mousepressed(x, y, b)
ScreenManager.mousepressed(x, y, b);
end
function love.mousereleased(x, y, b)
ScreenManager.mousereleased(x, y, b);
end
function love.mousemoved(x, y, dx, dy)
ScreenManager.mousemoved(x, y, dx, dy);
end
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local ScreenManager = require('lib.screenmanager.ScreenManager');
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local showDebug = false;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Check if the hardware supports certain features.
--
local function checkSupport()
print("\n---- SUPPORTED ---- ");
print("Canvas: " .. tostring(love.graphics.isSupported('canvas')));
print("PO2: " .. tostring(love.graphics.isSupported('npot')));
print("Subtractive BM: " .. tostring(love.graphics.isSupported('subtractive')));
print("Shaders: " .. tostring(love.graphics.isSupported('shader')));
print("HDR Canvas: " .. tostring(love.graphics.isSupported('hdrcanvas')));
print("Multicanvas: " .. tostring(love.graphics.isSupported('multicanvas')));
print("Mipmaps: " .. tostring(love.graphics.isSupported('mipmap')));
print("DXT: " .. tostring(love.graphics.isSupported('dxt')));
print("BC5: " .. tostring(love.graphics.isSupported('bc5')));
print("SRGB: " .. tostring(love.graphics.isSupported('srgb')));
print("\n---- RENDERER ---- ");
local name, version, vendor, device = love.graphics.getRendererInfo()
print(string.format("Name: %s \nVersion: %s \nVendor: %s \nDevice: %s", name, version, vendor, device));
print("\n---- SYSTEM ---- ");
print(love.system.getOS());
end
local function drawStats()
love.graphics.setColor(100, 100, 100, 255);
love.graphics.rectangle('fill', 5, love.window.getHeight() - 185, 200, 200);
love.graphics.setColor(255, 255, 255, 255);
love.graphics.print(string.format("FT: %.3f ms", 1000 * love.timer.getAverageDelta()), 10, love.window.getHeight() - 180);
love.graphics.print(string.format("FPS: %.3f fps", love.timer.getFPS()), 10, love.window.getHeight() - 160);
love.graphics.print(string.format("MEM: %.3f kb", collectgarbage("count")), 10, love.window.getHeight() - 140);
local stats = love.graphics.getStats();
love.graphics.print(string.format("Drawcalls: %d", stats.drawcalls), 10, love.window.getHeight() - 120);
love.graphics.print(string.format("Canvas Switches: %d", stats.canvasswitches), 10, love.window.getHeight() - 100);
love.graphics.print(string.format("TextureMemory: %.2f kb", stats.texturememory / 1024), 10, love.window.getHeight() - 80);
love.graphics.print(string.format("Images: %d", stats.images), 10, love.window.getHeight() - 60);
love.graphics.print(string.format("Canvases: %d", stats.canvases), 10, love.window.getHeight() - 40);
love.graphics.print(string.format("Fonts: %d", stats.fonts), 10, love.window.getHeight() - 20);
end
-- ------------------------------------------------
-- Callbacks
-- ------------------------------------------------
function love.load()
print("===================")
print(string.format("Title: '%s'", getTitle()));
print(string.format("Version: %.4d", getVersion()));
print(string.format("LOVE Version: %d.%d.%d (%s)", love.getVersion()));
print(string.format("Resolution: %dx%d", love.window.getDimensions()));
-- Check the user's hardware.
checkSupport();
print("===================")
print(os.date('%c', os.time()));
print("===================")
local screens = {
selection = require('src.screens.SelectionScreen');
main = require('src.screens.MainScreen');
};
ScreenManager.init(screens, 'selection');
end
function love.draw()
ScreenManager.draw();
if showDebug then
drawStats();
end
end
function love.update(dt)
ScreenManager.update(dt);
end
function love.quit(q)
ScreenManager.quit(q);
end
function love.resize(x, y)
ScreenManager.resize(x, y);
end
function love.keypressed(key)
if key == ' ' then
key = 'space';
elseif tonumber(key) then
key = tonumber(key);
end
if key == 'f1' then
showDebug = not showDebug;
end
ScreenManager.keypressed(key);
end
function love.mousepressed(x, y, b)
ScreenManager.mousepressed(x, y, b);
end
function love.mousereleased(x, y, b)
ScreenManager.mousereleased(x, y, b);
end
function love.mousemoved(x, y, dx, dy)
ScreenManager.mousemoved(x, y, dx, dy);
end
|
Fix controls
|
Fix controls
Transforms the keyconstants which love.keypressed receives as parameters
to numbers (if possible) and the ' ' character to 'space'. This is done
so they correspond to the keybindings read from the config file.
Maybe it would be "cleaner" to fix this in the config reader, but for
now this should work.
|
Lua
|
mit
|
rm-code/logivi
|
c1542ef75f27ad349468bdbaacdd89ee49f8f8eb
|
LogisticsWagons/wagons/proxywagon.lua
|
LogisticsWagons/wagons/proxywagon.lua
|
-- Wagon class definitions and functions
local class = require 'middleclass'
ProxyWagon = class('ProxyWagon',Wagon)
function ProxyWagon:initialize(parent,data)
debugLog("Proxy wagon init")
Wagon.initialize(self, parent, data)
self.wagonType = "ProxyWagon"
if(data == nil) then
if parent ~= nil then
self.valid = true
self.parent = parent
self.proxy = nil
self.inventoryCount = -1
self.proxyCount = -1
end
else
self.valid = data.valid
self.parent = data.parent
self.proxy = data.proxy
self.inventoryCount = data.inventoryCount or -1
self.proxyCount = data.proxyCount or -1
end
end
function ProxyWagon:updateDataSerialisation()
Wagon.updateDataSerialisation(self)
self.data.proxy = self.proxy
self.data.inventoryCount = self.inventoryCount
self.data.proxyCount = self.proxyCount
end
function ProxyWagon:updateWagon(tick)
if(self.proxy ~= nil) then
if(self:isMoving() and not self:allowsProxyWhileMoving()) then
-- Moving and not allowing proxy while moving, should remove the proxy
self:removeProxy()
self.proxy = nil
else
-- Standing still, should update the proxy count
-- But only do it every so often
if(tick % 5 == 3) then
self:syncProxyAndInventory()
end
end
else
if(not self:isMoving() or (self:isMoving() and self:allowsProxyWhileMoving())) then
-- No proxy, but there should be one
self.proxy = self:createProxyType()
end
end
end
function ProxyWagon:allowsProxyWhileMoving()
return false
end
function ProxyWagon:getProxyPosition()
debugLog("Trying to get position of : " .. serpent.dump(self.parent))
local parentEntity = self.parent
if(parentEntity ~= nil) then
local proxyPosition = parentEntity.position
proxyPosition.x = proxyPosition.x
return proxyPosition
end
return nil
end
function ProxyWagon:moveProxy(parent)
self.proxy.position = self:getProxyPosition()
end
function ProxyWagon:createProxy(proxyType, makeOperable)
-- debugLog("Creating new proxy of type " .. proxyType)
if makeOperable == nil then
makeOperable = false
end
local proxy = {}
local parentEntity = self.parent
if parentEntity ~= nil and parentEntity.valid then
self.inventoryCount = -1
self.proxyCount = -1
local proxyPosition = self:getProxyPosition()
debugLog("Creating " .. proxyType .. " at " .. proxyPosition.x .. " " .. proxyPosition.y)
game.createentity{name=proxyType, position=proxyPosition, force=game.player.force}
proxysearch = game.findentitiesfiltered{area = {{proxyPosition.x - 1, proxyPosition.y - 1}, {proxyPosition.x + 1, proxyPosition.y + 1}}, name=proxyType}
for i,e in ipairs(proxysearch) do
proxy = e
end
proxy.operable = makeOperable;
return proxy
else
debugLog("not valid?")
-- debugLog(serpent.dump(self))
end
return nil
end
function ProxyWagon:emptyProxy()
if (self.proxy.valid) then
local container = self.proxy.getinventory(1)
local contents = container.getcontents()
for name,count in pairs(contents) do
container.remove({name=name,count=count})
end
end
end
function ProxyWagon:removeProxy()
debugLog("Trying to remove proxy: " .. serpent.dump(self.proxy))
self:emptyProxy()
self.proxy.destroy()
self.inventoryCount = -1
self.proxyCount = -1
end
function ProxyWagon:syncProxyAndInventory()
if self.proxy == nil or not self.proxy.valid then
debugLog("Proxy does not exist. something is wrong, we should not be here")
--glob.logisticWagons[wagon]["proxy"] = nil
return
end
local wagonInventory = self.parent.getinventory(1)
local proxyInventory = self.proxy.getinventory(1)
-- Should be saved, testing copying for now
if wagonInventory.getitemcount() ~= self.inventoryCount then
debugLog("currentCount: " .. wagonInventory.getitemcount() .. " previous: " .. self.inventoryCount)
debugLog("copy to proxy")
self:copyInventory(wagonInventory, proxyInventory)
self.inventoryCount = wagonInventory.getitemcount()
self.proxyCount = proxyInventory.getitemcount()
return true
elseif not self:compareInventories(wagonInventory, proxyInventory) then
debugLog("wagon count: " .. wagonInventory.getitemcount() .. " previous: " .. self.inventoryCount)
debugLog("proxy count: " .. proxyInventory.getitemcount() .. " previous: " .. self.proxyCount)
debugLog("copy to wagon")
self:copyInventory(proxyInventory, wagonInventory)
self.inventoryCount = wagonInventory.getitemcount()
self.proxyCount = proxyInventory.getitemcount()
return true
end
return false
end
function ProxyWagon:compareInventories(inventoryA, inventoryB)
if inventoryA.getitemcount() ~= inventoryB.getitemcount() then
return false
else
local contentsA = inventoryA.getcontents()
local contentsB = inventoryB.getcontents()
for name, count in pairs(contentsA) do
if contentsB[name] == nil or contentsB[name] ~= count then
return false
end
end
end
return true
end
function ProxyWagon:copyInventory(copyFrom, copyTo)
if copyFrom ~= nil and copyTo ~= nil then
local action = {}
local fromContents = copyFrom.getcontents()
local toContents = copyTo.getcontents()
for name,count in pairs(fromContents) do
local diff = self:getItemDifference(name,fromContents[name], toContents[name])
if diff ~= 0 then
action[name] = diff
end
end
for name,count in pairs(toContents) do
if fromContents[name] == nul then
action[name] = self:getItemDifference(name,fromContents[name],toContents[name])
end
end
for name,diff in pairs(action) do
debugLog("#################itemName: " .. name .. " diff: " .. diff)
if diff > 0 then
copyTo.insert({name=name,count=diff})
elseif diff < 0 then
copyTo.remove({name=name,count=0-diff})
end
end
end
end
function ProxyWagon:getItemDifference(item, syncFromItemCount, syncToItemCount)
if syncFromItemCount == nil then
if syncToItemCount ~= nil then
return 0 - syncToItemCount
end
elseif syncToItemCount == nil then
return syncFromItemCount
else
return syncFromItemCount - syncToItemCount
end
return 0
end
|
-- Wagon class definitions and functions
local class = require 'middleclass'
ProxyWagon = class('ProxyWagon',Wagon)
function ProxyWagon:initialize(parent,data)
debugLog("Proxy wagon init")
Wagon.initialize(self, parent, data)
self.wagonType = "ProxyWagon"
if(data == nil) then
if parent ~= nil then
self.valid = true
self.parent = parent
self.proxy = nil
self.inventoryCount = -1
self.proxyCount = -1
end
else
self.valid = data.valid
self.parent = data.parent
self.proxy = data.proxy
self.inventoryCount = data.inventoryCount or -1
self.proxyCount = data.proxyCount or -1
end
end
function ProxyWagon:updateDataSerialisation()
Wagon.updateDataSerialisation(self)
self.data.proxy = self.proxy
self.data.inventoryCount = self.inventoryCount
self.data.proxyCount = self.proxyCount
end
function ProxyWagon:updateWagon(tick)
if(self.proxy ~= nil) then
if(self:isMoving() and not self:allowsProxyWhileMoving()) then
-- Moving and not allowing proxy while moving, should remove the proxy
self:removeProxy()
self.proxy = nil
else
-- Standing still, should update the proxy count
-- But only do it every so often
--if(tick % 500 == 3) then
self:syncProxyAndInventory()
--end
end
else
if(not self:isMoving() or (self:isMoving() and self:allowsProxyWhileMoving())) then
-- No proxy, but there should be one
self.proxy = self:createProxyType()
end
end
end
function ProxyWagon:allowsProxyWhileMoving()
return false
end
function ProxyWagon:getProxyPosition()
debugLog("Trying to get position of : " .. serpent.dump(self.parent))
local parentEntity = self.parent
if(parentEntity ~= nil) then
local proxyPosition = parentEntity.position
proxyPosition.x = proxyPosition.x + 0
return proxyPosition
end
return nil
end
function ProxyWagon:moveProxy(parent)
self.proxy.position = self:getProxyPosition()
end
function ProxyWagon:createProxy(proxyType, makeOperable)
-- debugLog("Creating new proxy of type " .. proxyType)
if makeOperable == nil then
makeOperable = false
end
local proxy = {}
local parentEntity = self.parent
if parentEntity ~= nil and parentEntity.valid then
self.inventoryCount = -1
self.proxyCount = -1
local proxyPosition = self:getProxyPosition()
debugLog("Creating " .. proxyType .. " at " .. proxyPosition.x .. " " .. proxyPosition.y)
game.createentity{name=proxyType, position=proxyPosition, force=game.player.force}
proxysearch = game.findentitiesfiltered{area = {{proxyPosition.x - 1, proxyPosition.y - 1}, {proxyPosition.x + 1, proxyPosition.y + 1}}, name=proxyType}
for i,e in ipairs(proxysearch) do
proxy = e
end
proxy.operable = makeOperable;
return proxy
else
debugLog("not valid?")
-- debugLog(serpent.dump(self))
end
return nil
end
function ProxyWagon:emptyProxy()
if (self.proxy.valid) then
local container = self.proxy.getinventory(1)
local contents = container.getcontents()
for name,count in pairs(contents) do
container.remove({name=name,count=count})
end
end
end
function ProxyWagon:removeProxy()
debugLog("Trying to remove proxy: " .. serpent.dump(self.proxy))
self:emptyProxy()
self.proxy.destroy()
self.inventoryCount = -1
self.proxyCount = -1
end
function ProxyWagon:syncProxyAndInventory()
if self.proxy == nil or not self.proxy.valid then
debugLog("Proxy does not exist. something is wrong, we should not be here")
--glob.logisticWagons[wagon]["proxy"] = nil
return
end
local wagonInventory = self.parent.getinventory(1)
local proxyInventory = self.proxy.getinventory(1)
-- Should be saved, testing copying for now
if wagonInventory.getitemcount() ~= self.inventoryCount then
-- debugLog("currentCount: " .. wagonInventory.getitemcount() .. " previous: " .. self.inventoryCount)
-- debugLog("proxy count: " .. proxyInventory.getitemcount() .. " previous: " .. self.proxyCount)
-- debugLog("copy to proxy")
self:copyInventory(wagonInventory, proxyInventory)
self.inventoryCount = wagonInventory.getitemcount()
self.proxyCount = proxyInventory.getitemcount()
return true
elseif proxyInventory.getitemcount() ~= self.proxyCount then
-- debugLog("wagon count: " .. wagonInventory.getitemcount() .. " previous: " .. self.inventoryCount)
-- debugLog("proxy count: " .. proxyInventory.getitemcount() .. " previous: " .. self.proxyCount)
-- debugLog("copy to wagon")
self:copyInventory(proxyInventory, wagonInventory)
self.inventoryCount = wagonInventory.getitemcount()
self.proxyCount = proxyInventory.getitemcount()
return true
end
return false
end
function ProxyWagon:copyInventory(copyFrom, copyTo)
if copyFrom ~= nil and copyTo ~= nil then
local action = {}
local fromContents = copyFrom.getcontents()
local toContents = copyTo.getcontents()
for name,count in pairs(fromContents) do
local diff = self:getItemDifference(name,fromContents[name], toContents[name])
if diff ~= 0 then
action[name] = diff
end
end
for name,count in pairs(toContents) do
if fromContents[name] == nul then
action[name] = self:getItemDifference(name,fromContents[name],toContents[name])
end
end
for name,diff in pairs(action) do
-- debugLog("#################itemName: " .. name .. " diff: " .. diff)
if diff > 0 then
copyTo.insert({name=name,count=diff})
elseif diff < 0 then
copyTo.remove({name=name,count=0-diff})
end
end
end
end
function ProxyWagon:getItemDifference(item, syncFromItemCount, syncToItemCount)
if syncFromItemCount == nil then
if syncToItemCount ~= nil then
return 0 - syncToItemCount
end
elseif syncToItemCount == nil then
return syncFromItemCount
else
return syncFromItemCount - syncToItemCount
end
return 0
end
|
Bug seems to have been in factorio, removing testing code
|
Bug seems to have been in factorio, removing testing code
|
Lua
|
mit
|
gnzzz/Factorio-Logistics-Wagons
|
6b70224faaa24e97abb23f0e76e9d7a9831200c1
|
luastatic.lua
|
luastatic.lua
|
-- The author disclaims copyright to this source code.
local infile = arg[1]
local libluapath = arg[2]
if not infile or not libluapath then
print("usage: luastatic infile.lua /path/to/liblua.a")
os.exit()
end
if libluapath then
local f = io.open(libluapath, "r")
if not f then
print(("liblua.a not found: %s"):format(libluapath))
os.exit(1)
end
end
local CC = "cc"
do
local f = io.popen(CC .. " --version")
f:read("*all")
if not f:close() then
print("C compiler not found.")
os.exit(1)
end
end
local infd = io.open(infile, "r")
if not infd then
print(("Lua file not found: %s"):format(infile))
os.exit(1)
end
function binToCData(bindata, name)
local fmt = [[
unsigned char %s_lua[] = {
%s
};
unsigned int %s_lua_len = %u;
]]
local hex = {}
for b in bindata:gmatch"." do
table.insert(hex, ("0x%02x"):format(string.byte(b)))
end
local hexstr = table.concat(hex, ", ")
return fmt:format(name, hexstr, name, #bindata)
end
local basename = io.popen(("basename %s"):format(infile)):read("*all")
basename = basename:match("(.+)%.")
function luaProgramToCData(filename)
--~ local basename = filename:match("(.+)%.")
local f = io.open(filename, "r")
local strdata = f:read("*all")
-- load the chunk to check for syntax errors
local chunk, err = load(strdata)
if not chunk then
print(("load: %s"):format(err))
os.exit(1)
end
local bindata = string.dump(chunk)
f:close()
return binToCData(bindata, basename)
end
local luaprogramcdata = luaProgramToCData(infile)
--~ local basename = infile:match("(.+)%.")
local cprog = ([[
//#include <lauxlib.h>
//#include <lua.h>
//#include <lualib.h>
#include <stdio.h>
%s
// try to avoid having to resolve the Lua include path
typedef struct lua_State lua_State;
typedef int (*lua_CFunction) (lua_State *L);
lua_State *(luaL_newstate) (void);
const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
#define LUA_MULTRET (-1)
#define LUA_OK 0
int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
const char *name, const char *mode);
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
int ctx, lua_CFunction k);
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
// copied from lua.c
static void createargtable (lua_State *L, char **argv, int argc, int script) {
int i, narg;
if (script == argc) script = 0; /* no script name? */
narg = argc - (script + 1); /* number of positive indices */
lua_createtable(L, narg, script + 1);
for (i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i - script);
}
lua_setglobal(L, "arg");
}
int
main(int argc, char *argv[])
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_loadbuffer(L, (const char*)%s_lua, %s_lua_len, "%s"))
{
puts(lua_tostring(L, 1));
return 1;
}
createargtable(L, argv, argc, 0);
int err = lua_pcall(L, 0, LUA_MULTRET, 0);
if (err != LUA_OK)
{
puts(lua_tostring(L, 1));
return 1;
}
return 0;
}
]]):format(luaprogramcdata, basename, basename, basename)
local outfile = io.open(("%s.c"):format(infile), "w+")
outfile:write(cprog)
outfile:close()
do
-- statically link Lua, but dynamically link everything else
-- http://lua-users.org/lists/lua-l/2009-05/msg00147.html
local ccformat
= "%s -Os %s.c -rdynamic %s -lm -ldl -o %s"
local ccformat = ccformat:format(CC, infile, libluapath, basename)
print(ccformat)
io.popen(ccformat):read("*all")
end
|
-- The author disclaims copyright to this source code.
local infile = arg[1]
local libluapath = arg[2]
if not infile or not libluapath then
print("usage: luastatic infile.lua /path/to/liblua.a")
os.exit()
end
if libluapath then
local f = io.open(libluapath, "r")
if not f then
print(("liblua.a not found: %s"):format(libluapath))
os.exit(1)
end
end
local CC = "cc"
do
local f = io.popen(CC .. " --version")
f:read("*all")
if not f:close() then
print("C compiler not found.")
os.exit(1)
end
end
local infd = io.open(infile, "r")
if not infd then
print(("Lua file not found: %s"):format(infile))
os.exit(1)
end
function binToCData(bindata, name)
local fmt = [[
unsigned char %s_lua[] = {
%s
};
unsigned int %s_lua_len = %u;
]]
local hex = {}
for b in bindata:gmatch"." do
table.insert(hex, ("0x%02x"):format(string.byte(b)))
end
local hexstr = table.concat(hex, ", ")
return fmt:format(name, hexstr, name, #bindata)
end
local basename = io.popen(("basename %s"):format(infile)):read("*all")
basename = basename:match("(.+)%.")
function luaProgramToCData(filename)
--~ local basename = filename:match("(.+)%.")
local f = io.open(filename, "r")
local strdata = f:read("*all")
-- load the chunk to check for syntax errors
local chunk, err = load(strdata)
if not chunk then
print(("load: %s"):format(err))
os.exit(1)
end
local bindata = string.dump(chunk)
f:close()
return binToCData(bindata, basename)
end
local luaprogramcdata = luaProgramToCData(infile)
--~ local basename = infile:match("(.+)%.")
local cprog = ([[
//#include <lauxlib.h>
//#include <lua.h>
//#include <lualib.h>
#include <stdio.h>
%s
// try to avoid having to resolve the Lua include path
typedef struct lua_State lua_State;
typedef int (*lua_CFunction) (lua_State *L);
lua_State *(luaL_newstate) (void);
void (luaL_openlibs) (lua_State *L);
const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
const char *(lua_pushstring) (lua_State *L, const char *s);
void (lua_setglobal) (lua_State *L, const char *var);
void (lua_rawseti) (lua_State *L, int idx, int n);
#define LUA_MULTRET (-1)
#define LUA_OK 0
int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
const char *name, const char *mode);
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
int ctx, lua_CFunction k);
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
void (lua_createtable) (lua_State *L, int narr, int nrec);
// copied from lua.c
static void createargtable (lua_State *L, char **argv, int argc, int script) {
int i, narg;
if (script == argc) script = 0; /* no script name? */
narg = argc - (script + 1); /* number of positive indices */
lua_createtable(L, narg, script + 1);
for (i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i - script);
}
lua_setglobal(L, "arg");
}
int
main(int argc, char *argv[])
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_loadbuffer(L, (const char*)%s_lua, %s_lua_len, "%s"))
{
puts(lua_tostring(L, 1));
return 1;
}
createargtable(L, argv, argc, 0);
int err = lua_pcall(L, 0, LUA_MULTRET, 0);
if (err != LUA_OK)
{
puts(lua_tostring(L, 1));
return 1;
}
return 0;
}
]]):format(luaprogramcdata, basename, basename, basename)
local outfile = io.open(("%s.c"):format(infile), "w+")
outfile:write(cprog)
outfile:close()
do
-- statically link Lua, but dynamically link everything else
-- http://lua-users.org/lists/lua-l/2009-05/msg00147.html
local ccformat
= "%s -Os %s.c -rdynamic %s -lm -ldl -o %s"
local ccformat = ccformat:format(CC, infile, libluapath, basename)
print(ccformat)
io.popen(ccformat):read("*all")
end
|
fix warnings
|
fix warnings
|
Lua
|
cc0-1.0
|
ers35/luastatic,ers35/luastatic
|
ea2c17839cb1560df6ef1827291aec4773966547
|
_config/awesome/theme/theme.lua
|
_config/awesome/theme/theme.lua
|
---------------------------
-- Default awesome theme --
---------------------------
theme = {}
theme.font = "sans 8"
theme.bg_normal = "#222222"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.border_width = 1
theme.border_normal = "#000000"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- taglist_[bg|fg]_[focus|urgent|occupied|empty]
-- tasklist_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = "/home/nequi/.config/awesome/theme/taglist/squarefw.png"
theme.taglist_squares_unsel = "/home/nequi/.config/awesome/theme/taglist/squarew.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = "/home/nequi/.config/awesome/theme/submenu.png"
theme.menu_height = 15
theme.menu_width = 100
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
theme.titlebar_close_button_normal = "/home/nequi/.config/awesome/theme/titlebar/close_normal.png"
theme.titlebar_close_button_focus = "/home/nequi/.config/awesome/theme/titlebar/close_focus.png"
theme.titlebar_ontop_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/maximized_focus_active.png"
theme.wallpaper = "/home/nequi/.config/awesome/wallpaper.jpg"
-- You can use your own layout icons like this:
theme.layout_fairh = "/home/nequi/.config/awesome/theme/layouts/fairhw.png"
theme.layout_fairv = "/home/nequi/.config/awesome/theme/layouts/fairvw.png"
theme.layout_floating = "/home/nequi/.config/awesome/theme/layouts/floatingw.png"
theme.layout_magnifier = "/home/nequi/.config/awesome/theme/layouts/magnifierw.png"
theme.layout_max = "/home/nequi/.config/awesome/theme/layouts/maxw.png"
theme.layout_fullscreen = "/home/nequi/.config/awesome/theme/layouts/fullscreenw.png"
theme.layout_tilebottom = "/home/nequi/.config/awesome/theme/layouts/tilebottomw.png"
theme.layout_tileleft = "/home/nequi/.config/awesome/theme/layouts/tileleftw.png"
theme.layout_tile = "/home/nequi/.config/awesome/theme/layouts/tilew.png"
theme.layout_tiletop = "/home/nequi/.config/awesome/theme/layouts/tiletopw.png"
theme.layout_spiral = "/home/nequi/.config/awesome/theme/layouts/spiralw.png"
theme.layout_dwindle = "/home/nequi/.config/awesome/theme/layouts/dwindlew.png"
theme.awesome_icon = "/nix/store/4ifqpn2c7g450h2kam5k33jj832s46ih-awesome-3.5.9/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
---------------------------
-- Default awesome theme --
---------------------------
theme = {}
theme.font = "sans 8"
theme.bg_normal = "#222222"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.border_width = 1
theme.border_normal = "#000000"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- taglist_[bg|fg]_[focus|urgent|occupied|empty]
-- tasklist_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = "/home/nequi/.config/awesome/theme/taglist/squarefw.png"
theme.taglist_squares_unsel = "/home/nequi/.config/awesome/theme/taglist/squarew.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = "/home/nequi/.config/awesome/theme/submenu.png"
theme.menu_height = 15
theme.menu_width = 100
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
theme.titlebar_close_button_normal = "/home/nequi/.config/awesome/theme/titlebar/close_normal.png"
theme.titlebar_close_button_focus = "/home/nequi/.config/awesome/theme/titlebar/close_focus.png"
theme.titlebar_ontop_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = "/home/nequi/.config/awesome/theme/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = "/home/nequi/.config/awesome/theme/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = "/home/nequi/.config/awesome/theme/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = "/home/nequi/.config/awesome/theme/titlebar/maximized_focus_active.png"
theme.wallpaper = "/home/nequi/.config/awesome/wallpaper.jpg"
-- You can use your own layout icons like this:
theme.layout_fairh = "/home/nequi/.config/awesome/theme/layouts/fairhw.png"
theme.layout_fairv = "/home/nequi/.config/awesome/theme/layouts/fairvw.png"
theme.layout_floating = "/home/nequi/.config/awesome/theme/layouts/floatingw.png"
theme.layout_magnifier = "/home/nequi/.config/awesome/theme/layouts/magnifierw.png"
theme.layout_max = "/home/nequi/.config/awesome/theme/layouts/maxw.png"
theme.layout_fullscreen = "/home/nequi/.config/awesome/theme/layouts/fullscreenw.png"
theme.layout_tilebottom = "/home/nequi/.config/awesome/theme/layouts/tilebottomw.png"
theme.layout_tileleft = "/home/nequi/.config/awesome/theme/layouts/tileleftw.png"
theme.layout_tile = "/home/nequi/.config/awesome/theme/layouts/tilew.png"
theme.layout_tiletop = "/home/nequi/.config/awesome/theme/layouts/tiletopw.png"
theme.layout_spiral = "/home/nequi/.config/awesome/theme/layouts/spiralw.png"
theme.layout_dwindle = "/home/nequi/.config/awesome/theme/layouts/dwindlew.png"
theme.awesome_icon = "/nix/store/lqybivxf8dlggp0ysc8kxgs5ppklaw99-awesome-3.5.9/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
Fix awesome path
|
Fix awesome path
|
Lua
|
unlicense
|
NeQuissimus/DevSetup
|
c21f5e502301b9d7957d47595bbf47bcf4dd9f8c
|
src/common/http.lua
|
src/common/http.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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
--]]
Http = newclass "Http"
function Http:init(loader)
self.loader = loader
end
function Http:get(url, headers, extra)
local response, result, code = http.get(url, {
headers = self:_convertHeaders(headers)
})
return response
end
function Http:download(url, outFile, headers)
local response, code = http.download(url, outFile, {
headers = self:_convertHeaders(headers)
})
return response
end
function Http:downloadFromArchive(url, pattern, iszip)
if url:contains(".zip") or iszip then
return self:downloadFromZip(url, pattern)
end
return self:downloadFromTarGz(url, pattern)
end
function Http:downloadFromZipTo(url, destination, pattern)
pattern = iif(pattern == nil and not pattern == false and type(pattern) == "boolean", "*", pattern)
local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip")
self:download(url, zipFile)
zip.extract(zipFile, destination)
if pattern then
return os.matchfiles(path.join(destination, pattern))
else
return destination
end
end
function Http:downloadFromTarGzTo(url, destination, pattern)
pattern = iif(pattern == nil and not pattern == false and type(pattern) == "boolean", "*", pattern)
local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz")
self:download(url, zipFile)
os.executef("tar xzf %s -C %s", zipFile, destination)
if pattern then
return os.matchfiles(path.join(destination, pattern))
else
return destination
end
end
function Http:downloadFromZip(url, pattern)
local dest = path.join(self.loader.temp, os.uuid())
zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest)
return self:downloadFromZipTo(url, dest, pattern)
end
function Http:downloadFromTarGz(url, pattern)
local dest = path.join(self.loader.temp, os.uuid())
zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest)
return self:downloadFromTarGzTo(url, dest, pattern)
end
function Http:_convertHeaders(headers)
headers = iif(headers == nil, { }, headers)
if not zpm.util.isArray(t) then
local nheaders = {}
for k, v in pairs(headers) do
table.insert(nheaders, string.format("%s: %s", k, v))
end
return nheaders
end
return headers
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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
--]]
Http = newclass "Http"
function Http:init(loader)
self.loader = loader
end
function Http:get(url, headers, extra)
local response, result, code = http.get(url, {
headers = self:_convertHeaders(headers)
})
return response
end
function Http:download(url, outFile, headers)
local response, code = http.download(url, outFile, {
headers = self:_convertHeaders(headers)
})
return response
end
function Http:downloadFromArchive(url, pattern, iszip)
if url:contains(".zip") or iszip then
return self:downloadFromZip(url, pattern)
end
return self:downloadFromTarGz(url, pattern)
end
function Http:downloadFromZipTo(url, destination, pattern)
pattern = iif(pattern == nil and type(pattern) ~= "boolean", "*", pattern)
local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip")
self:download(url, zipFile)
zip.extract(zipFile, destination)
if pattern then
return os.matchfiles(path.join(destination, pattern))
else
return destination
end
end
function Http:downloadFromTarGzTo(url, destination, pattern)
pattern = iif(pattern == nil and type(pattern) ~= "boolean", "*", pattern)
local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz")
self:download(url, zipFile)
os.executef("tar xzf %s -C %s", zipFile, destination)
if pattern then
return os.matchfiles(path.join(destination, pattern))
else
return destination
end
end
function Http:downloadFromZip(url, pattern)
local dest = path.join(self.loader.temp, os.uuid())
zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest)
return self:downloadFromZipTo(url, dest, pattern)
end
function Http:downloadFromTarGz(url, pattern)
local dest = path.join(self.loader.temp, os.uuid())
zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest)
return self:downloadFromTarGzTo(url, dest, pattern)
end
function Http:_convertHeaders(headers)
headers = iif(headers == nil, { }, headers)
if not zpm.util.isArray(t) then
local nheaders = {}
for k, v in pairs(headers) do
table.insert(nheaders, string.format("%s: %s", k, v))
end
return nheaders
end
return headers
end
|
Fixed pattern matching
|
Fixed pattern matching
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
c04d57e6411c4d6f3dba1a7d4306f3b42f071277
|
src_trunk/resources/startup/s_startup.lua
|
src_trunk/resources/startup/s_startup.lua
|
-- This is a fix for the global resource not starting up
function resStart(res)
if (res==getThisResource()) then
setTimer(loadGlobal, 1000, 1)
end
end
addEventHandler("onResourceStart", getRootElement(), resStart)
function loadGlobal()
restartResource(getResourceFromName("account-system"))
restartResource(getResourceFromName("interior-system"))
restartResource(getResourceFromName("fuel-system"))
restartResource(getResourceFromName("mods-system"))
restartResource(getResourceFromName("global"))
setTimer(displayCredits, 1000, 1)
setTimer(freeRAM, 3600000, 0)
end
function displayCredits()
exports.irc:sendMessage("-------------------------------------------------------------")
exports.irc:sendMessage("-- VG MTA:RP Script V2 Loaded - By vG.MTA Scripting Team --")
exports.irc:sendMessage("-- www.valhallagaming.net --")
exports.irc:sendMessage("-------------------------------------------------------------")
end
function freeRAM()
restartResource(getResourceFromName("elevator-system"))
restartResource(getResourceFromName("carshop-system"))
restartResource(getResourceFromName("global"))
restartResource(getResourceFromName("paynspray-system"))
restartResource(getResourceFromName("shop-system"))
end
|
-- This is a fix for the global resource not starting up
function resStart(res)
if (res==getThisResource()) then
setTimer(loadGlobal, 1000, 1)
end
end
addEventHandler("onResourceStart", getRootElement(), resStart)
function loadGlobal()
restartResource(getResourceFromName("account-system"))
restartResource(getResourceFromName("interior-system"))
restartResource(getResourceFromName("fuel-system"))
restartResource(getResourceFromName("mods-system"))
restartResource(getResourceFromName("global"))
setTimer(displayCredits, 1000, 1)
setTimer(freeRAM, 3600000, 0)
end
function displayCredits()
exports.irc:sendMessage("-------------------------------------------------------------")
exports.irc:sendMessage("-- VG MTA:RP Script V2 Loaded - By vG.MTA Scripting Team --")
exports.irc:sendMessage("-- www.valhallagaming.net --")
exports.irc:sendMessage("-------------------------------------------------------------")
end
function freeRAM()
restartResource(getResourceFromName("elevator-system"))
restartResource(getResourceFromName("global"))
restartResource(getResourceFromName("paynspray-system"))
restartResource(getResourceFromName("shop-system"))
end
|
Fixed vehicles disappearing
|
Fixed vehicles disappearing
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@589 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
2a9333eb09180edc7ef0e6aeef18020943e9321c
|
src/program/packetblaster/lwaftr/lwaftr.lua
|
src/program/packetblaster/lwaftr/lwaftr.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local engine = require("core.app")
local config = require("core.config")
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local intel10g = require("apps.intel.intel10g")
local intel_app = require("apps.intel.intel_app")
local main = require("core.main")
local S = require("syscall")
local Lwaftrgen = require("apps.test.lwaftr").Lwaftrgen
local Tap = require("apps.tap.tap").Tap
local lib = require("core.lib")
local ffi = require("ffi")
local C = ffi.C
local usage = require("program.packetblaster.lwaftr.README_inc")
local long_opts = {
pci = "p", -- PCI/tap address
duration = "D", -- terminate after n seconds
verbose = "V", -- verbose, display stats
help = "h", -- display help text
size = "S", -- packet size list (defaults to IMIX)
src_mac = "s", -- source ethernet address
dst_mac = "d", -- destination ethernet address
vlan = "v", -- VLAN id
b4 = "b", -- B4 start IPv6_address,IPv4_address,port
aftr = "a", -- fix AFTR public IPv6_address
ipv4 = "I", -- fix public IPv4 address
count = "c", -- how many b4 clients to simulate
rate = "r", -- rate in MPPS (0 => listen only)
v4only = "P", -- generate only public IPv4 traffic
v6only = "E" -- generate only public IPv6 encapsulated traffic
}
local function dir_exists(path)
local stat = S.stat(path)
return stat and stat.isdir
end
function run (args)
local opt = {}
local duration
local c = config.new()
function opt.D (arg)
duration = assert(tonumber(arg), "duration is not a number!")
end
local verbose
function opt.V (arg)
verbose = true
end
function opt.h (arg)
print(usage)
main.exit(0)
end
local sizes = { 64, 64, 64, 64, 64, 64, 64, 594, 594, 594, 1500 }
local sizes_ipv6 = { 104, 104, 104, 104, 104, 104, 104, 634, 634, 634, 1540 }
function opt.S (arg)
sizes = {}
sizes_ipv6 = {}
for size in string.gmatch(arg, "%d+") do
local s = tonumber(size)
if s < 28 then
s = 28
print("Warning: Increasing IPv4 packet size to 28")
end
sizes[#sizes+1] = s
sizes_ipv6[#sizes_ipv6+1] = s + 40
end
end
local src_mac = "00:00:00:00:00:00"
function opt.s (arg) src_mac = arg end
local dst_mac = "00:00:00:00:00:00"
function opt.d (arg) dst_mac = arg end
local b4_ipv6, b4_ipv4, b4_port = "2001:db8::", "10.0.0.0", 1024
function opt.b (arg)
for s in string.gmatch(arg, "[%w.:]+") do
if string.find(s, ":") then
b4_ipv6 = s
elseif string.find(s, '.',1,true) then
b4_ipv4 = s
else
b4_port = assert(tonumber(s), string.format("UDP port %s is not a number!", s))
end
end
end
local public_ipv4 = "8.8.8.8"
function opt.I (arg) public_ipv4 = arg end
local aftr_ipv6 = "2001:db8:ffff::100"
function opt.a (arg) aftr_ipv6 = arg end
local count = 1
function opt.c (arg)
count = assert(tonumber(arg), "count is not a number!")
end
local rate = 1
function opt.r (arg)
rate = assert(tonumber(arg), "rate is not a number!")
end
local pciaddr
function opt.p (arg)
pciaddr = arg
end
local ipv4_only = false
function opt.P () ipv4_only = true end
local ipv6_only = false
function opt.E () ipv6_only = true end
local vlan = nil
function opt.v ()
vlan = assert(tonumber(arg), "duration is not a number!")
end
-- TODO how can I use digit options like -4? function opt.4 isn't valid in lua
args = lib.dogetopt(args, opt, "VD:hS:s:a:d:b:iI:c:r:PEp:v:", long_opts)
if not pciaddr then
print(usage)
main.exit(1)
end
print(string.format("packetblaster lwaftr: Sending %d clients at %.3f MPPS to %s", count, rate, pciaddr))
print()
if not ipv4_only then
print(string.format("IPv6: %s > %s: %s:%d > %s:12345", b4_ipv6, aftr_ipv6, b4_ipv4, b4_port, public_ipv4))
print(" source IPv6 and source IPv4/Port adjusted per client")
print("IPv6 packet sizes: " .. table.concat(sizes_ipv6,","))
end
if not ipv6_only then
print()
print(string.format("IPv4: %s:12345 > %s:%d", public_ipv4, b4_ipv4, b4_port))
print(" destination IPv4 and Port adjusted per client")
print("IPv4 packet sizes: " .. table.concat(sizes,","))
end
print()
if ipv4_only and ipv6_only then
print("Remove options v4only and v6only to generate both")
main.exit(1)
end
config.app(c, "generator", Lwaftrgen, {
sizes = sizes, count = count, aftr_ipv6 = aftr_ipv6, rate = rate,
src_mac = src_mac, dst_mac = dst_mac,
b4_ipv6 = b4_ipv6, b4_ipv4 = b4_ipv4, b4_port = b4_port,
public_ipv4 = public_ipv4,
ipv4_only = ipv4_only, ipv6_only = ipv6_only })
if nil == pciaddr then
print(usage)
main.exit(1)
end
local input, output
if dir_exists(("/sys/devices/virtual/net/%s"):format(pciaddr)) then
config.app(c, "tap", Tap, pciaddr)
input, output = "tap.input", "tap.output"
else
local device_info = pci.device_info(pciaddr)
print(string.format("src_mac=%s", src_mac))
if device_info then
local vmdq = false
if vlan then
vmdq = true
end
config.app(c, "nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = vmdq, vlan = vlan, mtu = 9500})
input, output = "nic.rx", "nic.tx"
else
fatal(("Couldn't find device info for PCI or tap device %s"):format(pciaddr))
end
end
config.link(c, output .. " -> generator.input")
config.link(c, "generator.output -> " .. input)
engine.busywait = true
engine.configure(c)
if verbose then
print ("enabling verbose")
local fn = function ()
print("Transmissions (last 1 sec):")
engine.report_apps()
end
local t = timer.new("report", fn, 1e9, 'repeating')
timer.activate(t)
end
if duration then engine.main({duration=duration})
else engine.main() end
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local engine = require("core.app")
local config = require("core.config")
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local intel10g = require("apps.intel.intel10g")
local intel_app = require("apps.intel.intel_app")
local main = require("core.main")
local S = require("syscall")
local Lwaftrgen = require("apps.test.lwaftr").Lwaftrgen
local Tap = require("apps.tap.tap").Tap
local lib = require("core.lib")
local ffi = require("ffi")
local C = ffi.C
local usage = require("program.packetblaster.lwaftr.README_inc")
local long_opts = {
pci = "p", -- PCI/tap address
duration = "D", -- terminate after n seconds
verbose = "V", -- verbose, display stats
help = "h", -- display help text
size = "S", -- packet size list (defaults to IMIX)
src_mac = "s", -- source ethernet address
dst_mac = "d", -- destination ethernet address
vlan = "v", -- VLAN id
b4 = "b", -- B4 start IPv6_address,IPv4_address,port
aftr = "a", -- fix AFTR public IPv6_address
ipv4 = "I", -- fix public IPv4 address
count = "c", -- how many b4 clients to simulate
rate = "r", -- rate in MPPS (0 => listen only)
v4only = "P", -- generate only public IPv4 traffic
v6only = "E" -- generate only public IPv6 encapsulated traffic
}
local function dir_exists(path)
local stat = S.stat(path)
return stat and stat.isdir
end
function run (args)
local opt = {}
local duration
local c = config.new()
function opt.D (arg)
duration = assert(tonumber(arg), "duration is not a number!")
end
local verbose
function opt.V (arg)
verbose = true
end
function opt.h (arg)
print(usage)
main.exit(0)
end
local sizes = { 64, 64, 64, 64, 64, 64, 64, 594, 594, 594, 1500 }
local sizes_ipv6 = { 104, 104, 104, 104, 104, 104, 104, 634, 634, 634, 1540 }
function opt.S (arg)
sizes = {}
sizes_ipv6 = {}
for size in string.gmatch(arg, "%d+") do
local s = tonumber(size)
if s < 28 then
s = 28
print("Warning: Increasing IPv4 packet size to 28")
end
sizes[#sizes+1] = s
sizes_ipv6[#sizes_ipv6+1] = s + 40
end
end
local src_mac = "00:00:00:00:00:00"
function opt.s (arg) src_mac = arg end
local dst_mac = "00:00:00:00:00:00"
function opt.d (arg) dst_mac = arg end
local b4_ipv6, b4_ipv4, b4_port = "2001:db8::", "10.0.0.0", 1024
function opt.b (arg)
for s in string.gmatch(arg, "[%w.:]+") do
if string.find(s, ":") then
b4_ipv6 = s
elseif string.find(s, '.',1,true) then
b4_ipv4 = s
else
b4_port = assert(tonumber(s), string.format("UDP port %s is not a number!", s))
end
end
end
local public_ipv4 = "8.8.8.8"
function opt.I (arg) public_ipv4 = arg end
local aftr_ipv6 = "2001:db8:ffff::100"
function opt.a (arg) aftr_ipv6 = arg end
local count = 1
function opt.c (arg)
count = assert(tonumber(arg), "count is not a number!")
end
local rate = 1
function opt.r (arg)
rate = assert(tonumber(arg), "rate is not a number!")
end
local pciaddr
function opt.p (arg)
pciaddr = arg
end
local ipv4_only = false
function opt.P () ipv4_only = true end
local ipv6_only = false
function opt.E () ipv6_only = true end
local vlan = nil
function opt.v (arg)
vlan = assert(tonumber(arg), "duration is not a number!")
end
-- TODO how can I use digit options like -4? function opt.4 isn't valid in lua
args = lib.dogetopt(args, opt, "VD:hS:s:a:d:b:iI:c:r:PEp:v:", long_opts)
if not pciaddr then
print(usage)
main.exit(1)
end
print(string.format("packetblaster lwaftr: Sending %d clients at %.3f MPPS to %s", count, rate, pciaddr))
print()
if not ipv4_only then
print(string.format("IPv6: %s > %s: %s:%d > %s:12345", b4_ipv6, aftr_ipv6, b4_ipv4, b4_port, public_ipv4))
print(" source IPv6 and source IPv4/Port adjusted per client")
print("IPv6 packet sizes: " .. table.concat(sizes_ipv6,","))
end
if not ipv6_only then
print()
print(string.format("IPv4: %s:12345 > %s:%d", public_ipv4, b4_ipv4, b4_port))
print(" destination IPv4 and Port adjusted per client")
print("IPv4 packet sizes: " .. table.concat(sizes,","))
end
print()
if ipv4_only and ipv6_only then
print("Remove options v4only and v6only to generate both")
main.exit(1)
end
config.app(c, "generator", Lwaftrgen, {
sizes = sizes, count = count, aftr_ipv6 = aftr_ipv6, rate = rate,
src_mac = src_mac, dst_mac = dst_mac,
b4_ipv6 = b4_ipv6, b4_ipv4 = b4_ipv4, b4_port = b4_port,
public_ipv4 = public_ipv4,
ipv4_only = ipv4_only, ipv6_only = ipv6_only })
if nil == pciaddr then
print(usage)
main.exit(1)
end
local input, output
if dir_exists(("/sys/devices/virtual/net/%s"):format(pciaddr)) then
config.app(c, "tap", Tap, pciaddr)
input, output = "tap.input", "tap.output"
else
local device_info = pci.device_info(pciaddr)
local vmdq = false
if vlan then
vmdq = true
print(string.format("vlan set to %d", vlan))
end
if device_info then
config.app(c, "nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = vmdq, macaddr = src_mac, vlan = vlan, mtu = 9500})
input, output = "nic.rx", "nic.tx"
else
fatal(("Couldn't find device info for PCI or tap device %s"):format(pciaddr))
end
end
config.link(c, output .. " -> generator.input")
config.link(c, "generator.output -> " .. input)
engine.busywait = true
engine.configure(c)
if verbose then
print ("enabling verbose")
local fn = function ()
print("Transmissions (last 1 sec):")
engine.report_apps()
end
local t = timer.new("report", fn, 1e9, 'repeating')
timer.activate(t)
end
if duration then engine.main({duration=duration})
else engine.main() end
end
|
fix vlan support via vmdq
|
fix vlan support via vmdq
|
Lua
|
apache-2.0
|
alexandergall/snabbswitch,kbara/snabb,alexandergall/snabbswitch,eugeneia/snabb,heryii/snabb,kbara/snabb,dpino/snabbswitch,snabbco/snabb,wingo/snabb,alexandergall/snabbswitch,wingo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabb,eugeneia/snabb,dpino/snabb,Igalia/snabbswitch,heryii/snabb,heryii/snabb,wingo/snabb,Igalia/snabb,alexandergall/snabbswitch,wingo/snabbswitch,eugeneia/snabb,snabbco/snabb,dpino/snabbswitch,Igalia/snabb,eugeneia/snabb,heryii/snabb,eugeneia/snabb,snabbco/snabb,mixflowtech/logsensor,wingo/snabb,SnabbCo/snabbswitch,dpino/snabb,heryii/snabb,snabbco/snabb,snabbco/snabb,kbara/snabb,dpino/snabb,mixflowtech/logsensor,dpino/snabb,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,mixflowtech/logsensor,eugeneia/snabbswitch,Igalia/snabbswitch,wingo/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,dpino/snabbswitch,snabbco/snabb,eugeneia/snabb,wingo/snabb,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,heryii/snabb,Igalia/snabbswitch,mixflowtech/logsensor,kbara/snabb,wingo/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,kbara/snabb,snabbco/snabb,eugeneia/snabbswitch,dpino/snabbswitch,kbara/snabb,mixflowtech/logsensor,wingo/snabbswitch,dpino/snabb,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,wingo/snabb,Igalia/snabb
|
641baa4af267928c3af49c47ddfb02e6c4f22104
|
UCDsafeZones/client.lua
|
UCDsafeZones/client.lua
|
local LS = createColTube(1181, -1324, 10, 30, 10) -- All Saints Hospital
local LS2 = createColRectangle(1980, -1454, 125, 80) -- Jefferson Hospital
local SF = createColRectangle(-2745, 576, 135, 100) -- SF Hospital
local LV = createColPolygon(1559, 1801, 1559, 1801, 1558, 1910, 1674, 1910, 1681, 1806) -- LV Hospital
local sZone = {LS, JF, SF1, LV}
function isElementWithinSafeZone(element)
if not isElement(element) then return false end
if (getElementDimension(element) ~= 0) or (getElementInterior(element) ~= 0) then return false end
for i, sZone in pairs(sZone) do
if (isElementWithinColShape(element, sZone)) then return true end
end
return false
end
function controlCheck()
toggleControl("fire", false)
end
function zoneEntry(element, matchingDimension)
if (element ~= localPlayer or not matchingDimension) then return end
exports.UCDdx:new("You have entered a safe zone", 50, 200, 70)
toggleControl("fire", false)
g = Timer(controlCheck, 1500, 0)
end
function zoneExit()
exports.UCDdx:new("You have left a safe zone", 50, 200, 70)
if (not localPlayer.frozen) then
toggleControl("fire", true)
end
if (isTimer(g)) then killTimer(g) end
end
for i, sZone in pairs(sZone) do
addEventHandler("onClientColShapeHit", sZone, zoneEntry)
addEventHandler("onClientColShapeLeave", sZone, zoneExit)
end
function cancelDmg()
if (isElementWithinSafeZone(localPlayer)) then
if (getPlayerWantedLevel(localPlayer) > 0) then return end
cancelEvent()
end
end
addEventHandler("onClientPlayerDamage", root, cancelDmg)
|
local LS = createColTube(1181, -1324, 10, 30, 10) -- All Saints Hospital
local LS2 = createColRectangle(1980, -1454, 125, 80) -- Jefferson Hospital
local SF = createColRectangle(-2745, 576, 135, 100) -- SF Hospital
local LV = createColPolygon(1559, 1801, 1559, 1801, 1558, 1910, 1674, 1910, 1681, 1806) -- LV Hospital
local sZone = {LS, JF, SF1, LV}
function isElementWithinSafeZone(element)
if not isElement(element) then return false end
if (getElementDimension(element) ~= 0) or (getElementInterior(element) ~= 0) then return false end
for i, sZone in pairs(sZone) do
if (isElementWithinColShape(element, sZone)) then return true end
end
return false
end
function controlCheck()
toggleControl("fire", false)
end
function zoneEntry(element, matchingDimension)
if (element ~= localPlayer or not matchingDimension) then return end
exports.UCDdx:new("You have entered a safe zone", 50, 200, 70)
toggleControl("fire", false)
g = Timer(controlCheck, 1500, 0)
end
function zoneExit(element, matchingDimension)
if (element ~= localPlayer or not matchingDimension) then return end
exports.UCDdx:new("You have left a safe zone", 50, 200, 70)
if (not localPlayer.frozen) then
toggleControl("fire", true)
end
if (isTimer(g)) then killTimer(g) end
end
for i, sZone in pairs(sZone) do
addEventHandler("onClientColShapeHit", sZone, zoneEntry)
addEventHandler("onClientColShapeLeave", sZone, zoneExit)
end
function cancelDmg()
if (isElementWithinSafeZone(localPlayer)) then
if (getPlayerWantedLevel(localPlayer) > 0) then return end
cancelEvent()
end
end
addEventHandler("onClientPlayerDamage", root, cancelDmg)
|
UCDsafeZones
|
UCDsafeZones
- Fixed a bug where the exit message would output twice.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
b4bffa1694bbfb800ae904bfccd24f56455dfe30
|
visitor/recurrentvisitorchain.lua
|
visitor/recurrentvisitorchain.lua
|
------------------------------------------------------------------------
--[[ RecurrentVisitorChain ]]--
-- Composite, Visitor, Chain of Responsibility
-- Used by Recurrent Neural Networks to visit sequences of batches
------------------------------------------------------------------------
local RecurrentVisitorChain, parent = torch.class("dp.RecurrentVisitorChain", "dp.VisitorChain")
RecurrentVisitorChain.isRecurrentVisitorChain = true
function RecurrentVisitorChain:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, visit_interval = xlua.unpack(
{config},
'RecurrentVisitorChain',
'A composite chain of visitors used to visit recurrent models. '..
'Subscribes to Mediator channel "doneSequence", which when '..
'published to, forces a visit. Otherwise, visits models every '..
'visit_interval epochs.',
{arg='visit_interval', type='number', req=true,
help='model is visited every visit_interval epochs'}
)
config.name = config.name or 'recurrentvisitorchain'
parent.__init(self, config)
self._visit_interval = visit_interval
self._n_visit = 0
end
function RecurrentVisitorChain:setup(config)
parent.setup(self, config)
-- published by SentenceSampler
self._mediator:subscribe('doneSequence', self, 'doneSequence')
end
function RecurrentVisitorChain:doneSequence()
self._force_visit = true
end
function RecurrentVisitorChain:_visitModel(model)
self._n_visit = self._n_visit + 1
if self._force_visit or self._n_visit == self._visit_interval then
parent._visitModel(self, model)
self._force_visit = false
end
end
|
------------------------------------------------------------------------
--[[ RecurrentVisitorChain ]]--
-- Composite, Visitor, Chain of Responsibility
-- Used by Recurrent Neural Networks to visit sequences of batches
------------------------------------------------------------------------
local RecurrentVisitorChain, parent = torch.class("dp.RecurrentVisitorChain", "dp.VisitorChain")
RecurrentVisitorChain.isRecurrentVisitorChain = true
function RecurrentVisitorChain:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, visit_interval = xlua.unpack(
{config},
'RecurrentVisitorChain',
'A composite chain of visitors used to visit recurrent models. '..
'Subscribes to Mediator channel "doneSequence", which when '..
'published to, forces a visit. Otherwise, visits models every '..
'visit_interval epochs.',
{arg='visit_interval', type='number', req=true,
help='model is visited every visit_interval epochs'}
)
config.name = config.name or 'recurrentvisitorchain'
parent.__init(self, config)
self._visit_interval = visit_interval
self._force_visit = false
self._n_visit = 0
end
function RecurrentVisitorChain:setup(config)
parent.setup(self, config)
-- published by SentenceSampler
self._mediator:subscribe('doneSequence', self, 'doneSequence')
self._mediator:subscribe('doneEpoch', self, 'doneEpoch')
end
function RecurrentVisitorChain:doneSequence()
self._force_visit = true
end
function RecurrentVisitorChain:doneEpoch()
self._n_visit = 0
end
function RecurrentVisitorChain:_visitModel(model)
self._n_visit = self._n_visit + 1
if self._force_visit or self._n_visit == self._visit_interval then
parent._visitModel(self, model)
self._n_visit = 0
self._force_visit = false
end
end
|
RecurrentVisitorChain fix
|
RecurrentVisitorChain fix
|
Lua
|
bsd-3-clause
|
eulerreich/dp,kracwarlock/dp,fiskio/dp,nicholas-leonard/dp,rickyHong/dptorchLib,jnhwkim/dp,sagarwaghmare69/dp
|
6d44027431cc689e975bd78d1a956b23839a4996
|
util/multitable.lua
|
util/multitable.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local select = select;
local t_insert = table.insert;
local unpack, pairs, next, type = unpack, pairs, next, type;
module "multitable"
local function get(self, ...)
local t = self.data;
for n = 1,select('#', ...) do
t = t[select(n, ...)];
if not t then break; end
end
return t;
end
local function add(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-1 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t_insert(t, (select(count, ...)));
end
local function set(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-2 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t[(select(count-1, ...))] = (select(count, ...));
end
local function r(t, n, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
t[k] = nil;
return;
end
if k then
local v = t[k];
if v then
r(v, n+1, _end, ...);
if not next(v) then
t[k] = nil;
end
end
else
for _,b in pairs(t) do
r(b, n+1, _end, ...);
if not next(b) then
t[_] = nil;
end
end
end
end
local function remove(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
r(self.data, 1, _end, ...);
end
local function s(t, n, results, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
if k == nil then
for _, v in pairs(t) do
t_insert(results, v);
end
else
t_insert(results, t[k]);
end
return;
end
if k then
local v = t[k];
if v then
s(v, n+1, results, _end, ...);
end
else
for _,b in pairs(t) do
s(b, n+1, results, _end, ...);
end
end
end
-- Search for keys, nil == wildcard
local function search(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
local results = {};
s(self.data, 1, results, _end, ...);
return results;
end
-- Append results to an existing list
local function search_add(self, results, ...)
if not results then results = {}; end
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
s(self.data, 1, results, _end, ...);
return results;
end
function iter(self, ...)
local query = { ... };
local maxdepth = select("#", ...);
local stack = { self.data };
local keys = { };
local function it(self)
local depth = #stack;
local key = next(stack[depth], keys[depth]);
if key == nil then -- Go up the stack
stack[depth], keys[depth] = nil, nil;
if depth > 1 then
return it(self);
end
return; -- The end
else
keys[depth] = key;
end
local value = stack[depth][key];
if depth == maxdepth then -- Result
local result = {}; -- Collect keys forming path to result
for i = 1, depth do
result[i] = keys[i];
end
return unpack(result, 1, depth);
else
if (query[depth] == nil or key == query[depth]) and type(value) == "table" then -- Descend
t_insert(stack, value);
end
return it(self);
end
end;
return it, self;
end
function new()
return {
data = {};
get = get;
add = add;
set = set;
remove = remove;
search = search;
search_add = search_add;
iter = iter;
};
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local select = select;
local t_insert = table.insert;
local unpack, pairs, next, type = unpack, pairs, next, type;
module "multitable"
local function get(self, ...)
local t = self.data;
for n = 1,select('#', ...) do
t = t[select(n, ...)];
if not t then break; end
end
return t;
end
local function add(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-1 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t_insert(t, (select(count, ...)));
end
local function set(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-2 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t[(select(count-1, ...))] = (select(count, ...));
end
local function r(t, n, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
t[k] = nil;
return;
end
if k then
local v = t[k];
if v then
r(v, n+1, _end, ...);
if not next(v) then
t[k] = nil;
end
end
else
for _,b in pairs(t) do
r(b, n+1, _end, ...);
if not next(b) then
t[_] = nil;
end
end
end
end
local function remove(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
r(self.data, 1, _end, ...);
end
local function s(t, n, results, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
if k == nil then
for _, v in pairs(t) do
t_insert(results, v);
end
else
t_insert(results, t[k]);
end
return;
end
if k then
local v = t[k];
if v then
s(v, n+1, results, _end, ...);
end
else
for _,b in pairs(t) do
s(b, n+1, results, _end, ...);
end
end
end
-- Search for keys, nil == wildcard
local function search(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
local results = {};
s(self.data, 1, results, _end, ...);
return results;
end
-- Append results to an existing list
local function search_add(self, results, ...)
if not results then results = {}; end
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
s(self.data, 1, results, _end, ...);
return results;
end
function iter(self, ...)
local query = { ... };
local maxdepth = select("#", ...);
local stack = { self.data };
local keys = { };
local function it(self)
local depth = #stack;
local key = next(stack[depth], keys[depth]);
if key == nil then -- Go up the stack
stack[depth], keys[depth] = nil, nil;
if depth > 1 then
return it(self);
end
return; -- The end
else
keys[depth] = key;
end
local value = stack[depth][key];
if query[depth] == nil or key == query[depth] then
if depth == maxdepth then -- Result
local result = {}; -- Collect keys forming path to result
for i = 1, depth do
result[i] = keys[i];
end
result[depth+1] = value;
return unpack(result, 1, depth+1);
elseif type(value) == "table" then
t_insert(stack, value); -- Descend
end
end
return it(self);
end;
return it, self;
end
function new()
return {
data = {};
get = get;
add = add;
set = set;
remove = remove;
search = search;
search_add = search_add;
iter = iter;
};
end
return _M;
|
util.multitable: Some fixes for iter()... always match against query, and pass value after path results
|
util.multitable: Some fixes for iter()... always match against query, and pass value after path results
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
d1c65f95bd970cda79895812b248907723a2b1e1
|
extensions/dialog/init.lua
|
extensions/dialog/init.lua
|
--- === hs.dialog ===
---
--- A collection of useful dialog boxes, alerts and panels for user interaction.
--- === hs.dialog.font ===
---
--- A panel that allows users to select font styles.
--- === hs.dialog.color ===
---
--- A panel that allows users to select a color.
local USERDATA_TAG = "hs.dialog"
local module = require(USERDATA_TAG..".internal")
local color = require("hs.drawing.color")
-- Private Variables & Methods -----------------------------------------
-- Public Interface ------------------------------------------------------
module.font.panelModes = ls.makeConstantsTable(module.font.panelModes)
color.panel = module.color
--- hs.dialog.alert(rect, callbackFn, message, [informativeText], [buttonOne], [buttonTwo], [style]) -> string
--- Function
--- Displays a simple non-blocking dialog box using `NSAlert` and a hidden `hs.webview` that's automatically destroyed when the alert is closed.
---
--- Parameters:
--- * x - A number containing the horizontal co-ordinate of the top-left point of the dialog box.
--- * y - A number containing the vertical co-ordinate of the top-left point of the dialog box.
--- * callbackFn - The callback function that's called when a button is pressed.
--- * message - The message text to display.
--- * [informativeText] - Optional informative text to display.
--- * [buttonOne] - An optional value for the first button as a string. Defaults to "OK".
--- * [buttonTwo] - An optional value for the second button as a string. If `nil` is used, no second button will be displayed.
--- * [style] - An optional style of the dialog box as a string. Defaults to "warning".
---
--- Returns:
--- * nil
---
--- Notes:
--- * The optional values must be entered in order (i.e. you can't supply `style` without also supplying `buttonOne` and `buttonTwo`).
--- * [style] can be "warning", "informational" or "critical". If something other than these string values is given, it will use "informational".
--- * Example:
--- ```testCallbackFn = function(result) print("Callback Result: " .. result) end
--- hs.dialog.alert(100, 100, testCallbackFn, "Message", "Informative Text", "Button One", "Button Two", "NSCriticalAlertStyle")
--- hs.dialog.alert(200, 200, testCallbackFn, "Message", "Informative Text", "Single Button")```
function module.alert(x, y, callback, ...)
local rect = {}
if type(x) == "number" then rect.x = x end
if type(y) == "number" then rect.y = y end
rect.h, rect.w = 10, 10 -- Small enough to be hidden by the alert panel
local wv = hs.webview.new(rect):show()
hs.dialog.webviewAlert(wv, function(...)
wv:delete()
callback(...)
end, ...)
end
-- Return Module Object --------------------------------------------------
return module
|
--- === hs.dialog ===
---
--- A collection of useful dialog boxes, alerts and panels for user interaction.
--- === hs.dialog.font ===
---
--- A panel that allows users to select font styles.
--- === hs.dialog.color ===
---
--- A panel that allows users to select a color.
local USERDATA_TAG = "hs.dialog"
local module = require(USERDATA_TAG..".internal")
local color = require("hs.drawing.color")
local styledtext = require("hs.styledtext")
-- Private Variables & Methods -----------------------------------------
-- Public Interface ------------------------------------------------------
module.font.panelModes = ls.makeConstantsTable(module.font.panelModes)
color.panel = module.color
--- hs.dialog.alert(rect, callbackFn, message, [informativeText], [buttonOne], [buttonTwo], [style]) -> string
--- Function
--- Displays a simple non-blocking dialog box using `NSAlert` and a hidden `hs.webview` that's automatically destroyed when the alert is closed.
---
--- Parameters:
--- * x - A number containing the horizontal co-ordinate of the top-left point of the dialog box.
--- * y - A number containing the vertical co-ordinate of the top-left point of the dialog box.
--- * callbackFn - The callback function that's called when a button is pressed.
--- * message - The message text to display.
--- * [informativeText] - Optional informative text to display.
--- * [buttonOne] - An optional value for the first button as a string. Defaults to "OK".
--- * [buttonTwo] - An optional value for the second button as a string. If `nil` is used, no second button will be displayed.
--- * [style] - An optional style of the dialog box as a string. Defaults to "warning".
---
--- Returns:
--- * nil
---
--- Notes:
--- * The optional values must be entered in order (i.e. you can't supply `style` without also supplying `buttonOne` and `buttonTwo`).
--- * [style] can be "warning", "informational" or "critical". If something other than these string values is given, it will use "informational".
--- * Example:
--- ```testCallbackFn = function(result) print("Callback Result: " .. result) end
--- hs.dialog.alert(100, 100, testCallbackFn, "Message", "Informative Text", "Button One", "Button Two", "NSCriticalAlertStyle")
--- hs.dialog.alert(200, 200, testCallbackFn, "Message", "Informative Text", "Single Button")```
function module.alert(x, y, callback, ...)
local rect = {}
if type(x) == "number" then rect.x = x end
if type(y) == "number" then rect.y = y end
rect.h, rect.w = 10, 10 -- Small enough to be hidden by the alert panel
local wv = hs.webview.new(rect):show()
hs.dialog.webviewAlert(wv, function(...)
wv:delete()
callback(...)
end, ...)
end
-- Return Module Object --------------------------------------------------
return module
|
Bug Fix
|
Bug Fix
|
Lua
|
mit
|
Habbie/hammerspoon,bradparks/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon
|
448fb5c69799ac54e946fe1f8a2de2539d8cdbd8
|
modules/android/tests/test_android_project.lua
|
modules/android/tests/test_android_project.lua
|
local p = premake
local suite = test.declare("test_android_project")
local vc2010 = p.vstudio.vc2010
local android = p.modules.android
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2015")
wks, prj = test.createWorkspace()
end
local function prepare()
system "android"
local cfg = test.getconfig(prj, "Debug", platform)
vc2010.clCompile(cfg)
end
local function preparePropertyGroup()
system "android"
local cfg = test.getconfig(prj, "Debug", platform)
vc2010.propertyGroup(cfg)
android.androidApplicationType(cfg)
end
function suite.minVisualStudioVersion_14()
preparePropertyGroup()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'">
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>2.0</ApplicationTypeRevision>]]
end
function suite.minVisualStudioVersion_15()
p.action.set("vs2017")
preparePropertyGroup()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'">
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>3.0</ApplicationTypeRevision>]]
end
function suite.minVisualStudioVersion_16()
p.action.set("vs2019")
preparePropertyGroup()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'">
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>16.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>3.0</ApplicationTypeRevision>]]
end
function suite.noOptions()
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.rttiOff()
rtti "Off"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.rttiOn()
rtti "On"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
]]
end
function suite.exceptionHandlingOff()
exceptionhandling "Off"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.exceptionHandlingOn()
exceptionhandling "On"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<ExceptionHandling>Enabled</ExceptionHandling>
]]
end
function suite.cppdialect_cpp11()
cppdialect "C++11"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++11</CppLanguageStandard>
]]
end
function suite.cppdialect_cpp14()
cppdialect "C++14"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++1y</CppLanguageStandard>
]]
end
function suite.cppdialect_cpp17()
cppdialect "C++17"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++1z</CppLanguageStandard>
]]
end
|
local p = premake
local suite = test.declare("test_android_project")
local vc2010 = p.vstudio.vc2010
local android = p.modules.android
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2015")
system "android"
wks, prj = test.createWorkspace()
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
vc2010.clCompile(cfg)
end
local function prepareGlobals()
prj = test.getproject(wks, 1)
vc2010.globals(prj)
end
function suite.minVisualStudioVersion_14()
prepareGlobals()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid>
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>2.0</ApplicationTypeRevision>]]
end
function suite.minVisualStudioVersion_15()
p.action.set("vs2017")
prepareGlobals()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid>
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>3.0</ApplicationTypeRevision>]]
end
function suite.minVisualStudioVersion_16()
p.action.set("vs2019")
prepareGlobals()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid>
<Keyword>Android</Keyword>
<RootNamespace>MyProject</RootNamespace>
<MinimumVisualStudioVersion>16.0</MinimumVisualStudioVersion>
<ApplicationType>Android</ApplicationType>
<ApplicationTypeRevision>3.0</ApplicationTypeRevision>]]
end
function suite.noOptions()
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.rttiOff()
rtti "Off"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.rttiOn()
rtti "On"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
]]
end
function suite.exceptionHandlingOff()
exceptionhandling "Off"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
</ClCompile>]]
end
function suite.exceptionHandlingOn()
exceptionhandling "On"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<ExceptionHandling>Enabled</ExceptionHandling>
]]
end
function suite.cppdialect_cpp11()
cppdialect "C++11"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++11</CppLanguageStandard>
]]
end
function suite.cppdialect_cpp14()
cppdialect "C++14"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++1y</CppLanguageStandard>
]]
end
function suite.cppdialect_cpp17()
cppdialect "C++17"
prepare()
test.capture [[
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<Optimization>Disabled</Optimization>
<CppLanguageStandard>c++1z</CppLanguageStandard>
]]
end
|
Fixed inconsistencies in Android VS project test
|
Fixed inconsistencies in Android VS project test
|
Lua
|
bsd-3-clause
|
dcourtois/premake-core,noresources/premake-core,dcourtois/premake-core,starkos/premake-core,starkos/premake-core,premake/premake-core,premake/premake-core,dcourtois/premake-core,starkos/premake-core,starkos/premake-core,dcourtois/premake-core,noresources/premake-core,noresources/premake-core,noresources/premake-core,noresources/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,noresources/premake-core,premake/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,premake/premake-core,premake/premake-core,dcourtois/premake-core
|
1fb4780c1d63e667a7693463df2cd7322fe6f3f8
|
packages/lime-webui/src/model/essentials.lua
|
packages/lime-webui/src/model/essentials.lua
|
--[[
Copyright (C) 2016 Libre-Mesh.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
-- Libre-Mesh.org config
require("luci.sys")
local lime = Map("lime", "Libre-Mesh")
local config = require("lime.config")
-- Create sections
local system = lime:section(NamedSection, "system", "lime","System","System")
system.addremove = false
local network = lime:section(NamedSection, "network", "lime","Network","Network")
network.addremove = false
local wifi = lime:section(NamedSection, "wifi","WiFi","WiFi")
wifi.addremove = false
-- hostname
local hostname = system:option(Value,"hostname",translate("Hostname"),
translate("Name for this node"))
hostname.default = config.get("system","hostname")
-- network
local ipv4 = network:option(Value,"main_ipv4_address",translate("Main IPv4"),
translate("The main IPv4 configured for this node, with slash notation (for ex. 1.2.3.4/24)"))
ipv4.default = config.get("network","main_ipv4_address")
ipv4.optional = true
local ipv6 = network:option(Value,"main_ipv6_address",translate("Main IPv6"),
translate("The main IPv6 configured for this node, with slash notation (for ex. 2001:db8::1/64)"))
ipv6.default = config.get("network","main_ipv6_address")
ipv6.optional = true
-- wifi
local ap_ssid = wifi:option(Value,"ap_ssid",translate("Network SSID"),
translate("Access Point ESSID (usually name of your network)"))
ap_ssid.default = config.get("wifi","ap_ssid")
ap_ssid.optional = true
local ch_2 = wifi:option(Value,"channel_2ghz",translate("Channel 2.4 GHz"),
translate("Default channel used for 2.4 GHz radios"))
ch_2.default = config.get("wifi","channel_2ghz")
ch_2.optional = true
local ch_5 = wifi:option(Value,"channel_5ghz",translate("Channel 5 GHz"),
translate("Default channel used for 5 GHz radios"))
ch_5.default = config.get("wifi","channel_5ghz")
ch_5.optional = true
local country = wifi:option(Value,"country",translate("Country code"),
translate("Country code used for WiFi radios"))
country.default = config.get("wifi","country")
country.optional = true
local bssid = wifi:option(Value,"adhoc_bssid",translate("Mesh BSSID"),
translate("The BSSID (WiFi network identifier) used for the mesh network"))
bssid.default = config.get("wifi","adhoc_bssid")
bssid.optional = true
-- commit
function lime.on_commit(self,map)
luci.sys.call('(/usr/bin/lime-config > /tmp/lime-config.log 2>&1 && reload_config) &')
luci.sys.call('((/etc/init.d/bmx6 restart &> /dev/null)&)')
end
-- LibreMap.org config
limap = Map("libremap", "Libre-Map")
-- main settings
local settings = limap:section(NamedSection, "settings", "libremap",translate("General"),translate("General"))
settings.addremove = false
local com = settings:option(Value,"community",translate("Community name"),
translate("The name of your network community"))
com.default = config.get("wifi","ap_ssid")
-- location
local loc = limap:section(NamedSection, "location", "plugin",translate("Location"),translate("Map location"))
loc:option(Value,"latitude",translate("Latitude"),
translate("Latitude (this can be also configured in location tab)"))
loc:option(Value,"longitude",translate("Longitude"),
translate("Longitude (this can be also configured in location tab)"))
-- contact
local contact = limap:section(NamedSection, "contact", "plugin",translate("Contact"),translate("Contact information"))
contact:option(Value,"name",translate("Name"),
translate("Your name or alias (not required)"))
contact:option(Value,"email",translate("Email"),
translate("Your email (not required)"))
-- commit
function limap.on_commit(self,map)
luci.sys.call('/usr/sbin/libremap-agent &')
end
return lime,limap
|
--[[
Copyright (C) 2016 Libre-Mesh.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
-- Libre-Mesh.org config
require("luci.sys")
local lime = Map("lime", "Libre-Mesh")
local config = require("lime.config")
-- Create sections
local system = lime:section(NamedSection, "system", "lime","System","System")
system.addremove = false
local network = lime:section(NamedSection, "network", "lime","Network","Network")
network.addremove = false
local wifi = lime:section(NamedSection, "wifi","WiFi","WiFi")
wifi.addremove = false
-- hostname
local hostname = system:option(Value,"hostname",translate("Hostname"),
translate("Name for this node"))
hostname.default = config.get("system","hostname")
-- network
local ipv4 = network:option(Value,"main_ipv4_address",translate("Main IPv4"),
translate("The main IPv4 configured for this node, with slash notation (for ex. 1.2.3.4/24)"))
ipv4.default = config.get("network","main_ipv4_address")
ipv4.optional = true
local ipv6 = network:option(Value,"main_ipv6_address",translate("Main IPv6"),
translate("The main IPv6 configured for this node, with slash notation (for ex. 2001:db8::1/64)"))
ipv6.default = config.get("network","main_ipv6_address")
ipv6.optional = true
-- wifi
local ap_ssid = wifi:option(Value,"ap_ssid",translate("Network SSID"),
translate("Access Point ESSID (usually name of your network)"))
ap_ssid.default = config.get("wifi","ap_ssid")
ap_ssid.optional = true
local ch_2 = wifi:option(Value,"channel_2ghz",translate("Channel 2.4 GHz"),
translate("Default channel used for 2.4 GHz radios"))
ch_2.default = config.get("wifi","channel_2ghz")
ch_2.optional = true
local ch_5 = wifi:option(Value,"channel_5ghz",translate("Channel 5 GHz"),
translate("Default channel used for 5 GHz radios"))
ch_5.default = config.get("wifi","channel_5ghz")
ch_5.optional = true
local country = wifi:option(Value,"country",translate("Country code"),
translate("Country code used for WiFi radios"))
country.default = config.get("wifi","country")
country.optional = true
local bssid = wifi:option(Value,"adhoc_bssid",translate("Mesh BSSID"),
translate("The BSSID (WiFi network identifier) used for the mesh network"))
bssid.default = config.get("wifi","adhoc_bssid")
bssid.optional = true
-- commit
function lime.on_commit(self,map)
luci.sys.call('(/usr/bin/lime-config > /tmp/lime-config.log 2>&1 && reboot) &')
end
-- LibreMap.org config
limap = Map("libremap", "Libre-Map")
-- main settings
local settings = limap:section(NamedSection, "settings", "libremap",translate("General"),translate("General"))
settings.addremove = false
local com = settings:option(Value,"community",translate("Community name"),
translate("The name of your network community"))
com.default = config.get("wifi","ap_ssid")
-- location
local loc = limap:section(NamedSection, "location", "plugin",translate("Location"),translate("Map location"))
loc:option(Value,"latitude",translate("Latitude"),
translate("Latitude (this can be also configured in location tab)"))
loc:option(Value,"longitude",translate("Longitude"),
translate("Longitude (this can be also configured in location tab)"))
-- contact
local contact = limap:section(NamedSection, "contact", "plugin",translate("Contact"),translate("Contact information"))
contact:option(Value,"name",translate("Name"),
translate("Your name or alias (not required)"))
contact:option(Value,"email",translate("Email"),
translate("Your email (not required)"))
-- commit
function limap.on_commit(self,map)
luci.sys.call('/usr/sbin/libremap-agent &')
end
return lime,limap
|
lime-webui: fallback to doing 'reboot' on Save & Apply, since 'reload_config' triggers bugs
|
lime-webui: fallback to doing 'reboot' on Save & Apply, since 'reload_config' triggers bugs
|
Lua
|
agpl-3.0
|
p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
1596afd2ee226b1994f5429a7a892e052dfa052e
|
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+", "-")
artist = grl.encode(artist)
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
title = grl.encode(title)
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 = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.debug ("This Lyrics do not match our parser")
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
|
--[[
* 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+", "-")
artist = grl.encode(artist)
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
title = grl.encode(title)
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".->(.-)<p class="writers"'
local noise_array = {
{ noise = '<div id="mid%-song%-discussion".->.+</div>\n<p', sub = "<p" },
{ noise = '</div>', sub = "" },
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.debug ("This Lyrics do not match our parser")
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: fix html parser
|
metrolyrics: fix html parser
Seems that in some lyrics a new <div></div> can be included with some
info. That was breaking the html parser.
Instead on relying on ending </div> for the lyric, let's use something
else that is present and not so common (<p class="writers") as ending
point for the lyrics and remove what is not interesting for us.
https://bugzilla.gnome.org/show_bug.cgi?id=770806
|
Lua
|
lgpl-2.1
|
GNOME/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins
|
37f95326496dc8b645d18dbda08adb4bd60d8f94
|
lib/core/src/quanta/core/vessel/Vessel.lua
|
lib/core/src/quanta/core/vessel/Vessel.lua
|
u8R""__RAW_STRING__(
local U = require "togo.utility"
local FS = require "togo.filesystem"
local T = require "Quanta.Time"
local M = U.module(...)
local function check_initialized()
U.assertl(1, M.initialized, "Quanta.Vessel has not been initialized")
end
function M.active_bucket()
return M.work_local and "local" or "vessel"
end
function M.path(...)
check_initialized()
return U.join_paths(M.root, ...)
end
function M.log_path(...) return M.path(M.active_bucket(), "log", ...) end
function M.sys_path(...) return M.path(M.active_bucket(), "sys", ...) end
function M.data_path(...) return M.path(M.active_bucket(), "data", ...) end
function M.script_path(...) return M.path(M.active_bucket(), "scripts", ...) end
function M.sublime_path(...) return M.path(M.active_bucket(), "sublime", ...) end
function M.data_chrono_path(...) return M.data_path("chrono", ...) end
function M.tracker_path(date)
check_initialized()
if date ~= nil then
U.type_assert(date, "userdata")
local y, m, d = T.date_utc(date)
return M.data_chrono_path(string.format("%d/%d/%d.q", y, m, d))
else
local slug = nil
local f = io.open(M.data_chrono_path("active"), "r")
if f then
slug = f:read("*l")
f:close()
end
U.assert(slug ~= nil, "failed to read active tracker date")
return M.data_chrono_path(slug .. ".q")
end
end
function M.set_work_local(work_local)
check_initialized()
U.type_assert(work_local, "boolean")
M.work_local = work_local
end
function M.init(root_path, work_local)
local root = U.type_assert(root_path, "string", true) or os.getenv("QUANTA_ROOT")
U.assert(root, "vessel root not provided and not found ($QUANTA_ROOT)")
M.initialized = true
M.root = root
M.set_work_local(U.optional(work_local, true))
U.assert(FS.is_directory(M.root))
end
return M
)"__RAW_STRING__"
|
u8R""__RAW_STRING__(
local U = require "togo.utility"
local FS = require "togo.filesystem"
local T = require "Quanta.Time"
require "Quanta.Time.Gregorian"
local M = U.module(...)
local function check_initialized()
U.assertl(1, M.initialized, "Quanta.Vessel has not been initialized")
end
function M.active_bucket()
return M.work_local and "local" or "vessel"
end
function M.path(...)
check_initialized()
return U.join_paths(M.root, ...)
end
function M.log_path(...) return M.path(M.active_bucket(), "log", ...) end
function M.sys_path(...) return M.path(M.active_bucket(), "sys", ...) end
function M.data_path(...) return M.path(M.active_bucket(), "data", ...) end
function M.script_path(...) return M.path(M.active_bucket(), "scripts", ...) end
function M.sublime_path(...) return M.path(M.active_bucket(), "sublime", ...) end
function M.data_chrono_path(...) return M.data_path("chrono", ...) end
function M.tracker_path(date)
check_initialized()
if date ~= nil then
U.type_assert(date, "userdata")
local y, m, d = T.G.date_utc(date)
return M.data_chrono_path(string.format("%04d/%02d/%02d.q", y, m, d))
else
local slug = nil
local f = io.open(M.data_chrono_path("active"), "r")
if f then
slug = f:read("*l")
f:close()
end
U.assert(slug ~= nil, "failed to read active tracker date")
return M.data_chrono_path(slug .. ".q")
end
end
function M.set_work_local(work_local)
check_initialized()
U.type_assert(work_local, "boolean")
M.work_local = work_local
end
function M.init(root_path, work_local)
local root = U.type_assert(root_path, "string", true) or os.getenv("QUANTA_ROOT")
U.assert(root, "vessel root not provided and not found ($QUANTA_ROOT)")
M.initialized = true
M.root = root
M.set_work_local(U.optional(work_local, true))
U.assert(FS.is_directory(M.root))
end
return M
)"__RAW_STRING__"
|
lib/core/vessel/Vessel.lua: tracker_path(): fixed path formatting; fixed time calls.
|
lib/core/vessel/Vessel.lua: tracker_path(): fixed path formatting; fixed time calls.
|
Lua
|
mit
|
komiga/quanta,komiga/quanta,komiga/quanta
|
a8a72c1ec8bc0625dad70f22ec85ff7e9e477074
|
libs/web/luasrc/config.lua
|
libs/web/luasrc/config.lua
|
--[[
LuCI - Configuration
Description:
Some LuCI configuration values read from uci file "luci"
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 util = require "luci.util"
local pcall = pcall
local require = require
module "luci.config"
pcall(function()
setmetatable(_M, {__index=require "luci.model.uci".cursor():get_all("luci")})
end)
|
--[[
LuCI - Configuration
Description:
Some LuCI configuration values read from uci file "luci"
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.config",
function(m)
if pcall(require, "luci.model.uci") then
setmetatable(m, {__index = luci.model.uci.cursor():get_all("luci")})
end
end)
|
Fixed luci.config
|
Fixed luci.config
|
Lua
|
apache-2.0
|
Noltari/luci,lcf258/openwrtcn,bright-things/ionic-luci,david-xiao/luci,schidler/ionic-luci,mumuqz/luci,keyidadi/luci,LuttyYang/luci,sujeet14108/luci,shangjiyu/luci-with-extra,cshore/luci,lbthomsen/openwrt-luci,openwrt/luci,RuiChen1113/luci,aa65535/luci,sujeet14108/luci,rogerpueyo/luci,bittorf/luci,forward619/luci,kuoruan/lede-luci,palmettos/test,chris5560/openwrt-luci,ollie27/openwrt_luci,MinFu/luci,obsy/luci,nwf/openwrt-luci,slayerrensky/luci,male-puppies/luci,Noltari/luci,chris5560/openwrt-luci,teslamint/luci,deepak78/new-luci,openwrt-es/openwrt-luci,RuiChen1113/luci,cappiewu/luci,oyido/luci,bright-things/ionic-luci,Wedmer/luci,teslamint/luci,Hostle/luci,nwf/openwrt-luci,taiha/luci,jchuang1977/luci-1,openwrt/luci,shangjiyu/luci-with-extra,cshore/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,taiha/luci,male-puppies/luci,Noltari/luci,bittorf/luci,artynet/luci,openwrt-es/openwrt-luci,openwrt/luci,thess/OpenWrt-luci,dismantl/luci-0.12,jorgifumi/luci,david-xiao/luci,remakeelectric/luci,RuiChen1113/luci,wongsyrone/luci-1,urueedi/luci,hnyman/luci,lbthomsen/openwrt-luci,oneru/luci,urueedi/luci,LuttyYang/luci,forward619/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,NeoRaider/luci,jlopenwrtluci/luci,male-puppies/luci,thess/OpenWrt-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,oneru/luci,tcatm/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,cappiewu/luci,lbthomsen/openwrt-luci,remakeelectric/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,ollie27/openwrt_luci,teslamint/luci,artynet/luci,jlopenwrtluci/luci,palmettos/cnLuCI,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,taiha/luci,sujeet14108/luci,sujeet14108/luci,thesabbir/luci,ollie27/openwrt_luci,opentechinstitute/luci,Wedmer/luci,daofeng2015/luci,aa65535/luci,palmettos/test,bittorf/luci,remakeelectric/luci,florian-shellfire/luci,remakeelectric/luci,mumuqz/luci,tcatm/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,obsy/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,marcel-sch/luci,taiha/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,deepak78/new-luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,kuoruan/lede-luci,urueedi/luci,joaofvieira/luci,MinFu/luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,oyido/luci,lbthomsen/openwrt-luci,daofeng2015/luci,NeoRaider/luci,mumuqz/luci,maxrio/luci981213,joaofvieira/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,thesabbir/luci,obsy/luci,openwrt-es/openwrt-luci,Hostle/luci,zhaoxx063/luci,tobiaswaldvogel/luci,ff94315/luci-1,sujeet14108/luci,nmav/luci,keyidadi/luci,oyido/luci,forward619/luci,shangjiyu/luci-with-extra,ff94315/luci-1,ff94315/luci-1,zhaoxx063/luci,maxrio/luci981213,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,dismantl/luci-0.12,openwrt-es/openwrt-luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,maxrio/luci981213,Hostle/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,chris5560/openwrt-luci,ollie27/openwrt_luci,thess/OpenWrt-luci,daofeng2015/luci,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,MinFu/luci,tobiaswaldvogel/luci,cshore/luci,nmav/luci,nmav/luci,obsy/luci,schidler/ionic-luci,remakeelectric/luci,palmettos/cnLuCI,zhaoxx063/luci,shangjiyu/luci-with-extra,slayerrensky/luci,forward619/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,marcel-sch/luci,kuoruan/lede-luci,RuiChen1113/luci,oyido/luci,deepak78/new-luci,maxrio/luci981213,cshore/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,opentechinstitute/luci,bright-things/ionic-luci,teslamint/luci,Sakura-Winkey/LuCI,aa65535/luci,MinFu/luci,nwf/openwrt-luci,wongsyrone/luci-1,hnyman/luci,deepak78/new-luci,LuttyYang/luci,keyidadi/luci,palmettos/test,jchuang1977/luci-1,mumuqz/luci,palmettos/test,jlopenwrtluci/luci,LuttyYang/luci,artynet/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,981213/luci-1,wongsyrone/luci-1,bittorf/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,urueedi/luci,Hostle/luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,bittorf/luci,tobiaswaldvogel/luci,david-xiao/luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,Wedmer/luci,cappiewu/luci,tcatm/luci,cshore/luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,NeoRaider/luci,urueedi/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,schidler/ionic-luci,cshore/luci,taiha/luci,lcf258/openwrtcn,oyido/luci,male-puppies/luci,kuoruan/luci,kuoruan/lede-luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,dismantl/luci-0.12,artynet/luci,fkooman/luci,bright-things/ionic-luci,MinFu/luci,slayerrensky/luci,Kyklas/luci-proto-hso,Hostle/luci,cappiewu/luci,jchuang1977/luci-1,openwrt/luci,rogerpueyo/luci,dismantl/luci-0.12,rogerpueyo/luci,urueedi/luci,palmettos/cnLuCI,thesabbir/luci,fkooman/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,rogerpueyo/luci,nwf/openwrt-luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,david-xiao/luci,bright-things/ionic-luci,mumuqz/luci,Kyklas/luci-proto-hso,sujeet14108/luci,jorgifumi/luci,nmav/luci,palmettos/test,db260179/openwrt-bpi-r1-luci,forward619/luci,Sakura-Winkey/LuCI,marcel-sch/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,zhaoxx063/luci,maxrio/luci981213,kuoruan/lede-luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,opentechinstitute/luci,sujeet14108/luci,palmettos/cnLuCI,dwmw2/luci,palmettos/test,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,MinFu/luci,zhaoxx063/luci,ff94315/luci-1,oneru/luci,ff94315/luci-1,Noltari/luci,981213/luci-1,harveyhu2012/luci,teslamint/luci,palmettos/cnLuCI,rogerpueyo/luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,male-puppies/luci,LuttyYang/luci,Sakura-Winkey/LuCI,obsy/luci,remakeelectric/luci,lcf258/openwrtcn,jlopenwrtluci/luci,schidler/ionic-luci,maxrio/luci981213,shangjiyu/luci-with-extra,deepak78/new-luci,dwmw2/luci,nwf/openwrt-luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,harveyhu2012/luci,dwmw2/luci,cappiewu/luci,shangjiyu/luci-with-extra,RuiChen1113/luci,thesabbir/luci,RuiChen1113/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,opentechinstitute/luci,kuoruan/luci,tobiaswaldvogel/luci,daofeng2015/luci,lcf258/openwrtcn,slayerrensky/luci,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,MinFu/luci,male-puppies/luci,dwmw2/luci,harveyhu2012/luci,aa65535/luci,kuoruan/luci,Noltari/luci,palmettos/test,aa65535/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,RuiChen1113/luci,openwrt/luci,obsy/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,hnyman/luci,maxrio/luci981213,tcatm/luci,taiha/luci,aa65535/luci,981213/luci-1,tobiaswaldvogel/luci,dismantl/luci-0.12,tcatm/luci,florian-shellfire/luci,jorgifumi/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,thesabbir/luci,NeoRaider/luci,fkooman/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,deepak78/new-luci,hnyman/luci,Noltari/luci,zhaoxx063/luci,jorgifumi/luci,981213/luci-1,kuoruan/luci,nwf/openwrt-luci,forward619/luci,Noltari/luci,jchuang1977/luci-1,981213/luci-1,Wedmer/luci,thesabbir/luci,tcatm/luci,chris5560/openwrt-luci,mumuqz/luci,joaofvieira/luci,marcel-sch/luci,jlopenwrtluci/luci,nmav/luci,deepak78/new-luci,fkooman/luci,LuttyYang/luci,david-xiao/luci,nmav/luci,joaofvieira/luci,remakeelectric/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,openwrt/luci,Wedmer/luci,rogerpueyo/luci,deepak78/new-luci,keyidadi/luci,981213/luci-1,zhaoxx063/luci,cshore/luci,urueedi/luci,marcel-sch/luci,opentechinstitute/luci,jlopenwrtluci/luci,dwmw2/luci,nmav/luci,hnyman/luci,lcf258/openwrtcn,kuoruan/lede-luci,Noltari/luci,NeoRaider/luci,obsy/luci,kuoruan/luci,sujeet14108/luci,ollie27/openwrt_luci,rogerpueyo/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,artynet/luci,dwmw2/luci,jchuang1977/luci-1,teslamint/luci,kuoruan/luci,david-xiao/luci,jchuang1977/luci-1,male-puppies/luci,oneru/luci,kuoruan/lede-luci,ff94315/luci-1,david-xiao/luci,dismantl/luci-0.12,cshore/luci,nwf/openwrt-luci,palmettos/cnLuCI,slayerrensky/luci,lcf258/openwrtcn,chris5560/openwrt-luci,remakeelectric/luci,harveyhu2012/luci,taiha/luci,Hostle/luci,teslamint/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,forward619/luci,cshore-firmware/openwrt-luci,thesabbir/luci,shangjiyu/luci-with-extra,taiha/luci,thess/OpenWrt-luci,keyidadi/luci,lcf258/openwrtcn,cappiewu/luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,RuiChen1113/luci,bittorf/luci,NeoRaider/luci,tcatm/luci,oneru/luci,jlopenwrtluci/luci,Wedmer/luci,david-xiao/luci,florian-shellfire/luci,chris5560/openwrt-luci,oyido/luci,artynet/luci,florian-shellfire/luci,joaofvieira/luci,marcel-sch/luci,oneru/luci,opentechinstitute/luci,harveyhu2012/luci,daofeng2015/luci,cappiewu/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,aa65535/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,nmav/luci,kuoruan/luci,LuttyYang/luci,NeoRaider/luci,openwrt/luci,keyidadi/luci,Wedmer/luci,nmav/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,bittorf/luci,Hostle/luci,zhaoxx063/luci,bittorf/luci,oyido/luci,hnyman/luci,NeoRaider/luci,florian-shellfire/luci,artynet/luci,oneru/luci,tobiaswaldvogel/luci,palmettos/test,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,dwmw2/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,Wedmer/luci,981213/luci-1,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,slayerrensky/luci,joaofvieira/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,LuttyYang/luci,Hostle/luci,aa65535/luci,oneru/luci,cshore-firmware/openwrt-luci,male-puppies/luci,ff94315/luci-1,jorgifumi/luci,mumuqz/luci,lcf258/openwrtcn,maxrio/luci981213
|
f13e394c4d607e65ac3bb99076a8726e1ed79941
|
mods/builtin_item/init.lua
|
mods/builtin_item/init.lua
|
local time = tonumber(minetest.setting_get("remove_items"))
if not time then
time = 600
end
unwalkable_nodes = {}
minetest.after(0, function()
for itemname, node in pairs(minetest.registered_nodes) do
if node.walkable == false then
table.insert(unwalkable_nodes, 1, itemname)
end
end
end)
minetest.register_entity(":__builtin:item", {
initial_properties = {
hp_max = 1,
physical = true,
collisionbox = {-0.175, -0.175, -0.175, 0.175, 0.175, 0.175},
collide_with_objects = false,
visual = "sprite",
visual_size = {x=0.5, y=0.5},
textures = {""},
spritediv = {x=1, y=1},
initial_sprite_basepos = {x=0, y=0},
is_visible = false,
timer = 0,
},
itemstring = "",
physical_state = true,
set_item = function(self, itemstring)
self.itemstring = itemstring
local stack = ItemStack(itemstring)
local itemtable = stack:to_table()
local itemname = nil
if itemtable then
itemname = stack:to_table().name
end
local item_texture = nil
local item_type = ""
if minetest.registered_items[itemname] then
item_texture = minetest.registered_items[itemname].inventory_image
item_type = minetest.registered_items[itemname].type
end
local prop = {
is_visible = true,
visual = "sprite",
textures = {"unknown_item.png"}
}
if item_texture and item_texture ~= "" then
prop.visual = "wielditem"
prop.textures = {itemname}
prop.visual_size = {x=0.25, y=0.25}
else
prop.visual = "wielditem"
prop.textures = {itemname}
prop.visual_size = {x=0.25, y=0.25}
prop.automatic_rotate = math.pi * 0.5
end
self.object:set_properties(prop)
end,
get_staticdata = function(self)
--return self.itemstring
return minetest.serialize({
itemstring = self.itemstring,
always_collect = self.always_collect,
timer = self.timer,
})
end,
on_activate = function(self, staticdata, dtime_s)
if string.sub(staticdata, 1, string.len("return")) == "return" then
local data = minetest.deserialize(staticdata)
if data and type(data) == "table" then
self.itemstring = data.itemstring
self.always_collect = data.always_collect
self.timer = data.timer
if not self.timer then
self.timer = 0
end
self.timer = self.timer+dtime_s
end
else
self.itemstring = staticdata
end
self.object:set_armor_groups({immortal=1})
self.object:setvelocity({x=0, y=2, z=0})
self.object:setacceleration({x=0, y=-10, z=0})
self:set_item(self.itemstring)
end,
on_step = function(self, dtime)
if not self.timer then
self.timer = 0
end
self.timer = self.timer + dtime
if time ~= 0 and (self.timer > time) then
self.object:remove()
end
local p = self.object:getpos()
local name = minetest.get_node(p).name
if (minetest.registered_nodes[name] and minetest.registered_nodes[name].damage_per_second > 0) or name == "maptools:igniter" then
minetest.sound_play("builtin_item_lava", {pos = self.object:getpos(), gain = 0.5})
self.object:remove()
return
end
--[[ if name == "default:water_source" then
self.object:setacceleration({x = 0, y = 4, z = 0})
else
self.object:setacceleration({x = 0, y = -10, z = 0})
end
--]]
if not minetest.registered_nodes[name] then return end
if minetest.registered_nodes[name].liquidtype == "flowing" then
local get_flowing_dir = function(self)
local pos = self.object:getpos()
local param2 = minetest.get_node(pos).param2
for i,d in ipairs({-1, 1, -1, 1}) do
if i<3 then
pos.x = pos.x+d
else
pos.z = pos.z+d
end
local name = minetest.get_node(pos).name
local par2 = minetest.get_node(pos).param2
if name == "default:water_flowing" and par2 < param2 then
return pos
end
if i<3 then
pos.x = pos.x-d
else
pos.z = pos.z-d
end
end
end
local vec = get_flowing_dir(self)
if vec then
local v = self.object:getvelocity()
if vec and vec.x-p.x > 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 1, y = -0.22, z = 0})
elseif vec and vec.x-p.x < 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = -1, y = -0.22, z = 0})
elseif vec and vec.z-p.z > 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 0, y = -0.22, z = 1})
elseif vec and vec.z-p.z < 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 0, y = -0.22, z = -1})
end
self.object:setacceleration({x = 0, y = -10, z = 0})
self.physical_state = true
self.object:set_properties({
physical = true
})
return
end
end
p.y = p.y - 0.3
local nn = minetest.get_node(p).name
-- If node is not registered or node is walkably solid.
if not minetest.registered_nodes[nn] or minetest.registered_nodes[nn].walkable then
if self.physical_state then
self.object:setvelocity({x=0,y=0,z=0})
self.object:setacceleration({x=0, y=0, z=0})
self.physical_state = false
self.object:set_properties({
physical = false
})
end
else
if not self.physical_state then
self.object:setvelocity({x=0,y=0,z=0})
self.object:setacceleration({x=0, y=-10, z=0})
self.physical_state = true
self.object:set_properties({
physical = true
})
end
end
-- Eject if not walkable
local upnode = minetest.get_node({x = p.x, y = math.ceil(p.y), z = p.z}).name
if minetest.registered_nodes[upnode] and minetest.registered_nodes[upnode].walkable then
local minp, maxp = {x=p.x-1, y=math.ceil(p.y), z=p.z-1}, {x=p.x+1, y=math.ceil(p.y)+1, z=p.z+1}
local nodes = minetest.find_nodes_in_area(minp, maxp, unwalkable_nodes)
if table.getn(nodes) > 0 then
self.object:setpos(nodes[math.random(1,#nodes)])
end
end
end,
--[[ This causes a duplication glitch if a player walks upon an item and clicks on it at the same time.
on_punch = function(self, hitter)
if self.itemstring ~= "" then
local left = hitter:get_inventory():add_item("main", self.itemstring)
if not left:is_empty() then
self.itemstring = left:to_string()
return
end
end
self.object:remove()
end,
--]]
})
if minetest.setting_get("log_mods") then
minetest.log("action", "[builtin_item] loaded.")
end
|
local time = tonumber(minetest.setting_get("remove_items"))
if not time then
time = 600
end
unwalkable_nodes = {}
minetest.after(0, function()
for itemname, node in pairs(minetest.registered_nodes) do
if node.walkable == false then
table.insert(unwalkable_nodes, 1, itemname)
end
end
end)
local get_flowing_dir = function(self)
local pos = self.object:getpos()
local param2 = minetest.get_node(pos).param2
for i,d in ipairs({-1, 1, -1, 1}) do
if i<3 then
pos.x = pos.x+d
else
pos.z = pos.z+d
end
local name = minetest.get_node(pos).name
local par2 = minetest.get_node(pos).param2
if name == "default:water_flowing" and par2 < param2 then
return pos
end
if i<3 then
pos.x = pos.x-d
else
pos.z = pos.z-d
end
end
return nil
end
minetest.register_entity(":__builtin:item", {
initial_properties = {
hp_max = 1,
physical = true,
collisionbox = {-0.175, -0.175, -0.175, 0.175, 0.175, 0.175},
collide_with_objects = false,
visual = "sprite",
visual_size = {x=0.5, y=0.5},
textures = {""},
spritediv = {x=1, y=1},
initial_sprite_basepos = {x=0, y=0},
is_visible = false,
timer = 0,
},
itemstring = "",
physical_state = true,
set_item = function(self, itemstring)
self.itemstring = itemstring
local stack = ItemStack(itemstring)
local itemtable = stack:to_table()
local itemname = nil
if itemtable then
itemname = stack:to_table().name
end
local item_texture = nil
local item_type = ""
if minetest.registered_items[itemname] then
item_texture = minetest.registered_items[itemname].inventory_image
item_type = minetest.registered_items[itemname].type
end
local prop = {
is_visible = true,
visual = "sprite",
textures = {"unknown_item.png"}
}
if item_texture and item_texture ~= "" then
prop.visual = "wielditem"
prop.textures = {itemname}
prop.visual_size = {x=0.25, y=0.25}
else
prop.visual = "wielditem"
prop.textures = {itemname}
prop.visual_size = {x=0.25, y=0.25}
prop.automatic_rotate = math.pi * 0.5
end
self.object:set_properties(prop)
end,
get_staticdata = function(self)
--return self.itemstring
return minetest.serialize({
itemstring = self.itemstring,
always_collect = self.always_collect,
timer = self.timer,
})
end,
on_activate = function(self, staticdata, dtime_s)
if string.sub(staticdata, 1, string.len("return")) == "return" then
local data = minetest.deserialize(staticdata)
if data and type(data) == "table" then
self.itemstring = data.itemstring
self.always_collect = data.always_collect
self.timer = data.timer
if not self.timer then
self.timer = 0
end
self.timer = self.timer+dtime_s
end
else
self.itemstring = staticdata
end
self.object:set_armor_groups({immortal=1})
self.object:setvelocity({x=0, y=2, z=0})
self.object:setacceleration({x=0, y=-10, z=0})
self:set_item(self.itemstring)
end,
on_step = function(self, dtime)
if not self.timer then
self.timer = 0
end
self.timer = self.timer + dtime
if time ~= 0 and (self.timer > time) then
self.object:remove()
return
end
local p = self.object:getpos()
local name = minetest.get_node(p).name
if not minetest.registered_nodes[name] then return end
if minetest.registered_nodes[name].damage_per_second > 0 or name == "maptools:igniter" then
minetest.sound_play("builtin_item_lava", {pos = p, gain = 0.5})
self.object:remove()
return
end
--[[ if name == "default:water_source" then
self.object:setacceleration({x = 0, y = 4, z = 0})
else
self.object:setacceleration({x = 0, y = -10, z = 0})
end
--]]
if minetest.registered_nodes[name].liquidtype == "flowing" then
local vec = get_flowing_dir(self)
if vec then
local v = self.object:getvelocity()
if v and vec.x-p.x > 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 1, y = -0.22, z = 0})
elseif v and vec.x-p.x < 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = -1, y = -0.22, z = 0})
elseif v and vec.z-p.z > 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 0, y = -0.22, z = 1})
elseif v and vec.z-p.z < 0 then
self.object:setacceleration({x = 0, y = 0, z = 0})
self.object:setvelocity({x = 0, y = -0.22, z = -1})
end
self.object:setacceleration({x = 0, y = -10, z = 0})
self.physical_state = true
self.object:set_properties({
physical = true
})
return
end
end
p.y = p.y - 0.3
local nn = minetest.get_node(p).name
-- If node is not registered or node is walkably solid.
if not minetest.registered_nodes[nn] or minetest.registered_nodes[nn].walkable then
if self.physical_state then
self.object:setvelocity({x=0,y=0,z=0})
self.object:setacceleration({x=0, y=0, z=0})
self.physical_state = false
self.object:set_properties({
physical = false
})
end
else
if not self.physical_state then
self.object:setvelocity({x=0,y=0,z=0})
self.object:setacceleration({x=0, y=-10, z=0})
self.physical_state = true
self.object:set_properties({
physical = true
})
end
end
-- Eject if not walkable
local upnode = minetest.get_node({x = p.x, y = math.ceil(p.y), z = p.z}).name
if minetest.registered_nodes[upnode] and minetest.registered_nodes[upnode].walkable then
local minp, maxp = {x=p.x-1, y=math.ceil(p.y), z=p.z-1}, {x=p.x+1, y=math.ceil(p.y)+1, z=p.z+1}
local nodes = minetest.find_nodes_in_area(minp, maxp, unwalkable_nodes)
if table.getn(nodes) > 0 then
self.object:setpos(nodes[math.random(1,#nodes)])
end
end
end,
--[[ This causes a duplication glitch if a player walks upon an item and clicks on it at the same time.
on_punch = function(self, hitter)
if self.itemstring ~= "" then
local left = hitter:get_inventory():add_item("main", self.itemstring)
if not left:is_empty() then
self.itemstring = left:to_string()
return
end
end
self.object:remove()
end,
--]]
})
if minetest.setting_get("log_mods") then
minetest.log("action", "[builtin_item] loaded.")
end
|
try to fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/313 improve builtin_item
|
try to fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/313
improve builtin_item
|
Lua
|
unlicense
|
Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server
|
bc19818f35349c00715185391f7959ed4accb120
|
test_scripts/Polices/build_options/ATF_PTU_Trigger_IGN_cycles.lua
|
test_scripts/Polices/build_options/ATF_PTU_Trigger_IGN_cycles.lua
|
-- Requirement summary:
-- [PTU] Trigger: ignition cycles
--
-- Description:
-- When the amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of
-- "exchange_after_x_ignition_cycles" field ("module_config" section) of policies database, SDL must trigger a PTU sequence
-- 1. Used preconditions:
-- SDL is built with "DEXTENDED_POLICY: ON" flag
-- the 1-st IGN cycle, PTU was succesfully applied. Policies DataBase contains "exchange_after_x_ignition_cycles" = 10
-- 2. Performed steps: Perform ignition_on/off 11 times
--
-- Expected result:
-- When amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of "exchange_after_x_ignition_cycles"
-- field ("module_config" section) of policies database, SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ Local Variables ]]
local exchnage_after = 5
local sdl_preloaded_pt = "sdl_preloaded_pt.json"
local ptu_file = "files/ptu.json"
--[[ Local Functions ]]
local function genpattern2str(name, value_type)
return "(%s*\"" .. name .. "\"%s*:%s*)".. value_type
end
local function modify_file(file_name, pattern, value)
local f = io.open(file_name, "r")
local content = f:read("*a")
f:close()
local res = string.gsub(content, pattern, "%1"..value, 1)
f = io.open(file_name, "w+")
f:write(res)
f:close()
local check = string.find(res, value)
if check ~= nil then
return true
end
return false
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
config.defaultProtocolVersion = 2
-- Backup files
commonPreconditions:BackupFile(sdl_preloaded_pt)
os.execute("cp ".. ptu_file .. " " .. ptu_file .. ".BAK")
-- Update files
for _, v in pairs({config.pathToSDL .. sdl_preloaded_pt, ptu_file}) do
modify_file(v, genpattern2str("exchange_after_x_ignition_cycles", "%d+"), tostring(exchnage_after))
end
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:ActivateApp()
local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] })
EXPECT_HMIRESPONSE(requestId1)
:Do(function(_, data1)
if data1.result.isSDLAllowed ~= true then
local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{ language = "EN-US", messageCodes = { "DataConsent" } })
EXPECT_HMIRESPONSE(requestId2)
:Do(function()
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{ allowed = true, source = "GUI", device = { id = config.deviceMAC, name = "127.0.0.1" } })
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_, data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", { })
end)
:Times(1)
end)
end
end)
end
function Test:TestStep_SUCCEESS_Flow_EXTERNAL_PROPRIETARY()
testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
for i = 1, exchnage_after do
Test["Preconditions_perform_" .. tostring(i) .. "_IGN_OFF_ON"] = function() end
function Test:IGNITION_OFF()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
end
function Test.StopSDL()
StopSDL()
end
function Test.StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:InitHMI()
self:initHMI()
end
function Test:InitHMI_onReady()
self:initHMI_onReady()
end
function Test:Register_app()
self:connectMobile()
self.mobileSession = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
:Do(function()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" })
end)
if i == exchnage_after then
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" })
:Times(AtLeast(1))
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
function Test.Postcondition_RestoreFiles()
commonPreconditions:RestoreFile(sdl_preloaded_pt)
local ptu_file_bak = ptu_file..".BAK"
os.execute("cp -f " .. ptu_file_bak .. " " .. ptu_file)
os.execute("rm -f " .. ptu_file_bak)
end
return Test
|
-- Requirement summary:
-- [PTU] Trigger: ignition cycles
--
-- Description:
-- When the amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of
-- "exchange_after_x_ignition_cycles" field ("module_config" section) of policies database, SDL must trigger a PTU sequence
-- 1. Used preconditions:
-- SDL is built with "DEXTENDED_POLICY: ON" flag
-- the 1-st IGN cycle, PTU was succesfully applied. Policies DataBase contains "exchange_after_x_ignition_cycles" = 10
-- 2. Performed steps: Perform ignition_on/off 11 times
--
-- Expected result:
-- When amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of "exchange_after_x_ignition_cycles"
-- field ("module_config" section) of policies database, SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ Local Variables ]]
local exchnage_after = 5
local sdl_preloaded_pt = "sdl_preloaded_pt.json"
local ptu_file = "files/ptu.json"
--[[ Local Functions ]]
local function genpattern2str(name, value_type)
return "(%s*\"" .. name .. "\"%s*:%s*)".. value_type
end
local function modify_file(file_name, pattern, value)
local f = io.open(file_name, "r")
local content = f:read("*a")
f:close()
local res = string.gsub(content, pattern, "%1"..value, 1)
f = io.open(file_name, "w+")
f:write(res)
f:close()
local check = string.find(res, value)
if check ~= nil then
return true
end
return false
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
config.defaultProtocolVersion = 2
-- Backup files
commonPreconditions:BackupFile(sdl_preloaded_pt)
os.execute("cp ".. ptu_file .. " " .. ptu_file .. ".BAK")
-- Update files
for _, v in pairs({config.pathToSDL .. sdl_preloaded_pt, ptu_file}) do
modify_file(v, genpattern2str("exchange_after_x_ignition_cycles", "%d+"), tostring(exchnage_after))
end
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:TestStep_SUCCEESS_Flow_PROPRIETARY()
local policy_file_name = "PolicyTableUpdate"
local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls)
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",
{ requestType = "PROPRIETARY", fileName = policy_file_name})
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"})
:Do(function()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = policy_file_name}, ptu_file)
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,_data1)
self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {})
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = policy_file_path .. "/" .. policy_file_name })
end)
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UP_TO_DATE" })
end)
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
for i = 1, exchnage_after do
Test["Preconditions_perform_" .. tostring(i) .. "_IGN_OFF_ON"] = function() end
function Test:IGNITION_OFF()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
end
for j = 1, 3 do
Test["Waiting ".. j .." sec"] = function() os.execute("sleep 1") end
end
function Test.StopSDL()
StopSDL()
end
function Test.StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:InitHMI()
self:initHMI()
end
function Test:InitHMI_onReady()
self:initHMI_onReady()
end
function Test:StartMobileSession()
self:connectMobile()
self.mobileSession = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
function Test:Register_App()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" })
if i == exchnage_after then
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" })
:Times(AtLeast(1))
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
function Test.Postcondition_RestoreFiles()
commonPreconditions:RestoreFile(sdl_preloaded_pt)
local ptu_file_bak = ptu_file..".BAK"
os.execute("cp -f " .. ptu_file_bak .. " " .. ptu_file)
os.execute("rm -f " .. ptu_file_bak)
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.