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
|
|---|---|---|---|---|---|---|---|---|---|
6e574a681bca8b04395bb83d5f1e3e7e84a462dd
|
MMOCoreORB/bin/scripts/mobile/outfits/serverobjects.lua
|
MMOCoreORB/bin/scripts/mobile/outfits/serverobjects.lua
|
includeFile("outfits/band_bandfill_outfit.lua")
includeFile("outfits/band_fanfar_outfit.lua")
includeFile("outfits/band_fizz_outfit.lua")
includeFile("outfits/band_flute_droopy_outfit.lua")
includeFile("outfits/band_kloo_horn_outfit.lua")
includeFile("outfits/band_slitherhorn_outfit.lua")
includeFile("outfits/band_traz_outfit.lua")
includeFile("outfits/barada_outfit.lua")
includeFile("outfits/figrin_dan_band_outfit.lua")
includeFile("outfits/huff_darklighter_2_outfit.lua")
includeFile("outfits/huff_darklighter_outfit.lua")
includeFile("outfits/jilljoo_jab_outfit.lua")
includeFile("outfits/junk_dender_outfit.lua")
includeFile("outfits/kaja_orzee_outfit.lua")
includeFile("outfits/loam_redge_outfit.lua")
includeFile("outfits/lord_hethrir_outfit.lua")
includeFile("outfits/mara_jade_outfit.lua")
includeFile("outfits/mos_taike_guard_old_outfit.lua")
includeFile("outfits/mos_taike_guard_outfit.lua")
includeFile("outfits/mos_taike_mayor_outfit.lua")
includeFile("outfits/reelo_baruk_outfit.lua")
includeFile("outfits/stella_outfit.lua")
includeFile("outfits/testoutfit.lua")
includeFile("outfits/thracken_sal_solo_outfit.lua")
includeFile("outfits/vardias_tyne_outfit.lua")
|
includeFile("outfits/band_bandfill_outfit.lua")
includeFile("outfits/band_fanfar_outfit.lua")
includeFile("outfits/band_fizz_outfit.lua")
includeFile("outfits/band_flute_droopy_outfit.lua")
includeFile("outfits/band_kloo_horn_outfit.lua")
includeFile("outfits/band_slitherhorn_outfit.lua")
includeFile("outfits/band_traz_outfit.lua")
includeFile("outfits/barada_outfit.lua")
includeFile("outfits/figrin_dan_band_outfit.lua")
includeFile("outfits/huff_darklighter_2_outfit.lua")
includeFile("outfits/huff_darklighter_outfit.lua")
includeFile("outfits/jilljoo_jab_outfit.lua")
includeFile("outfits/junk_dender_outfit.lua")
includeFile("outfits/kaja_orzee_outfit.lua")
includeFile("outfits/loam_redge_outfit.lua")
includeFile("outfits/lord_hethrir_outfit.lua")
includeFile("outfits/mara_jade_outfit.lua")
includeFile("outfits/mat_rags_outfit.lua")
includeFile("outfits/mos_taike_guard_old_outfit.lua")
includeFile("outfits/mos_taike_guard_outfit.lua")
includeFile("outfits/mos_taike_mayor_outfit.lua")
includeFile("outfits/reelo_baruk_outfit.lua")
includeFile("outfits/stella_outfit.lua")
includeFile("outfits/tekil_barje_outfit.lua")
includeFile("outfits/testoutfit.lua")
includeFile("outfits/thracken_sal_solo_outfit.lua")
includeFile("outfits/vardias_tyne_outfit.lua")
|
[Fixed] Mat Rags & Tekil outfits not loading.
|
[Fixed] Mat Rags & Tekil outfits not loading.
Change-Id: I7e6ccd9b42c3cad7f6527bad8a2f9289d017556f
|
Lua
|
agpl-3.0
|
Tatwi/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,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
ca3d97576039ee390bc1c20621c4e2c416cc0a60
|
bhop/gamemode/mapfixes/bhop_exodus.lua
|
bhop/gamemode/mapfixes/bhop_exodus.lua
|
HOOKS["Intialize"] = function()
GAMEMODE:AddACArea(Vector(866, 162, -240),Vector(866, 162, -40),"You have entered the level select area as a result of this your timer has been stopped.")
GAMEMODE:AddACArea(Vector(-580, 772, -768),Vector(-315, 894, -568))
end
HOOKS["InitPostEntity"] = function()
for k,v in pairs(ents.FindByClass("trigger_teleport")) do
if(v:GetPos() == Vector(6560, 5112, 7412)) then
v:SetKeyValue("target","13")
end
end
for k,v in pairs(ents.FindByClass("func_brush")) do
if(v:GetName() == "aokilv6") then
v:SetName("disabled")
end
end
end
|
HOOKS["Initialize"] = function()
GAMEMODE:AddACArea(Vector(866, 162, -240),Vector(1371, 664, -40),"You have entered the level select area as a result of this your timer has been stopped.")
GAMEMODE:AddACArea(Vector(-580, 772, -768),Vector(-315, 894, -568))
end
[09:56:03] Min = Vector(867, 161, -240)
[09:56:03] Max = Vector(1371, 664, -240)
HOOKS["InitPostEntity"] = function()
for k,v in pairs(ents.FindByClass("trigger_teleport")) do
if(v:GetPos() == Vector(6560, 5112, 7412)) then
v:SetKeyValue("target","13")
end
end
for k,v in pairs(ents.FindByClass("func_brush")) do
if(v:GetName() == "aokilv6") then
v:SetName("disabled")
end
end
end
|
fixed exodus mapfix
|
fixed exodus mapfix
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
eaf379bf88ae0bc620b4a1de23e58b75626778ad
|
plugins/wikipedia.lua
|
plugins/wikipedia.lua
|
local command = 'wikipedia <query>'
local doc = [[```
/wikipedia <query>
Returns an article from Wikipedia.
Aliases: /w, /wiki
```]]
local triggers = {
'^/wikipedia[@'..bot.username..']*',
'^/wiki[@'..bot.username..']*',
'^/w[@'..bot.username..']*$',
'^/w[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local gurl = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q=site:wikipedia.org%20'
local wurl = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=4000&exsectionformat=plain&titles='
local jstr, res = HTTPS.request(gurl .. URL.escape(input))
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if not jdat.responseData then
sendReply(msg, config.errors.connection)
return
end
if not jdat.responseData.results[1] then
sendReply(msg, config.errors.results)
return
end
--
local url = jdat.responseData.results[1].unescapedUrl
local title = jdat.responseData.results[1].titleNoFormatting:gsub(' %- Wikipedia, the free encyclopedia', '')
-- 'https://en.wikipedia.org/wiki/':len ≡ 30
jstr, res = HTTPS.request(wurl .. url:sub(31))
if res ~= 200 then
sendReply(msg, config.error.connection)
return
end
local text = JSON.decode(jstr).query.pages
for k,v in pairs(text) do
text = v.extract
break -- Seriously, there's probably a way more elegant solution.
end
if not text then
sendReply(msg, config.errors.results)
return
end
text = text:gsub('</?.->', '')
local l = text:find('\n')
if l then
text = text:sub(1, l-1)
end
title = title:gsub('%(.+%)', '')
--local output = '[' .. title .. '](' .. url .. ')\n' .. text:gsub('%[.+]%','')
--local output = '*' .. title .. '*\n' .. text:gsub('%[.+]%','') .. '\n[Read more.](' .. url .. ')'
local output = text:gsub('%[.+%]',''):gsub(title, '*'..title..'*') .. '\n'
if url:find('%(') then
output = output .. url:gsub('_', '\\_')
else
output = output .. '[Read more.](' .. url .. ')'
end
--
--[[ Comment the previous block and uncomment this one for full-message,
-- "unlinked" link previews.
-- Invisible zero-width, non-joiner.
local output = '[](' .. jdat.responseData.results[1].url .. ')'
]]--
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
local command = 'wikipedia <query>'
local doc = [[```
/wikipedia <query>
Returns an article from Wikipedia.
Aliases: /w, /wiki
```]]
local triggers = {
'^/wikipedia[@'..bot.username..']*',
'^/wiki[@'..bot.username..']*',
'^/w[@'..bot.username..']*$',
'^/w[@'..bot.username..']* '
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local gurl = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q=site:wikipedia.org%20'
local wurl = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=4000&exsectionformat=plain&titles='
local jstr, res = HTTPS.request(gurl .. URL.escape(input))
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if not jdat.responseData then
sendReply(msg, config.errors.connection)
return
end
if not jdat.responseData.results[1] then
sendReply(msg, config.errors.results)
return
end
--
local url = jdat.responseData.results[1].unescapedUrl
local title = jdat.responseData.results[1].titleNoFormatting:gsub(' %- Wikipedia, the free encyclopedia', '')
-- 'https://en.wikipedia.org/wiki/':len ≡ 30
jstr, res = HTTPS.request(wurl .. url:sub(31))
if res ~= 200 then
sendReply(msg, config.error.connection)
return
end
local text = JSON.decode(jstr).query.pages
for k,v in pairs(text) do
text = v.extract
break -- Seriously, there's probably a way more elegant solution.
end
if not text then
sendReply(msg, config.errors.results)
return
end
text = text:gsub('</?.->', '')
local l = text:find('\n')
if l then
text = text:sub(1, l-1)
end
title = title:gsub('%(.+%)', '')
--local output = '[' .. title .. '](' .. url .. ')\n' .. text:gsub('%[.+]%','')
--local output = '*' .. title .. '*\n' .. text:gsub('%[.+]%','') .. '\n[Read more.](' .. url .. ')'
local esctitle = title:gsub("[%^$()%%.%[%]*+%-?]","%%%1")
local output = text:gsub('%[.+%]',''):gsub(esctitle, '*%1*') .. '\n'
if url:find('%(') then
output = output .. url:gsub('_', '\\_')
else
output = output .. '[Read more.](' .. url .. ')'
end
--
--[[ Comment the previous block and uncomment this one for full-message,
-- "unlinked" link previews.
-- Invisible zero-width, non-joiner.
local output = '[](' .. jdat.responseData.results[1].url .. ')'
]]--
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
Fix title escaping
|
Fix title escaping
|
Lua
|
mit
|
barreeeiroo/BarrePolice,TiagoDanin/SiD,bb010g/otouto,Brawl345/Brawlbot-v2,topkecleon/otouto
|
2ad23320556851f63e312a72c23a12b014a2772a
|
Peripherals/GPU/modules/screenshot.lua
|
Peripherals/GPU/modules/screenshot.lua
|
--GPU: Screenshot and Label image.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUKit, DevKit = ...
--luacheck: pop
local lg = love.graphics
local events = require("Engine.events")
local Path = GPUKit.Path
local MiscKit = GPUKit.Misc
local WindowKit = GPUKit.Window
local RenderKit = GPUKit.Render
local SharedKit = GPUKit.Shared
--==Kits Constants==--
local _LIKO_W, _LIKO_H = WindowKit.LIKO_W, WindowKit.LIKO_H
local systemMessage = MiscKit.systemMessage
local Verify = SharedKit.Verify
--==Local Variables==--
local _ScreenshotKey = Config._ScreenshotKey or "f5"
local _ScreenshotScale = Config._ScreenshotScale or 3
local _LabelCaptureKey = Config._LabelCaptureKey or "f6"
--==GPU Screenshot API==--
function GPU.screenshot(x,y,w,h)
x, y, w, h = x or 0, y or 0, w or _LIKO_W, h or _LIKO_H
x = Verify(x,"X","number",true)
y = Verify(y,"Y","number",true)
w = Verify(w,"W","number",true)
h = Verify(h,"H","number",true)
lg.setCanvas()
local imgdata = GPU.imagedata(RenderKit.ScreenCanvas:newImageData(1,1,x,y,w,h))
lg.setCanvas{RenderKit.ScreenCanvas,stencil=true}
return imgdata
end
--==Label Image==--
local newImageHandler = love.filesystem.load(Path.."scripts/imageHandler.lua")
local LabelImage = love.image.newImageData(_LIKO_W, _LIKO_H)
LabelImage:mapPixel(function() return 0,0,0,1 end)
local LIMGHandler; LIMGHandler = newImageHandler(_LIKO_W,_LIKO_H,function() end,function() end)
LIMGHandler("setImage",0,0,LabelImage)
--==Label Image API==--
function GPU.getLabelImage()
return GPU.imagedata(LabelImage)
end
--==Hooks==--
--Screenshot and LabelCapture keys handling.
events.register("love:keypressed", function(key)
if key == _ScreenshotKey then
local sc = GPU.screenshot()
sc = sc:enlarge(_ScreenshotScale)
local png = sc:exportOpaque()
love.filesystem.write("/Screenshots/LIKO12-"..os.time()..".png",png)
systemMessage("Screenshot has been taken successfully",2)
elseif key == _LabelCaptureKey then
lg.setCanvas()
LabelImage:paste(RenderKit.ScreenCanvas:newImageData(),0,0,0,0,_LIKO_W,_LIKO_H)
lg.setCanvas{RenderKit.ScreenCanvas,stencil=true}
systemMessage("Captured label image successfully !",2)
end
end)
--==DevKit Exports==--
DevKit.LIMGHandler = LIMGHandler
|
--GPU: Screenshot and Label image.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUKit, DevKit = ...
--luacheck: pop
local lg = love.graphics
local events = require("Engine.events")
local Path = GPUKit.Path
local MiscKit = GPUKit.Misc
local WindowKit = GPUKit.Window
local RenderKit = GPUKit.Render
local SharedKit = GPUKit.Shared
--==Kits Constants==--
local _LIKO_W, _LIKO_H = WindowKit.LIKO_W, WindowKit.LIKO_H
local systemMessage = MiscKit.systemMessage
local Verify = SharedKit.Verify
--==Local Variables==--
local _ScreenshotKey = Config._ScreenshotKey or "f5"
local _ScreenshotScale = Config._ScreenshotScale or 3
local _LabelCaptureKey = Config._LabelCaptureKey or "f6"
--==GPU Screenshot API==--
function GPU.screenshot(x,y,w,h)
x, y, w, h = x or 0, y or 0, w or _LIKO_W, h or _LIKO_H
x = Verify(x,"X","number",true)
y = Verify(y,"Y","number",true)
w = Verify(w,"W","number",true)
h = Verify(h,"H","number",true)
lg.setCanvas()
local imgdata = GPU.imagedata(RenderKit.ScreenCanvas:newImageData(1,1,x,y,w,h))
lg.setCanvas{RenderKit.ScreenCanvas,stencil=true}
return imgdata
end
--==Label Image==--
local newImageHandler = love.filesystem.load(Path.."scripts/imageHandler.lua")
local LabelImage = love.image.newImageData(_LIKO_W, _LIKO_H)
LabelImage:mapPixel(function() return 0,0,0,1 end)
local LIMGHandler; LIMGHandler = newImageHandler(_LIKO_W,_LIKO_H,function() end,function() end)
LIMGHandler("setImage",0,0,LabelImage)
--==Label Image API==--
function GPU.getLabelImage()
return GPU.imagedata(LabelImage)
end
--==Hooks==--
--Screenshot and LabelCapture keys handling.
events.register("love:keypressed", function(key)
if key == _ScreenshotKey then
local sc = GPU.screenshot()
sc = sc:enlarge(_ScreenshotScale)
local png = sc:exportOpaque()
love.filesystem.write("/Screenshots/LIKO12-"..os.time()..".png",png)
systemMessage("Screenshot has been taken successfully",2)
elseif key == _LabelCaptureKey then
lg.setCanvas()
LabelImage:paste(RenderKit.ScreenCanvas:newImageData(),0,0,0,0,_LIKO_W,_LIKO_H)
lg.setCanvas{RenderKit.ScreenCanvas,stencil=true}
systemMessage("Captured label image successfully !",2)
end
end)
--==DevKit Exports==--
DevKit.LIMGHandler = LIMGHandler
DevKit.LabelImage = LabelImage
|
Fix png saving
|
Fix png saving
Former-commit-id: ed0575ae8f710e23ebc6635e891cae12b52a5727
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
2f2e7dd99b8c3ad68f3f5620365ccef86015043e
|
modules/unicode.lua
|
modules/unicode.lua
|
local sql = require'lsqlite3'
local util = require'util'
-- utf-8 functions (C) Rici Lake
-- http://luaparse.luaforge.net/libquery.lua.html
local function X(str) return tonumber(str, 16) end
local elevenBits = X"7FF"
local sixteenBits = X"FFFF"
local math = require 'math'
local mod = math.mod
local strchar = string.char
local strbyte = string.byte
local strfind = string.find
local offset2 = X"C0" * 64 + X"80"
local offset3 = X"E0" * 4096 + X"80" * (64 + 1)
local offset4 = X"F0" * 262144 + X"80" * (4096 + 64 + 1)
local function toUtf8(i)
i = X(i)
if i <= 127 then return strchar(i)
elseif i <= elevenBits then
return strchar(i / 64 + 192, mod(i, 64) + 128)
elseif i <= sixteenBits then
return strchar(i / 4096 + 224,
mod(i / 64, 64) + 128,
mod(i, 64) + 128)
else
return strchar(i / 262144 + 240,
mod(i / 4096, 64) + 128,
mod(i / 64, 64) + 128,
mod(i, 64) + 128)
end
end
local function fromUtf8(str)
if strfind(str, "^[\1-\127%z]$") then return strbyte(str)
elseif strfind(str, "^[\194-\223][\128-\191]$") then
return strbyte(str, 1) * 64 + strbyte(str, 2) - offset2
elseif strfind(str, "^[\225-\236\238\239][\128-\191][\128-\191]$")
or strfind(str, "^\224[\160-\191][\128-\191]$")
or strfind(str, "^\237[\128-\159][\128-\191]$") then
return strbyte(str, 1) * 4096 + strbyte(str, 2) * 64 + strbyte(str, 3)
- offset3
elseif strfind(str, "^\240[\144-\191][\128-\191][\128-\191]$")
or strfind(str, "^[\241\242\243][\128-\191][\128-\191][\128-\191]$")
or strfind(str, "^\244[\128-\143][\128-\191][\128-\191]$") then
return (strbyte(str, 1) * 262144 - offset4)
+ strbyte(str, 2) * 4096 + strbyte(str, 3) * 64 + strbyte(str, 4)
end
end
local function handleSearch(self, source, destination, name)
local db = sql.open("cache/unicode.sql")
local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 50')
selectStmt:bind_values('%'..name..'%')
local out = {}
for row in selectStmt:nrows() do
table.insert(out, string.format('%s %s', toUtf8(row.cp), row.name))
end
db:close()
<<<<<<< HEAD
if(#out) then
self:Msg('privmsg', destination, source, table.concat(out, ', '))
=======
if #out > 0 then
say(table.concat(out, ', '))
else
say('No match. ಠ_ಠ')
>>>>>>> 527be1c... unicode: gfind -> gmatch. Proper check for matches
end
end
local function handleSearchShort(self, source, destination, name)
local db = sql.open("cache/unicode.sql")
local selectStmt = db:prepare('SELECT cp FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 500')
selectStmt:bind_values('%'..name..'%')
local out = {}
for row in selectStmt:nrows() do
table.insert(out, string.format('%s', toUtf8(row.cp)))
end
db:close()
<<<<<<< HEAD
if(#out) then
self:Msg('privmsg', destination, source, table.concat(out, ''))
=======
if #out > 0 then
say(table.concat(out, ''))
else
say('No match. ಠ_ಠ')
>>>>>>> 527be1c... unicode: gfind -> gmatch. Proper check for matches
end
end
local function handleLookup(self, source, destination, str)
local db = sql.open("cache/unicode.sql")
local out = {}
for uchar in string.gmatch(str, "([%z\1-\127\194-\244][\128-\191]*)") do
uchar = fromUtf8(uchar)
if uchar then
local cp = string.format('%04x', uchar)
local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(cp) LIKE LOWER(?)')
selectStmt:bind_values(cp)
for row in selectStmt:nrows() do
table.insert(out, string.format('U+%s %s', (row.cp), row.name))
end
end
end
db:close()
if #out > 0 then
say(table.concat(out, ', '))
else
say('No match. ಠ_ಠ')
end
end
local function genMojibake(self, source, destination, str)
local factor = 0.65
local db = sql.open("cache/unicode.sql")
local out = {}
for uchar in util.utf8.chars(str) do
local ucp = fromUtf8(uchar)
if ucp and math.random() >= factor then
local cp = string.format('%04x', ucp)
local stmt = db:prepare('SELECT name FROM unicode WHERE LOWER(cp) LIKE LOWER(?)')
stmt:bind_values(cp)
local code = stmt:step()
if code == sql.ROW then
local name = stmt:get_value(0)
name = string.format('%s with%%', name)
local stmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) ORDER BY random() LIMIT 1')
stmt:bind_values(name)
local code = stmt:step()
if code == sql.ROW then
local cp = stmt:get_value(0)
table.insert(out, string.format('%s', toUtf8(cp)))
else
table.insert(out, uchar)
end
else
table.insert(out, uchar)
end
else
table.insert(out, uchar)
end
end
db:close()
say(table.concat(out))
end
return {
PRIVMSG = {
['^%pu (.*)$'] = handleSearch,
['^%pus (.*)$'] = handleSearchShort,
['^%pw (.*)$'] = handleLookup,
['^%pmojibake (.*)$'] = genMojibake,
}
}
|
local sql = require'lsqlite3'
local util = require'util'
-- utf-8 functions (C) Rici Lake
-- http://luaparse.luaforge.net/libquery.lua.html
local function X(str) return tonumber(str, 16) end
local elevenBits = X"7FF"
local sixteenBits = X"FFFF"
local math = require 'math'
local mod = math.mod
local strchar = string.char
local strbyte = string.byte
local strfind = string.find
local offset2 = X"C0" * 64 + X"80"
local offset3 = X"E0" * 4096 + X"80" * (64 + 1)
local offset4 = X"F0" * 262144 + X"80" * (4096 + 64 + 1)
local function toUtf8(i)
i = X(i)
if i <= 127 then return strchar(i)
elseif i <= elevenBits then
return strchar(i / 64 + 192, mod(i, 64) + 128)
elseif i <= sixteenBits then
return strchar(i / 4096 + 224,
mod(i / 64, 64) + 128,
mod(i, 64) + 128)
else
return strchar(i / 262144 + 240,
mod(i / 4096, 64) + 128,
mod(i / 64, 64) + 128,
mod(i, 64) + 128)
end
end
local function fromUtf8(str)
if strfind(str, "^[\1-\127%z]$") then return strbyte(str)
elseif strfind(str, "^[\194-\223][\128-\191]$") then
return strbyte(str, 1) * 64 + strbyte(str, 2) - offset2
elseif strfind(str, "^[\225-\236\238\239][\128-\191][\128-\191]$")
or strfind(str, "^\224[\160-\191][\128-\191]$")
or strfind(str, "^\237[\128-\159][\128-\191]$") then
return strbyte(str, 1) * 4096 + strbyte(str, 2) * 64 + strbyte(str, 3)
- offset3
elseif strfind(str, "^\240[\144-\191][\128-\191][\128-\191]$")
or strfind(str, "^[\241\242\243][\128-\191][\128-\191][\128-\191]$")
or strfind(str, "^\244[\128-\143][\128-\191][\128-\191]$") then
return (strbyte(str, 1) * 262144 - offset4)
+ strbyte(str, 2) * 4096 + strbyte(str, 3) * 64 + strbyte(str, 4)
end
end
local function handleSearch(self, source, destination, name)
local db = sql.open("cache/unicode.sql")
local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 50')
selectStmt:bind_values('%'..name..'%')
local out = {}
for row in selectStmt:nrows() do
table.insert(out, string.format('%s %s', toUtf8(row.cp), row.name))
end
db:close()
if #out > 0 then
say(table.concat(out, ', '))
else
say('No match. ಠ_ಠ')
end
end
local function handleSearchShort(self, source, destination, name)
local db = sql.open("cache/unicode.sql")
local selectStmt = db:prepare('SELECT cp FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 500')
selectStmt:bind_values('%'..name..'%')
local out = {}
for row in selectStmt:nrows() do
table.insert(out, string.format('%s', toUtf8(row.cp)))
end
db:close()
if #out > 0 then
say(table.concat(out, ''))
else
say('No match. ಠ_ಠ')
end
end
local function handleLookup(self, source, destination, str)
local db = sql.open("cache/unicode.sql")
local out = {}
for uchar in string.gmatch(str, "([%z\1-\127\194-\244][\128-\191]*)") do
uchar = fromUtf8(uchar)
if uchar then
local cp = string.format('%04x', uchar)
local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(cp) LIKE LOWER(?)')
selectStmt:bind_values(cp)
for row in selectStmt:nrows() do
table.insert(out, string.format('U+%s %s', (row.cp), row.name))
end
end
end
db:close()
if #out > 0 then
say(table.concat(out, ', '))
else
say('No match. ಠ_ಠ')
end
end
local function genMojibake(self, source, destination, str)
local factor = 0.65
local db = sql.open("cache/unicode.sql")
local out = {}
for uchar in util.utf8.chars(str) do
local ucp = fromUtf8(uchar)
if ucp and math.random() >= factor then
local cp = string.format('%04x', ucp)
local stmt = db:prepare('SELECT name FROM unicode WHERE LOWER(cp) LIKE LOWER(?)')
stmt:bind_values(cp)
local code = stmt:step()
if code == sql.ROW then
local name = stmt:get_value(0)
name = string.format('%s with%%', name)
local stmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) ORDER BY random() LIMIT 1')
stmt:bind_values(name)
local code = stmt:step()
if code == sql.ROW then
local cp = stmt:get_value(0)
table.insert(out, string.format('%s', toUtf8(cp)))
else
table.insert(out, uchar)
end
else
table.insert(out, uchar)
end
else
table.insert(out, uchar)
end
end
db:close()
say(table.concat(out))
end
return {
PRIVMSG = {
['^%pu (.*)$'] = handleSearch,
['^%pus (.*)$'] = handleSearchShort,
['^%pw (.*)$'] = handleLookup,
['^%pmojibake (.*)$'] = genMojibake,
}
}
|
unicode: Fix epic merge failure...
|
unicode: Fix epic merge failure...
Former-commit-id: 24f9e5ee4ee0b3143fcd0becc6435b70573ec93b [formerly f5096bf55a684fd1dba9d68d1341521c9384aa00]
Former-commit-id: a63395fdf78d0a8093d67412fc7a119d4d18e49b
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
|
0134545ecb3a930b44ff241ac3c28bebdb80a462
|
tests/tests.lua
|
tests/tests.lua
|
package.cpath = package.cpath .. ";../lib/?.so"
require "lunique"
require "luaunit"
function valid(uuid)
local len = string.len(uuid)
local pos = string.find(uuid, '[^a-f0-9-]')
return len, pos
end
Testing = {}
function Testing:testGenerate()
-- It is hard to test if the string is unique...
-- I test that the length is 36 and that the string only contains
-- letters: a-z
-- numbers: 0-9
-- dashes: -
local uuid = lunique.generate()
local len, pos = valid(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
end
function Testing:testGenerateTime()
-- This test might fail, I can't be 100% sure the time is not off by a
-- second. Maybe I should change to test if diff < X number of seconds...
local uuid = lunique.generate_time()
local t = os.date('*t')
local len, pos = valid(uuid)
local time1 = os.time(t)
local time2, valid = lunique.time(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
assertEquals(time1, time2)
assertEquals(valid, 0)
end
function Testing:testGenerateTimeSafe()
-- This test might fail, I can't be 100% sure the time is not off by a
-- second. Maybe I should change to test if diff < X number of seconds...
local uuid, status = lunique.generate_time_safe()
local t = os.date('*t')
local len, pos = valid(uuid)
local time1 = os.time(t)
local time2, valid = lunique.time(uuid)
status = (status == -1 or status == 0)
assertEquals(len, 36)
assertEquals(pos, nil)
assertEquals(time1, time2)
assertEquals(status, true)
assertEquals(valid, 0)
end
function Testing:testGenerateRandom()
local uuid = lunique.generate_random()
local len, pos = valid(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
end
function Testing:testTime()
-- UUID is generated Thu Nov 8 13:36:36 2012
local time1 = 1352381796
local time2, valid = lunique.time("51715676-29a9-11e2-8668-001a4b53924b")
assertEquals(time1, time2)
assertEquals(valid, 0)
end
function Testing:testTime_Fails()
local time, valid = lunique.time("Hello-World")
assertEquals(valid, -1)
end
function Testing:testCompare()
local uuid1 = "778d279d-dad5-4d32-b2a6-d325affeadbf"
local uuid2 = "833fb502-51eb-412c-800e-03902045e0cb"
local eq, s1 = lunique.compare(uuid1, uuid1)
local lt, s2 = lunique.compare(uuid1, uuid2)
local gt, s3 = lunique.compare(uuid2, uuid1)
assertEquals(eq, 0)
assertEquals(s1, 0)
assertEquals(lt, -1)
assertEquals(s2, 0)
assertEquals(gt, 1)
assertEquals(s3, 0)
end
function Testing:testCompare_Fail()
-- inavlid uuid note the '+' character
local uuid1 = "778d279d+dad5-4d32-b2a6-d325affeadbf"
local uuid2 = "833fb502-51eb-412c-800e-03902045e0cb"
-- invalid uuid it is empty
local uuid3 = ""
local f1, s1 = lunique.compare(uuid1, uuid1)
local f2, s2 = lunique.compare(uuid1, uuid2)
local f3, s3 = lunique.compare(uuid2, uuid1)
local f4, s4 = lunique.compare(uuid2, uuid3)
assertEquals(f1, -1)
assertEquals(s1, -3)
assertEquals(f2, -1)
assertEquals(s2, -1)
assertEquals(f3, 0)
assertEquals(s3, -2)
assertEquals(f4, 0)
assertEquals(s4, -2)
end
function Testing:testValid()
local result
-- Test a hardcoded valid, invalid, empty uuid string and to long uuid
result = lunique.valid("778d279d-dad5-4d32-b2a6-d325affeadbf")
assertEquals(result, true)
result = lunique.valid("778d279d+dad5-4d32-b2a6-d325affeadbf")
assertEquals(result, false)
result = lunique.valid("")
assertEquals(result, false)
result = lunique.valid("778d279d-dad5-4d32-b2a6-d325affeadbf-d325affeadbf")
assertEquals(result, false)
-- Test all the uuid generator functions
result = lunique.valid(lunique.generate())
assertEquals(result, true)
result = lunique.valid(lunique.generate_time())
assertEquals(result, true)
result = lunique.valid(lunique.generate_time_safe())
assertEquals(result, true)
result = lunique.valid(lunique.generate_random())
assertEquals(result, true)
end
LuaUnit:run()
|
package.cpath = package.cpath .. ";../lib/?.so"
require "lunique"
require "luaunit"
function valid(uuid)
local len = string.len(uuid)
local pos = string.find(uuid, '[^a-f0-9-]')
return len, pos
end
Testing = {}
function Testing:testGenerate()
-- It is hard to test if the string is unique...
-- I test that the length is 36 and that the string only contains
-- letters: a-z
-- numbers: 0-9
-- dashes: -
local uuid = lunique.generate()
local len, pos = valid(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
end
function Testing:testGenerateTime()
-- This test might fail, I can't be 100% sure the time is not off by a
-- second. Maybe I should change to test if diff < X number of seconds...
local uuid = lunique.generate_time()
local t = os.date('*t')
local len, pos = valid(uuid)
local time1 = os.time(t)
local time2, valid = lunique.time(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
assertEquals(time1, time2)
assertEquals(valid, 0)
end
function Testing:testGenerateTimeSafe()
-- This test might fail, I can't be 100% sure the time is not off by a
-- second. Maybe I should change to test if diff < X number of seconds...
local uuid, status = lunique.generate_time_safe()
local t = os.date('*t')
local len, pos = valid(uuid)
local time1 = os.time(t)
local time2, valid = lunique.time(uuid)
status = (status == -1 or status == 0)
assertEquals(len, 36)
assertEquals(pos, nil)
assertEquals(time1, time2)
assertEquals(status, true)
assertEquals(valid, 0)
end
function Testing:testGenerateRandom()
local uuid = lunique.generate_random()
local len, pos = valid(uuid)
assertEquals(len, 36)
assertEquals(pos, nil)
end
function Testing:testTime()
-- UUID is generated Thu Nov 8 13:36:36 2012
local time1 = 1352381796
local time2, valid = lunique.time("51715676-29a9-11e2-8668-001a4b53924b")
assertEquals(time1, time2)
assertEquals(valid, 0)
end
function Testing:testTime_Fails()
local time, valid = lunique.time("Hello-World")
assertEquals(valid, -1)
end
function Testing:testCompare()
local uuid1 = "778d279d-dad5-4d32-b2a6-d325affeadbf"
local uuid2 = "833fb502-51eb-412c-800e-03902045e0cb"
local eq, s1 = lunique.compare(uuid1, uuid1)
local lt, s2 = lunique.compare(uuid1, uuid2)
local gt, s3 = lunique.compare(uuid2, uuid1)
assertEquals(eq, 0)
assertEquals(s1, 0)
assertEquals(lt, -1)
assertEquals(s2, 0)
assertEquals(gt, 1)
assertEquals(s3, 0)
end
function Testing:testCompare_Fail()
-- inavlid uuid note the '+' character
local uuid1 = "778d279d+dad5-4d32-b2a6-d325affeadbf"
local uuid2 = "833fb502-51eb-412c-800e-03902045e0cb"
-- invalid uuid it is empty
local uuid3 = ""
local f1, s1 = lunique.compare(uuid1, uuid1)
local f2, s2 = lunique.compare(uuid1, uuid2)
local f3, s3 = lunique.compare(uuid2, uuid1)
local f4, s4 = lunique.compare(uuid2, uuid3)
assertEquals(s1, -3)
assertEquals(s2, -1)
assertEquals(s3, -2)
assertEquals(s4, -2)
end
function Testing:testValid()
local result
-- Test a hardcoded valid, invalid, empty uuid string and to long uuid
result = lunique.valid("778d279d-dad5-4d32-b2a6-d325affeadbf")
assertEquals(result, true)
result = lunique.valid("778d279d+dad5-4d32-b2a6-d325affeadbf")
assertEquals(result, false)
result = lunique.valid("")
assertEquals(result, false)
result = lunique.valid("778d279d-dad5-4d32-b2a6-d325affeadbf-d325affeadbf")
assertEquals(result, false)
-- Test all the uuid generator functions
result = lunique.valid(lunique.generate())
assertEquals(result, true)
result = lunique.valid(lunique.generate_time())
assertEquals(result, true)
result = lunique.valid(lunique.generate_time_safe())
assertEquals(result, true)
result = lunique.valid(lunique.generate_random())
assertEquals(result, true)
end
LuaUnit:run()
|
Fixed error in unittest and removed uninteresting test
|
Fixed error in unittest and removed uninteresting test
No need to test the actual result when we are comparing "garbage".
The status is the interesting value, testCompare() tests the other part.
|
Lua
|
mit
|
dauer/lunique
|
259ffdb62f564688007d887f6f78e97826b79f4a
|
src/program/snabbvmx/check/check.lua
|
src/program/snabbvmx/check/check.lua
|
module(..., package.seeall)
local config = require("core.config")
local lib = require("core.lib")
local lwcheck = require("program.lwaftr.check.util")
local lwconf = require("apps.lwaftr.conf")
local setup = require("program.snabbvmx.lwaftr.setup")
local diff_counters = lwcheck.diff_counters
local load_requested_counters = lwcheck.load_requested_counters
local read_counters = lwcheck.read_counters
local validate_diff = lwcheck.validate_diff
local regen_counters = lwcheck.regen_counters
local function show_usage(code)
print(require("program.snabbvmx.check.README_inc"))
main.exit(code)
end
local function parse_args (args)
local handlers = {}
local opts = {}
function handlers.h() show_usage(0) end
function handlers.r() opts.r = true end
args = lib.dogetopt(args, handlers, "hrD:",
{ help="h", regen="r", duration="D" })
if #args ~= 5 and #args ~= 6 then show_usage(1) end
if not opts.duration then opts.duration = 0.10 end
return opts, args
end
function run(args)
local opts, args = parse_args(args)
local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path =
unpack(args)
local c = config.new()
setup.load_check(c, conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
engine.configure(c)
if counters_path then
local initial_counters = read_counters(c)
engine.main({duration=opts.duration})
local final_counters = read_counters(c)
local counters_diff = diff_counters(final_counters, initial_counters)
if opts.r then
regen_counters(counters_diff, counters_path)
else
local req_counters = load_requested_counters(counters_path)
validate_diff(counters_diff, req_counters)
end
else
engine.main({duration=opts.duration})
end
print("done")
end
|
module(..., package.seeall)
local config = require("core.config")
local lib = require("core.lib")
local util = require("program.lwaftr.check.util")
local lwcounter = require("program.lwaftr.lwcounter")
local setup = require("program.snabbvmx.lwaftr.setup")
local function show_usage(code)
print(require("program.snabbvmx.check.README_inc"))
main.exit(code)
end
local function parse_args (args)
local handlers = {}
local opts = {}
function handlers.h() show_usage(0) end
function handlers.r() opts.r = true end
args = lib.dogetopt(args, handlers, "hrD:",
{ help="h", regen="r", duration="D" })
if #args ~= 5 and #args ~= 6 then show_usage(1) end
if not opts.duration then opts.duration = 0.10 end
return opts, args
end
function run(args)
local opts, args = parse_args(args)
local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path =
unpack(args)
local c = config.new()
setup.load_check(c, conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
engine.configure(c)
if counters_path then
local initial_counters = lwcounter.read_counters(c)
engine.main({duration=opts.duration})
local final_counters = lwcounter.read_counters(c)
local counters_diff = util.diff_counters(final_counters,
initial_counters)
if opts.r then
util.regen_counters(counters_diff, counters_path)
else
local req_counters = util.load_requested_counters(counters_path)
util.validate_diff(counters_diff, req_counters)
end
else
engine.main({duration=opts.duration})
end
print("done")
end
|
Attempt to fix snabbvmx check
|
Attempt to fix snabbvmx check
|
Lua
|
apache-2.0
|
alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,Igalia/snabbswitch,dpino/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,dpino/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabb,SnabbCo/snabbswitch,dpino/snabb,Igalia/snabb,snabbco/snabb,snabbco/snabb,dpino/snabb,eugeneia/snabbswitch,Igalia/snabb,Igalia/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabb,dpino/snabbswitch,snabbco/snabb,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabbswitch,dpino/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,dpino/snabbswitch,eugeneia/snabb,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch
|
99f94acacfbb30388182a5ff06729eacee081dd1
|
lua_examples/onewire-ds18b20.lua
|
lua_examples/onewire-ds18b20.lua
|
--'
-- 18b20 one wire example for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
--'
pin = 9
ow.setup(pin)
count = 0
repeat
count = count + 1
addr = ow.reset_search(pin)
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
if (addr == nil) then
print("No more addresses.")
else
print(addr:byte(1,8))
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
print("Device is a DS18S20 family device.")
repeat
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
print("CRC="..crc)
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256) * 625
if (addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
t1 = t / 10000
t2 = t % 10000
print("Temperature= "..t1.."."..t2.." Centigrade")
end
tmr.wdclr()
until false
else
print("Device family is not recognized.")
end
else
print("CRC is not valid!")
end
end
|
--'
-- 18b20 one wire example for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
--'
pin = 9
ow.setup(pin)
count = 0
repeat
count = count + 1
addr = ow.reset_search(pin)
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
if (addr == nil) then
print("No more addresses.")
else
print(addr:byte(1,8))
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
print("Device is a DS18S20 family device.")
repeat
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
print("CRC="..crc)
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256)
-- handle negative temperatures
if (t > 0x7fff) then
t = t - 0x10000
end
if (addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
t1 = t / 10000
t2 = t % 10000
print("Temperature= "..t1.."."..t2.." Centigrade")
end
tmr.wdclr()
until false
else
print("Device family is not recognized.")
end
else
print("CRC is not valid!")
end
end
|
Add negative temp handling; fix multiplier
|
Add negative temp handling; fix multiplier
Negative temperatures (less than 0°C) are returned as a sign-extended
two's complement number. Subtract 0x10000 to recover the proper
negative value.
Also, do not multiply by 625 twice (thanks to @TerryE).
Signed-off-by: Nick Andrew <75ef9faee755c70589550b513ad881e5a603182c@nick-andrew.net>
|
Lua
|
mit
|
zerog2k/nodemcu-firmware,zerog2k/nodemcu-firmware,zerog2k/nodemcu-firmware
|
140f55cd5c08d84092af74b9dacf4098e337eeea
|
src/sailor/test.lua
|
src/sailor/test.lua
|
--------------------------------------------------------------------------------
-- test.lua, v0.4: Helper functions for testing functionality
-- This file is a part of Sailor project
-- Copyright (c) 2014-2015 Etiene Dalcol <dalcol@etiene.net>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local sailor = require "sailor"
local M = {req = {}}
local page
-- Prepares for making a request
function M:prepare(write_func, headers_in)
headers_in = headers_in or {}
M.req = { uri = '', write = write_func, puts = write_func, headers_in = headers_in, headers_out = {} }
page = sailor.init(M.req)
return self
end
-- Loads tests fixtures into the database
-- Warning, this will truncate the table, make sure you have configured a test database
-- Returns table with objects created
function M.load_fixtures(model_name)
local db = require "sailor.db"
local Model = sailor.model(model_name)
local fixtures = require("tests.fixtures."..model_name) or {}
local objects = {}
db.connect()
db.query('truncate table ' .. Model.db.table .. ';') -- Reseting current state
db.close()
for _,v in pairs(fixtures) do -- loading fixtures
local o = Model:new(v)
o:save(false)
table.insert(objects, o)
end
return objects
end
-- Function that is a part of the request response.
-- Verifies if the request redirected somewhere
-- Requires path: string
-- Returns boolean
local function redirected(response, path)
if response.status ~= 302 then return false end
return (response.headers['Location']):match(path) and true or false
end
-- Makes a mockup request to an internal sailor path
-- path: string. The path you want to make a request to, such as a controller or controller/action. Example: 'user/view'
-- data: table. A table containing some data you want to send to the request, such as get or post. Example: {get = {id = 1}}
-- additional_headers: A table containing additional headers you may want to send. Example: {ACCEPT = 'application/json'}
-- Returns a table with the following fields:
-- status: number. The status of the response.
-- body: string. The body of the response.
-- headers: table. Any headers out that were set.
-- redirected: function. The above redirect function
function M.request(path, data, additional_headers)
local conf = require "conf.conf"
data = data or {}
local body = ''
local function write(_,data) body = body .. data end
conf.sailor.friendly_urls = false
M:prepare(write,additional_headers)
page.POST = data.post or {}
page.GET = data.get or {}
page.GET[conf.sailor.route_parameter] = path
local status = sailor.route(page)
return {status = status, body = body, headers = M.req.headers_out, redirected = redirected}
end
return M:prepare()
|
--------------------------------------------------------------------------------
-- test.lua, v0.4: Helper functions for testing functionality
-- This file is a part of Sailor project
-- Copyright (c) 2014-2015 Etiene Dalcol <dalcol@etiene.net>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local sailor = require "sailor"
local lfs = require "lfs"
local M = {req = {}}
local page
-- Prepares for making a request
function M:prepare(write_func, headers_in)
headers_in = headers_in or {}
M.req = { uri = '', write = write_func, puts = write_func, headers_in = headers_in, headers_out = {} }
page = sailor.init(M.req)
return self
end
-- Loads tests fixtures into the database
-- Warning, this will truncate the table, make sure you have configured a test database
-- Returns table with objects created
function load_fixtures(model_name)
local db = require "sailor.db"
local Model = sailor.model(model_name)
local fixtures = require("tests.fixtures."..model_name) or {}
local objects = {}
db.connect()
db.query('truncate table ' .. Model.db.table .. ';') -- Reseting current state
db.close()
for _,v in pairs(fixtures) do -- loading fixtures
local o = Model:new(v)
o:save(false)
table.insert(objects, o)
end
return objects
end
function M.load_fixtures(model_name)
-- if model name is specific, load fixtures from a file
if model_name then
return load_fixtures(model_name)
end
-- if not specified, loads all fixtures in fixtures dir
for filename,_ in lfs.dir(sailor.path..'/tests/fixtures') do
model_name = string.match(filename,'(%w*).lua')
if model_name then
load_fixtures(model_name)
end
end
end
-- Function that is a part of the request response.
-- Verifies if the request redirected somewhere
-- Requires path: string
-- Returns boolean
local function redirected(response, path)
if response.status ~= 302 then return false end
return (response.headers['Location']):match(path) and true or false
end
-- Makes a mockup request to an internal sailor path
-- path: string. The path you want to make a request to, such as a controller or controller/action. Example: 'user/view'
-- data: table. A table containing some data you want to send to the request, such as get or post. Example: {get = {id = 1}}
-- additional_headers: A table containing additional headers you may want to send. Example: {ACCEPT = 'application/json'}
-- Returns a table with the following fields:
-- status: number. The status of the response.
-- body: string. The body of the response.
-- headers: table. Any headers out that were set.
-- redirected: function. The above redirect function
function M.request(path, data, additional_headers)
local conf = require "conf.conf"
data = data or {}
local body = ''
local function write(_,data) body = body .. data end
conf.sailor.friendly_urls = false
M:prepare(write,additional_headers)
page.POST = data.post or {}
page.GET = data.get or {}
page.GET[conf.sailor.route_parameter] = path
local status = sailor.route(page)
return {status = status, body = body, headers = M.req.headers_out, redirected = redirected}
end
return M:prepare()
|
chore(tests): Adds change to test.load_fixtures
|
chore(tests): Adds change to test.load_fixtures
Before a model_name had to be specified. Now if a name is not specified, it will load all fixtures inside the fixtures folder.
|
Lua
|
mit
|
Etiene/sailor,mpeterv/sailor,felipedaragon/sailor,Etiene/sailor,felipedaragon/sailor,mpeterv/sailor,sailorproject/sailor
|
d082c77003c8cfc1429489c99ecf176daf3b09bb
|
lib/luvit/timer.lua
|
lib/luvit/timer.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Timer = require('uv').Timer
local os = require('os')
local table = require('table')
local TIMEOUT_MAX = 2147483647
local lists = {}
local function init(list)
list._idleNext = list
list._idlePrev = list
end
local function peek(list)
if list._idlePrev == list then
return nil
end
return list._idlePrev
end
local function remove(item)
if item._idleNext then
item._idleNext._idlePrev = item._idlePrev
end
if item._idlePrev then
item._idlePrev._idleNext = item._idleNext
end
item._idleNext = nil
item._idlePrev = nil
end
local function shift(list)
local elem = list._idlePrev
remove(elem)
return elem
end
local function append(list, item)
remove(item)
item._idleNext = list._idleNext
list._idleNext._idlePrev = item
item._idlePrev = list
list._idleNext = item
end
local function isEmpty(list)
return list._idleNext == list
end
local expiration
expiration = function(timer, msecs)
return function()
local now = Timer.now()
while peek(timer) do
local elem = peek(timer)
local diff = now - elem._idleStart;
if ((diff + 1) < msecs) == true then
timer:start(msecs - diff, 0, expiration(timer, msecs))
return
else
remove(elem)
if elem._onTimeout then
elem._onTimeout()
end
end
end
-- Remove the timer if it wasn't already
-- removed by unenroll
if lists[msecs] ~= nil then
timer:stop()
timer:close()
lists[msecs] = nil
end
end
end
local function _insert(item, msecs)
item._idleStart = Timer.now()
item._idleTimeout = msecs
if msecs < 0 then return end
local list
if lists[msecs] then
list = lists[msecs]
else
list = Timer:new()
init(list)
list:start(msecs, 0, expiration(list, msecs))
lists[msecs] = list
end
append(list, item)
end
local function unenroll(item)
remove(item)
local list = lists[item._idleTimeout]
if list and isEmpty(list) then
-- empty list
list:stop()
list:close()
lists[item._idleTimeout] = nil
end
item._idleTimeout = -1
end
-- does not start the timer, just initializes the item
local function enroll(item, msecs)
if item._idleNext then
unenroll(item)
end
item._idleTimeout = msecs
init(item)
end
-- call this whenever the item is active (not idle)
local function active(item)
local msecs = item._idleTimeout
if msecs and msecs >= 0 then
local list = lists[msecs]
if not list or isEmpty(list) then
_insert(item, msecs)
else
item._idleStart = Timer.now()
append(lists[msecs], item)
end
end
end
local function setTimeout(duration, callback, ...)
local args = {...}
if duration < 1 or duration > TIMEOUT_MAX then
duration = 1
end
local timer = {}
timer._idleTimeout = duration
timer._idleNext = timer
timer._idlePrev = timer
timer._onTimeout = function()
callback(unpack(args))
end
active(timer)
return timer
end
local function setInterval(period, callback, ...)
local args = {...}
local timer = Timer:new()
timer:start(period, period, function (status)
callback(unpack(args))
end)
return timer
end
local function clearTimer(timer)
if not timer then
return
end
if timer._onTimeout then
timer._onTimeout = nil
if timer.close then
timer:close()
else
unenroll(timer)
end
else
timer:close()
end
end
local exports = {}
exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimer = clearTimer
exports.unenroll = unenroll
exports.enroll = enroll
exports.active = active
return exports
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Timer = require('uv').Timer
local os = require('os')
local table = require('table')
local TIMEOUT_MAX = 2147483647
local lists = {}
local function init(list)
list._idleNext = list
list._idlePrev = list
end
local function peek(list)
if list._idlePrev == list then
return nil
end
return list._idlePrev
end
local function remove(item)
if item._idleNext then
item._idleNext._idlePrev = item._idlePrev
end
if item._idlePrev then
item._idlePrev._idleNext = item._idleNext
end
item._idleNext = nil
item._idlePrev = nil
end
local function shift(list)
local elem = list._idlePrev
remove(elem)
return elem
end
local function append(list, item)
remove(item)
item._idleNext = list._idleNext
list._idleNext._idlePrev = item
item._idlePrev = list
list._idleNext = item
end
local function isEmpty(list)
return list._idleNext == list
end
local expiration
expiration = function(timer, msecs)
return function()
local now = Timer.now()
while peek(timer) do
local elem = peek(timer)
local diff = now - elem._idleStart;
if ((diff + 1) < msecs) == true then
timer:start(msecs - diff, 0, expiration(timer, msecs))
return
else
remove(elem)
if elem._onTimeout then
elem._onTimeout()
end
end
end
-- Remove the timer if it wasn't already
-- removed by unenroll
local list = lists[msecs]
if list and isEmpty(list) then
list:stop()
list:close()
lists[msecs] = nil
end
end
end
local function _insert(item, msecs)
item._idleStart = Timer.now()
item._idleTimeout = msecs
if msecs < 0 then return end
local list
if lists[msecs] then
list = lists[msecs]
else
list = Timer:new()
init(list)
list:start(msecs, 0, expiration(list, msecs))
lists[msecs] = list
end
append(list, item)
end
local function unenroll(item)
remove(item)
local list = lists[item._idleTimeout]
if list and isEmpty(list) then
-- empty list
list:stop()
list:close()
lists[item._idleTimeout] = nil
end
item._idleTimeout = -1
end
-- does not start the timer, just initializes the item
local function enroll(item, msecs)
if item._idleNext then
unenroll(item)
end
item._idleTimeout = msecs
init(item)
end
-- call this whenever the item is active (not idle)
local function active(item)
local msecs = item._idleTimeout
if msecs and msecs >= 0 then
local list = lists[msecs]
if not list or isEmpty(list) then
_insert(item, msecs)
else
item._idleStart = Timer.now()
append(lists[msecs], item)
end
end
end
local function setTimeout(duration, callback, ...)
local args = {...}
if duration < 1 or duration > TIMEOUT_MAX then
duration = 1
end
local timer = {}
timer._idleTimeout = duration
timer._idleNext = timer
timer._idlePrev = timer
timer._onTimeout = function()
callback(unpack(args))
end
active(timer)
return timer
end
local function setInterval(period, callback, ...)
local args = {...}
local timer = Timer:new()
timer:start(period, period, function (status)
callback(unpack(args))
end)
return timer
end
local function clearTimer(timer)
if not timer then
return
end
if timer._onTimeout then
timer._onTimeout = nil
if timer.close then
timer:close()
else
unenroll(timer)
end
else
timer:close()
end
end
local exports = {}
exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimer = clearTimer
exports.unenroll = unenroll
exports.enroll = enroll
exports.active = active
return exports
|
Fix an issue with closing a wrong timer which could cause the same timmer to be closed twice.
|
Fix an issue with closing a wrong timer which could cause the same timmer to be
closed twice.
|
Lua
|
apache-2.0
|
GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,luvit/luvit,boundary/luvit,bsn069/luvit,rjeli/luvit,sousoux/luvit,zhaozg/luvit,boundary/luvit,kaustavha/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,DBarney/luvit,sousoux/luvit,luvit/luvit,zhaozg/luvit,rjeli/luvit,sousoux/luvit,sousoux/luvit,DBarney/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,rjeli/luvit,kaustavha/luvit,bsn069/luvit,rjeli/luvit,bsn069/luvit,sousoux/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,boundary/luvit
|
d1d7c40be32fce8f878bf72f29e07509a88eee73
|
pretrained/classify.lua
|
pretrained/classify.lua
|
--
-- Copyright (c) 2016, Manuel Araoz
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- classifies an image using a trained model
--
require 'torch'
require 'paths'
require 'cudnn'
require 'cunn'
require 'image'
local t = require '../datasets/transforms'
local imagenetLabel = require './imagenet'
if #arg < 2 then
io.stderr:write('Usage: th classify.lua [MODEL] [FILE]...\n')
os.exit(1)
end
for _, f in ipairs(arg) do
if not paths.filep(f) then
io.stderr:write('file not found: ' .. f .. '\n')
os.exit(1)
end
end
-- Load the model
local model = torch.load(arg[1])
local softMaxLayer = cudnn.SoftMax():cuda()
-- add Softmax layer
model:add(softMaxLayer)
-- The model was trained with this input normalization
local meanstd = {
mean = { 0.485, 0.456, 0.406 },
std = { 0.229, 0.224, 0.225 },
}
local transform = t.Compose{
t.Scale(256),
t.ColorNormalize(meanstd),
t.CenterCrop(224),
}
local features
local N = 5
for i=2,#arg do
-- load the image as a RGB float tensor with values 0..1
local img = image.load(arg[i], 3, 'float')
local name = arg[i]:match( "([^/]+)$" )
-- Scale, normalize, and crop the image
img = transform(img)
-- View as mini-batch of size 1
batch = img:view(1, table.unpack(img:size():totable()))
-- Get the output of the softmax
local output = model:forward(batch:cuda()):squeeze()
-- Get the top 5 class indexes and probabilities
local probs, indexes = output:topk(N, true, true)
print('Classes for', arg[i])
for n=1,N do
print(probs[n], imagenetLabel[indexes[n]])
end
print('')
end
|
--
-- Copyright (c) 2016, Manuel Araoz
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- classifies an image using a trained model
--
require 'torch'
require 'paths'
require 'cudnn'
require 'cunn'
require 'image'
local t = require '../datasets/transforms'
local imagenetLabel = require './imagenet'
if #arg < 2 then
io.stderr:write('Usage: th classify.lua [MODEL] [FILE]...\n')
os.exit(1)
end
for _, f in ipairs(arg) do
if not paths.filep(f) then
io.stderr:write('file not found: ' .. f .. '\n')
os.exit(1)
end
end
-- Load the model
local model = torch.load(arg[1])
local softMaxLayer = cudnn.SoftMax():cuda()
-- add Softmax layer
model:add(softMaxLayer)
-- Evaluate mode
model:evaluate()
-- The model was trained with this input normalization
local meanstd = {
mean = { 0.485, 0.456, 0.406 },
std = { 0.229, 0.224, 0.225 },
}
local transform = t.Compose{
t.Scale(256),
t.ColorNormalize(meanstd),
t.CenterCrop(224),
}
local features
local N = 5
for i=2,#arg do
-- load the image as a RGB float tensor with values 0..1
local img = image.load(arg[i], 3, 'float')
local name = arg[i]:match( "([^/]+)$" )
-- Scale, normalize, and crop the image
img = transform(img)
-- View as mini-batch of size 1
batch = img:view(1, table.unpack(img:size():totable()))
-- Get the output of the softmax
local output = model:forward(batch:cuda()):squeeze()
-- Get the top 5 class indexes and probabilities
local probs, indexes = output:topk(N, true, true)
print('Classes for', arg[i])
for n=1,N do
print(probs[n], imagenetLabel[indexes[n]])
end
print('')
end
|
Run model in evaluate() mode in classify.lua
|
Run model in evaluate() mode in classify.lua
Fixes #28
|
Lua
|
bsd-3-clause
|
ltrottier/pelu.resnet.torch,ltrottier/pelu.resnet.torch
|
54bc99852636e00ba14a438b8d3d09e5902bcd6f
|
resources/maps/init.lua
|
resources/maps/init.lua
|
-- Chargement des maps
-- Dossier des maps
local mapsPath = core.atl.Loader.path
local path = '.'
-- Fonction récursive de chargement
local function load(path)
-- Tableau
local res = {}
-- Liste des dossiers
local files = love.filesystem.getDirectoryItems(mapsPath .. '/' .. path)
print(mapsPath .. '/' .. path, #files)
-- Charger tout le dossier
for f, fileName in ipairs(files) do
local filePath = string.gsub(mapsPath .. '/' .. path .. '/' .. fileName, '%./', '')
local fileRelativePath = string.gsub(path .. '/' .. fileName, '%./', '')
local name = string.match(fileName, '^[^.]+')
-- Fichier
if love.filesystem.isFile(filePath) and fileName ~= 'init.lua' then
local map = core.atl.Loader.load('/' .. fileRelativePath)
res[tonumber(name) or name] = map
-- Dossier
elseif love.filesystem.isDirectory(filePath) then
res[tonumber(fileName) or fileName] = load(fileRelativePath)
end
end
return res
end
return load(path)
|
-- Chargement des maps
return {
forest = {
[1] = core.atl.Loader.load('/forest/1.tmx')
}
}
--[[
-- Dossier des maps
local mapsPath = core.atl.Loader.path
local path = '.'
-- Fonction récursive de chargement
local function load(path)
-- Tableau
local res = {}
-- Liste des dossiers
local files = love.filesystem.getDirectoryItems(mapsPath .. '/' .. path)
print(mapsPath .. '/' .. path, #files)
-- Charger tout le dossier
for f, fileName in ipairs(files) do
local filePath = string.gsub(mapsPath .. '/' .. path .. '/' .. fileName, '%./', '')
local fileRelativePath = string.gsub(path .. '/' .. fileName, '%./', '')
local name = string.match(fileName, '^[^.]+')
-- Fichier
if love.filesystem.isFile(filePath) and fileName ~= 'init.lua' then
local map = core.atl.Loader.load('/' .. fileRelativePath)
res[tonumber(name) or name] = map
-- Dossier
elseif love.filesystem.isDirectory(filePath) then
res[tonumber(fileName) or fileName] = load(fileRelativePath)
end
end
return res
end
return load(path)]]
|
Correction temporaire d'un bug lorsque le jeu est lancé en version zippée
|
Correction temporaire d'un bug lorsque le jeu est lancé en version zippée
|
Lua
|
mit
|
etienne-gauvin/projet-tut
|
0d9de559445dda6e7e9bedc7297254bc7581d53d
|
reader.lua
|
reader.lua
|
#!./kpdfview
--[[
KindlePDFViewer: a reader implementation
Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
require "alt_getopt"
KEY_PAGEUP = 109 -- nonstandard
KEY_PAGEDOWN = 124 -- nonstandard
KEY_BACK = 91 -- nonstandard
KEY_MENU = 139
-- DPad:
KEY_UP = 122 -- nonstandard
KEY_DOWN = 123 -- nonstandard
KEY_LEFT = 105
KEY_RIGHT = 106
KEY_BTN = 92 -- nonstandard
-- constants from <linux/input.h>
EV_KEY = 1
-- event values
EVENT_VALUE_KEY_PRESS = 1
EVENT_VALUE_KEY_REPEAT = 2
EVENT_VALUE_KEY_RELEASE = 0
-- option parsing:
longopts = {
password = "p",
goto = "g",
gamma = "G",
device = "d",
help = "h"
}
optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts)
if optarg["h"] or ARGV[optind] == nil then
print("usage: ./reader.lua [OPTION] ... DOCUMENT.PDF")
print("Read PDFs on your E-Ink reader")
print("")
print("-p, --password=PASSWORD set password for reading PDF document")
print("-g, --goto=page start reading on page")
print("-G, --gamma=GAMMA set gamma correction")
print(" (floating point notation, e.g. \"1.5\")")
print("-d, --device=DEVICE set device specific configuration,")
print(" currently one of \"kdxg\" (default), \"k3\"")
print("-h, --help show this usage help")
print("")
print("This software is licensed under the GPLv3.")
print("See http://github.com/hwhw/kindlepdfviewer for more info.")
return
end
rcount = 5
rcountmax = 5
globalzoom = -1
if optarg["d"] == "k3" then
-- for now, the only difference is the additional input device
input.open("/dev/input/event0")
input.open("/dev/input/event1")
input.open("/dev/input/event2")
elseif optarg["d"] == "emu" then
input.open("")
-- SDL key codes
KEY_PAGEDOWN = 112
KEY_PAGEUP = 117
KEY_BACK = 22 -- backspace
KEY_MENU = 67 -- F1
KEY_UP = 111
KEY_DOWN = 116
KEY_LEFT = 113
KEY_RIGHT = 114
KEY_BTN = 36 -- enter for now
else
input.open("/dev/input/event0")
input.open("/dev/input/event1")
end
doc = pdf.openDocument(ARGV[optind], optarg["p"] or "")
print("pdf has "..doc:getPages().." pages.")
fb = einkfb.open("/dev/fb0")
width, height = fb:getSize()
nulldc = pdf.newDC()
cache = {
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil },
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil },
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil }
}
function freecache()
for i = 1, #cache do
if cache[i].page ~= nil then
print("freeing slot="..i.." oldpage="..cache[i].no)
cache[i].page:close()
cache[i].page = nil
end
end
end
function checkcache(no)
for i = 1, #cache do
if cache[i].no == no then
print("cache hit: slot="..i.." page="..no)
return i
end
end
print("cache miss")
return nil
end
function cacheslot()
freeslot = nil
while freeslot == nil do
for i = 1, #cache do
if cache[i].age > 0 then
print("aging slot="..i)
cache[i].age = cache[i].age - 1
else
if cache[i].page ~= nil then
print("freeing slot="..i.." oldpage="..cache[i].no)
cache[i].page:close()
cache[i].page = nil
end
freeslot = i
end
end
end
print("returning free slot="..freeslot)
return freeslot
end
function draworcache(no)
local slot = checkcache(no)
if slot == nil then
slot = cacheslot()
cache[slot].no = no
cache[slot].age = #cache
cache[slot].page = doc:openPage(no)
setzoom(slot)
print("drawing page="..no.." to slot="..slot)
cache[slot].page:draw(cache[slot].dc, cache[slot].bb, 0, 0)
end
return slot
end
function setzoom(cacheslot)
local pwidth, pheight = cache[cacheslot].page:getSize(nulldc)
-- default zoom: fit to page
local zoom = width / pwidth
local offset_x = 0
local offset_y = (height - (zoom * pheight)) / 2
if height / pheight < zoom then
zoom = height / pheight
offset_x = (width - (zoom * pwidth)) / 2
offset_y = 0
end
cache[cacheslot].dc:setZoom(zoom)
cache[cacheslot].dc:setOffset(offset_x, offset_y)
-- set gamma here, we don't have any other good place for this right now:
if optarg["G"] then
print("gamma correction: "..optarg["G"])
cache[cacheslot].dc:setGamma(optarg["G"])
end
end
function show(no)
local slot = draworcache(no)
fb:blitFullFrom(cache[slot].bb)
if rcount == rcountmax then
print("full refresh")
rcount = 1
fb:refresh(0)
else
print("partial refresh")
rcount = rcount + 1
fb:refresh(1)
end
slot_visible = slot;
end
function goto(no)
if no < 1 or no > doc:getPages() then
return
end
pageno = no
show(no)
if no < doc:getPages() then
-- always pre-cache next page
draworcache(no+1)
end
end
function modify_gamma(offset)
local slot = slot_visible
local gamma = cache[slot].dc:getGamma();
if gamma == -1 then
gamma = 1
end
print("modify_gamma slot="..slot.." gamma="..gamma.." offset="..offset)
gamma = gamma + offset;
cache[slot].dc:setGamma( gamma );
optarg["G"] = gamma; -- for next page
cache[slot].page:draw(cache[slot].dc, cache[slot].bb, 0, 0)
fb:blitFullFrom(cache[slot].bb)
fb:refresh(0)
end
function mainloop()
while 1 do
local ev = input.waitForEvent()
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
local secs, usecs = util.gettime()
if ev.code == KEY_PAGEUP then
print(cache)
goto(pageno + 1)
print(cache)
elseif ev.code == KEY_PAGEDOWN then
print(cache)
goto(pageno - 1)
print(cache)
elseif ev.code == KEY_BACK then
return
elseif ev.code == KEY_UP then
modify_gamma( 0.2 )
elseif ev.code == KEY_DOWN then
modify_gamma( -0.2 )
end
local nsecs, nusecs = util.gettime()
local dur = (nsecs - secs) * 1000000 + nusecs - usecs
print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur)
end
end
end
goto(tonumber(optarg["g"]) or 1)
mainloop()
|
#!./kpdfview
--[[
KindlePDFViewer: a reader implementation
Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
require "alt_getopt"
KEY_PAGEUP = 109 -- nonstandard
KEY_PAGEDOWN = 124 -- nonstandard
KEY_BACK = 91 -- nonstandard
KEY_MENU = 139
-- DPad:
KEY_UP = 122 -- nonstandard
KEY_DOWN = 123 -- nonstandard
KEY_LEFT = 105
KEY_RIGHT = 106
KEY_BTN = 92 -- nonstandard
-- constants from <linux/input.h>
EV_KEY = 1
-- event values
EVENT_VALUE_KEY_PRESS = 1
EVENT_VALUE_KEY_REPEAT = 2
EVENT_VALUE_KEY_RELEASE = 0
-- option parsing:
longopts = {
password = "p",
goto = "g",
gamma = "G",
device = "d",
help = "h"
}
optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts)
if optarg["h"] or ARGV[optind] == nil then
print("usage: ./reader.lua [OPTION] ... DOCUMENT.PDF")
print("Read PDFs on your E-Ink reader")
print("")
print("-p, --password=PASSWORD set password for reading PDF document")
print("-g, --goto=page start reading on page")
print("-G, --gamma=GAMMA set gamma correction")
print(" (floating point notation, e.g. \"1.5\")")
print("-d, --device=DEVICE set device specific configuration,")
print(" currently one of \"kdxg\" (default), \"k3\"")
print("-h, --help show this usage help")
print("")
print("This software is licensed under the GPLv3.")
print("See http://github.com/hwhw/kindlepdfviewer for more info.")
return
end
rcount = 5
rcountmax = 5
globalzoom = -1
if optarg["d"] == "k3" then
-- for now, the only difference is the additional input device
input.open("/dev/input/event0")
input.open("/dev/input/event1")
input.open("/dev/input/event2")
elseif optarg["d"] == "emu" then
input.open("")
-- SDL key codes
KEY_PAGEDOWN = 112
KEY_PAGEUP = 117
KEY_BACK = 22 -- backspace
KEY_MENU = 67 -- F1
KEY_UP = 111
KEY_DOWN = 116
KEY_LEFT = 113
KEY_RIGHT = 114
KEY_BTN = 36 -- enter for now
else
input.open("/dev/input/event0")
input.open("/dev/input/event1")
end
doc = pdf.openDocument(ARGV[optind], optarg["p"] or "")
print("pdf has "..doc:getPages().." pages.")
fb = einkfb.open("/dev/fb0")
width, height = fb:getSize()
nulldc = pdf.newDC()
cache = {
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil },
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil },
{ age = 0, no = 0, bb = blitbuffer.new(width, height), dc = pdf.newDC(), page = nil }
}
function freecache()
for i = 1, #cache do
if cache[i].page ~= nil then
print("freeing slot="..i.." oldpage="..cache[i].no)
cache[i].page:close()
cache[i].page = nil
end
end
end
function checkcache(no)
for i = 1, #cache do
if cache[i].no == no and cache[i].page ~= nil then
print("cache hit: slot="..i.." page="..no)
return i
end
end
print("cache miss")
return nil
end
function cacheslot()
freeslot = nil
while freeslot == nil do
for i = 1, #cache do
if cache[i].age > 0 then
print("aging slot="..i)
cache[i].age = cache[i].age - 1
else
if cache[i].page ~= nil then
print("freeing slot="..i.." oldpage="..cache[i].no)
cache[i].page:close()
cache[i].page = nil
end
freeslot = i
end
end
end
print("returning free slot="..freeslot)
return freeslot
end
function draworcache(no)
local slot = checkcache(no)
if slot == nil then
slot = cacheslot()
cache[slot].no = no
cache[slot].age = #cache
cache[slot].page = doc:openPage(no)
setzoom(slot)
print("drawing page="..no.." to slot="..slot)
cache[slot].page:draw(cache[slot].dc, cache[slot].bb, 0, 0)
end
return slot
end
function setzoom(cacheslot)
local pwidth, pheight = cache[cacheslot].page:getSize(nulldc)
-- default zoom: fit to page
local zoom = width / pwidth
local offset_x = 0
local offset_y = (height - (zoom * pheight)) / 2
if height / pheight < zoom then
zoom = height / pheight
offset_x = (width - (zoom * pwidth)) / 2
offset_y = 0
end
cache[cacheslot].dc:setZoom(zoom)
cache[cacheslot].dc:setOffset(offset_x, offset_y)
-- set gamma here, we don't have any other good place for this right now:
if optarg["G"] then
print("gamma correction: "..optarg["G"])
cache[cacheslot].dc:setGamma(optarg["G"])
end
end
function show(no)
local slot = draworcache(no)
fb:blitFullFrom(cache[slot].bb)
if rcount == rcountmax then
print("full refresh")
rcount = 1
fb:refresh(0)
else
print("partial refresh")
rcount = rcount + 1
fb:refresh(1)
end
slot_visible = slot;
end
function goto(no)
if no < 1 or no > doc:getPages() then
return
end
pageno = no
show(no)
if no < doc:getPages() then
-- always pre-cache next page
draworcache(no+1)
end
end
function modify_gamma(offset)
local slot = slot_visible
local gamma = cache[slot].dc:getGamma();
if gamma == -1 then
gamma = 1
end
local no = cache[slot].no
print("modify_gamma "..no.." slot="..slot.." gamma="..gamma.." offset="..offset)
gamma = gamma + offset;
optarg["G"] = gamma; -- for next page
freecache()
goto(no)
end
function mainloop()
while 1 do
local ev = input.waitForEvent()
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
local secs, usecs = util.gettime()
if ev.code == KEY_PAGEUP then
print(cache)
goto(pageno + 1)
print(cache)
elseif ev.code == KEY_PAGEDOWN then
print(cache)
goto(pageno - 1)
print(cache)
elseif ev.code == KEY_BACK then
return
elseif ev.code == KEY_UP then
modify_gamma( 0.2 )
elseif ev.code == KEY_DOWN then
modify_gamma( -0.2 )
end
local nsecs, nusecs = util.gettime()
local dur = (nsecs - secs) * 1000000 + nusecs - usecs
print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur)
end
end
end
goto(tonumber(optarg["g"]) or 1)
mainloop()
|
modify_gamma now use cache correctly
|
modify_gamma now use cache correctly
This exposed small bug in checkcache which checked just page no
which didn't get invalidated when closing page, so we now check if page
is also not nil
|
Lua
|
agpl-3.0
|
koreader/koreader-base,frankyifei/koreader,Frenzie/koreader-base,frankyifei/koreader-base,poire-z/koreader,mihailim/koreader,Hzj-jie/koreader-base,robert00s/koreader,Frenzie/koreader-base,koreader/koreader-base,pazos/koreader,koreader/koreader,houqp/koreader,Frenzie/koreader-base,Frenzie/koreader,NickSavage/koreader,koreader/koreader-base,ashang/koreader,houqp/koreader-base,NiLuJe/koreader-base,apletnev/koreader,houqp/koreader-base,Hzj-jie/koreader-base,chihyang/koreader,noname007/koreader,houqp/koreader-base,Hzj-jie/koreader-base,lgeek/koreader,NiLuJe/koreader,NiLuJe/koreader-base,apletnev/koreader-base,mwoz123/koreader,ashhher3/koreader,Hzj-jie/koreader-base,apletnev/koreader-base,poire-z/koreader,apletnev/koreader-base,NiLuJe/koreader,koreader/koreader,NiLuJe/koreader-base,Frenzie/koreader-base,chrox/koreader,frankyifei/koreader-base,houqp/koreader-base,Hzj-jie/koreader,NiLuJe/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,Markismus/koreader,Frenzie/koreader,koreader/koreader-base,apletnev/koreader-base
|
824a5172ca4163deaabfe22bac740825301f6aca
|
private/osx/Users/user/.hydra/init.lua
|
private/osx/Users/user/.hydra/init.lua
|
-- Hi!
-- Save this as ~/.hydra/init.lua and choose Reload Config from the menu
hydra.alert("Hydra config by justmao945 loaded", 1.5)
-- Uncomment this if you want Hydra to make sure it launches at login
autolaunch.set(true)
-- main modkey
local modkey = {"cmd", "ctrl"}
-- open a repl
-- the repl is a Lua prompt; type "print('hello world')"
-- when you're in the repl, type "help" to get started
-- almost all readline functionality works in the repl
hotkey.bind(modkey, "R", repl.open)
-- I've worked hard to make Hydra useful and easy to use. I've also
-- released it with a liberal open source license, so that you can do
-- with it as you please. So, instead of charging for licenses, I'm
-- asking for donations. If you find it helpful, I encourage you to
-- donate what you believe would have been a fair price for a license:
local function donate()
os.execute("open 'https://www.paypal.com/cgi-bin/webscr?business=sbdegutis@gmail.com&cmd=_donations&item_name=Hydra.app%20donation'")
end
hotkey.bind({"cmd", "alt", "ctrl"}, "D", donate)
-- move the window
function movewindow(fn)
local win = window.focusedwindow()
local newframe = win:screen():frame_without_dock_or_menu()
fn(newframe);
win:setframe(newframe)
end
-- move the window to the right half of the screen
function movewindow_righthalf()
movewindow(function(newframe)
newframe.w = newframe.w / 2
newframe.x = newframe.w -- comment this line to push it to left half of screen
end)
end
-- move the window to the left half of the screen
function movewindow_lefthalf()
movewindow(function(newframe)
newframe.w = newframe.w / 2
newframe.x = 0
end)
end
hotkey.new(modkey, "H", movewindow_lefthalf):enable()
hotkey.new(modkey, "L", movewindow_righthalf):enable()
-- Maximize the window
hotkey.new(modkey, "M", function()
window.focusedwindow():maximize()
end):enable()
-- Update
-- save the time when updates are checked
function checkforupdates()
updates.check(updates.available)
settings.set('lastcheckedupdates', os.time())
end
-- show available updates
local function showupdate()
os.execute('open https://github.com/sdegutis/Hydra/releases')
end
-- what to do when an update is checked
function updates.available(available)
if available then
notify.show("Hydra update available", "", "Click here to see the changelog and maybe even install it", "showupdate")
else
hydra.alert("No update available.")
end
end
-- check for updates every week
timer.new(timer.weeks(1), checkforupdates):start()
notify.register("showupdate", showupdate)
-- if this is your first time running Hydra, you're launching it more than a week later, check now
local lastcheckedupdates = settings.get('lastcheckedupdates')
if lastcheckedupdates == nil or lastcheckedupdates <= os.time() - timer.days(7) then
checkforupdates()
end
-- show a helpful menu
menu.show(function()
local updatetitles = {[true] = "Install Update", [false] = "Check for Update..."}
local updatefns = {[true] = updates.install, [false] = checkforupdates}
local hasupdate = (updates.newversion ~= nil)
return {
{title = "Reload Config", fn = hydra.reload},
{title = "Open REPL", fn = repl.open},
{title = "-"},
{title = "About", fn = hydra.showabout},
{title = updatetitles[hasupdate], fn = updatefns[hasupdate]},
{title = "Quit Hydra", fn = os.exit},
}
end)
|
-- Hi!
-- Save this as ~/.hydra/init.lua and choose Reload Config from the menu
hydra.alert("Hydra config by justmao945 loaded", 1.5)
-- Uncomment this if you want Hydra to make sure it launches at login
autolaunch.set(true)
-- main modkey
local modkey = {"cmd", "ctrl"}
-- open a repl
-- the repl is a Lua prompt; type "print('hello world')"
-- when you're in the repl, type "help" to get started
-- almost all readline functionality works in the repl
hotkey.bind(modkey, "R", repl.open)
-- I've worked hard to make Hydra useful and easy to use. I've also
-- released it with a liberal open source license, so that you can do
-- with it as you please. So, instead of charging for licenses, I'm
-- asking for donations. If you find it helpful, I encourage you to
-- donate what you believe would have been a fair price for a license:
local function donate()
os.execute("open 'https://www.paypal.com/cgi-bin/webscr?business=sbdegutis@gmail.com&cmd=_donations&item_name=Hydra.app%20donation'")
end
hotkey.bind({"cmd", "alt", "ctrl"}, "D", donate)
-- move the window
function movewindow(fn)
local win = window.focusedwindow()
if win == nil then
return
end
local newframe = win:screen():frame_without_dock_or_menu()
fn(newframe);
win:setframe(newframe)
end
-- move the window to the right half of the screen
function movewindow_righthalf()
movewindow(function(newframe)
newframe.w = newframe.w / 2
newframe.x = newframe.w -- comment this line to push it to left half of screen
end)
end
-- move the window to the left half of the screen
function movewindow_lefthalf()
movewindow(function(newframe)
newframe.w = newframe.w / 2
newframe.x = 0
end)
end
hotkey.new(modkey, "H", movewindow_lefthalf):enable()
hotkey.new(modkey, "L", movewindow_righthalf):enable()
-- Maximize the window
hotkey.new(modkey, "M", function()
local win = window.focusedwindow()
if win ~= nil then
win:maximize()
end
end):enable()
-- Update
-- save the time when updates are checked
function checkforupdates()
updates.check(updates.available)
settings.set('lastcheckedupdates', os.time())
end
-- show available updates
local function showupdate()
os.execute('open https://github.com/sdegutis/Hydra/releases')
end
-- what to do when an update is checked
function updates.available(available)
if available then
notify.show("Hydra update available", "", "Click here to see the changelog and maybe even install it", "showupdate")
else
hydra.alert("No update available.")
end
end
-- check for updates every week
timer.new(timer.weeks(1), checkforupdates):start()
notify.register("showupdate", showupdate)
-- if this is your first time running Hydra, you're launching it more than a week later, check now
local lastcheckedupdates = settings.get('lastcheckedupdates')
if lastcheckedupdates == nil or lastcheckedupdates <= os.time() - timer.days(7) then
checkforupdates()
end
-- show a helpful menu
menu.show(function()
local updatetitles = {[true] = "Install Update", [false] = "Check for Update..."}
local updatefns = {[true] = updates.install, [false] = checkforupdates}
local hasupdate = (updates.newversion ~= nil)
return {
{title = "Reload Config", fn = hydra.reload},
{title = "Open REPL", fn = repl.open},
{title = "-"},
{title = "About", fn = hydra.showabout},
{title = updatetitles[hasupdate], fn = updatefns[hasupdate]},
{title = "Quit Hydra", fn = os.exit},
}
end)
|
fix nil error on minimized window
|
fix nil error on minimized window
|
Lua
|
mit
|
justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab,justmao945/lab
|
f9fa4a71db078e608da75a0be1fd4d1532237345
|
src/characters/troy.lua
|
src/characters/troy.lua
|
local anim8 = require 'vendor/anim8'
local plyr = {}
plyr.name = 'troy'
plyr.offset = 11
plyr.ow = 6
plyr.costumes = {
{name='Troy Barnes', sheet='images/troy.png'},
-- {name='Barry the Plumber', sheet='images/troy_barry.png'},
-- {name='Blanketsburg', sheet='images/troy_blanket.png'},
{name='Bumblebee', sheet='images/troy_bumblebee.png'},
-- {name='Constable Reggie', sheet='images/troy_reggie.png'},
-- {name='Eddie Murphy', sheet='images/troy_eddie.png'},
{name='Detective', sheet='images/troy_detective.png'},
{name='Kickpuncher', sheet='images/troy_kick.png'},
-- {name='King of Clubs', sheet='images/troy_clubs.png'},
{name='Library Nerd', sheet='images/troy_library.png'},
-- {name='Ripley', sheet='images/troy_ridley.png'},
{name='Pant Suit', sheet='images/troy_pantsuit.png'},
{name='Paintball', sheet='images/troy_paintball.png'},
{name='Sexy Dracula', sheet='images/troy_sexyvampire.png'},
{name='Spiderman', sheet='images/troy_spidey.png'},
{name='Star Quarterback', sheet='images/troy_football.png'},
{name='Troy and Abed Sewn Together', sheet='images/troy_sewn.png'},
{name='Night Troy', sheet='images/troy_night.png'},
}
local beam = love.graphics.newImage('images/troy_beam.png')
function plyr.new(sheet)
local new_plyr = {}
new_plyr.sheet = sheet
new_plyr.sheet:setFilter('nearest', 'nearest')
new_plyr.beam = beam
local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(),
new_plyr.sheet:getHeight())
local warp = anim8.newGrid(36, 223, beam:getWidth(),
beam:getHeight())
new_plyr.hand_offset = 18
new_plyr.animations = {
dead = {
right = anim8.newAnimation('once', g('9,5'), 1),
left = anim8.newAnimation('once', g('9,6'), 1)
},
hold = {
right = anim8.newAnimation('once', g(5,6), 1),
left = anim8.newAnimation('once', g(5,5), 1),
},
holdwalk = {
right = anim8.newAnimation('loop', g('4-6,10', '5,10'), 0.16),
left = anim8.newAnimation('loop', g('4-6,9', '5,9'), 0.16),
},
jump = {
right = anim8.newAnimation('loop', g('5-7,2', '6,2'), 0.10),
left = anim8.newAnimation('loop', g('5-7,1', '6,1'), 0.10)
},
walk = {
right = anim8.newAnimation('loop', g('2-4,2', '3,2'), 0.16),
left = anim8.newAnimation('loop', g('2-4,1', '3,1'), 0.16)
},
crouch = {
right = anim8.newAnimation('once', g(9,2), 1),
left = anim8.newAnimation('once', g(9,1), 1)
},
crouchwalk = { --state for walking towards the camera
left = anim8.newAnimation('loop', g('3-4,3'), 0.16),
right = anim8.newAnimation('loop', g('3-4,3'), 0.16),
},
gaze = {
right = anim8.newAnimation('once', g(9,4), 1),
left = anim8.newAnimation('once', g(9,3), 1),
},
gazewalk = { --state for walking away from the camera
left = anim8.newAnimation('loop', g('2-3,4'), 0.16),
right = anim8.newAnimation('loop', g('2-3,4'), 0.16),
},
idle = {
right = anim8.newAnimation('once', g(1,2), 1),
left = anim8.newAnimation('once', g(1,1), 1)
},
warp = anim8.newAnimation('once', warp('1-4,1'), 0.08),
}
return new_plyr
end
return plyr
|
local anim8 = require 'vendor/anim8'
local plyr = {}
plyr.name = 'troy'
plyr.offset = 11
plyr.ow = 6
plyr.costumes = {
{name='Troy Barnes', sheet='images/troy.png'},
-- {name='Barry the Plumber', sheet='images/troy_barry.png'},
-- {name='Blanketsburg', sheet='images/troy_blanket.png'},
{name='Bumblebee', sheet='images/troy_bumblebee.png'},
-- {name='Constable Reggie', sheet='images/troy_reggie.png'},
-- {name='Eddie Murphy', sheet='images/troy_eddie.png'},
{name='Detective', sheet='images/troy_detective.png'},
{name='Kickpuncher', sheet='images/troy_kick.png'},
-- {name='King of Clubs', sheet='images/troy_clubs.png'},
{name='Library Nerd', sheet='images/troy_library.png'},
{name='Night Troy', sheet='images/troy_night.png'},
-- {name='Ripley', sheet='images/troy_ridley.png'},
{name='Pant Suit', sheet='images/troy_pantsuit.png'},
{name='Paintball', sheet='images/troy_paintball.png'},
{name='Sexy Dracula', sheet='images/troy_sexyvampire.png'},
{name='Spiderman', sheet='images/troy_spidey.png'},
{name='Star Quarterback', sheet='images/troy_football.png'},
{name='Troy and Abed Sewn Together', sheet='images/troy_sewn.png'},
}
local beam = love.graphics.newImage('images/troy_beam.png')
function plyr.new(sheet)
local new_plyr = {}
new_plyr.sheet = sheet
new_plyr.sheet:setFilter('nearest', 'nearest')
new_plyr.beam = beam
local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(),
new_plyr.sheet:getHeight())
local warp = anim8.newGrid(36, 223, beam:getWidth(),
beam:getHeight())
new_plyr.hand_offset = 18
new_plyr.animations = {
dead = {
right = anim8.newAnimation('once', g('9,5'), 1),
left = anim8.newAnimation('once', g('9,6'), 1)
},
hold = {
right = anim8.newAnimation('once', g(5,6), 1),
left = anim8.newAnimation('once', g(5,5), 1),
},
holdwalk = {
right = anim8.newAnimation('loop', g('4-6,10', '5,10'), 0.16),
left = anim8.newAnimation('loop', g('4-6,9', '5,9'), 0.16),
},
jump = {
right = anim8.newAnimation('loop', g('5-7,2', '6,2'), 0.10),
left = anim8.newAnimation('loop', g('5-7,1', '6,1'), 0.10)
},
walk = {
right = anim8.newAnimation('loop', g('2-4,2', '3,2'), 0.16),
left = anim8.newAnimation('loop', g('2-4,1', '3,1'), 0.16)
},
crouch = {
right = anim8.newAnimation('once', g(9,2), 1),
left = anim8.newAnimation('once', g(9,1), 1)
},
crouchwalk = { --state for walking towards the camera
left = anim8.newAnimation('loop', g('3-4,3'), 0.16),
right = anim8.newAnimation('loop', g('3-4,3'), 0.16),
},
gaze = {
right = anim8.newAnimation('once', g(9,4), 1),
left = anim8.newAnimation('once', g(9,3), 1),
},
gazewalk = { --state for walking away from the camera
left = anim8.newAnimation('loop', g('2-3,4'), 0.16),
right = anim8.newAnimation('loop', g('2-3,4'), 0.16),
},
idle = {
right = anim8.newAnimation('once', g(1,2), 1),
left = anim8.newAnimation('once', g(1,1), 1)
},
warp = anim8.newAnimation('once', warp('1-4,1'), 0.08),
}
return new_plyr
end
return plyr
|
fixed the troy night costume to fit alphabetically
|
fixed the troy night costume to fit alphabetically
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
c1b4dab10f6a439943d94a58bbea661b4478cdc4
|
plugins/lua/env.lua
|
plugins/lua/env.lua
|
local ENV = {}
--
-- Returns a copy of a table with all current members read-only
-- If target is defined, the returned result will be equal to target
--
local function ProtectTable( tab, target )
local index = {}
local ret = target or {}
-- Copy new variables in to our table
-- Tables are also protected
for k, v in pairs( tab ) do
if v == target then
index[ k ] = ret
elseif not getmetatable( v ) and type( v ) == "table" then
index[ k ] = ProtectTable( tab[ k ] )
else
index[ k ] = tab[ k ]
end
end
local meta = {}
meta.__index = index
meta.__metatable = false
function meta:__newindex( k, v )
if rawget( index, k, v ) then
error( "attempt to modify read-only member '" .. k .. "'", 2 )
return
end
rawset( self, k, v )
end
function meta:__pairs()
local t = {}
for k, v in next, self, nil do
t[ k ] = v
end
for k, v in pairs( meta.__index ) do
t[ k ] = v
end
return next, t, nil
end
return setmetatable( ret, meta )
end
local INDEX = {
_G = ENV,
_VERSION = _VERSION,
assert = assert,
collectgarbage = collectgarbage,
coroutine = coroutine,
error = error,
getmetatable = getmetatable,
ipairs = ipairs,
next = next,
pairs = pairs,
pcall = pcall,
print = print,
rawequal = rawequal,
select = select,
setmetatable = setmetatable,
tonumber = tonumber,
tostring = tostring,
type = type,
xpcall = xpcall,
math = math,
string = string,
table = table,
utf8 = utf8,
cookie = require "cookie",
hook = require "hook",
include = require "user_include",
require = require "user_require",
timer = require "timer",
io = {
write = function( ... )
io.write( ... )
end
},
os = {
time = os.time,
clock = os.clock,
date = os.date
}
}
function INDEX.load( chunk, chunkname )
return load( chunk, chunkname, "t", ENV )
end
return ProtectTable( INDEX, ENV )
|
local ENV = {}
--
-- Returns a copy of a table with all current members read-only
-- If target is defined, the returned result will be equal to target
--
local function ProtectTable( tab, target )
local index = {}
local ret = target or {}
-- Copy new variables in to our table
-- Tables are also protected
for k, v in pairs( tab ) do
if v == target then
index[ k ] = ret
index[ k ] = ProtectTable( tab[ k ] )
else
index[ k ] = tab[ k ]
end
end
local meta = {}
meta.__index = index
meta.__metatable = false
function meta:__newindex( k, v )
if rawget( index, k, v ) then
error( "attempt to modify read-only member '" .. k .. "'", 2 )
return
end
rawset( self, k, v )
end
function meta:__pairs()
local t = {}
for k, v in next, self, nil do
t[ k ] = v
end
for k, v in pairs( meta.__index ) do
t[ k ] = v
end
return next, t, nil
end
return setmetatable( ret, meta )
end
local INDEX = {
_G = ENV,
_VERSION = _VERSION,
assert = assert,
collectgarbage = collectgarbage,
coroutine = coroutine,
error = error,
getmetatable = getmetatable,
ipairs = ipairs,
next = next,
pairs = pairs,
pcall = pcall,
print = print,
rawequal = rawequal,
select = select,
setmetatable = setmetatable,
tonumber = tonumber,
tostring = tostring,
type = type,
xpcall = xpcall,
math = math,
string = string,
table = table,
utf8 = utf8,
cookie = require "cookie",
hook = require "hook",
include = require "user_include",
require = require "user_require",
timer = require "timer",
io = {
write = function( ... )
io.write( ... )
end
},
os = {
time = os.time,
clock = os.clock,
date = os.date
}
}
function INDEX.load( chunk, chunkname )
return load( chunk, chunkname, "t", ENV )
end
return ProtectTable( INDEX, ENV )
|
Fix tables we don't want protected being protected
|
Fix tables we don't want protected being protected
|
Lua
|
cc0-1.0
|
mcd1992/hash.js,ModMountain/hash.js,LennyPenny/hash.js,SwadicalRag/hash.js,meepdarknessmeep/hash.js
|
906e72397075200e8cb8b98bc8b7b7f96d992907
|
src/datastore/src/Server/DataStore.lua
|
src/datastore/src/Server/DataStore.lua
|
--[=[
Wraps the datastore object to provide async cached loading and saving. See [DataStoreStage] for more API.
Has the following features
* Automatic save
* Jitter
* De-duplication (only updates data it needs)
```lua
local playerMoneyValue = Instance.new("IntValue")
playerMoneyValue.Value = 0
local dataStore = DataStore.new(DataStoreService:GetDataStore("test"), test-store")
dataStore:Load("money", 0):Then(function(money)
playerMoneyValue.Value = money
dataStore:StoreOnValueChange("money", playerMoneyValue)
end):Catch(function()
-- TODO: Notify player
end)
```
@server
@class DataStore
]=]
local require = require(script.Parent.loader).load(script)
local DataStoreDeleteToken = require("DataStoreDeleteToken")
local DataStorePromises = require("DataStorePromises")
local DataStoreStage = require("DataStoreStage")
local Maid = require("Maid")
local Promise = require("Promise")
local Signal = require("Signal")
local DEBUG_WRITING = false
local AUTO_SAVE_TIME = 60*5
local CHECK_DIVISION = 15
local JITTER = 20 -- Randomly assign jitter so if a ton of players join at once we don't hit the datastore at once
local DataStore = setmetatable({}, DataStoreStage)
DataStore.ClassName = "DataStore"
DataStore.__index = DataStore
--[=[
Constructs a new DataStore. See [DataStoreStage] for more API.
@param robloxDataStore DataStore
@param key string
]=]
function DataStore.new(robloxDataStore, key)
local self = setmetatable(DataStoreStage.new(), DataStore)
self._key = key or error("No key")
self._robloxDataStore = robloxDataStore or error("No robloxDataStore")
--[=[
Prop that fires when saving. Promise will resolve once saving is complete.
@prop Saving Signal<Promise>
@within DataStore
]=]
self.Saving = Signal.new() -- :Fire(promise)
self._maid:GiveTask(self.Saving)
task.spawn(function()
while self.Destroy do
for _=1, CHECK_DIVISION do
task.wait(AUTO_SAVE_TIME/CHECK_DIVISION)
if not self.Destroy then
break
end
end
if not self.Destroy then
break
end
-- Apply additional jitter on auto-save
task.wait(math.random(1, JITTER))
if not self.Destroy then
break
end
self:Save()
end
end)
return self
end
--[=[
Returns the full path for the datastore
@return string
]=]
function DataStore:GetFullPath()
return ("RobloxDataStore@%s"):format(self._key)
end
--[=[
Returns whether the datastore failed.
@return boolean
]=]
function DataStore:DidLoadFail()
if not self._loadPromise then
return false
end
if self._loadPromise:IsRejected() then
return true
end
return false
end
function DataStore:PromiseLoadSuccessful()
return self._maid:GivePromise(self:_promiseLoad()):Then(function()
return true
end, function()
return false
end)
end
--[=[
Saves all stored data.
@return Promise
]=]
function DataStore:Save()
if self:DidLoadFail() then
warn("[DataStore] - Not saving, failed to load")
return Promise.rejected("Load not successful, not saving")
end
if DEBUG_WRITING then
print("[DataStore.Save] - Starting save routine")
end
-- Avoid constructing promises for every callback down the datastore
-- upon save.
return (self:_promiseInvokeSavingCallbacks() or Promise.resolved())
:Then(function()
if not self:HasWritableData() then
-- Nothing to save, don't update anything
if DEBUG_WRITING then
print("[DataStore.Save] - Not saving, nothing staged")
end
return nil
else
return self:_saveData(self:GetNewWriter())
end
end)
end
--[=[
Loads data. This returns the originally loaded data.
@param keyName string
@param defaultValue any?
@return any?
]=]
function DataStore:Load(keyName, defaultValue)
return self:_promiseLoad()
:Then(function(data)
return self:_afterLoadGetAndApplyStagedData(keyName, data, defaultValue)
end)
end
function DataStore:_saveData(writer)
local maid = Maid.new()
local promise = Promise.new()
promise:Resolve(maid:GivePromise(DataStorePromises.updateAsync(self._robloxDataStore, self._key, function(data)
if promise:IsRejected() then
-- Cancel if we have another request
return nil
end
data = writer:WriteMerge(data or {})
assert(data ~= DataStoreDeleteToken, "Cannot delete from UpdateAsync")
if DEBUG_WRITING then
print("[DataStore] - Writing", game:GetService("HttpService"):JSONEncode(data))
end
return data
end, function(err)
-- Might be caused by Maid rejecting state
warn("[DataStore] - Failed to UpdateAsync data", err)
return Promise.rejected(err)
end)))
self._maid._saveMaid = maid
if self.Saving.Destroy then
self.Saving:Fire(promise)
end
return promise
end
function DataStore:_promiseLoad()
if self._loadPromise then
return self._loadPromise
end
self._loadPromise = self._maid:GivePromise(DataStorePromises.getAsync(self._robloxDataStore, self._key)
:Then(function(data)
if data == nil then
return {}
elseif type(data) == "table" then
return data
else
return Promise.rejected("Failed to load data. Wrong type '" .. type(data) .. "'")
end
end, function(err)
-- Log:
warn("[DataStore] - Failed to GetAsync data", err)
return Promise.rejected(err)
end))
return self._loadPromise
end
return DataStore
|
--[=[
Wraps the datastore object to provide async cached loading and saving. See [DataStoreStage] for more API.
Has the following features
* Automatic save
* Jitter
* De-duplication (only updates data it needs)
```lua
local playerMoneyValue = Instance.new("IntValue")
playerMoneyValue.Value = 0
local dataStore = DataStore.new(DataStoreService:GetDataStore("test"), test-store")
dataStore:Load("money", 0):Then(function(money)
playerMoneyValue.Value = money
dataStore:StoreOnValueChange("money", playerMoneyValue)
end):Catch(function()
-- TODO: Notify player
end)
```
@server
@class DataStore
]=]
local require = require(script.Parent.loader).load(script)
local DataStoreDeleteToken = require("DataStoreDeleteToken")
local DataStorePromises = require("DataStorePromises")
local DataStoreStage = require("DataStoreStage")
local Maid = require("Maid")
local Promise = require("Promise")
local Signal = require("Signal")
local DEBUG_WRITING = false
local AUTO_SAVE_TIME = 60*5
local CHECK_DIVISION = 15
local JITTER = 20 -- Randomly assign jitter so if a ton of players join at once we don't hit the datastore at once
local DEFAULT_CACHE_TIME_SECONDS = math.huge
local DataStore = setmetatable({}, DataStoreStage)
DataStore.ClassName = "DataStore"
DataStore.__index = DataStore
--[=[
Constructs a new DataStore. See [DataStoreStage] for more API.
@param robloxDataStore DataStore
@param key string
]=]
function DataStore.new(robloxDataStore, key)
local self = setmetatable(DataStoreStage.new(), DataStore)
self._key = key or error("No key")
self._robloxDataStore = robloxDataStore or error("No robloxDataStore")
self._cacheTimeSeconds = DEFAULT_CACHE_TIME_SECONDS
--[=[
Prop that fires when saving. Promise will resolve once saving is complete.
@prop Saving Signal<Promise>
@within DataStore
]=]
self.Saving = Signal.new() -- :Fire(promise)
self._maid:GiveTask(self.Saving)
task.spawn(function()
while self.Destroy do
for _=1, CHECK_DIVISION do
task.wait(AUTO_SAVE_TIME/CHECK_DIVISION)
if not self.Destroy then
break
end
end
if not self.Destroy then
break
end
-- Apply additional jitter on auto-save
task.wait(math.random(1, JITTER))
if not self.Destroy then
break
end
self:Save()
end
end)
return self
end
--[=[
Sets how long the datastore will cache for
@param cacheTimeSeconds number?
]=]
function DataStore:SetCacheTime(cacheTimeSeconds)
assert(type(cacheTimeSeconds) == "number" or cacheTimeSeconds == nil, "Bad cacheTimeSeconds")
self._cacheTimeSeconds = cacheTimeSeconds or DEFAULT_CACHE_TIME_SECONDS
end
--[=[
Returns the full path for the datastore
@return string
]=]
function DataStore:GetFullPath()
return ("RobloxDataStore@%s"):format(self._key)
end
--[=[
Returns whether the datastore failed.
@return boolean
]=]
function DataStore:DidLoadFail()
if not self._loadPromise then
return false
end
if self._loadPromise:IsRejected() then
return true
end
return false
end
function DataStore:PromiseLoadSuccessful()
return self._maid:GivePromise(self:_promiseLoad()):Then(function()
return true
end, function()
return false
end)
end
--[=[
Saves all stored data.
@return Promise
]=]
function DataStore:Save()
if self:DidLoadFail() then
warn("[DataStore] - Not saving, failed to load")
return Promise.rejected("Load not successful, not saving")
end
if DEBUG_WRITING then
print("[DataStore.Save] - Starting save routine")
end
-- Avoid constructing promises for every callback down the datastore
-- upon save.
return (self:_promiseInvokeSavingCallbacks() or Promise.resolved())
:Then(function()
if not self:HasWritableData() then
-- Nothing to save, don't update anything
if DEBUG_WRITING then
print("[DataStore.Save] - Not saving, nothing staged")
end
return nil
else
return self:_saveData(self:GetNewWriter())
end
end)
end
--[=[
Loads data. This returns the originally loaded data.
@param keyName string
@param defaultValue any?
@return any?
]=]
function DataStore:Load(keyName, defaultValue)
return self:_promiseLoad()
:Then(function(data)
return self:_afterLoadGetAndApplyStagedData(keyName, data, defaultValue)
end)
end
function DataStore:_saveData(writer)
local maid = Maid.new()
local promise = Promise.new()
promise:Resolve(maid:GivePromise(DataStorePromises.updateAsync(self._robloxDataStore, self._key, function(data)
if promise:IsRejected() then
-- Cancel if we have another request
return nil
end
data = writer:WriteMerge(data or {})
assert(data ~= DataStoreDeleteToken, "Cannot delete from UpdateAsync")
if DEBUG_WRITING then
print("[DataStore] - Writing", game:GetService("HttpService"):JSONEncode(data))
end
return data
end, function(err)
-- Might be caused by Maid rejecting state
warn("[DataStore] - Failed to UpdateAsync data", err)
return Promise.rejected(err)
end)))
self._maid._saveMaid = maid
if self.Saving.Destroy then
self.Saving:Fire(promise)
end
return promise
end
function DataStore:_promiseLoad()
if self._loadPromise then
return self._loadPromise
end
self._loadPromise = self._maid:GivePromise(DataStorePromises.getAsync(self._robloxDataStore, self._key)
:Then(function(data)
if data == nil then
return {}
elseif type(data) == "table" then
return data
else
return Promise.rejected("Failed to load data. Wrong type '" .. type(data) .. "'")
end
end, function(err)
-- Log:
warn("[DataStore] - Failed to GetAsync data", err)
return Promise.rejected(err)
end))
return self._loadPromise
end
return DataStore
|
fix: Add DataStore SetCacheTime (not implemented yet)
|
fix: Add DataStore SetCacheTime (not implemented yet)
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
14f9c00f28e3fdc2e00012125da3f4c570d566db
|
wezterm/wezterm.lua
|
wezterm/wezterm.lua
|
local wezterm = require 'wezterm'
local os = require 'os'
local act = wezterm.action
local nvtop = { domain = "CurrentPaneDomain", args = {"nvtop"}, }
local htop = { domain = "CurrentPaneDomain", args = {"htop"}, }
local ytop = { domain = "CurrentPaneDomain", args = {"ytop", "-ps",}, }
local cursols = {
{ key = "Enter", mods = "CTRL", action = act.CopyMode { SetSelectionMode = "Block" }, },
{ key = "Escape", mods = "NONE", action = act.CopyMode "Close", },
{ key = "a", mods = "CTRL", action = act.CopyMode "MoveToStartOfLineContent" },
{ key = "b", mods = "ALT", action = act.CopyMode "MoveBackwardWord", },
{ key = "b", mods = "CTRL", action = act.CopyMode "MoveLeft", },
{ key = "e", mods = "CTRL", action = act.CopyMode "MoveToEndOfLineContent" },
{ key = "f", mods = "ALT", action = act.CopyMode "MoveForwardWord", },
{ key = "f", mods = "CTRL", action = act.CopyMode "MoveRight", },
{ key = "g", mods = "CTRL", action = act.CopyMode "Close", },
{ key = "p", mods = "CTRL", action = act.CopyMode "MoveUp", },
{ key = "p", mods = "ALT", action = act.CopyMode "PageUp", },
{ key = "n", mods = "CTRL", action = act.CopyMode "MoveDown", },
{ key = "n", mods = "ALT", action = act.CopyMode "PageDown", },
{ key = "q", mods = "NONE", action = act.CopyMode "Close", },
{ key = "Space", mods = "NONE", action = act.CopyMode { SetSelectionMode = "Cell" }, },
}
local assigned_keys = {
-- emacs like keybindings
{ key = "c", mods = "LEADER", action = act{ SpawnTab = "CurrentPaneDomain" }, },
{ key = "d", mods = "LEADER", action = act{ CloseCurrentTab = { confirm = false }, }, },
{ key = "d", mods = "LEADER|CTRL", action = act{ CloseCurrentPane = { confirm = false }, }, },
{ key = "[", mods = "LEADER", action = "ActivateCopyMode" },
{ key = "w", mods = "LEADER", action = act{ CopyTo = "Clipboard" }, },
{ key = "y", mods = "LEADER", action = act{ PasteFrom = "Clipboard" }, },
{ key = "n", mods = "LEADER", action = act{ ActivateTabRelative = 1 }, },
{ key = "p", mods = "LEADER", action = act{ ActivateTabRelative = -1 }, },
{ key = "v", mods = "LEADER", action = act{ SplitVertical = { domain = "CurrentPaneDomain", }, }, },
{ key = "h", mods = "LEADER", action = act{ SplitHorizontal = { domain = "CurrentPaneDomain", }, }, },
{ key = "o", mods = "LEADER", action = act{ ActivatePaneDirection = "Next", }, },
{ key = "l", mods = "LEADER", action = "ReloadConfiguration", },
{ key = "r", mods = "LEADER|CTRL", action = act{ SplitHorizontal = nvtop }, },
{ key = "R", mods = "LEADER|CTRL", action = act{ SplitVertical = ytop }, },
{ key = "=", mods = "LEADER|SUPER", action = "IncreaseFontSize", },
{ key = "-", mods = "LEADER|SUPER", action = "DecreaseFontSize", },
{ key = "r", mods = "LEADER|SUPER", action = "ResetFontSize", },
}
for i = 0, 9 do
local key_string = tostring(i)
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|ALT",
action = act{ ActivateTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER|CTRL",
action = act{ MoveTab = i },
})
table.insert(assigned_keys,{
key = key_string,
mods = "LEADER",
action = act{ ActivatePaneByIndex = i },
})
end
local base_dir = wezterm.home_dir .. "/.local/share/wezterm/"
local socket = base_dir .. "wezterm.socket"
local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
wezterm.on("update-right-status", function(window, _)
local date = wezterm.strftime("%Y/%m/%d(%a) %H:%M ");
local bat = ""
for _, b in ipairs(wezterm.battery_info()) do
bat = "🔋 " .. string.format("%.0f%%", b.state_of_charge * 100)
end
window:set_right_status(wezterm.format({
{ Background = { Color = "#2b2042", }, },
{ Foreground = { Color = "#808080", }, },
{ Text = bat .. " "..date },
}));
end)
wezterm.on("format-tab-title", function(tab, _, _, _, hover, max_width)
local edge_background = "#0b0022"
local background = "#1b1032"
local foreground = "#808080"
if tab.is_active then
background = "#2b2042"
foreground = "#c0c0c0"
elseif hover then
background = "#3b3052"
foreground = "#909090"
end
local edge_foreground = background
-- ensure that the titles fit in the available space,
-- and that we have room for the edges.
local title = wezterm.truncate_right(tab.active_pane.title, max_width-2)
return {
{ Background = { Color = edge_background }, },
{ Foreground = { Color = edge_foreground }, },
{ Text = SOLID_LEFT_ARROW },
{ Background = { Color = background, }, },
{ Foreground = { Color = foreground, }, },
{ Text = title },
{ Background = { Color = edge_background, }, },
{ Foreground = { Color = edge_foreground, }, },
{ Text = SOLID_RIGHT_ARROW, },
}
end)
return {
adjust_window_size_when_changing_font_size = false,
color_scheme = "Dracula",
default_gui_startup_args = { "connect", "wezterm" },
disable_default_key_bindings = true,
font = wezterm.font "Noto Mono for Powerline",
font_size = 10.0,
keys = assigned_keys,
key_tables = {
copy_mode = cursols,
},
leader = { key="t", mods="CTRL", timeout_milliseconds=1000 },
tab_bar_at_bottom = true,
use_ime = true,
unix_domains = {
{
name = "wezterm",
socket_path = socket,
},
},
daemon_options = {
stdout = base_dir .. "stdout",
stderr = base_dir .. "stderr",
pid_file = base_dir .. "pid",
}
}
|
local wezterm = require 'wezterm'
local os = require 'os'
local act = wezterm.action
local nvtop = { domain = "CurrentPaneDomain", args = {"nvtop"}, }
local htop = { domain = "CurrentPaneDomain", args = {"htop"}, }
local ytop = { domain = "CurrentPaneDomain", args = {"ytop", "-ps",}, }
local cursols = {
{ key = "Enter", mods = "CTRL", action = act.CopyMode { SetSelectionMode = "Block" }, },
{ key = "Escape", mods = "NONE", action = act.CopyMode "Close", },
{ key = "a", mods = "CTRL", action = act.CopyMode "MoveToStartOfLineContent" },
{ key = "b", mods = "ALT", action = act.CopyMode "MoveBackwardWord", },
{ key = "b", mods = "CTRL", action = act.CopyMode "MoveLeft", },
{ key = "e", mods = "CTRL", action = act.CopyMode "MoveToEndOfLineContent" },
{ key = "f", mods = "ALT", action = act.CopyMode "MoveForwardWord", },
{ key = "f", mods = "CTRL", action = act.CopyMode "MoveRight", },
{ key = "g", mods = "CTRL", action = act.CopyMode "Close", },
{ key = "p", mods = "CTRL", action = act.CopyMode "MoveUp", },
{ key = "p", mods = "ALT", action = act.CopyMode "PageUp", },
{ key = "n", mods = "CTRL", action = act.CopyMode "MoveDown", },
{ key = "n", mods = "ALT", action = act.CopyMode "PageDown", },
{ key = "q", mods = "NONE", action = act.CopyMode "Close", },
{ key = "Space", mods = "NONE", action = act.CopyMode { SetSelectionMode = "Cell" }, },
}
local assigned_keys = {
-- emacs like keybindings
{ key = "c", mods = "LEADER", action = act{ SpawnTab = "CurrentPaneDomain" }, },
{ key = "d", mods = "LEADER", action = act{ CloseCurrentTab = { confirm = false }, }, },
{ key = "d", mods = "LEADER|CTRL", action = act{ CloseCurrentPane = { confirm = false }, }, },
{ key = "[", mods = "LEADER", action = "ActivateCopyMode" },
{ key = "w", mods = "LEADER", action = act{ CopyTo = "Clipboard" }, },
{ key = "y", mods = "LEADER", action = act{ PasteFrom = "Clipboard" }, },
{ key = "n", mods = "LEADER", action = act{ ActivateTabRelative = 1 }, },
{ key = "p", mods = "LEADER", action = act{ ActivateTabRelative = -1 }, },
{ key = "v", mods = "LEADER", action = act{ SplitVertical = { domain = "CurrentPaneDomain", }, }, },
{ key = "h", mods = "LEADER", action = act{ SplitHorizontal = { domain = "CurrentPaneDomain", }, }, },
{ key = "o", mods = "LEADER", action = act{ ActivatePaneDirection = "Next", }, },
{ key = "l", mods = "LEADER", action = "ReloadConfiguration", },
{ key = "r", mods = "LEADER|CTRL", action = act{ SplitHorizontal = nvtop }, },
{ key = "R", mods = "LEADER|CTRL", action = act{ SplitVertical = ytop }, },
{ key = "=", mods = "LEADER|SUPER", action = "IncreaseFontSize", },
{ key = "-", mods = "LEADER|SUPER", action = "DecreaseFontSize", },
{ key = "r", mods = "LEADER|SUPER", action = "ResetFontSize", },
}
for i = 0, 9 do
local key_string = tostring(i)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER|ALT",
action = act { ActivateTab = i },
}
)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER|CTRL",
action = act{ MoveTab = i },
}
)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER",
action = act{ ActivatePaneByIndex = i },
}
)
end
local base_dir = wezterm.home_dir .. "/.local/share/wezterm/"
local socket = base_dir .. "wezterm.socket"
local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
wezterm.on(
"update-right-status",
function(window, _)
local date = wezterm.strftime("%Y/%m/%d(%a) %H:%M ");
local bat = ""
for _, b in ipairs(wezterm.battery_info()) do
bat = "🔋 " .. string.format("%.0f%%", b.state_of_charge * 100)
end
window:set_right_status(
wezterm.format(
{
{ Background = { Color = "#2b2042", }, },
{ Foreground = { Color = "#808080", }, },
{ Text = bat .. " "..date },
}
)
);
end)
wezterm.on(
"format-tab-title",
function(tab, _, _, _, hover, max_width)
local edge_background = "#0b0022"
local background = "#1b1032"
local foreground = "#808080"
if tab.is_active then
background = "#2b2042"
foreground = "#c0c0c0"
elseif hover then
background = "#3b3052"
foreground = "#909090"
end
local edge_foreground = background
-- ensure that the titles fit in the available space,
-- and that we have room for the edges.
local title = wezterm.truncate_right(tab.active_pane.title, max_width-2)
return {
{ Background = { Color = edge_background }, },
{ Foreground = { Color = edge_foreground }, },
{ Text = SOLID_LEFT_ARROW },
{ Background = { Color = background, }, },
{ Foreground = { Color = foreground, }, },
{ Text = title },
{ Background = { Color = edge_background, }, },
{ Foreground = { Color = edge_foreground, }, },
{ Text = SOLID_RIGHT_ARROW, },
}
end)
return {
adjust_window_size_when_changing_font_size = false,
color_scheme = "Dracula",
default_gui_startup_args = { "connect", "wezterm" },
disable_default_key_bindings = true,
font = wezterm.font "Noto Mono for Powerline",
font_size = 10.0,
keys = assigned_keys,
key_tables = {
copy_mode = cursols,
},
leader = { key="t", mods="CTRL", timeout_milliseconds=1000 },
tab_bar_at_bottom = true,
use_ime = true,
unix_domains = {
{
name = "wezterm",
socket_path = socket,
},
},
daemon_options = {
stdout = base_dir .. "stdout",
stderr = base_dir .. "stderr",
pid_file = base_dir .. "pid",
}
}
|
fix indent for lua-mode
|
fix indent for lua-mode
|
Lua
|
mit
|
katsyoshi/dotfiles,katsyoshi/dotfiles,katsyoshi/dotfiles
|
b54d4477924d0271a5e66cfb57d495862c9cfbd2
|
extensions/websocket/test_websocket.lua
|
extensions/websocket/test_websocket.lua
|
local websocket = require "hs.websocket"
local timer = require "hs.timer"
local doAfter = timer.doAfter
--
-- Variables:
--
TEST_STRING = "ABC123"
ECHO_URL = "wss://echo.websocket.org/"
FAKE_URL = "wss://fake.com/"
--
-- Test creating a new object:
--
function testNew()
local websocketObject = websocket.new(ECHO_URL, function() end)
assertIsUserdataOfType("hs.websocket", websocketObject)
assertTrue(#tostring(websocketObject) > 0)
return success()
end
--
-- Test sending an echo:
--
echoTestObj = nil
event = ""
message = ""
function testEcho()
echoTestObj = websocket.new(ECHO_URL, function(e, m)
event = e
message = m
end)
doAfter(5, function()
echoTestObj:send(TEST_STRING)
end)
return success()
end
function testEchoValues()
if type(event) == "string" and event == "received" and type(message) == "string" and message == TEST_STRING then
return success()
else
print("Waiting for echo...")
end
end
--
-- Test the status of an open websocket:
--
openStatusTestObj = nil
function testOpenStatus()
openStatusTestObj = websocket.new(ECHO_URL, function() end)
return success()
end
function testOpenStatusValues()
if openStatusTestObj:status() == "open" then
return success()
else
print("Waiting for websocket to open...")
end
end
--
-- Test the status of an closing websocket:
--
closingStatusTestObj = nil
function testClosingStatus()
closingStatusTestObj = websocket.new(FAKE_URL, function() end)
closingStatusTestObj:close()
return success()
end
function testClosingStatusValues()
if closingStatusTestObj:status() == "closing" then
return success()
else
print("Waiting for websocket to start closing...")
end
end
--
-- Test the status of an closed websocket:
--
closedStatusTestObj = nil
function testClosedStatus()
closedStatusTestObj = websocket.new(FAKE_URL, function() end)
return success()
end
function testClosedStatusValues()
if closedStatusTestObj:status() == "closed" then
return success()
else
print("Waiting for websocket to close...")
end
end
--
-- Test hs.http.websocket wrapper
--
wrapperTestObj = nil
wrapperMessage = ""
function testLegacy()
local http = require("hs.http")
local legacy = http.websocket
wrapperTestObj = legacy(ECHO_URL, function(m)
wrapperMessage = m
end)
doAfter(5, function()
wrapperTestObj:send(TEST_STRING)
end)
return success()
end
function testLegacyValues()
if type(wrapperMessage) == "string" and wrapperMessage == TEST_STRING then
return success()
else
print("Waiting for echo...")
end
end
|
local websocket = require "hs.websocket"
local timer = require "hs.timer"
local doAfter = timer.doAfter
--
-- Variables:
--
local TEST_STRING = "ABC123"
local ECHO_URL = "wss://echo.websocket.org/"
local FAKE_URL = "wss://fake.com/"
--
-- Test creating a new object:
--
function testNew()
local websocketObject = websocket.new(ECHO_URL, function() end)
assertIsUserdataOfType("hs.websocket", websocketObject)
assertTrue(#tostring(websocketObject) > 0)
return success()
end
--
-- Test sending an echo:
--
local echoTestObj = nil
local event = ""
local message = ""
function testEcho()
echoTestObj = websocket.new(ECHO_URL, function(e, m)
event = e
message = m
end)
doAfter(5, function()
echoTestObj:send(TEST_STRING)
end)
return success()
end
function testEchoValues()
if type(event) == "string" and event == "received" and type(message) == "string" and message == TEST_STRING then
return success()
else
print("Waiting for echo...")
end
end
--
-- Test the status of an open websocket:
--
local openStatusTestObj = nil
function testOpenStatus()
openStatusTestObj = websocket.new(ECHO_URL, function() end)
return success()
end
function testOpenStatusValues()
if openStatusTestObj:status() == "open" then
return success()
else
print("Waiting for websocket to open...")
end
end
--
-- Test the status of an closing websocket:
--
local closingStatusTestObj = nil
function testClosingStatus()
closingStatusTestObj = websocket.new(FAKE_URL, function() end)
closingStatusTestObj:close()
return success()
end
function testClosingStatusValues()
if closingStatusTestObj:status() == "closing" then
return success()
else
print("Waiting for websocket to start closing...")
end
end
--
-- Test the status of an closed websocket:
--
local closedStatusTestObj = nil
function testClosedStatus()
closedStatusTestObj = websocket.new(FAKE_URL, function() end)
return success()
end
function testClosedStatusValues()
if closedStatusTestObj:status() == "closed" then
return success()
else
print("Waiting for websocket to close...")
end
end
--
-- Test hs.http.websocket wrapper
--
local wrapperTestObj = nil
local wrapperMessage = ""
function testLegacy()
local http = require("hs.http")
local legacy = http.websocket
wrapperTestObj = legacy(ECHO_URL, function(m)
wrapperMessage = m
end)
doAfter(5, function()
wrapperTestObj:send(TEST_STRING)
end)
return success()
end
function testLegacyValues()
if type(wrapperMessage) == "string" and wrapperMessage == TEST_STRING then
return success()
else
print("Waiting for echo...")
end
end
|
Fixed @stickler-ci errors in tests
|
Fixed @stickler-ci errors in tests
|
Lua
|
mit
|
latenitefilms/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon
|
349d5416ef357cb9b6e0643ac0aa92be6ae3e89f
|
core/EventSource.lua
|
core/EventSource.lua
|
local assert = assert
--- Events can be used for iter object communication.
-- Using the vent source mixin makes sense, if can't know which objects may wan't
-- to react on an event. Also you don't need to worry about the targets life time,
-- since EventSource will automatically forget about targets without any further references.
local EventSource = {}
function EventSource:initializeEventSource()
self.events = {}
end
function EventSource:destroyEventSource()
end
local eventMetaTable = { __mode = 'k' }
function EventSource:addEventTarget( eventName, target, callback )
assert(eventName and target and callback)
local event = self.events[eventName]
if not event then
event = setmetatable({}, eventMetaTable)
self.events[eventName] = event
end
event[target] = callback
end
function EventSource:removeEventTarget( eventName, target )
assert(eventName and target)
local event = self.events[eventName]
if event then
event[target] = nil
end
end
function EventSource:fireEvent( eventName, ... )
local event = self.events[eventName]
if event then
for target, callback in pairs(event) do
callback(target, ...)
end
end
end
return EventSource
|
local assert = assert
--- Events can be used for inter object communication.
-- This mixin is practical if you can't know which objects may want to react
-- on an event. Also you don't need to worry about the targets life time,
-- since EventSource will automatically forget about event targets, which have
-- no further references.
local EventSource = {}
function EventSource:initializeEventSource()
self.events = {}
end
function EventSource:destroyEventSource()
end
local eventMetaTable = { __mode = 'k' }
function EventSource:addEventTarget( eventName, target, callback )
assert(eventName and target and callback)
local event = self.events[eventName]
if not event then
event = setmetatable({}, eventMetaTable)
self.events[eventName] = event
end
event[target] = callback
end
function EventSource:removeEventTarget( eventName, target )
assert(eventName and target)
local event = self.events[eventName]
if event then
event[target] = nil
end
end
function EventSource:fireEvent( eventName, ... )
local event = self.events[eventName]
if event then
for target, callback in pairs(event) do
callback(target, ...)
end
end
end
return EventSource
|
Fixed spelling mistake in EventSource.
|
Fixed spelling mistake in EventSource.
|
Lua
|
mit
|
henry4k/konstrukt,henry4k/konstrukt,henry4k/apoapsis,henry4k/apoapsis,henry4k/apoapsis,henry4k/konstrukt
|
8fc0803ce35dbe2cb4f83b9d73ae3f87c96b30b2
|
lua/drivers.lua
|
lua/drivers.lua
|
local mod = {}
local dpdkc = require "dpdkc"
local ffi = require "ffi"
mod.rte_i40e_pmd = require "driver.i40e"
mod.rte_ixgbe_pmd = require "driver.ixgbe"
mod.rte_ixgbevf_pmd = require "driver.ixgbevf"
mod.rte_igb_pmd = require "driver.igb"
mod.rte_virtio_pmd = require "driver.virtio"
mod.rte_vmxnet3_pmd = require "driver.vmxnet3"
function mod.initDriver(dev)
local device = require "device"
local driver = mod[dev:getDriverName()]
if driver then
if not getmetatable(driver) then
driver.__index = driver
driver.__eq = device.__devicePrototype.__eq
driver.__tostring = device.__devicePrototype.__tostring
setmetatable(driver, device.__devicePrototype)
end
setmetatable(dev, driver)
end
dev.driverInfo = dev.driverInfo or {}
end
-- retrieve driver-specific information
-- required for driver-specific configuration variables
function mod.getDriverInfo(driverName)
return (mod[driverName] or {}).driverInfo or {}
end
return mod
|
local mod = {}
local dpdkc = require "dpdkc"
local ffi = require "ffi"
mod.net_i40e = require "driver.i40e"
mod.net_ixgbe = require "driver.ixgbe"
mod.net_ixgbevf = require "driver.ixgbevf"
mod.net_igb = require "driver.igb"
mod.net_virtio = require "driver.virtio"
mod.net_vmxnet3 = require "driver.vmxnet3"
function mod.initDriver(dev)
local device = require "device"
local driver = mod[dev:getDriverName()]
if driver then
if not getmetatable(driver) then
driver.__index = driver
driver.__eq = device.__devicePrototype.__eq
driver.__tostring = device.__devicePrototype.__tostring
setmetatable(driver, device.__devicePrototype)
end
setmetatable(dev, driver)
end
dev.driverInfo = dev.driverInfo or {}
end
-- retrieve driver-specific information
-- required for driver-specific configuration variables
function mod.getDriverInfo(driverName)
return (mod[driverName] or {}).driverInfo or {}
end
return mod
|
fix driver names for dpdk 17.05
|
fix driver names for dpdk 17.05
|
Lua
|
mit
|
libmoon/libmoon,emmericp/libmoon,scholzd/libmoon,emmericp/libmoon,libmoon/libmoon,scholzd/libmoon,emmericp/libmoon,libmoon/libmoon,scholzd/libmoon
|
ab442c2434f647d41d8bdfdab6e6e1a4110f3350
|
frontend/gettext.lua
|
frontend/gettext.lua
|
local isAndroid, android = pcall(require, "android")
local DEBUG = require("dbg")
local GetText = {
translation = {},
current_lang = "C",
dirname = "l10n",
textdomain = "koreader"
}
local GetText_mt = {
__index = {}
}
function GetText_mt.__call(gettext, string)
return gettext.translation[string] or string
end
local function c_escape(what)
if what == "\n" then return ""
elseif what == "a" then return "\a"
elseif what == "b" then return "\b"
elseif what == "f" then return "\f"
elseif what == "n" then return "\n"
elseif what == "r" then return "\r"
elseif what == "t" then return "\t"
elseif what == "v" then return "\v"
elseif what == "0" then return "\0" -- shouldn't happen, though
else
return what
end
end
-- for PO file syntax, see
-- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
-- we only implement a sane subset for now
function GetText_mt.__index.changeLang(new_lang)
GetText.translation = {}
GetText.current_lang = "C"
-- the "C" locale disables localization alltogether
if new_lang == "C" or new_lang == nil then return end
-- strip encoding suffix in locale like "zh_CN.utf8"
new_lang = new_lang:sub(1, new_lang:find(".%."))
local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po"
local po = io.open(file, "r")
if not po then
DEBUG("cannot open translation file " .. file)
return
end
local data = {}
local what = nil
while true do
local line = po:read("*l")
if line == nil or line == "" then
if data.msgid and data.msgstr and data.msgstr ~= "" then
GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape)
end
-- stop at EOF:
if line == nil then break end
data = {}
what = nil
else
-- comment
if not line:match("^#") then
-- new data item (msgid, msgstr, ...
local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$")
if w then
what = w
else
-- string continuation
s = line:match("^%s*\"(.*)\"%s*$")
end
if what and s then
data[what] = (data[what] or "") .. s
end
end
end
end
GetText.current_lang = new_lang
end
setmetatable(GetText, GetText_mt)
if os.getenv("LANGUAGE") then
GetText.changeLang(os.getenv("LANGUAGE"))
elseif os.getenv("LC_ALL") then
GetText.changeLang(os.getenv("LC_ALL"))
elseif os.getenv("LC_MESSAGES") then
GetText.changeLang(os.getenv("LC_MESSAGES"))
elseif os.getenv("LANG") then
GetText.changeLang(os.getenv("LANG"))
end
if isAndroid then
local ffi = require("ffi")
local buf = ffi.new("char[?]", 16)
ffi.C.AConfiguration_getLanguage(android.app.config, buf)
local lang = ffi.string(buf)
ffi.C.AConfiguration_getCountry(android.app.config, buf)
local country = ffi.string(buf)
if lang and country then
GetText.changeLang(lang.."_"..country)
end
end
return GetText
|
local isAndroid, android = pcall(require, "android")
local DEBUG = require("dbg")
local GetText = {
translation = {},
current_lang = "C",
dirname = "l10n",
textdomain = "koreader"
}
local GetText_mt = {
__index = {}
}
function GetText_mt.__call(gettext, string)
return gettext.translation[string] or string
end
local function c_escape(what)
if what == "\n" then return ""
elseif what == "a" then return "\a"
elseif what == "b" then return "\b"
elseif what == "f" then return "\f"
elseif what == "n" then return "\n"
elseif what == "r" then return "\r"
elseif what == "t" then return "\t"
elseif what == "v" then return "\v"
elseif what == "0" then return "\0" -- shouldn't happen, though
else
return what
end
end
-- for PO file syntax, see
-- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
-- we only implement a sane subset for now
function GetText_mt.__index.changeLang(new_lang)
GetText.translation = {}
GetText.current_lang = "C"
-- the "C" locale disables localization alltogether
if new_lang == "C" or new_lang == nil then return end
-- strip encoding suffix in locale like "zh_CN.utf8"
new_lang = new_lang:sub(1, new_lang:find(".%."))
local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po"
local po = io.open(file, "r")
if not po then
DEBUG("cannot open translation file " .. file)
return
end
local data = {}
local what = nil
while true do
local line = po:read("*l")
if line == nil or line == "" then
if data.msgid and data.msgstr and data.msgstr ~= "" then
GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape)
end
-- stop at EOF:
if line == nil then break end
data = {}
what = nil
else
-- comment
if not line:match("^#") then
-- new data item (msgid, msgstr, ...
local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$")
if w then
what = w
else
-- string continuation
s = line:match("^%s*\"(.*)\"%s*$")
end
if what and s then
-- unescape \n or msgid won't match
s = s:gsub("\\n", "\n")
data[what] = (data[what] or "") .. s
end
end
end
end
GetText.current_lang = new_lang
end
setmetatable(GetText, GetText_mt)
if os.getenv("LANGUAGE") then
GetText.changeLang(os.getenv("LANGUAGE"))
elseif os.getenv("LC_ALL") then
GetText.changeLang(os.getenv("LC_ALL"))
elseif os.getenv("LC_MESSAGES") then
GetText.changeLang(os.getenv("LC_MESSAGES"))
elseif os.getenv("LANG") then
GetText.changeLang(os.getenv("LANG"))
end
if isAndroid then
local ffi = require("ffi")
local buf = ffi.new("char[?]", 16)
ffi.C.AConfiguration_getLanguage(android.app.config, buf)
local lang = ffi.string(buf)
ffi.C.AConfiguration_getCountry(android.app.config, buf)
local country = ffi.string(buf)
if lang and country then
GetText.changeLang(lang.."_"..country)
end
end
return GetText
|
gettext: unescape \n
|
gettext: unescape \n
Fixes the problem that any msgid with \n in it wouldn't show up translated.
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader,poire-z/koreader,ashhher3/koreader,mihailim/koreader,Frenzie/koreader,mwoz123/koreader,chihyang/koreader,apletnev/koreader,koreader/koreader,frankyifei/koreader,lgeek/koreader,houqp/koreader,Markismus/koreader,noname007/koreader,poire-z/koreader,pazos/koreader,chrox/koreader,Frenzie/koreader,ashang/koreader,NickSavage/koreader,koreader/koreader,NiLuJe/koreader,NiLuJe/koreader,robert00s/koreader
|
1f93dfb5f81f5bf03ef1eb5d8152bdbe45936bf0
|
dotfiles/nvim/init.lua
|
dotfiles/nvim/init.lua
|
-- functions that are not behavior added to the editor
local u = require('utils')
-- shotcuts to common functions
local api = vim.api -- nvim api access
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
-- plugin management
cmd 'packadd paq-nvim' -- load the package manager
local paq = require('paq-nvim').paq -- a convenient alias
paq {'savq/paq-nvim', opt = true} -- paq-nvim manages itself
paq 'sheerun/vim-polyglot' -- plugin: syntax highlighting
paq 'guns/vim-sexp' -- plugin: precision edit of S-expressions
-- colors
cmd 'colorscheme torte'
-- general editor options
local indent = 2
u.opt('b', 'expandtab', true) -- Use spaces instead of tabs
u.opt('b', 'shiftwidth', indent) -- Size of an indent
u.opt('b', 'smartindent', true) -- Insert indents automatically
u.opt('b', 'tabstop', indent) -- Number of spaces tabs count for
u.opt('o', 'hidden', true) -- Enable modified buffers in background
u.opt('o', 'joinspaces', false) -- No double spaces with join after a dot
u.opt('o', 'scrolloff', 4 ) -- Lines of context
u.opt('o', 'shiftround', true) -- Round indent
u.opt('o', 'sidescrolloff', 8 ) -- Columns of context
u.opt('o', 'smartcase', true) -- Don't ignore case with capitals
u.opt('o', 'splitbelow', true) -- Put new windows below current
u.opt('o', 'splitright', true) -- Put new windows right of current
u.opt('o', 'termguicolors', true) -- True color support
u.opt('o', 'wildmode', 'list:longest') -- Command-line completion mode
u.opt('w', 'number', true) -- Print line number
u.opt('w', 'relativenumber', true) -- Relative line numbers
u.opt('w', 'wrap', false)
-- simple maps (no binding with function)
u.map('n', '<leader><leader>', '<c-^>') -- '\\' alternate between buffers
u.map('n', '<cr>', ':nohlsearch<cr>') -- clear search when hit CR
u.map('', '<C-z>', ':wa|:suspend<cr>') -- save files when suspending with CTRL-Z
u.map('', 'Q', '<nop>') -- disable Ex Mode
-- smart_tab: triggers CTRL-P completion when hitting TAB
function smart_tab()
local cur_col = fn.col(".")
local cur_char = api.nvim_get_current_line():sub(cur_col - 1, cur_col + 1)
-- %g if we match to a printable character we try to complete
return cur_char:match('%g') and u.t'<c-p>' or u.t'<tab>'
end
-- bind <tab> to smar_tab() function
api.nvim_set_keymap('i', '<tab>', 'v:lua.smart_tab()', {expr = true, noremap = true })
-- shortcut to reload init.lua
cmd 'command! -nargs=0 Init :luafile ~/.config/nvim/init.lua'
--u.map('', '<leader>t', ' v:lua.selecta_open()', {expr = true, noremap = true })
--function selecta_open(args)
-- fn.system('ls -1 | selecta')
--end
api.nvim_exec([[
" Run a given vim command on the results of fuzzy selecting from a given shell
" command.
function! SelectaCommand(choice_command)
try
let selection = system(a:choice_command . " | selecta ")
catch /Vim:Interrupt/
" Swallow the ^C so that the redraw below happens; otherwise there will be
" leftovers from selecta on the screen
redraw!
return ""
endtry
redraw!
return selection
endfunction
]], true)
cmd 'command! -nargs=* Selecta call SelectaCommand(<q-args>)'
api.nvim_exec([[
" CSE means Clear Screen and Execute, use it by
" mapping (depending of the project) to a test runner command
" map <leader>r CSE('rspec', '--color')<cr>
function! CSE(runthis, ...)
:wa
exec ':!' . a:runthis . ' ' . join(a:000, ' ')
endfunction
function! QuickCSE(cmd)
exec "map <leader>r :call CSE(\"" . a:cmd . "\")<cr>"
endfunction
]], true)
cmd 'command! -nargs=* QuickCSE call QuickCSE(<q-args>)'
|
-- functions that are not behavior added to the editor
local u = require('utils')
-- shotcuts to common functions
local api = vim.api -- nvim api access
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
-- plugin management
cmd 'packadd paq-nvim' -- load the package manager
local paq = require('paq-nvim').paq -- a convenient alias
paq {'savq/paq-nvim', opt = true} -- paq-nvim manages itself
paq 'sheerun/vim-polyglot' -- plugin: syntax highlighting
paq 'guns/vim-sexp' -- plugin: precision edit of S-expressions
-- colors
cmd 'colorscheme torte'
-- general editor options
local indent = 2
u.opt('b', 'expandtab', true) -- Use spaces instead of tabs
u.opt('b', 'shiftwidth', indent) -- Size of an indent
u.opt('b', 'smartindent', true) -- Insert indents automatically
u.opt('b', 'tabstop', indent) -- Number of spaces tabs count for
u.opt('o', 'hidden', true) -- Enable modified buffers in background
u.opt('o', 'joinspaces', false) -- No double spaces with join after a dot
u.opt('o', 'scrolloff', 4 ) -- Lines of context
u.opt('o', 'shiftround', true) -- Round indent
u.opt('o', 'sidescrolloff', 8 ) -- Columns of context
u.opt('o', 'smartcase', true) -- Don't ignore case with capitals
u.opt('o', 'splitbelow', true) -- Put new windows below current
u.opt('o', 'splitright', true) -- Put new windows right of current
u.opt('o', 'termguicolors', true) -- True color support
u.opt('o', 'wildmode', 'list:longest') -- Command-line completion mode
u.opt('w', 'number', true) -- Print line number
u.opt('w', 'relativenumber', true) -- Relative line numbers
u.opt('w', 'wrap', false)
-- simple maps (no binding with function)
u.map('n', '<leader><leader>', '<c-^>') -- '\\' alternate between buffers
u.map('n', '<cr>', ':nohlsearch<cr>') -- clear search when hit CR
u.map('', '<C-z>', ':wa|:suspend<cr>') -- save files when suspending with CTRL-Z
u.map('', 'Q', '<nop>') -- disable Ex Mode
-- smart_tab: triggers CTRL-P completion when the
-- character before the cursor is not empty otherwise
-- just return TAB
function smart_tab()
local cur_col = fn.col(".")
local cur_char = api.nvim_get_current_line():sub(cur_col - 2, cur_col - 1)
-- %g matches printable character in Lua
return cur_char:match('%g') and u.t'<c-p>' or u.t'<tab>'
end
-- bind <tab> to smar_tab() function
api.nvim_set_keymap('i', '<tab>', 'v:lua.smart_tab()', {expr = true, noremap = true })
-- shortcut to reload init.lua
cmd 'command! -nargs=0 Init :luafile ~/.config/nvim/init.lua'
--u.map('', '<leader>t', ' v:lua.selecta_open()', {expr = true, noremap = true })
--function selecta_open(args)
-- fn.system('ls -1 | selecta')
--end
api.nvim_exec([[
" Run a given vim command on the results of fuzzy selecting from a given shell
" command.
function! SelectaCommand(choice_command)
try
let selection = system(a:choice_command . " | selecta ")
catch /Vim:Interrupt/
" Swallow the ^C so that the redraw below happens; otherwise there will be
" leftovers from selecta on the screen
redraw!
return ""
endtry
redraw!
return selection
endfunction
]], true)
cmd 'command! -nargs=* Selecta call SelectaCommand(<q-args>)'
api.nvim_exec([[
" CSE means Clear Screen and Execute, use it by
" mapping (depending of the project) to a test runner command
" map <leader>r CSE('rspec', '--color')<cr>
function! CSE(runthis, ...)
:wa
exec ':!' . a:runthis . ' ' . join(a:000, ' ')
endfunction
function! QuickCSE(cmd)
exec "map <leader>r :call CSE(\"" . a:cmd . "\")<cr>"
endfunction
]], true)
cmd 'command! -nargs=* QuickCSE call QuickCSE(<q-args>)'
|
Fix c-p trigger before a word
|
Fix c-p trigger before a word
If the cursor (_) is in position: _some-world and
we hit TAB, we should issue a TAB and not auto-complete.
If the cursor is in position: some_ than we
should issue a auto-comple.
|
Lua
|
mit
|
mavcunha/bash,mavcunha/bash
|
9214c9fbb357f3b3dfd920277ddf1f1ac8296645
|
MMOCoreORB/bin/scripts/mobile/lok/nym_pirate_weak.lua
|
MMOCoreORB/bin/scripts/mobile/lok/nym_pirate_weak.lua
|
nym_pirate_weak = Creature:new {
objectName = "@mob/creature_names:nym_pirate_weak",
socialGroup = "Nym",
pvpFaction = "Nym",
faction = "",
level = 26,
chanceHit = 0.36,
damageMin = 250,
damageMax = 260,
baseXp = 2730,
baseHAM = 7700,
baseHAMmax = 9400,
armor = 0,
resists = {25,10,25,25,25,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_nym_pirate_weak_hum_f.iff",
"object/mobile/dressed_nym_pirate_weak_rod_m.iff",
"object/mobile/dressed_nym_pirate_weak_nikto_m.iff",
"object/mobile/dressed_nym_pirate_weak_hum_m.iff",
"object/mobile/dressed_nym_pirate_weak_rod_f.iff",
"object/mobile/dressed_nym_pirate_weak_wee_m.iff"},
lootGroups = {
{
groups = {
{group = "nyms_common", chance = 2500000},
{group = "rifles", chance = 2500000},
{group = "carbines", chance = 2500000},
{group = "tailor_components", chance = 2500000}
},
lootChance = 6500000
}
},
weapons = {"pirate_weapons_heavy"},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(nym_pirate_weak, "nym_pirate_weak")
|
nym_pirate_weak = Creature:new {
objectName = "@mob/creature_names:nym_pirate_weak",
socialGroup = "Nym",
pvpFaction = "Nym",
faction = "",
level = 26,
chanceHit = 0.36,
damageMin = 250,
damageMax = 260,
baseXp = 2730,
baseHAM = 7700,
baseHAMmax = 9400,
armor = 0,
resists = {25,10,25,25,25,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_nym_pirate_weak_hum_f.iff",
"object/mobile/dressed_nym_pirate_weak_rod_m.iff",
"object/mobile/dressed_nym_pirate_weak_nikto_m.iff",
"object/mobile/dressed_nym_pirate_weak_hum_m.iff",
"object/mobile/dressed_nym_pirate_weak_rod_f.iff"},
lootGroups = {
{
groups = {
{group = "nyms_common", chance = 2500000},
{group = "rifles", chance = 2500000},
{group = "carbines", chance = 2500000},
{group = "tailor_components", chance = 2500000}
},
lootChance = 6500000
}
},
weapons = {"pirate_weapons_heavy"},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(nym_pirate_weak, "nym_pirate_weak")
|
[fixed] wrong nym_pirate_weak template
|
[fixed] wrong nym_pirate_weak template
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4823 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
e274df6f7d81d50330bd7df404606d4f38651066
|
dotfiles/config/nvim/lua/keymapping.lua
|
dotfiles/config/nvim/lua/keymapping.lua
|
local function map(mode, lhs, rhs, options)
vim.api.nvim_set_keymap(mode, lhs, rhs, vim.tbl_extend("force", {
noremap = true,
silent = true,
}, options or {}))
end
local function map_plug(mode, lhs, rhs)
map(mode, lhs, rhs, {noremap = false})
end
-- Leader key
map("", "<Space>", "<Nop>")
vim.g.mapleader = " "
-- Dvorak navigation
map("", "t", "j")
map("", "n", "k")
map("", "s", "l")
map("", "T", "")
map("", "N", "")
map("", "H", "0")
map("", "S", "$")
map("", "gt", "gj")
map("", "gn", "gk")
map("i", "+", "<Right><Esc>")
map("v", "+", "<Esc><Esc>")
map("", "+", ":update<CR>")
-- Joining
map("", "k", "J")
map("", "K", "gJ")
-- Undo/redo
map("", "U", "<C-R>")
map("", "<C-R>", "<Nop>")
-- Terminal
map("t", "<Esc>", "<C-\\><C-n>")
-- FZF
map("", "<leader>e", ":Files<CR>")
map("", "<leader>E", ":Buffers<CR>")
map("", "<leader>o", ":GFiles?<CR>")
map("", "<leader>a", ":Rg<space>", {silent = false})
map("", "<leader>A", ":Rg<space><Up><CR>")
map("", "<leader>i", ":Rg<space>/<C-R>=fnameescape(expand('%:t:r'))<CR><CR>")
map("", "<leader>B", ":History<CR>")
-- File navigation
map("", "<leader>u", "ZZ")
map("", "<leader>b", "<C-^>")
map("", "<C-d>", ":q<CR>")
-- Selection
map_plug("", "<leader>v", "Vii")
map("", "<leader>V", "ggVG")
-- Jumping
map_plug("", "o", "<Plug>(easymotion-overwin-f2)")
map_plug("", "O", "<Plug>(easymotion-overwin-f2)")
map_plug("", "f", "<Plug>Sneak_f")
map_plug("", "F", "<Plug>Sneak_F")
map_plug("", "l", "<Plug>Sneak_t")
map_plug("", "L", "<Plug>Sneak_T")
map_plug("", "(", "<Plug>Sneak_,")
map_plug("", ")", "<Plug>Sneak_;")
-- Search
map("", "j", "n")
map("", "J", "N")
map("", "gj", "gn")
map("", "gJ", "gN")
map("n", "*", " /\\C\\<<C-R><C-W>\\><CR>")
map("n", "<leader>*", " :Rg <C-R><C-W><CR>")
map("x", "*", " \"zy/<C-R><C-R>z<CR>")
map("x", "<leader>*", " \"zy:Rg <C-R><C-R>z<CR>")
map("n", "gx", "/export<CR>")
-- Entering insertion
map("", ",", "A")
map("", "<leader>,", "GA")
map("", "<CR>", "o")
map("", "g<CR>", "O")
-- Repeat pasting
map("x", "gp", "\"0p")
map("x", "gP", "\"0P")
map("n", "gp", "V\"0p")
map("n", "gP", "V\"0p")
-- Repeat operator
map("x", ".", ":norm.<CR>")
map_plug("", "<leader>.", "/\\C\\<\"\\><CR>.")
-- Window splitting
map("", "<leader>h", ":aboveleft vsplit<CR>")
map("", "<leader>t", ":belowright split<CR>")
map("", "<leader>n", ":aboveleft split<CR>")
map("", "<leader>s", ":belowright vsplit<CR>")
-- Tmux window navigation
map("n", "<C-H>", ":TmuxNavigateLeft<CR>")
map("n", "<C-T>", ":TmuxNavigateDown<CR>")
map("n", "<C-N>", ":TmuxNavigateUp<CR>")
map("n", "<C-S>", ":TmuxNavigateRight<CR>")
map("v", "<C-H>", "<Esc><Esc>:TmuxNavigateLeft<CR>")
map("v", "<C-T>", "<Esc><Esc>:TmuxNavigateDown<CR>")
map("v", "<C-N>", "<Esc><Esc>:TmuxNavigateUp<CR>")
map("v", "<C-S>", "<Esc><Esc>:TmuxNavigateRight<CR>")
map("i", "<C-H>", "<Right><Esc>:TmuxNavigateLeft<CR>")
map("i", "<C-T>", "<Right><Esc>:TmuxNavigateDown<CR>")
map("i", "<C-N>", "<Right><Esc>:TmuxNavigateUp<CR>")
map("i", "<C-S>", "<Right><Esc>:TmuxNavigateRight<CR>")
map("t", "<C-H>", "<C-\\><C-N>:TmuxNavigateLeft<CR>")
map("t", "<C-T>", "<C-\\><C-N>:TmuxNavigateDown<CR>")
map("t", "<C-N>", "<C-\\><C-N>:TmuxNavigateUp<CR>")
map("t", "<C-S>", "<C-\\><C-N>:TmuxNavigateRight<CR>")
map("c", "<C-H>", "<Nop>")
map("c", "<C-T>", "<Nop>")
map("c", "<C-N>", "<Nop>")
map("c", "<C-S>", "<Nop>")
-- Git
map("", "<leader>gb", ":Git blame<CR>")
map("", "<leader>gr", ":Gread<CR>")
map("", "<leader>gw", ":Gwrite<CR>")
map_plug("", "<leader>ga", "<Plug>(GitGutterStageHunk)")
map_plug("", "<leader>gu", "<Plug>(GitGutterUndoHunk)")
map_plug("", "]h", "<Plug>(GitGutterNextHunk)")
map_plug("", "[h", "<Plug>(GitGutterPrevHunk)")
map_plug("o", "ih", "<Plug>(GitGutterTextObjectInnerPending)")
map_plug("o", "ah", "<Plug>(GitGutterTextObjectOuterPending)")
map_plug("x", "ih", "<Plug>(GitGutterTextObjectInnerVisual)")
map_plug("x", "ah", "<Plug>(GitGutterTextObjectOuterVisual)")
-- Toggle settings
map("", "<leader>w", ":set wrap!<CR>")
map("", "<leader>W", ":set colorcolumn=80<CR>")
map("", "<leader>/", ":nohlsearch<CR>")
-- Slime
map_plug("x", "<leader>p", "<Plug>SlimeRegionSend")
map_plug("n", "<leader>p", "<Plug>SlimeParagraphSend")
map_plug("n", "<leader>P", "<Plug>SlimeConfig")
-- Refactoring
map("v", "<C-K>", [[:s/^\( *\)\([^:]\+\):.*$/\1"\2",/<CR>]])
map("n", "<C-K>", "cl<CR><Esc>lf<Space>")
map("", "ga", ":.Subvert/{true,false}/{false,true}/g<CR>:nohlsearch<CR>")
map("n", "<leader>r", [[:%s/\<<C-R><C-W>\>/<C-R><C-W>/g<Left><Left>]])
map("x", "<leader>r", [["zy:%s/\<<C-R><C-R>z\>/<C-R><C-R>z/g<Left><Left>]])
map("", "<leader>f", ":Neoformat<CR>")
map_plug("x", "<leader>x",
[["lc<C-R>=substitute(system('node -p', @l), '\n\+$', '', '')<CR><ESC>]])
map("i", "<C-K>", "<C-R>=strftime(\"%F\")<CR>")
vim.cmd([[
function! ExecuteMacroOverVisualRange()
echo "@".getcmdline()
execute ":'<,'>normal @".nr2char(getchar())
endfunction
]])
map("x", "@", ":<C-u>call ExecuteMacroOverVisualRange()<CR>")
vim.cmd([[
function! FillLine(str)
.s/\s*$//
let reps = (79 - col('$')) / len(a:str)
if reps > 0
.s/$/\=(' '.repeat(a:str, reps))/
endif
endfunction
]])
map("n", "<leader>~", ":call FillLine(\"~\")<CR>")
-- Nvim tree
map("", "-", ":NvimTreeFindFile<CR>")
map("", "g-", ":NvimTreeToggle<CR>")
function create_nvim_tree_bindings()
local function tree_map(key, cb_name)
vim.api.nvim_buf_set_keymap(0, "n", key,
require("nvim-tree.config").nvim_tree_callback(cb_name), {
noremap = true,
silent = true,
nowait = true,
})
end
tree_map("<CR>", "edit")
tree_map("i", "edit")
tree_map("<2-LeftMouse>", "edit")
tree_map("g<CR>", "cd")
tree_map("gi", "cd")
tree_map("[h", "prev_git_item")
tree_map("]h", "next_git_item")
tree_map("-", "dir_up")
tree_map("a", "create")
tree_map("a", "create")
tree_map("d", "remove")
tree_map("x", "cut")
tree_map("y", "copy")
tree_map("Y", "copy_path")
tree_map("gy", "copy_absolute_path")
tree_map("p", "paste")
tree_map("r", "rename")
tree_map("R", "refresh")
tree_map(".", "toggle_dotfiles")
tree_map(",", "toggle_ignored")
tree_map("<", "prev_sibling")
tree_map(">", "next_sibling")
tree_map("<BS>", "close_node")
tree_map("<Tab>", "preview")
tree_map("<leader>s", "vsplit")
tree_map("<leader>h", "vsplit")
tree_map("<leader>t", "split")
tree_map("<leader>n", "split")
end
vim.cmd("au Filetype NvimTree :lua create_nvim_tree_bindings()")
|
local function map(mode, lhs, rhs, options)
vim.api.nvim_set_keymap(mode, lhs, rhs, vim.tbl_extend("force", {
noremap = true,
silent = true,
}, options or {}))
end
local function map_plug(mode, lhs, rhs)
map(mode, lhs, rhs, {noremap = false})
end
-- Leader key
map("", "<Space>", "<Nop>")
vim.g.mapleader = " "
-- Dvorak navigation
map("", "t", "j")
map("", "n", "k")
map("", "s", "l")
map("", "T", "")
map("", "N", "")
map("", "H", "0")
map("", "S", "$")
map("", "gt", "gj")
map("", "gn", "gk")
map("i", "+", "<Right><Esc>")
map("v", "+", "<Esc><Esc>")
map("", "+", ":update<CR>")
-- Joining
map("", "k", "J")
map("", "K", "gJ")
-- Undo/redo
map("", "U", "<C-R>")
map("", "<C-R>", "<Nop>")
-- Terminal
map("t", "<Esc>", "<C-\\><C-n>")
-- FZF
map("", "<leader>e", ":Files<CR>")
map("", "<leader>E", ":Buffers<CR>")
map("", "<leader>o", ":GFiles?<CR>")
map("", "<leader>a", ":Rg<space>", {silent = false})
map("", "<leader>A", ":Rg<space><Up><CR>")
map("", "<leader>i", ":Rg<space>/<C-R>=fnameescape(expand('%:t:r'))<CR><CR>")
map("", "<leader>B", ":History<CR>")
-- File navigation
map("", "<leader>u", "ZZ")
map("", "<leader>b", "<C-^>")
map("", "<C-d>", ":q<CR>")
-- Selection
map_plug("", "<leader>v", "Vii")
map("", "<leader>V", "ggVG")
-- Jumping
map_plug("", "o", "<Plug>(easymotion-overwin-f2)")
map_plug("", "O", "<Plug>(easymotion-overwin-f2)")
map_plug("", "f", "<Plug>Sneak_f")
map_plug("", "F", "<Plug>Sneak_F")
map_plug("", "l", "<Plug>Sneak_t")
map_plug("", "L", "<Plug>Sneak_T")
map_plug("", "(", "<Plug>Sneak_,")
map_plug("", ")", "<Plug>Sneak_;")
-- Search
map("", "j", "n")
map("", "J", "N")
map("", "gj", "gn")
map("", "gJ", "gN")
map("n", "*", " /\\C\\<<C-R><C-W>\\><CR>")
map("n", "<leader>*", " :Rg <C-R><C-W><CR>")
map("x", "*", " \"zy/<C-R><C-R>z<CR>")
map("x", "<leader>*", " \"zy:Rg <C-R><C-R>z<CR>")
map("n", "gx", "/export<CR>")
-- Entering insertion
map("", ",", "A")
map("", "<leader>,", "GA")
map("", "<CR>", "o")
map("", "g<CR>", "O")
-- Repeat pasting
map("x", "gp", "\"0p")
map("x", "gP", "\"0P")
map("n", "gp", "V\"0p")
map("n", "gP", "V\"0p")
-- Repeat operator
map("x", ".", ":norm.<CR>")
map_plug("", "<leader>.", "/\\C\\<\"\\><CR>.")
-- Window splitting
map("", "<leader>h", ":aboveleft vsplit<CR>")
map("", "<leader>t", ":belowright split<CR>")
map("", "<leader>n", ":aboveleft split<CR>")
map("", "<leader>s", ":belowright vsplit<CR>")
-- Tmux window navigation
map("n", "<C-H>", ":TmuxNavigateLeft<CR>")
map("n", "<C-T>", ":TmuxNavigateDown<CR>")
map("n", "<C-N>", ":TmuxNavigateUp<CR>")
map("n", "<C-S>", ":TmuxNavigateRight<CR>")
map("v", "<C-H>", "<Esc><Esc>:TmuxNavigateLeft<CR>")
map("v", "<C-T>", "<Esc><Esc>:TmuxNavigateDown<CR>")
map("v", "<C-N>", "<Esc><Esc>:TmuxNavigateUp<CR>")
map("v", "<C-S>", "<Esc><Esc>:TmuxNavigateRight<CR>")
map("i", "<C-H>", "<Right><Esc>:TmuxNavigateLeft<CR>")
map("i", "<C-T>", "<Right><Esc>:TmuxNavigateDown<CR>")
map("i", "<C-N>", "<Right><Esc>:TmuxNavigateUp<CR>")
map("i", "<C-S>", "<Right><Esc>:TmuxNavigateRight<CR>")
map("t", "<C-H>", "<C-\\><C-N>:TmuxNavigateLeft<CR>")
map("t", "<C-T>", "<C-\\><C-N>:TmuxNavigateDown<CR>")
map("t", "<C-N>", "<C-\\><C-N>:TmuxNavigateUp<CR>")
map("t", "<C-S>", "<C-\\><C-N>:TmuxNavigateRight<CR>")
map("c", "<C-H>", "<Nop>")
map("c", "<C-T>", "<Nop>")
map("c", "<C-N>", "<Nop>")
map("c", "<C-S>", "<Nop>")
-- Git
map("", "<leader>gb", ":Git blame<CR>")
map("", "<leader>gr", ":Gread<CR>")
map("", "<leader>gw", ":Gwrite<CR>")
map_plug("", "<leader>ga", "<Plug>(GitGutterStageHunk)")
map_plug("", "<leader>gu", "<Plug>(GitGutterUndoHunk)")
map_plug("", "]h", "<Plug>(GitGutterNextHunk)")
map_plug("", "[h", "<Plug>(GitGutterPrevHunk)")
map_plug("o", "ih", "<Plug>(GitGutterTextObjectInnerPending)")
map_plug("o", "ah", "<Plug>(GitGutterTextObjectOuterPending)")
map_plug("x", "ih", "<Plug>(GitGutterTextObjectInnerVisual)")
map_plug("x", "ah", "<Plug>(GitGutterTextObjectOuterVisual)")
-- Toggle settings
map("", "<leader>w", ":set wrap!<CR>")
map("", "<leader>W", ":set colorcolumn=80<CR>")
map("", "<leader>/", ":nohlsearch<CR>")
-- Slime
map_plug("x", "<leader>p", "<Plug>SlimeRegionSend")
map_plug("n", "<leader>p", "<Plug>SlimeParagraphSend")
map_plug("n", "<leader>P", "<Plug>SlimeConfig")
-- Refactoring
map("v", "<C-K>", [[:s/^\( *\)\([^:]\+\):.*$/\1"\2",/<CR>]])
map("n", "<C-K>", "cl<CR><Esc>lf<Space>")
map("", "ga", ":.Subvert/{true,false}/{false,true}/g<CR>:nohlsearch<CR>")
map("n", "<leader>r", [[:%s/\<<C-R><C-W>\>/<C-R><C-W>/g<Left><Left>]], { silent = false })
map("x", "<leader>r", [["zy:%s/\<<C-R><C-R>z\>/<C-R><C-R>z/g<Left><Left>]], { silent = false })
map("", "<leader>f", ":Neoformat<CR>")
map_plug("x", "<leader>x",
[["lc<C-R>=substitute(system('node -p', @l), '\n\+$', '', '')<CR><ESC>]])
map("i", "<C-K>", "<C-R>=strftime(\"%F\")<CR>")
vim.cmd([[
function! ExecuteMacroOverVisualRange()
echo "@".getcmdline()
execute ":'<,'>normal @".nr2char(getchar())
endfunction
]])
map("x", "@", ":<C-u>call ExecuteMacroOverVisualRange()<CR>")
vim.cmd([[
function! FillLine(str)
.s/\s*$//
let reps = (79 - col('$')) / len(a:str)
if reps > 0
.s/$/\=(' '.repeat(a:str, reps))/
endif
endfunction
]])
map("n", "<leader>~", ":call FillLine(\"~\")<CR>")
-- Nvim tree
map("", "-", ":NvimTreeFindFile<CR>")
map("", "g-", ":NvimTreeToggle<CR>")
function create_nvim_tree_bindings()
local function tree_map(key, cb_name)
vim.api.nvim_buf_set_keymap(0, "n", key,
require("nvim-tree.config").nvim_tree_callback(cb_name), {
noremap = true,
silent = true,
nowait = true,
})
end
tree_map("<CR>", "edit")
tree_map("i", "edit")
tree_map("<2-LeftMouse>", "edit")
tree_map("g<CR>", "cd")
tree_map("gi", "cd")
tree_map("[h", "prev_git_item")
tree_map("]h", "next_git_item")
tree_map("-", "dir_up")
tree_map("a", "create")
tree_map("a", "create")
tree_map("d", "remove")
tree_map("x", "cut")
tree_map("y", "copy")
tree_map("Y", "copy_path")
tree_map("gy", "copy_absolute_path")
tree_map("p", "paste")
tree_map("r", "rename")
tree_map("R", "refresh")
tree_map(".", "toggle_dotfiles")
tree_map(",", "toggle_ignored")
tree_map("<", "prev_sibling")
tree_map(">", "next_sibling")
tree_map("<BS>", "close_node")
tree_map("<Tab>", "preview")
tree_map("<leader>s", "vsplit")
tree_map("<leader>h", "vsplit")
tree_map("<leader>t", "split")
tree_map("<leader>n", "split")
end
vim.cmd("au Filetype NvimTree :lua create_nvim_tree_bindings()")
|
Fix vim rename refactor key map
|
Fix vim rename refactor key map
|
Lua
|
mit
|
davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles
|
cea40ec902a0772f055c2e505b9b6632947a7ab9
|
frontend/ui/device.lua
|
frontend/ui/device.lua
|
Device = {
screen_saver_mode = false,
charging_mode = false,
survive_screen_saver = false,
touch_dev = nil,
model = nil,
firmware_rev = nil,
frontlight = nil,
}
BaseFrontLight = {
min = 1, max = 10,
intensity = nil,
}
KindleFrontLight = {
min = 0, max = 24,
kpw_fl = "/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity",
intensity = nil,
lipc_handle = nil,
}
KoboFrontLight = {
min = 1, max = 100,
intensity = 20,
restore_settings = true,
fl = nil,
}
function Device:getModel()
if self.model then return self.model end
if util.isEmulated() then
self.model = "Emulator"
return self.model
end
local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r")
local cpu_mod = std_out:read()
if not cpu_mod then
local ret = os.execute("grep 'Hardware : Mario Platform' /proc/cpuinfo", "r")
if ret ~= 0 then
self.model = nil
else
self.model = "KindleDXG"
end
end
if cpu_mod == "MX50" then
-- for KPW
local pw_test_fd = lfs.attributes(KindleFrontLight.kpw_fl)
-- for Kobo
local kg_test_fd = lfs.attributes("/bin/kobo_config.sh")
-- for KT
local kt_test_fd = lfs.attributes("/sys/devices/platform/whitney-button")
-- another special file for KT is Neonode zForce touchscreen:
-- /sys/devices/platform/zforce.0/
if pw_test_fd then
self.model = "KindlePaperWhite"
elseif kg_test_fd then
local std_out = io.popen("/bin/kobo_config.sh", "r")
local codename = std_out:read()
self.model = "Kobo_" .. codename
local version_file = io.open("/mnt/onboard/.kobo/version", "r")
self.firmware_rev = string.sub(version_file:read(),24,28)
version_file:close()
elseif kt_test_fd then
self.model = "KindleTouch"
else
self.model = "Kindle4"
end
elseif cpu_mod == "MX35" then
-- check if we are running on Kindle 3 (additional volume input)
self.model = "Kindle3"
elseif cpu_mod == "MX3" then
self.model = "Kindle2"
else
self.model = nil
end
return self.model
end
function Device:getFirmVer()
if not self.model then self:getModel() end
return self.firmware_rev
end
function Device:isKindle4()
return (self:getModel() == "Kindle4")
end
function Device:isKindle3()
return (self:getModel() == "Kindle3")
end
function Device:isKindle2()
return (self:getModel() == "Kindle2")
end
function Device:isKobo()
return string.find(self:getModel(),"Kobo_") == 1
end
function Device:hasNoKeyboard()
return self:isTouchDevice() or (self:getModel() == "Kindle4")
end
function Device:hasKeyboard()
return not self:hasNoKeyboard()
end
function Device:isTouchDevice()
local model = self:getModel()
return (model == "KindlePaperWhite") or (model == "KindleTouch") or self:isKobo() or util.isEmulated()
end
function Device:hasFrontlight()
local model = self:getModel()
return (model == "KindlePaperWhite") or (model == "Kobo_dragon") or (model == "Kobo_kraken") or (model == "Kobo_phoenix") or util.isEmulated()
end
function Device:setTouchInputDev(dev)
self.touch_dev = dev
end
function Device:getTouchInputDev()
return self.touch_dev
end
function Device:intoScreenSaver()
--os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
--UIManager:show(InfoMessage:new{
--text = "Going into screensaver... ",
--timeout = 2,
--})
--util.sleep(1)
--os.execute("killall -cont cvm")
self.screen_saver_mode = true
end
end
function Device:outofScreenSaver()
--os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt")
if self.screen_saver_mode == true and self.charging_mode == false then
-- wait for native system update screen before we recover saved
-- Blitbuffer.
util.usleep(1500000)
--os.execute("killall -stop cvm")
Screen:restoreFromSavedBB()
Screen:refresh(0)
self.survive_screen_saver = true
end
self.screen_saver_mode = false
end
function Device:Suspend()
UIManager:show(InfoMessage:new{
text = _("Standby"),
timeout = 2,
})
if self.fl ~= nil then
self.fl:sleep()
end
self.screen_saver_mode = true
os.execute("./kobo_suspend.sh")
end
function Device:Resume()
--util.usleep(1500000)
os.execute("echo 0 > /sys/power/state-extended")
if self.fl ~= nil then
self.fl:resume()
end
-- Screen:refresh(0)
self.screen_saver_mode = false
end
function Device:Power()
if self.screen_saver_mode == true then
Device:Resume()
else
Device:Suspend()
end
end
function Device:usbPlugIn()
--os.execute("echo 'usb in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
--UIManager:show(InfoMessage:new{
--text = "Going into USB mode... ",
--timeout = 2,
--})
--util.sleep(1)
--os.execute("killall -cont cvm")
end
self.charging_mode = true
end
function Device:usbPlugOut()
--os.execute("echo 'usb out' >> /mnt/us/event_test.txt")
if self.charging_mode == true and self.screen_saver_mode == false then
--util.usleep(1500000)
--os.execute("killall -stop cvm")
Screen:restoreFromSavedBB()
Screen:refresh(0)
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
self.charging_mode = false
end
function Device:getFrontlight()
if self.frontlight ~= nil then
return self.frontlight
elseif self:hasFrontlight() then
if self:getModel() == "KindlePaperWhite" then
self.frontlight = KindleFrontLight
elseif self:isKobo() then
self.frontlight = KoboFrontLight
else -- emulated FrontLight
self.frontlight = BaseFrontLight
end
self.frontlight:init()
end
return self.frontlight
end
function BaseFrontLight:init() end
function BaseFrontLight:toggle() end
function BaseFrontLight:setIntensityHW() end
function BaseFrontLight:setIntensity(intensity)
intensity = intensity < self.min and self.min or intensity
intensity = intensity > self.max and self.max or intensity
self.intensity = intensity
self:setIntensityHW()
end
function KindleFrontLight:init()
require "liblipclua"
self.lipc_handle = lipc.init("com.github.koreader")
if self.lipc_handle then
self.intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity")
end
end
function KindleFrontLight:toggle()
local f = io.open(self.kpw_fl, "r")
local sysint = tonumber(f:read("*all"):match("%d+"))
f:close()
if sysint == 0 then
self:setIntensity(self.intensity)
else
os.execute("echo -n 0 > " .. self.kpw_fl)
end
end
KindleFrontLight.setIntensity = BaseFrontLight.setIntensity
function KindleFrontLight:setIntensityHW()
if self.lipc_handle ~= nil then
self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.intensity)
end
end
function KoboFrontLight:init()
self.fl = kobolight.open()
end
function KoboFrontLight:toggle()
if self.fl ~= nil then
self.fl:toggle()
end
end
KoboFrontLight.setIntensity = BaseFrontLight.setIntensity
function KoboFrontLight:setIntensityHW()
if self.fl ~= nil then
self.fl:setBrightness(self.intensity)
end
end
|
Device = {
screen_saver_mode = false,
charging_mode = false,
survive_screen_saver = false,
touch_dev = nil,
model = nil,
firmware_rev = nil,
frontlight = nil,
}
BaseFrontLight = {
min = 1, max = 10,
intensity = nil,
}
KindleFrontLight = {
min = 0, max = 24,
kpw_fl = "/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity",
intensity = nil,
lipc_handle = nil,
}
KoboFrontLight = {
min = 1, max = 100,
intensity = 20,
restore_settings = true,
fl = nil,
}
function Device:getModel()
if self.model then return self.model end
if util.isEmulated() then
self.model = "Emulator"
return self.model
end
local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r")
local cpu_mod = std_out:read()
if not cpu_mod then
local ret = os.execute("grep 'Hardware : Mario Platform' /proc/cpuinfo", "r")
if ret ~= 0 then
self.model = nil
else
self.model = "KindleDXG"
end
end
if cpu_mod == "MX50" then
-- for KPW
local pw_test_fd = lfs.attributes(KindleFrontLight.kpw_fl)
-- for Kobo
local kg_test_fd = lfs.attributes("/bin/kobo_config.sh")
-- for KT
local kt_test_fd = lfs.attributes("/sys/devices/platform/whitney-button")
-- another special file for KT is Neonode zForce touchscreen:
-- /sys/devices/platform/zforce.0/
if pw_test_fd then
self.model = "KindlePaperWhite"
elseif kg_test_fd then
local std_out = io.popen("/bin/kobo_config.sh", "r")
local codename = std_out:read()
self.model = "Kobo_" .. codename
local version_file = io.open("/mnt/onboard/.kobo/version", "r")
self.firmware_rev = string.sub(version_file:read(),24,28)
version_file:close()
elseif kt_test_fd then
self.model = "KindleTouch"
else
self.model = "Kindle4"
end
elseif cpu_mod == "MX35" then
-- check if we are running on Kindle 3 (additional volume input)
self.model = "Kindle3"
elseif cpu_mod == "MX3" then
self.model = "Kindle2"
else
self.model = nil
end
return self.model
end
function Device:getFirmVer()
if not self.model then self:getModel() end
return self.firmware_rev
end
function Device:isKindle4()
return (self:getModel() == "Kindle4")
end
function Device:isKindle3()
return (self:getModel() == "Kindle3")
end
function Device:isKindle2()
return (self:getModel() == "Kindle2")
end
function Device:isKobo()
return string.find(self:getModel(),"Kobo_") == 1
end
function Device:hasNoKeyboard()
return self:isTouchDevice() or (self:getModel() == "Kindle4")
end
function Device:hasKeyboard()
return not self:hasNoKeyboard()
end
function Device:isTouchDevice()
local model = self:getModel()
return (model == "KindlePaperWhite") or (model == "KindleTouch") or self:isKobo() or util.isEmulated()
end
function Device:hasFrontlight()
local model = self:getModel()
return (model == "KindlePaperWhite") or (model == "Kobo_dragon") or (model == "Kobo_kraken") or (model == "Kobo_phoenix") or util.isEmulated()
end
function Device:setTouchInputDev(dev)
self.touch_dev = dev
end
function Device:getTouchInputDev()
return self.touch_dev
end
function Device:intoScreenSaver()
--os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
--UIManager:show(InfoMessage:new{
--text = "Going into screensaver... ",
--timeout = 2,
--})
--util.sleep(1)
--os.execute("killall -cont cvm")
self.screen_saver_mode = true
end
end
function Device:outofScreenSaver()
--os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt")
if self.screen_saver_mode == true and self.charging_mode == false then
-- wait for native system update screen before we recover saved
-- Blitbuffer.
util.usleep(1500000)
--os.execute("killall -stop cvm")
Screen:restoreFromSavedBB()
Screen:refresh(0)
self.survive_screen_saver = true
end
self.screen_saver_mode = false
end
function Device:Suspend()
UIManager:show(InfoMessage:new{
text = _("Standby"),
timeout = 4,
})
Screen:refresh(0)
local fl = self:getFrontlight()
if fl ~= nil then
fl:sleep()
end
util.usleep(1500000)
self.screen_saver_mode = true
os.execute("./kobo_suspend.sh")
end
function Device:Resume()
--util.usleep(1500000)
os.execute("echo 0 > /sys/power/state-extended")
Screen:refresh(0)
local fl = self:getFrontlight()
if fl ~= nil then
fl:resume()
end
self.screen_saver_mode = false
end
function Device:Power()
if self.screen_saver_mode == true then
self:Resume()
else
self:Suspend()
end
end
function Device:usbPlugIn()
--os.execute("echo 'usb in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
--UIManager:show(InfoMessage:new{
--text = "Going into USB mode... ",
--timeout = 2,
--})
--util.sleep(1)
--os.execute("killall -cont cvm")
end
self.charging_mode = true
end
function Device:usbPlugOut()
--os.execute("echo 'usb out' >> /mnt/us/event_test.txt")
if self.charging_mode == true and self.screen_saver_mode == false then
--util.usleep(1500000)
--os.execute("killall -stop cvm")
Screen:restoreFromSavedBB()
Screen:refresh(0)
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
self.charging_mode = false
end
function Device:getFrontlight()
if self.frontlight ~= nil then
return self.frontlight
elseif self:hasFrontlight() then
if self:getModel() == "KindlePaperWhite" then
self.frontlight = KindleFrontLight
elseif self:isKobo() then
self.frontlight = KoboFrontLight
else -- emulated FrontLight
self.frontlight = BaseFrontLight
end
self.frontlight:init()
end
return self.frontlight
end
function BaseFrontLight:init() end
function BaseFrontLight:toggle() end
function BaseFrontLight:setIntensityHW() end
function BaseFrontLight:setIntensity(intensity)
intensity = intensity < self.min and self.min or intensity
intensity = intensity > self.max and self.max or intensity
self.intensity = intensity
self:setIntensityHW()
end
function KindleFrontLight:init()
require "liblipclua"
self.lipc_handle = lipc.init("com.github.koreader")
if self.lipc_handle then
self.intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity")
end
end
function KindleFrontLight:toggle()
local f = io.open(self.kpw_fl, "r")
local sysint = tonumber(f:read("*all"):match("%d+"))
f:close()
if sysint == 0 then
self:setIntensity(self.intensity)
else
os.execute("echo -n 0 > " .. self.kpw_fl)
end
end
KindleFrontLight.setIntensity = BaseFrontLight.setIntensity
function KindleFrontLight:setIntensityHW()
if self.lipc_handle ~= nil then
self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.intensity)
end
end
function KoboFrontLight:init()
self.fl = kobolight.open()
end
function KoboFrontLight:toggle()
if self.fl ~= nil then
self.fl:toggle()
end
end
KoboFrontLight.setIntensity = BaseFrontLight.setIntensity
function KoboFrontLight:setIntensityHW()
if self.fl ~= nil then
self.fl:setBrightness(self.intensity)
end
end
|
Fixes for light.
|
Fixes for light.
|
Lua
|
agpl-3.0
|
chihyang/koreader,ashang/koreader,apletnev/koreader,mwoz123/koreader,houqp/koreader,frankyifei/koreader,poire-z/koreader,chrox/koreader,koreader/koreader,pazos/koreader,lgeek/koreader,Frenzie/koreader,Markismus/koreader,ashhher3/koreader,robert00s/koreader,NiLuJe/koreader,poire-z/koreader,NiLuJe/koreader,mihailim/koreader,NickSavage/koreader,noname007/koreader,koreader/koreader,Hzj-jie/koreader,Frenzie/koreader
|
5661954c35570f67148f096c209ac679f9742a1b
|
share/lua/meta/art/01_musicbrainz.lua
|
share/lua/meta/art/01_musicbrainz.lua
|
--[[
Gets an artwork from amazon
$Id$
Copyright © 2007-2010 the VideoLAN team
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.
--]]
function try_query(query)
local l = vlc.object.libvlc()
local t = vlc.var.get( l, "musicbrainz-previousdate" )
if t ~= nil then
if t + 1000000. > vlc.misc.mdate() then
vlc.msg.warn( "We must wait 1 second between requests unless we want to be blacklisted from the musicbrainz server." )
vlc.misc.mwait( t + 1000000. )
end
vlc.var.set( l, "musicbrainz-previousdate", vlc.misc.mdate() )
else
vlc.var.create( l, "musicbrainz-previousdate", vlc.misc.mdate() )
end
l = nil
vlc.msg.dbg( query )
local s = vlc.stream( query )
if not s then return nil end
local page = s:read( 65653 )
-- FIXME: multiple results may be available
_,_,asin = string.find( page, "<asin>(.-)</asin>" )
if asin then
return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg"
else
return nil
end
end
function fuzzy(query)
-- http://musicbrainz.org/doc/TextSearchSyntax#Fuzzy_searches
-- we could even tweak the fuzziness
return string.gsub(query, "([^%s]+)", "%1~")
end
-- Return the artwork
function fetch_art()
local meta = vlc.item:metas()
if not (meta["artist"] and meta["album"]) then
return nil
end
local query1 = "http://musicbrainz.org/ws/1/release/?type=xml&artist="..vlc.strings.encode_uri_component(meta["artist"]).."&title="..vlc.strings.encode_uri_component(meta["album"])
local query2 = "http://musicbrainz.org/ws/1/release/?type=xml&query="..vlc.strings.encode_uri_component(meta["album"].." AND ".."artist:"..meta["artist"])
local query3 = "http://musicbrainz.org/ws/1/release/?type=xml&query="..vlc.strings.encode_uri_component(fuzzy(meta["album"]).." AND ".."artist:"..fuzzy(meta["artist"]))
return try_query(query1) or try_query(query2) or try_query(query3)
end
|
--[[
Gets an artwork from amazon
$Id$
Copyright © 2007-2010 the VideoLAN team
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.
--]]
function try_query(query)
local l = vlc.object.libvlc()
local t = vlc.var.get( l, "musicbrainz-previousdate" )
if t ~= nil then
if t + 1000000. > vlc.misc.mdate() then
vlc.msg.warn( "We must wait 1 second between requests unless we want to be blacklisted from the musicbrainz server." )
vlc.misc.mwait( t + 1000000. )
end
vlc.var.set( l, "musicbrainz-previousdate", vlc.misc.mdate() )
else
vlc.var.create( l, "musicbrainz-previousdate", vlc.misc.mdate() )
end
l = nil
vlc.msg.dbg( query )
local s = vlc.stream( query )
if not s then return nil end
local page = s:read( 65653 )
-- FIXME: multiple results may be available
asin = string.find( page, "<asin>(%w+)</asin>" )
if asin then
vlc.msg.dbg( asin )
return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg"
else
return nil
end
end
-- Return the artwork
function fetch_art()
local meta = vlc.item:metas()
if not (meta["artist"] and meta["album"]) then
return nil
end
local query1 = "http://musicbrainz.org/ws/1/release/?type=xml&artist="..vlc.strings.encode_uri_component(meta["artist"]).."&title=\""..vlc.strings.encode_uri_component(meta["album"].."\"")
local query2 = "http://musicbrainz.org/ws/1/release/?type=xml&query=\""..vlc.strings.encode_uri_component(meta["album"].."\" AND ".."artist:"..meta["artist"])
local query3 = "http://musicbrainz.org/ws/1/release/?type=xml&query=\""..vlc.strings.encode_uri_component(meta["album"].."\"~ AND ".."artist:"..meta["artist"].."~")
return try_query(query1) or try_query(query2) or try_query(query3)
end
|
lua: fix fuzzy musicbrainz search and use " " around title/artists
|
lua: fix fuzzy musicbrainz search and use " " around title/artists
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc
|
0ae87791d28dcdae40d736259cf5939ba820b02d
|
durden/clipboard.lua
|
durden/clipboard.lua
|
-- Copyright: 2015, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
--
-- Description: Basic clipboard handling, currently text only but there's
-- little stopping us from using more advanced input and output formats.
--
clipboard_debug = suppl_add_logfn("clipboard");
local function clipboard_add(ctx, source, msg, multipart)
clipboard_debug(string.format(
"add:multipart=%d:message=%s", multipart and 1 or 0, msg));
if (multipart) then
if (ctx.mpt[source] == nil) then
ctx.mpt[source] = {};
end
-- simple cutoff to prevent nasty clients from sending multipart forever
table.insert(ctx.mpt[source], msg);
if (#ctx.mpt[source] < ctx.mpt_cutoff) then
return;
end
end
-- if there's previous multipart tracking, combine them now
if (ctx.mpt[source]) then
msg = table.concat(ctx.mpt[source], "") .. msg;
ctx.mpt[source] = nil;
end
-- quick-check for uri. like strings (not that comprehensive), store
-- in a separate global history that we can grab from at will
if (string.len(msg) < 1024) then
for k in string.gmatch(msg, "%a+://[^%s]+") do
table.insert_unique_i(ctx.urls, 1, k);
if (#ctx.urls > 10) then
table.remove(ctx.urls, #ctx.urls);
end
end
end
if (ctx.locals[source] == nil) then
ctx.locals[source] = {};
end
-- default is promote to global, but less trusted won't be allowed to
if (not ctx.locals[source].blocked) then
ctx:set_global(msg, source);
end
-- skip duplicates
for k,v in ipairs(ctx.locals[source]) do
if (v == msg) then
return;
end
end
table.insert_unique_i(ctx.locals[source], 1, msg);
if (#ctx.locals[source] > ctx.history_size) then
table.remove(ctx.locals[source], #ctx.locals[source]);
end
end
local function clipboard_setglobal(ctx, msg, src)
table.insert_unique_i(ctx.globals, 1, msg);
clipboard_debug(string.format("global:message=%s", msg));
if (#ctx.globals > ctx.history_size) then
table.remove(ctx.globals, #ctx.globals);
end
if (ctx.monitor and type(ctx.monitor) == "function") then
ctx:monitor(msg, true, src);
end
end
-- by default, we don't retain history that is connected to a dead window
local function clipboard_lost(ctx, source)
clipboard_debug(string.format("lost:source=%d", source));
ctx.mpt[source] = nil;
ctx.locals[source] = nil;
end
local function clipboard_save(ctx, fn)
zap_resource(fn);
local wout = open_nonblock(fn, 1);
if (not wout) then
warning("clipboard/save: couldn't open " .. fn .. " for writing.");
return false;
end
wout:write(string.format("local res = { globals = {}; urls = {}; };\n"));
for k,v in ipairs(ctx.globals) do
wout:write(string.format("table.insert(res.globals, %q);\n", v));
end
for k,v in ipairs(ctx.urls) do
wout:write(string.format("table.insert(res.urls, %q);\n", v));
end
wout:write("return res;\n");
wout:close();
return true;
end
local function clipboard_monitor(ctx, fctx)
-- set or drop?
if (ctx.monitor) then
ctx.monitor();
end
ctx.monitor = fctx;
end
local function clipboard_load(ctx, fn)
if (not resource(fn)) then
return;
end
local res = system_load(fn, 0);
if (not res) then
warning("parsing error loading clipboard history from: " .. fn);
return;
end
local okstate, map = pcall(res);
if (not okstate) then
warning("execution error loading clipboard history from: " .. fn);
return;
end
if (map and type(map) == "table" and
map.globals and type(map.globals) == "table" and
map.urls and type(map.urls) == "table") then
ctx.globals = map.globals;
ctx.urls = map.urls;
end
return true;
end
local function clipboard_locals(ctx, source)
return ctx.locals[source] and ctx.locals[source] or {};
end
local function clipboard_text(ctx)
return ctx.global and ctx.global or "";
end
-- premade filters to help in cases where we get a lot of junk like
-- copy / paste from terminals.
local pastemodes = {
normal = {"Normal", function(instr) return instr; end},
trim = {"Trim", function(instr)
return (string.gsub(instr, "^%s*(.-)%s*$", "%1")); end},
nocrlf = {"No CR/LF", function(instr)
return (string.gsub(instr, "[\n\r]+", "")); end},
nodspace = {"Single Spaces", function(instr)
return (string.gsub(instr, "%s+", " ")); end}
};
local function clipboard_pastemodes(ctx, key)
local res = {};
-- try match by index, else match by labelstr else default
if (key) then
local ent = pastemodes[key] and pastemodes[key] or pastemodes[1];
for k,v in pairs(pastemodes) do
if (v[1] == key) then
ent = v;
break;
end
end
return ent[2], ent[1];
end
for k,v in pairs(pastemodes) do
table.insert(res, v[1]);
end
table.sort(res);
return res;
end
return {
mpt = {}, -- mulitpart tracking
locals = {}, -- local clipboard history (of history_size size)
globals = {},
urls = {},
modes = pastemodes,
history_size = 10,
mpt_cutoff = 10,
add = clipboard_add,
text = clipboard_text,
lost = clipboard_lost,
save = clipboard_save,
load = clipboard_load,
set_monitor = clipboard_monitor,
pastemodes = clipboard_pastemodes,
set_global = clipboard_setglobal,
list_local = clipboard_locals,
};
|
-- Copyright: 2015-2019, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
-- Description: Basic clipboard handling, currently text only but there's
-- little stopping us from using more advanced input and output formats.
--
local clipboard_debug
if suppl_add_logfn then
clipboard_debug = suppl_add_logfn("clipboard");
else
clipboard_debug = warning
end
local function clipboard_add(ctx, source, msg, multipart)
clipboard_debug(string.format(
"add:multipart=%d:message=%s", multipart and 1 or 0, msg));
if (multipart) then
if (ctx.mpt[source] == nil) then
ctx.mpt[source] = {};
end
-- simple cutoff to prevent nasty clients from sending multipart forever
table.insert(ctx.mpt[source], msg);
if (#ctx.mpt[source] < ctx.mpt_cutoff) then
return;
end
end
-- if there's previous multipart tracking, combine them now
if (ctx.mpt[source]) then
msg = table.concat(ctx.mpt[source], "") .. msg;
ctx.mpt[source] = nil;
end
-- quick-check for uri. like strings (not that comprehensive), store
-- in a separate global history that we can grab from at will
if (string.len(msg) < 1024) then
for k in string.gmatch(msg, "%a+://[^%s]+") do
table.insert_unique_i(ctx.urls, 1, k);
if (#ctx.urls > 10) then
table.remove(ctx.urls, #ctx.urls);
end
end
end
if (ctx.locals[source] == nil) then
ctx.locals[source] = {};
end
-- default is promote to global, but less trusted won't be allowed to
if (not ctx.locals[source].blocked) then
ctx:set_global(msg, source);
end
-- skip duplicates
for k,v in ipairs(ctx.locals[source]) do
if (v == msg) then
return;
end
end
table.insert_unique_i(ctx.locals[source], 1, msg);
if (#ctx.locals[source] > ctx.history_size) then
table.remove(ctx.locals[source], #ctx.locals[source]);
end
end
local function clipboard_setglobal(ctx, msg, src)
table.insert_unique_i(ctx.globals, 1, msg);
clipboard_debug(string.format("global:message=%s", msg));
if (#ctx.globals > ctx.history_size) then
table.remove(ctx.globals, #ctx.globals);
end
if (ctx.monitor and type(ctx.monitor) == "function") then
ctx:monitor(msg, true, src);
end
end
-- by default, we don't retain history that is connected to a dead window
local function clipboard_lost(ctx, source)
clipboard_debug(string.format("lost:source=%d", source));
ctx.mpt[source] = nil;
ctx.locals[source] = nil;
end
local function clipboard_save(ctx, fn)
zap_resource(fn);
local wout = open_nonblock(fn, 1);
if (not wout) then
clipboard_debug(
string.format("save:kind=error:destination=%s:message=couldn't open", fn));
return false;
end
wout:write(string.format("local res = { globals = {}; urls = {}; };\n"));
for k,v in ipairs(ctx.globals) do
wout:write(string.format("table.insert(res.globals, %q);\n", v));
end
for k,v in ipairs(ctx.urls) do
wout:write(string.format("table.insert(res.urls, %q);\n", v));
end
wout:write("return res;\n");
wout:close();
return true;
end
local function clipboard_monitor(ctx, fctx)
-- set or drop?
if (ctx.monitor) then
ctx.monitor();
end
ctx.monitor = fctx;
end
local function clipboard_load(ctx, fn)
if (not resource(fn)) then
return;
end
local res = system_load(fn, 0);
if (not res) then
clipboard_debug(string.format("load:kind=error:source=%s:message=couldn't open", fn));
return;
end
local okstate, map = pcall(res);
if (not okstate) then
clipboard_debug(string.format("load:kind=error:source=%s:message=couldn't parse", fn));
return;
end
if (map and type(map) == "table" and
map.globals and type(map.globals) == "table" and
map.urls and type(map.urls) == "table") then
ctx.globals = map.globals;
ctx.urls = map.urls;
end
return true;
end
local function clipboard_locals(ctx, source)
return ctx.locals[source] and ctx.locals[source] or {};
end
local function clipboard_text(ctx)
return ctx.global and ctx.global or "";
end
-- premade filters to help in cases where we get a lot of junk like
-- copy / paste from terminals.
local pastemodes = {
normal = {
"Normal",
function(instr)
return instr;
end
},
trim = {
"Trim",
function(instr)
return (string.gsub(instr, "^%s*(.-)%s*$", "%1"));
end
},
nocrlf = {
"No CR/LF",
function(instr)
return (string.gsub(instr, "[\n\r]+", ""));
end
},
nodspace = {
"Single Spaces",
function(instr)
return (string.gsub(instr, "%s+", " "));
end
}
};
local function clipboard_pastemodes(ctx, key)
local res = {};
-- try match by index, else match by labelstr else default
if (key) then
local ent = pastemodes[key] and pastemodes[key] or pastemodes[1];
for k,v in pairs(pastemodes) do
if (v[1] == key) then
ent = v;
break;
end
end
return ent[2], ent[1];
end
for k,v in pairs(pastemodes) do
table.insert(res, v[1]);
end
table.sort(res);
return res;
end
return {
mpt = {}, -- mulitpart tracking
locals = {}, -- local clipboard history (of history_size size)
globals = {},
urls = {},
modes = pastemodes,
history_size = 10,
mpt_cutoff = 10,
add = clipboard_add,
text = clipboard_text,
lost = clipboard_lost,
save = clipboard_save,
load = clipboard_load,
set_monitor = clipboard_monitor,
pastemodes = clipboard_pastemodes,
set_global = clipboard_setglobal,
list_local = clipboard_locals,
};
|
clipboard logging fixes
|
clipboard logging fixes
|
Lua
|
bsd-3-clause
|
letoram/durden
|
b7de7caadf5b07f819f3e483f0f1712d06d9facc
|
packages/masters.lua
|
packages/masters.lua
|
if not SILE.scratch.masters then
SILE.scratch.masters = {}
end
local _currentMaster
local function defineMaster (_, args)
SU.required(args, "id", "defining master")
SU.required(args, "frames", "defining master")
SU.required(args, "firstContentFrame", "defining master")
SILE.scratch.masters[args.id] = { frames = {}, firstContentFrame = nil }
for frame, spec in pairs(args.frames) do
spec.id = frame
if spec.solve then
SILE.scratch.masters[args.id].frames[frame] = spec
else
SILE.scratch.masters[args.id].frames[frame] = SILE.newFrame(spec)
end
end
SILE.frames = { page = SILE.frames.page }
SILE.scratch.masters[args.id].firstContentFrame = SILE.scratch.masters[args.id].frames[args.firstContentFrame]
end
local function defineMasters (self, list)
if list then
for i = 1, #list do defineMaster(self, list[i]) end
end
end
local function doswitch (frames)
SILE.frames = { page = SILE.frames.page }
for id, frame in pairs(frames) do
SILE.frames[id] = frame
frame:invalidate()
end
end
local function switchMasterOnePage (id)
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.thisPageTemplate = SILE.scratch.masters[id]
doswitch(SILE.scratch.masters[id].frames)
SILE.typesetter:chuck()
SILE.typesetter:initFrame(SILE.scratch.masters[id].firstContentFrame)
end
local function switchMaster (id)
_currentMaster = id
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.documentClass.pageTemplate = SILE.scratch.masters[id]
SILE.documentState.thisPageTemplate = pl.tablex.deepcopy(SILE.documentState.documentClass.pageTemplate)
doswitch(SILE.scratch.masters[id].frames)
SILE.typesetter:initFrame(SILE.scratch.masters[id].firstContentFrame)
end
SILE.registerCommand("define-master-template", function(options, content)
SU.required(options, "id", "defining a master")
SU.required(options, "first-content-frame", "defining a master")
-- Subvert the <frame> functionality from baseclass
local spare = SILE.documentState.thisPageTemplate.frames
local sp2 = SILE.frames
SILE.frames = { page = SILE.frames.page }
SILE.documentState.thisPageTemplate.frames = {}
SILE.process(content)
SILE.scratch.masters[options.id] = {}
SILE.scratch.masters[options.id].frames = SILE.documentState.thisPageTemplate.frames
if not SILE.scratch.masters[options.id].frames[options["first-content-frame"]] then
SU.error("first-content-frame "..options["first-content-frame"].." not found")
end
SILE.scratch.masters[options.id].firstContentFrame = SILE.scratch.masters[options.id].frames[options["first-content-frame"]]
SILE.documentState.thisPageTemplate.frames = spare
SILE.frames = sp2
end)
SILE.registerCommand("switch-master-one-page", function (options, _)
SU.required(options, "id", "switching master")
switchMasterOnePage(options.id)
SILE.typesetter:leaveHmode()
end, "Switches the master for the current page")
SILE.registerCommand("switch-master", function (options, _)
SU.required(options, "id", "switching master")
switchMaster(options.id)
end, "Switches the master for the current page")
return {
init = defineMasters,
exports = {
switchMasterOnePage = switchMasterOnePage,
switchMaster = switchMaster,
defineMaster = defineMaster,
defineMasters = defineMasters,
currentMaster = function () return _currentMaster end
},
documentation = [[
\begin{document}
The masters functionality is also itself an add-on package. It allows a class to
define sets of frames and switch between them either temporarily or permanently.
It defines the commands \autodoc:command{\define-master-template} (which is pattern
on the \autodoc:command{\pagetemplate} function we will meet in chapter 8),
\autodoc:command{\switch-master} and \autodoc:command{\switch-master-one-page}.
See \code{tests/masters.sil} for more about this package.
\end{document}
]]
}
|
if not SILE.scratch.masters then
SILE.scratch.masters = {}
end
local _currentMaster
local function defineMaster (_, args)
SU.required(args, "id", "defining master")
SU.required(args, "frames", "defining master")
SU.required(args, "firstContentFrame", "defining master")
SILE.scratch.masters[args.id] = { frames = {}, firstContentFrame = nil }
for frame, spec in pairs(args.frames) do
spec.id = frame
if spec.solve then
SILE.scratch.masters[args.id].frames[frame] = spec
else
SILE.scratch.masters[args.id].frames[frame] = SILE.newFrame(spec)
end
end
SILE.scratch.masters[args.id].firstContentFrame = SILE.scratch.masters[args.id].frames[args.firstContentFrame]
end
local function defineMasters (self, list)
if list then
for i = 1, #list do
defineMaster(self, list[i])
end
end
end
local function doswitch (frames)
SILE.frames = { page = SILE.frames.page }
for id, frame in pairs(frames) do
SILE.frames[id] = frame
frame:invalidate()
end
end
local function switchMasterOnePage (id)
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.thisPageTemplate = SILE.scratch.masters[id]
doswitch(SILE.scratch.masters[id].frames)
SILE.typesetter:chuck()
SILE.typesetter:initFrame(SILE.scratch.masters[id].firstContentFrame)
end
local function switchMaster (id)
_currentMaster = id
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.documentClass.pageTemplate = SILE.scratch.masters[id]
SILE.documentState.thisPageTemplate = pl.tablex.deepcopy(SILE.documentState.documentClass.pageTemplate)
doswitch(SILE.scratch.masters[id].frames)
SILE.typesetter:initFrame(SILE.scratch.masters[id].firstContentFrame)
end
SILE.registerCommand("define-master-template", function(options, content)
SU.required(options, "id", "defining a master")
SU.required(options, "first-content-frame", "defining a master")
-- Subvert the <frame> functionality from baseclass
local spare = SILE.documentState.thisPageTemplate.frames
local sp2 = SILE.frames
SILE.frames = { page = SILE.frames.page }
SILE.documentState.thisPageTemplate.frames = {}
SILE.process(content)
SILE.scratch.masters[options.id] = {}
SILE.scratch.masters[options.id].frames = SILE.documentState.thisPageTemplate.frames
if not SILE.scratch.masters[options.id].frames[options["first-content-frame"]] then
SU.error("first-content-frame "..options["first-content-frame"].." not found")
end
SILE.scratch.masters[options.id].firstContentFrame = SILE.scratch.masters[options.id].frames[options["first-content-frame"]]
SILE.documentState.thisPageTemplate.frames = spare
SILE.frames = sp2
end)
SILE.registerCommand("switch-master-one-page", function (options, _)
SU.required(options, "id", "switching master")
switchMasterOnePage(options.id)
SILE.typesetter:leaveHmode()
end, "Switches the master for the current page")
SILE.registerCommand("switch-master", function (options, _)
SU.required(options, "id", "switching master")
switchMaster(options.id)
end, "Switches the master for the current page")
return {
init = defineMasters,
exports = {
switchMasterOnePage = switchMasterOnePage,
switchMaster = switchMaster,
defineMaster = defineMaster,
defineMasters = defineMasters,
currentMaster = function () return _currentMaster end
},
documentation = [[
\begin{document}
The masters functionality is also itself an add-on package. It allows a class to
define sets of frames and switch between them either temporarily or permanently.
It defines the commands \autodoc:command{\define-master-template} (which is pattern
on the \autodoc:command{\pagetemplate} function we will meet in chapter 8),
\autodoc:command{\switch-master} and \autodoc:command{\switch-master-one-page}.
See \code{tests/masters.sil} for more about this package.
\end{document}
]]
}
|
fix(packages): Don't destroy frames when defining masters, only when switching to one
|
fix(packages): Don't destroy frames when defining masters, only when switching to one
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
cdd55a16f197d2716f0711d1f3e86cd28c105469
|
minetestforfun_game/mods/sethome/init.lua
|
minetestforfun_game/mods/sethome/init.lua
|
local real_homes_file = minetest.get_worldpath() .. "/real_homes"
local nether_homes_file = minetest.get_worldpath() .. "/nether_homes"
local homepos = {real = {},nether = {}}
local function loadhomes()
local input = io.open(real_homes_file, "r")
if input then
repeat
local x = input:read("*n")
if x == nil then
break
end
local y = input:read("*n")
local z = input:read("*n")
local name = input:read("*l")
homepos.real[name:sub(2)] = {x = x, y = y, z = z}
until input:read(0) == nil
io.close(input)
else
homepos.real = {}
end
input = io.open(nether_homes_file, "r")
if input then
repeat
local x = input:read("*n")
if x == nil then
break
end
local y = input:read("*n")
local z = input:read("*n")
local name = input:read("*n")
homepos.nether[name:sub(2)] = {x = x, y = y, z = z}
until input:read(0) == nil
io.close(input)
else
homepos.nether = {}
end
end
loadhomes()
minetest.register_privilege("home", "Can use /sethome and /home")
local changed = false
minetest.register_chatcommand("home", {
description = "Teleport you to your home point",
privs = {home=true},
func = function(name)
local player = minetest.env:get_player_by_name(name)
if not player_in_nether then return end
local is_in_nether = table.icontains(players_in_nether, name)
if player == nil then
-- just a check to prevent the server crashing
return false
end
if homepos[player:get_player_name()] then
if is_in_nether then
player:setpos(nether.homepos[player:get_player_name()])
else
player:setpos(real.homepos[player:get_player_name()])
end
minetest.chat_send_player(name, "Teleported to home!")
else
minetest.chat_send_player(name, "Set a home using /sethome")
end
end,
})
minetest.register_chatcommand("sethome", {
description = "Set your home point",
privs = {home=true},
func = function(name)
local player = minetest.env:get_player_by_name(name)
local pos = player:getpos()
if not players_in_nether then return end
local is_in_nether = table.icontains(players_in_nether, name)
if is_in_nether then
homepos.nether[player:get_player_name()] = pos
else
homepos.real[player:get_player_name()] = pos
end
minetest.chat_send_player(name, "Home set!")
changed = true
if changed then
if is_in_nether then
local output = io.open(nether_homes_file, "w")
else
local output = io.open(real_homes_file, "w")
end
for i, v in pairs(homepos) do
output:write(v.x.." "..v.y.." "..v.z.." "..i.."\n")
end
io.close(output)
changed = false
end
end,
})
|
local real_homes_file = minetest.get_worldpath() .. "/real_homes"
local nether_homes_file = minetest.get_worldpath() .. "/nether_homes"
local homepos = {real = {},nether = {}}
local function loadhomes()
local input = io.open(real_homes_file, "r")
if input then
repeat
local x = input:read("*n")
if x == nil then
break
end
local y = input:read("*n")
local z = input:read("*n")
local name = input:read("*l")
homepos.real[name:sub(2)] = {x = x, y = y, z = z}
until input:read(0) == nil
io.close(input)
else
homepos.real = {}
end
input = io.open(nether_homes_file, "r")
if input then
repeat
local x = input:read("*n")
if x == nil then
break
end
local y = input:read("*n")
local z = input:read("*n")
local name = input:read("*n")
homepos.nether[name:sub(2)] = {x = x, y = y, z = z}
until input:read(0) == nil
io.close(input)
else
homepos.nether = {}
end
end
loadhomes()
minetest.register_privilege("home", "Can use /sethome and /home")
local changed = false
minetest.register_chatcommand("home", {
description = "Teleport you to your home point",
privs = {home=true},
func = function(name)
local player = minetest.env:get_player_by_name(name)
if not player_in_nether then return end
local is_in_nether = table.icontains(players_in_nether, name)
if player == nil then
-- just a check to prevent the server crashing
return false
end
if homepos[player:get_player_name()] then
if is_in_nether then
player:setpos(nether.homepos[player:get_player_name()])
else
player:setpos(real.homepos[player:get_player_name()])
end
minetest.chat_send_player(name, "Teleported to home!")
else
minetest.chat_send_player(name, "Set a home using /sethome")
end
end,
})
minetest.register_chatcommand("sethome", {
description = "Set your home point",
privs = {home=true},
func = function(name)
local player = minetest.env:get_player_by_name(name)
local pos = player:getpos()
-- Find players in the nether
local players_in_nether = {}
local seeking = 0
local nether_file = io.open(minetest.get_worldpath().."/nether_players","r")
if not nether_file then return end
local player_in_nether_read = nether_file:read()
--if player_in_nether_read == "" then
--if not players_in_nether then return end
player_in_nether = player_in_nether_read:split(" ")
local is_in_nether = table.icontains(players_in_nether, name)
if is_in_nether == true then
homepos.nether[player:get_player_name()] = pos
else
homepos.real[player:get_player_name()] = pos
end
minetest.chat_send_player(name, "Home set!")
changed = true
if changed then
local output = 0
if is_in_nether then
output = io.open(nether_homes_file, "w")
else
output = io.open(real_homes_file, "w")
end
if output == 0 then return end -- Had not open the file
for i, v in pairs(homepos) do
output:write(v.x.." "..v.y.." "..v.z.." "..i.."\n")
end
io.close(output)
changed = false
end
end,
})
|
Home fix - Now using nether_players file
|
Home fix
- Now using nether_players file
|
Lua
|
unlicense
|
crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun
|
3ecec3ddbf9bdec6cab0a775f4f419ec4a862369
|
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
|
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci".cursor()
-------------------- View --------------------
f = SimpleForm("siitwizward", "4over6-Assistent",
"Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.")
mode = f:field(ListValue, "mode", "Betriebsmodus")
mode:value("gateway", "Gateway")
mode:value("client", "Client")
dev = f:field(ListValue, "device", "WLAN-Gerät")
uci:foreach("wireless", "wifi-device",
function(section)
dev:value(section[".name"])
end)
lanip = f:field(Value, "ipaddr", "LAN IP Adresse")
lanip.value = "127.23.1.1"
lanmsk = f:field(Value, "netmask", "LAN Netzmaske")
lanmsk.value = "255.255.0.0"
-------------------- Control --------------------
LL_PREFIX = luci.ip.IPv6("fe80::/64")
--
-- find link-local address
--
function find_ll()
for _, r in ipairs(luci.sys.net.routes6()) do
if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then
return r.dest:sub(LL_PREFIX)
end
end
return luci.ip.IPv6("::")
end
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
elseif state == FORM_INVALID then
self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen."
end
return true
end
function mode.write(self, section, value)
--
-- Configure wifi device
--
local wifi_device = dev:formvalue(section)
local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net"
local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be"
local wifi_channel = uci:get("siit", "wifi", "channel") or "1"
-- nuke old device definition
uci:delete_all("wireless", "wifi-iface",
function(s) return s.device == wifi_device end )
uci:delete_all("network", "interface",
function(s) return s['.name'] == wifi_device end )
-- create wifi device definition
uci:tset("wireless", wifi_device, {
disabled = 0,
channel = wifi_channel,
-- txantenna = 1,
-- rxantenna = 1,
-- diversity = 0
})
uci:section("wireless", "wifi-iface", nil, {
encryption = "none",
mode = "adhoc",
network = wifi_device,
device = wifi_device,
ssid = wifi_essid,
bssid = wifi_bssid,
})
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000"
-- Find wifi interface
local device = dev:formvalue(section)
--
-- Generate ULA
--
local ula = luci.ip.IPv6("::/64")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(luci.ip.IPv6(prefix))
end
ula = ula:add(find_ll())
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
uci:set("network", "wan", "mtu", 1400)
-- use full siit subnet
siit_route = luci.ip.IPv6(siit_prefix .. "/96")
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
-- lan interface
local lan_net = luci.ip.IPv4(
lanip:formvalue(section) or "192.168.1.1",
lanmsk:formvalue(section) or "255.255.255.0"
)
uci:tset("network", "lan", {
mtu = 1400,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string()
})
-- derive siit subnet from lan config
siit_route = luci.ip.IPv6(
siit_prefix .. "/" .. (96 + lan_net:prefix())
):add(lan_net[2])
end
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "static",
ipaddr = "169.254.42.42",
netmask = "255.255.255.0"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = "siit0",
target = siit_route:string()
})
-- create wifi network interface
uci:section("network", "interface", wifi_device, {
proto = "static",
mtu = 1400,
ip6addr = ula:string()
})
-- nuke old olsrd interfaces
uci:delete_all("olsrd", "Interface",
function(s) return s.interface == wifi_device end)
-- configure olsrd interface
uci:foreach("olsrd", "olsrd",
function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end)
uci:section("olsrd", "Interface", nil, {
ignore = 0,
interface = wifi_device,
Ip6AddrType = "global"
})
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s)
if s.netaddr and s.prefix then
return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix))
end
end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
uci:save("wireless")
uci:save("network")
uci:save("olsrd")
end
return f
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci".cursor()
-------------------- View --------------------
f = SimpleForm("siitwizward", "4over6-Assistent",
"Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.")
mode = f:field(ListValue, "mode", "Betriebsmodus")
mode:value("gateway", "Gateway")
mode:value("client", "Client")
dev = f:field(ListValue, "device", "WLAN-Gerät")
uci:foreach("wireless", "wifi-device",
function(section)
dev:value(section[".name"])
end)
lanip = f:field(Value, "ipaddr", "LAN IP Adresse")
lanip.value = "172.23.1.1"
lanip:depends("mode", "client")
lanmsk = f:field(Value, "netmask", "LAN Netzmaske")
lanmsk.value = "255.255.0.0"
lanmsk:depends("mode", "client")
-------------------- Control --------------------
LL_PREFIX = luci.ip.IPv6("fe80::/64")
--
-- find link-local address
--
function find_ll()
for _, r in ipairs(luci.sys.net.routes6()) do
if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then
return r.dest:sub(LL_PREFIX)
end
end
return luci.ip.IPv6("::")
end
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
elseif state == FORM_INVALID then
self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen."
end
return true
end
function mode.write(self, section, value)
--
-- Configure wifi device
--
local wifi_device = dev:formvalue(section)
local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net"
local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be"
local wifi_channel = uci:get("siit", "wifi", "channel") or "1"
-- nuke old device definition
uci:delete_all("wireless", "wifi-iface",
function(s) return s.device == wifi_device end )
uci:delete_all("network", "interface",
function(s) return s['.name'] == wifi_device end )
-- create wifi device definition
uci:tset("wireless", wifi_device, {
disabled = 0,
channel = wifi_channel,
-- txantenna = 1,
-- rxantenna = 1,
-- diversity = 0
})
uci:section("wireless", "wifi-iface", nil, {
encryption = "none",
mode = "adhoc",
network = wifi_device,
device = wifi_device,
ssid = wifi_essid,
bssid = wifi_bssid,
})
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000"
-- Find wifi interface
local device = dev:formvalue(section)
--
-- Generate ULA
--
local ula = luci.ip.IPv6("::/64")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(luci.ip.IPv6(prefix))
end
ula = ula:add(find_ll())
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
uci:set("network", "wan", "mtu", 1400)
-- use full siit subnet
siit_route = luci.ip.IPv6(siit_prefix .. "/96")
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
-- lan interface
local lan_net = luci.ip.IPv4(
lanip:formvalue(section) or "192.168.1.1",
lanmsk:formvalue(section) or "255.255.255.0"
)
uci:tset("network", "lan", {
mtu = 1400,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string()
})
-- derive siit subnet from lan config
siit_route = luci.ip.IPv6(
siit_prefix .. "/" .. (96 + lan_net:prefix())
):add(lan_net[2])
end
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "static",
ipaddr = "169.254.42.42",
netmask = "255.255.255.0"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = "siit0",
target = siit_route:string()
})
-- create wifi network interface
uci:section("network", "interface", wifi_device, {
proto = "static",
mtu = 1400,
ip6addr = ula:string()
})
-- nuke old olsrd interfaces
uci:delete_all("olsrd", "Interface",
function(s) return s.interface == wifi_device end)
-- configure olsrd interface
uci:foreach("olsrd", "olsrd",
function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end)
uci:section("olsrd", "Interface", nil, {
ignore = 0,
interface = wifi_device,
Ip6AddrType = "global"
})
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s)
if s.netaddr and s.prefix then
return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix))
end
end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
uci:save("wireless")
uci:save("network")
uci:save("olsrd")
end
return f
|
applications/siitwizard: - fix default lan ip - make ip and netmask depend on client mode
|
applications/siitwizard:
- fix default lan ip
- make ip and netmask depend on client mode
|
Lua
|
apache-2.0
|
florian-shellfire/luci,thesabbir/luci,ff94315/luci-1,NeoRaider/luci,kuoruan/lede-luci,Wedmer/luci,kuoruan/luci,RedSnake64/openwrt-luci-packages,hnyman/luci,lcf258/openwrtcn,urueedi/luci,opentechinstitute/luci,cappiewu/luci,urueedi/luci,opentechinstitute/luci,nmav/luci,artynet/luci,aa65535/luci,schidler/ionic-luci,nmav/luci,oyido/luci,RedSnake64/openwrt-luci-packages,cshore/luci,schidler/ionic-luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,bright-things/ionic-luci,wongsyrone/luci-1,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,artynet/luci,jlopenwrtluci/luci,david-xiao/luci,daofeng2015/luci,nmav/luci,deepak78/new-luci,marcel-sch/luci,daofeng2015/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,kuoruan/lede-luci,male-puppies/luci,taiha/luci,Sakura-Winkey/LuCI,sujeet14108/luci,artynet/luci,fkooman/luci,nwf/openwrt-luci,lcf258/openwrtcn,opentechinstitute/luci,sujeet14108/luci,LuttyYang/luci,slayerrensky/luci,thess/OpenWrt-luci,nmav/luci,wongsyrone/luci-1,Wedmer/luci,MinFu/luci,cappiewu/luci,Noltari/luci,tcatm/luci,NeoRaider/luci,male-puppies/luci,artynet/luci,Wedmer/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,openwrt/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,hnyman/luci,thesabbir/luci,obsy/luci,forward619/luci,thess/OpenWrt-luci,wongsyrone/luci-1,kuoruan/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,thesabbir/luci,harveyhu2012/luci,artynet/luci,ollie27/openwrt_luci,artynet/luci,Sakura-Winkey/LuCI,david-xiao/luci,male-puppies/luci,oneru/luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,palmettos/cnLuCI,kuoruan/lede-luci,lcf258/openwrtcn,oneru/luci,bittorf/luci,remakeelectric/luci,david-xiao/luci,palmettos/test,kuoruan/lede-luci,cshore/luci,male-puppies/luci,ollie27/openwrt_luci,RuiChen1113/luci,zhaoxx063/luci,rogerpueyo/luci,obsy/luci,ollie27/openwrt_luci,openwrt/luci,Hostle/luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,cappiewu/luci,981213/luci-1,remakeelectric/luci,cshore-firmware/openwrt-luci,oneru/luci,deepak78/new-luci,aa65535/luci,nwf/openwrt-luci,slayerrensky/luci,RuiChen1113/luci,Hostle/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,palmettos/cnLuCI,bright-things/ionic-luci,chris5560/openwrt-luci,sujeet14108/luci,Noltari/luci,maxrio/luci981213,daofeng2015/luci,keyidadi/luci,palmettos/test,joaofvieira/luci,dwmw2/luci,ff94315/luci-1,Wedmer/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,forward619/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,fkooman/luci,dwmw2/luci,kuoruan/luci,rogerpueyo/luci,thess/OpenWrt-luci,male-puppies/luci,keyidadi/luci,florian-shellfire/luci,jchuang1977/luci-1,nwf/openwrt-luci,shangjiyu/luci-with-extra,NeoRaider/luci,cappiewu/luci,dismantl/luci-0.12,chris5560/openwrt-luci,cappiewu/luci,shangjiyu/luci-with-extra,MinFu/luci,RuiChen1113/luci,palmettos/test,aa65535/luci,bittorf/luci,wongsyrone/luci-1,dwmw2/luci,remakeelectric/luci,daofeng2015/luci,openwrt-es/openwrt-luci,maxrio/luci981213,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,thesabbir/luci,Hostle/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,ollie27/openwrt_luci,Noltari/luci,NeoRaider/luci,thess/OpenWrt-luci,fkooman/luci,dwmw2/luci,NeoRaider/luci,palmettos/cnLuCI,nmav/luci,Hostle/luci,palmettos/cnLuCI,palmettos/test,maxrio/luci981213,Hostle/luci,taiha/luci,dwmw2/luci,aa65535/luci,mumuqz/luci,deepak78/new-luci,marcel-sch/luci,taiha/luci,deepak78/new-luci,male-puppies/luci,shangjiyu/luci-with-extra,mumuqz/luci,openwrt-es/openwrt-luci,Hostle/luci,teslamint/luci,joaofvieira/luci,dwmw2/luci,marcel-sch/luci,bittorf/luci,forward619/luci,oyido/luci,ff94315/luci-1,daofeng2015/luci,hnyman/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,oneru/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,male-puppies/luci,MinFu/luci,lbthomsen/openwrt-luci,dismantl/luci-0.12,palmettos/cnLuCI,cshore/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,dismantl/luci-0.12,981213/luci-1,jchuang1977/luci-1,oneru/luci,forward619/luci,tcatm/luci,tobiaswaldvogel/luci,LuttyYang/luci,slayerrensky/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,deepak78/new-luci,MinFu/luci,sujeet14108/luci,chris5560/openwrt-luci,palmettos/test,bittorf/luci,Wedmer/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,bright-things/ionic-luci,fkooman/luci,maxrio/luci981213,chris5560/openwrt-luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,thess/OpenWrt-luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,NeoRaider/luci,maxrio/luci981213,bittorf/luci,Kyklas/luci-proto-hso,hnyman/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,aa65535/luci,david-xiao/luci,Sakura-Winkey/LuCI,taiha/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,mumuqz/luci,kuoruan/lede-luci,forward619/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,daofeng2015/luci,palmettos/test,ff94315/luci-1,Kyklas/luci-proto-hso,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,Kyklas/luci-proto-hso,keyidadi/luci,slayerrensky/luci,mumuqz/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,oyido/luci,fkooman/luci,tobiaswaldvogel/luci,aa65535/luci,cshore-firmware/openwrt-luci,obsy/luci,jchuang1977/luci-1,urueedi/luci,marcel-sch/luci,joaofvieira/luci,jchuang1977/luci-1,wongsyrone/luci-1,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,deepak78/new-luci,florian-shellfire/luci,shangjiyu/luci-with-extra,joaofvieira/luci,daofeng2015/luci,thesabbir/luci,hnyman/luci,Sakura-Winkey/LuCI,fkooman/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,cshore/luci,nwf/openwrt-luci,Wedmer/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,openwrt/luci,taiha/luci,teslamint/luci,LuttyYang/luci,RuiChen1113/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,openwrt/luci,harveyhu2012/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,981213/luci-1,Kyklas/luci-proto-hso,dismantl/luci-0.12,urueedi/luci,harveyhu2012/luci,NeoRaider/luci,teslamint/luci,nmav/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,aa65535/luci,rogerpueyo/luci,ff94315/luci-1,Noltari/luci,palmettos/test,joaofvieira/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,schidler/ionic-luci,tcatm/luci,sujeet14108/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,florian-shellfire/luci,hnyman/luci,jlopenwrtluci/luci,remakeelectric/luci,nmav/luci,palmettos/cnLuCI,joaofvieira/luci,oneru/luci,harveyhu2012/luci,deepak78/new-luci,remakeelectric/luci,kuoruan/lede-luci,jchuang1977/luci-1,ff94315/luci-1,LuttyYang/luci,zhaoxx063/luci,NeoRaider/luci,urueedi/luci,Kyklas/luci-proto-hso,lcf258/openwrtcn,cshore-firmware/openwrt-luci,jorgifumi/luci,slayerrensky/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,urueedi/luci,keyidadi/luci,chris5560/openwrt-luci,zhaoxx063/luci,cshore/luci,opentechinstitute/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,Noltari/luci,jorgifumi/luci,981213/luci-1,slayerrensky/luci,981213/luci-1,shangjiyu/luci-with-extra,oyido/luci,harveyhu2012/luci,fkooman/luci,zhaoxx063/luci,florian-shellfire/luci,obsy/luci,tcatm/luci,kuoruan/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,david-xiao/luci,oyido/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,obsy/luci,taiha/luci,ff94315/luci-1,jlopenwrtluci/luci,kuoruan/luci,Wedmer/luci,marcel-sch/luci,chris5560/openwrt-luci,forward619/luci,nmav/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,oyido/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,oyido/luci,rogerpueyo/luci,fkooman/luci,openwrt/luci,LuttyYang/luci,MinFu/luci,marcel-sch/luci,jlopenwrtluci/luci,cshore/luci,marcel-sch/luci,tobiaswaldvogel/luci,sujeet14108/luci,urueedi/luci,palmettos/cnLuCI,Noltari/luci,nmav/luci,rogerpueyo/luci,cappiewu/luci,keyidadi/luci,tobiaswaldvogel/luci,teslamint/luci,Wedmer/luci,Noltari/luci,kuoruan/luci,florian-shellfire/luci,schidler/ionic-luci,bright-things/ionic-luci,obsy/luci,tobiaswaldvogel/luci,forward619/luci,schidler/ionic-luci,cappiewu/luci,tcatm/luci,tcatm/luci,rogerpueyo/luci,Hostle/luci,remakeelectric/luci,obsy/luci,harveyhu2012/luci,opentechinstitute/luci,openwrt/luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,jorgifumi/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,sujeet14108/luci,wongsyrone/luci-1,keyidadi/luci,zhaoxx063/luci,oyido/luci,jorgifumi/luci,artynet/luci,zhaoxx063/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,jorgifumi/luci,lcf258/openwrtcn,jorgifumi/luci,mumuqz/luci,david-xiao/luci,aa65535/luci,maxrio/luci981213,daofeng2015/luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,schidler/ionic-luci,schidler/ionic-luci,teslamint/luci,thesabbir/luci,jlopenwrtluci/luci,thesabbir/luci,forward619/luci,remakeelectric/luci,florian-shellfire/luci,Noltari/luci,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,dismantl/luci-0.12,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,cshore/luci,oneru/luci,jlopenwrtluci/luci,MinFu/luci,RuiChen1113/luci,cshore-firmware/openwrt-luci,cshore/luci,teslamint/luci,urueedi/luci,remakeelectric/luci,ollie27/openwrt_luci,david-xiao/luci,taiha/luci,bittorf/luci,male-puppies/luci,deepak78/new-luci,981213/luci-1,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,MinFu/luci,openwrt-es/openwrt-luci,kuoruan/luci,lcf258/openwrtcn,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,artynet/luci,marcel-sch/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,obsy/luci,openwrt/luci,jchuang1977/luci-1,mumuqz/luci,slayerrensky/luci,kuoruan/luci,opentechinstitute/luci,Noltari/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,cappiewu/luci,slayerrensky/luci,Kyklas/luci-proto-hso,schidler/ionic-luci,openwrt/luci,bittorf/luci,LuttyYang/luci
|
934d3ac0dc97e8a7ee65473109d26446b5ce77ed
|
src/observablecollection/src/Shared/ObservableSet.lua
|
src/observablecollection/src/Shared/ObservableSet.lua
|
--[=[
A list that can be observed for blend and other components
@class ObservableSet
]=]
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local Observable = require("Observable")
local Maid = require("Maid")
local Brio = require("Brio")
local RxValueBaseUtils = require("RxValueBaseUtils")
local ObservableSet = {}
ObservableSet.ClassName = "ObservableSet"
ObservableSet.__index = ObservableSet
--[=[
Constructs a new ObservableSet
@return ObservableSet
]=]
function ObservableSet.new()
local self = setmetatable({}, ObservableSet)
self._maid = Maid.new()
self._set = {}
self._countValue = Instance.new("IntValue")
self._countValue.Value = 0
self._maid:GiveTask(self._countValue)
--[=[
Fires when an item is added
@readonly
@prop ItemAdded Signal<T>
@within ObservableSet
]=]
self.ItemAdded = Signal.new()
self._maid:GiveTask(self.ItemAdded)
--[=[
Fires when an item is removed.
@readonly
@prop ItemRemoved Signal<T>
@within ObservableSet
]=]
self.ItemRemoved = Signal.new()
self._maid:GiveTask(self.ItemRemoved)
--[=[
Fires when the count changes.
@prop CountChanged RBXScriptSignal
@within ObservableSet
]=]
self.CountChanged = self._countValue.Changed
return self
end
--[=[
Returns whether the set is an observable set
@param value any
@return boolean
]=]
function ObservableSet.isObservableSet(value)
return type(value) == "table" and getmetatable(value) == ObservableSet
end
--[=[
Observes all items in the set
@return Observable<Brio<T>>
]=]
function ObservableSet:ObserveItemsBrio()
return Observable.new(function(sub)
local maid = Maid.new()
local function handleItem(item)
local brio = Brio.new(item)
maid[item] = brio
sub:Fire(brio)
end
for item, _ in pairs(self._set) do
handleItem(item)
end
maid:GiveTask(self.ItemAdded:Connect(handleItem))
maid:GiveTask(self.ItemRemoved:Connect(function(item)
maid[item] = nil
end))
self._maid[sub] = maid
maid:GiveTask(function()
self._maid[sub] = nil
sub:Complete()
end)
return maid
end)
end
--[=[
Returns whether the set contains the item
@param item T
@return boolean
]=]
function ObservableSet:Contains(item)
assert(item ~= nil, "Bad item")
return self._set[item] == true
end
--[=[
Gets the count of items in the set
@return number
]=]
function ObservableSet:GetCount()
return self._countValue.Value
end
--[=[
Observes the count of the set
@return Observable<number>
]=]
function ObservableSet:ObserveCount()
return RxValueBaseUtils.observeValue(self._countValue)
end
--[=[
Adds the item to the set if it does not exists.
@param item T
]=]
function ObservableSet:Add(item)
assert(item ~= nil, "Bad item")
if not self._set[item] then
self._countValue.Value = self._countValue.Value + 1
self._set[item] = true
self.ItemAdded:Fire(item)
end
return function()
if self.Destroy then
self:Remove(item)
end
end
end
--[=[
Removes the item from the set if it exists.
@param item T
]=]
function ObservableSet:Remove(item)
assert(item ~= nil, "Bad item")
if self._set[item] then
self._countValue.Value = self._countValue.Value - 1
self._set[item] = nil
self.ItemRemoved:Fire(item)
end
end
function ObservableSet:GetFirstItem()
local value = next(self._set)
return value
end
--[=[
Gets a list of all entries.
@return { T }
]=]
function ObservableSet:GetList()
local list = {}
for item, _ in pairs(self._set) do
table.insert(list, item)
end
return list
end
--[=[
Cleans up the ObservableSet and sets the metatable to nil.
]=]
function ObservableSet:Destroy()
self._maid:DoCleaning()
setmetatable(self, nil)
end
return ObservableSet
|
--[=[
A list that can be observed for blend and other components
@class ObservableSet
]=]
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local Observable = require("Observable")
local Maid = require("Maid")
local Brio = require("Brio")
local RxValueBaseUtils = require("RxValueBaseUtils")
local ObservableSet = {}
ObservableSet.ClassName = "ObservableSet"
ObservableSet.__index = ObservableSet
--[=[
Constructs a new ObservableSet
@return ObservableSet
]=]
function ObservableSet.new()
local self = setmetatable({}, ObservableSet)
self._maid = Maid.new()
self._set = {}
self._countValue = Instance.new("IntValue")
self._countValue.Value = 0
self._maid:GiveTask(self._countValue)
--[=[
Fires when an item is added
@readonly
@prop ItemAdded Signal<T>
@within ObservableSet
]=]
self.ItemAdded = Signal.new()
self._maid:GiveTask(self.ItemAdded)
--[=[
Fires when an item is removed.
@readonly
@prop ItemRemoved Signal<T>
@within ObservableSet
]=]
self.ItemRemoved = Signal.new()
self._maid:GiveTask(self.ItemRemoved)
--[=[
Fires when the count changes.
@prop CountChanged RBXScriptSignal
@within ObservableSet
]=]
self.CountChanged = self._countValue.Changed
return self
end
--[=[
Returns whether the set is an observable set
@param value any
@return boolean
]=]
function ObservableSet.isObservableSet(value)
return type(value) == "table" and getmetatable(value) == ObservableSet
end
--[=[
Observes all items in the set
@return Observable<Brio<T>>
]=]
function ObservableSet:ObserveItemsBrio()
return Observable.new(function(sub)
local maid = Maid.new()
local function handleItem(item)
local brio = Brio.new(item)
maid[item] = brio
sub:Fire(brio)
end
for item, _ in pairs(self._set) do
handleItem(item)
end
maid:GiveTask(self.ItemAdded:Connect(handleItem))
maid:GiveTask(self.ItemRemoved:Connect(function(item)
maid[item] = nil
end))
self._maid[sub] = maid
maid:GiveTask(function()
self._maid[sub] = nil
sub:Complete()
end)
return maid
end)
end
--[=[
Returns whether the set contains the item
@param item T
@return boolean
]=]
function ObservableSet:Contains(item)
assert(item ~= nil, "Bad item")
return self._set[item] == true
end
--[=[
Gets the count of items in the set
@return number
]=]
function ObservableSet:GetCount()
return self._countValue.Value
end
--[=[
Observes the count of the set
@return Observable<number>
]=]
function ObservableSet:ObserveCount()
return RxValueBaseUtils.observeValue(self._countValue)
end
--[=[
Adds the item to the set if it does not exists.
@param item T
]=]
function ObservableSet:Add(item)
assert(item ~= nil, "Bad item")
if not self._set[item] then
self._countValue.Value = self._countValue.Value + 1
self._set[item] = true
self.ItemAdded:Fire(item)
end
return function()
if self.Destroy then
self:Remove(item)
end
end
end
--[=[
Removes the item from the set if it exists.
@param item T
]=]
function ObservableSet:Remove(item)
assert(item ~= nil, "Bad item")
if self._set[item] then
self._countValue.Value = self._countValue.Value - 1
self._set[item] = nil
if self.Destroy then
self.ItemRemoved:Fire(item)
end
end
end
function ObservableSet:GetFirstItem()
local value = next(self._set)
return value
end
--[=[
Gets a list of all entries.
@return { T }
]=]
function ObservableSet:GetList()
local list = {}
for item, _ in pairs(self._set) do
table.insert(list, item)
end
return list
end
--[=[
Cleans up the ObservableSet and sets the metatable to nil.
]=]
function ObservableSet:Destroy()
self._maid:DoCleaning()
setmetatable(self, nil)
end
return ObservableSet
|
fix: Do not error if observable set is already cleaned up, but we're removing
|
fix: Do not error if observable set is already cleaned up, but we're removing
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
ecde3d18fe9c87c563c39f81454e493aa6d6d4fc
|
packages/lime-system/files/usr/lib/lua/lime/proto/batadv.lua
|
packages/lime-system/files/usr/lib/lua/lime/proto/batadv.lua
|
#!/usr/bin/lua
batadv = {}
function batadv.setup_interface(interface, ifname)
uci:set("network", interface, "interface")
uci:set("network", interface, "ifname", ifname)
uci:set("network", interface, "proto", "batadv")
uci:set("network", interface, "mesh", "bat0")
uci:set("network", interface, "mtu", "1528")
uci:save("network")
end
function batadv.clean()
print("Clearing batman-adv config...")
uci:delete("batman-adv", "bat0")
end
function batadv.init()
-- TODO
end
function batadv.configure()
batadv.clean()
uci:set("batman-adv", "bat0", "mesh")
uci:set("batman-adv", "bat0", "brige_loop_avoidance", "1")
uci:save("batman-adv")
end
function batadv.apply()
-- TODO (i.e. /etc/init.d/network restart)
end
return batadv
|
#!/usr/bin/lua
batadv = {}
function batadv.setup_interface(interface, ifname)
uci:set("network", interface, "interface")
uci:set("network", interface, "ifname", ifname)
uci:set("network", interface, "proto", "batadv")
uci:set("network", interface, "mesh", "bat0")
uci:set("network", interface, "mtu", "1528")
uci:save("network")
end
function batadv.clean()
print("Clearing batman-adv config...")
uci:delete("batman-adv", "bat0")
if not fs.lstat("/etc/config/batman-adv") then fs.writefile("/etc/config/batman-adv", "") end
end
function batadv.init()
-- TODO
end
function batadv.configure()
batadv.clean()
uci:set("batman-adv", "bat0", "mesh")
uci:set("batman-adv", "bat0", "bridge_loop_avoidance", "1")
uci:save("batman-adv")
end
function batadv.apply()
-- TODO (i.e. /etc/init.d/network restart)
end
return batadv
|
bugfixes in batadv.lua: create /etc/config/batman-adv if nonexistant, and fix typo on bridge_loop_avoidance option
|
bugfixes in batadv.lua: create /etc/config/batman-adv if nonexistant, and fix typo on bridge_loop_avoidance option
|
Lua
|
agpl-3.0
|
p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages
|
7a310e81f67ea019ad610e4f7107fb497094ece8
|
mods/mapfix/init.lua
|
mods/mapfix/init.lua
|
local function mapfix(minp, maxp)
local vm = minetest.get_voxel_manip(minp, maxp)
vm:update_liquids()
vm:write_to_map()
vm:update_map()
end
local previous = -math.huge
local default_size = tonumber(minetest.setting_get("mapfix_default_size")) or 40
local max_size = tonumber(minetest.setting_get("mapfix_max_size")) or 50
local delay = tonumber(minetest.setting_get("mapfix_delay")) or 15
minetest.register_chatcommand("mapfix", {
params = "<size>",
description = "Recalculate the flowing liquids and the light of a chunk",
func = function(name, param)
local pos = minetest.get_player_by_name(name):getpos()
local size = tonumber(param) or 40
local privs = minetest.check_player_privs(name, {server=true})
local time = os.clock()
if not privs then
if size > 50 and not privs then
return false, "You need the server privilege to exceed the radius of " .. max_size .. " blocks"
elseif time - previous < 15 then
return false, "Wait at least " .. delay .. " seconds from the previous \"/mapfix\"."
end
previous = time
end
local minp = vector.round(vector.subtract(pos, size - 0.5))
local maxp = vector.round(vector.add(pos, size + 0.5))
minetest.log("action", name .. " uses mapfix at " .. minetest.pos_to_string(vector.round(pos)) .. " with radius " .. size)
mapfix(minp, maxp)
return true, "Done."
end,
})
|
local function mapfix(minp, maxp)
local vm = minetest.get_voxel_manip(minp, maxp)
vm:update_liquids()
vm:write_to_map()
vm:update_map()
end
local previous = os.time()
local default_size = tonumber(minetest.setting_get("mapfix_default_size")) or 40
local max_size = tonumber(minetest.setting_get("mapfix_max_size")) or 50
local delay = tonumber(minetest.setting_get("mapfix_delay")) or 15
minetest.register_chatcommand("mapfix", {
params = "<size>",
description = "Recalculate the flowing liquids and the light of a chunk",
func = function(name, param)
local pos = minetest.get_player_by_name(name):getpos()
local size = tonumber(param) or default_size
local privs = minetest.check_player_privs(name, {server=true})
local time = os.time()
if not privs then
if size > max_size then
return false, "You need the server privilege to exceed the radius of " .. max_size .. " blocks"
elseif time - previous < delay then
return false, "Wait at least " .. delay .. " seconds from the previous \"/mapfix\"."
end
previous = time
end
local minp = vector.round(vector.subtract(pos, size - 0.5))
local maxp = vector.round(vector.add(pos, size + 0.5))
minetest.log("action", name .. " uses mapfix at " .. minetest.pos_to_string(vector.round(pos)) .. " with radius " .. size)
mapfix(minp, maxp)
return true, "Done."
end,
})
|
[mapfix] Update
|
[mapfix] Update
|
Lua
|
unlicense
|
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
|
20b5d7d26a8aa6ecc2880f56d7298c18b1165a97
|
extensions/osascript/test_javascript.lua
|
extensions/osascript/test_javascript.lua
|
hs.osascript = require("hs.osascript")
function testJavaScriptParseError()
local js = "2 +"
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual(descriptor.OSAScriptErrorBriefMessageKey, "Error on line 1: SyntaxError: Unexpected end of script")
return success()
end
function testJavaScriptAddition()
local js = "2+2"
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 4)
return success()
end
function testJavaScriptDestructuring()
local js = [[
var obj = { cat: 1, dog: 2 };
var { cat, dog } = obj;
cat + dog;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 3)
return success()
end
function testJavaScriptString()
local js = [[
var str1 = "Hello", str2 = "World";
str1 + ", " + str2 + "!";
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, "Hello, World!")
return success()
end
function testJavaScriptArray()
local js = [[
[1, "a", 3.14, "b", null, false]
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object[1], 1)
assertIsEqual(object[2], "a")
assertIsEqual(object[3], 3.14)
assertIsEqual(object[4], "b")
assertIsEqual(object[5], false)
return success()
end
function testJavaScriptJsonStringify()
local js = [[
var obj = {
a: 1,
"b": "two",
"c": true
};
json = JSON.stringify(obj);
json;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, '{"a":1,"b":"two","c":true}')
return success()
end
function testJavaScriptJsonParse()
local js = [[
var json = '{"a":1, "b": "two", "c": true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertIsEqual(status, true)
assertIsEqual(object.a, 1)
assertIsEqual(object.b, "two")
assertIsEqual(object.c, true)
return success()
end
function testJavaScriptJsonParseError()
local js = [[
var json = '{"a":1, "b": "two", c: true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual("Error: SyntaxError: JSON Parse error: Property name must be a string literal", descriptor.OSAScriptErrorBriefMessageKey)
return success()
end
|
hs.osascript = require("hs.osascript")
function testJavaScriptParseError()
local js = "2 +"
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual(descriptor.OSAScriptErrorBriefMessageKey, "Error on line 1: SyntaxError: Unexpected end of script")
return success()
end
function testJavaScriptAddition()
local js = "2+2"
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 4)
return success()
end
function testJavaScriptDestructuring()
local js = [[
var obj = { cat: 1, dog: 2 };
var { cat, dog } = obj;
cat + dog;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 3)
return success()
end
function testJavaScriptString()
local js = [[
var str1 = "Hello", str2 = "World";
str1 + ", " + str2 + "!";
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, "Hello, World!")
return success()
end
function testJavaScriptArray()
local js = [[
[1, "a", 3.14, "b", null, false]
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object[1], 1)
assertIsEqual(object[2], "a")
assertIsEqual(object[3], 3.14)
assertIsEqual(object[4], "b")
assertIsEqual(object[5], false)
return success()
end
function testJavaScriptJsonStringify()
local js = [[
var obj = {
a: 1,
"b": "two",
"c": true
};
json = JSON.stringify(obj);
json;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, '{"a":1,"b":"two","c":true}')
return success()
end
function testJavaScriptJsonParse()
local js = [[
var json = '{"a":1, "b": "two", "c": true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertIsEqual(status, true)
assertIsEqual(object.a, 1)
assertIsEqual(object.b, "two")
assertIsEqual(object.c, true)
return success()
end
function testJavaScriptJsonParseError()
local js = [[
var json = '{"a":1, "b": "two", c: true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual("Error", descriptor.OSAScriptErrorMessageKey and descriptor.OSAScriptErrorMessageKey:sub(1, 5))
return success()
end
|
Fixed bug in testJavaScriptJsonParseError
|
Fixed bug in testJavaScriptJsonParseError
|
Lua
|
mit
|
latenitefilms/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,CommandPost/CommandPost-App,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon
|
9ea1eb91f7e87cea210e0a0216cf3e9a35a55b32
|
levent/socket.lua
|
levent/socket.lua
|
--[[
-- author: xjdrew
-- date: 2014-07-17
--]]
local c = require "levent.socket.c"
local errno = require "levent.errno.c"
local class = require "levent.class"
local hub = require "levent.hub"
local timeout = require "levent.timeout"
local closed_socket = setmetatable({}, {__index = function(t, key)
if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then
return function(...)
return nil, errno.EBADF
end
end
end})
local function _wait(watcher, sec)
local t
if sec and sec > 0 then
t = timeout.start_new(sec)
end
local ok, excepiton = xpcall(hub.wait, debug.traceback, hub, watcher)
if not ok then
print(ok, excepiton)
end
if t then
t:cancel()
end
return ok, excepiton
end
local Socket = class("Socket")
function Socket:_init(cobj)
assert(type(cobj.fileno) == "function", cobj)
self.cobj = cobj
self.cobj:setblocking(false)
local loop = hub.loop
self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ)
self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE)
-- timeout
self.timeout = nil
end
function Socket:setblocking(flag)
if flag then
self.timeout = nil
else
self.timeout = 0.0
end
end
function Socket:set_timeout(sec)
self.timeout = sec
end
function Socket:get_timeout()
return self.timeout
end
function Socket:bind(ip, port)
self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1)
local ok, code = self.cobj:bind(ip, port)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:listen(backlog)
local ok, code = self.cobj:listen(backlog)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:_need_block(err)
if self.timeout == 0 then
return false
end
if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then
return false
end
return true
end
function Socket:accept()
local csock, err
while true do
csock, err = self.cobj:accept()
if csock then
break
end
if not self:_need_block(err) then
return nil, errno.strerror(err)
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
return Socket.new(csock)
end
function Socket:_recv(func, ...)
while true do
local data, err = func(self.cobj, ...)
if data then
return data
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args:len
function Socket:recvfrom(len)
return self:_recv(self.cobj.recvfrom, len)
end
-- args: len
function Socket:recv(len)
return self:_recv(self.cobj.recv, len)
end
function Socket:_send(func, ...)
while true do
local nwrite, err = func(self.cobj, ...)
if nwrite then
return nwrite
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args: data, from
-- from: count from 0
function Socket:send(data, from)
return self:_send(self.cobj.send, data, from)
end
-- args:
function Socket:sendto(ip, port, data, from)
return self:_send(self.cobj.sendto, ip, port, data, from)
end
-- from: count from 0
function Socket:sendall(data, from)
local from = from or 0
local total = #data - from
local sent = 0
while sent < total do
local nwrite, err = self:send(data, from + sent)
if not nwrite then
return sent, err
end
sent = sent + nwrite
end
return sent
end
function Socket:connect(ip, port)
while true do
local ok, err = self.cobj:connect(ip, port)
if ok then
return ok
end
if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK) then
return ok, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
function Socket:fileno()
return self.cobj:fileno()
end
function Socket:getpeername()
return self.cobj:getpeername()
end
function Socket:getsockname()
return self.cobj:getsockname()
end
function Socket:getsockopt(level, optname, buflen)
return self.cobj:getsockopt(level, optname, buflen)
end
function Socket:setsockopt(level, optname, value)
return self.cobj:setsockopt(level, optname, value)
end
function Socket:close()
if self.cobj ~= closed_socket then
hub:cancel_wait(self._read_event)
hub:cancel_wait(self._write_event)
self.cobj:close()
self.cobj = closed_socket
end
end
local socket = {}
function socket.socket(family, _type, protocol)
local cobj, err = c.socket(family, _type, protocol)
if not cobj then
return nil, errno.strerror(err)
end
return Socket.new(cobj)
end
return setmetatable(socket, {__index = c} )
|
--[[
-- author: xjdrew
-- date: 2014-07-17
--]]
local c = require "levent.socket.c"
local errno = require "levent.errno.c"
local class = require "levent.class"
local hub = require "levent.hub"
local timeout = require "levent.timeout"
local closed_socket = setmetatable({}, {__index = function(t, key)
if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then
return function(...)
return nil, errno.EBADF
end
end
end})
local function _wait(watcher, sec)
local t
if sec and sec > 0 then
t = timeout.start_new(sec)
end
local ok, excepiton = xpcall(hub.wait, debug.traceback, hub, watcher)
if not ok then
print(ok, excepiton)
end
if t then
t:cancel()
end
return ok, excepiton
end
local Socket = class("Socket")
function Socket:_init(cobj)
assert(type(cobj.fileno) == "function", cobj)
self.cobj = cobj
self.cobj:setblocking(false)
local loop = hub.loop
self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ)
self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE)
-- timeout
self.timeout = nil
end
function Socket:setblocking(flag)
if flag then
self.timeout = nil
else
self.timeout = 0.0
end
end
function Socket:set_timeout(sec)
self.timeout = sec
end
function Socket:get_timeout()
return self.timeout
end
function Socket:bind(ip, port)
self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1)
local ok, code = self.cobj:bind(ip, port)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:listen(backlog)
local ok, code = self.cobj:listen(backlog)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:_need_block(err)
if self.timeout == 0 then
return false
end
if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then
return false
end
return true
end
function Socket:accept()
local csock, err
while true do
csock, err = self.cobj:accept()
if csock then
break
end
if not self:_need_block(err) then
return nil, errno.strerror(err)
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
return Socket.new(csock)
end
function Socket:_recv(func, ...)
while true do
local data, err = func(self.cobj, ...)
if data then
return data
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args:len
function Socket:recvfrom(len)
return self:_recv(self.cobj.recvfrom, len)
end
-- args: len
function Socket:recv(len)
return self:_recv(self.cobj.recv, len)
end
function Socket:_send(func, ...)
while true do
local nwrite, err = func(self.cobj, ...)
if nwrite then
return nwrite
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args: data, from
-- from: count from 0
function Socket:send(data, from)
return self:_send(self.cobj.send, data, from)
end
-- args:
function Socket:sendto(ip, port, data, from)
return self:_send(self.cobj.sendto, ip, port, data, from)
end
-- from: count from 0
function Socket:sendall(data, from)
local from = from or 0
local total = #data - from
local sent = 0
while sent < total do
local nwrite, err = self:send(data, from + sent)
if not nwrite then
return sent, err
end
sent = sent + nwrite
end
return sent
end
function Socket:connect(ip, port)
while true do
local ok, err = self.cobj:connect(ip, port)
if ok then
return ok
end
if err == errno.EISCONN then
return true
end
if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK and err ~= errno.EALREADY) then
return ok, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
function Socket:fileno()
return self.cobj:fileno()
end
function Socket:getpeername()
return self.cobj:getpeername()
end
function Socket:getsockname()
return self.cobj:getsockname()
end
function Socket:getsockopt(level, optname, buflen)
return self.cobj:getsockopt(level, optname, buflen)
end
function Socket:setsockopt(level, optname, value)
return self.cobj:setsockopt(level, optname, value)
end
function Socket:close()
if self.cobj ~= closed_socket then
hub:cancel_wait(self._read_event)
hub:cancel_wait(self._write_event)
self.cobj:close()
self.cobj = closed_socket
end
end
local socket = {}
function socket.socket(family, _type, protocol)
local cobj, err = c.socket(family, _type, protocol)
if not cobj then
return nil, errno.strerror(err)
end
return Socket.new(cobj)
end
return setmetatable(socket, {__index = c} )
|
bugfix: first connect return EINPROGRESS and then return EISCONN
|
bugfix: first connect return EINPROGRESS and then return EISCONN
|
Lua
|
mit
|
xjdrew/levent
|
38dc71af93d1ee72351f63c4329a1d23604375f3
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
else
m.pageaction = false
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
|
Add support for changing ULA prefix
|
Add support for changing ULA prefix
git-svn-id: b12fe9853c2c9793030bd743626f1e993aa2455c@9849 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux,opentechinstitute/luci-commotion-linux
|
2bfe7bca4175b839fea5018b6397a9c1d268a741
|
src/lluv/websocket/luasocket.lua
|
src/lluv/websocket/luasocket.lua
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Copyright (C) 2016 Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-websocket library.
--
------------------------------------------------------------------
---
-- Implement LuaSocket API on top of WebSocket
--
-- socket:bind(url, application)
-- e.g. socket:bind("ws://127.0.0.1:5555", "echo")
--
-- socket:connect(url, application)
-- e.g. socket:connect("ws://127.0.0.1:5555", "echo")
--
-- socket:receive([pat])
-- supports only 2 patterns
-- `*r` - return any recived data (can return not full frame)
-- `*l` - return entire frame
-- also `receive` returns `opcode` and `fin`
--
-- socket:send(frame[, opcode])
--
local trace -- = function(...) print(os.date("[LWS][%x %X]"), ...) end
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.luasocket"
local ws = require "lluv.websocket"
local unpack = unpack or table.unpack
local tconcat = table.concat
local tappend = function(t, v) t[#t + 1] = v return t end
local WsSocket = ut.class(socket._TcpSocket) do
local function is_sock(s)
local ts = type(s)
if ts == 'userdata' then return true end
if ts ~= 'table' then return false end
return
s.start_read and
s.write and
s.connect and
true
end
local function is_ws_sock(s)
return is_sock(s) and
s._client_handshake and
s._server_handshake and
true
end
function WsSocket:__init(p)
if is_sock(p) then
WsSocket.__base.__init(self, p)
else
self._ws_opt = p
WsSocket.__base.__init(self)
end
return self
end
function WsSocket:_reset()
if self._sock then self._sock:close() end
self._sock = ws.new(self._ws_opt)
end
function WsSocket:_start_read()
self._sock:start_read("*f", function(cli, err, data, opcode, fin)
if err then return self:_on_io_error(err) end
if data then self._buf:append{data, opcode, fin} end
if self:_waiting("read") then return self:_resume(true) end
end)
self._frame = {}
return self
end
function WsSocket:receive(mode)
while true do
local frame, err = WsSocket.__base.receive(self, '*r')
if not frame then return nil, err end
if mode == '*r' then return unpack(frame) end
local opcode = frame[2]
if opcode == ws.PING or opcode == ws.PONG then
return frame[1], opcode, true
end
if not self._opcode then
self._frame, self._opcode = {}, opcode
end
tappend(self._frame, frame[1])
if frame[3] then
local msg, opcode = tconcat(self._frame), self._opcode
self._frame, self._opcode = nil
return msg, opcode, true
end
end
end
function WsSocket:send(data, opcode, fin)
if not self._sock then return nil, self._err end
local terminated
local function fn(cli, err)
if trace then trace("SEND CB>", self, #data, opcode, fin, fn) end
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true)
end;
if trace then trace("SEND>", self, #data, opcode, fin, fn) end
self:_start("write")
self._sock:write(data, opcode, fin, fn)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
return nil, self._err
end
return ok, err
end
function WsSocket:_connect(url, proto)
self:_start("conn")
local terminated
self._sock:connect(url, proto, function(sock, err, headers)
if terminated then return end
return self:_resume(not err, err, headers)
end)
local ok, err, headers = self:_yield()
terminated = true
self:_stop("conn")
if not ok then
self:_reset()
return nil, err
end
return self, headers
end
function WsSocket:connect(host, port)
local ok, err = self:_connect(host, port)
if not ok then return nil, err end
local headers = err
ok, err = self:_start_read()
if not ok then return nil, err end
return self, headers
end
function WsSocket:accept()
local cli, err = self:_accept()
if not cli then return nil, err end
return cli:handshake()
end
function WsSocket:handshake()
if not self._sock then return nil, self._err end
local terminated
self:_start("write")
self._sock:handshake(function(cli, err, protocol, headers)
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true, nil, protocol, headers)
end)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
self._sock:stop_read()
return nil, self._err
end
local ok, err, protocol, headers = self:_start_read()
if not ok then return nil, err end
return self, protocol, headers
end
function WsSocket:__tostring()
return "lluv.ws.luasocket (" .. tostring(self._sock) .. ")"
end
function WsSocket:close(code, reason)
if self._sock then
local terminated
local function fn(cli, clean, code, reason)
if trace then trace("CLOSE CB>", self, clean, code, reason) end
if terminated then return end
return self:_resume(clean, code, reason)
end;
if trace then trace("CLOSE>", self, code, reason, fn) end
self:_start("write")
self._sock:close(code, reason, fn)
local ok, code, reason = self:_yield()
terminated = true
self:_stop("write")
self._sock = nil
return ok, code, reason
end
end
end
return {
ws = WsSocket.new;
TEXT = ws.TEXT;
BINARY = ws.BINARY;
PING = ws.PING;
PONG = ws.PONG;
CONTINUATION = ws.CONTINUATION;
CLOSE = ws.CLOSE;
_WsSocket = WsSocket
}
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Copyright (C) 2016 Alexey Melnichuk <alexeymelnichuck@gmail.com>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-websocket library.
--
------------------------------------------------------------------
---
-- Implement LuaSocket API on top of WebSocket
--
-- socket:bind(url, application)
-- e.g. socket:bind("ws://127.0.0.1:5555", "echo")
--
-- socket:connect(url, application)
-- e.g. socket:connect("ws://127.0.0.1:5555", "echo")
--
-- socket:receive([pat])
-- supports only 2 patterns
-- `*r` - return any recived data (can return not full frame)
-- `*l` - return entire frame
-- also `receive` returns `opcode` and `fin`
--
-- socket:send(frame[, opcode])
--
local trace -- = function(...) print(os.date("[LWS][%x %X]"), ...) end
local uv = require "lluv"
local ut = require "lluv.utils"
local socket = require "lluv.luasocket"
local ws = require "lluv.websocket"
local unpack = unpack or table.unpack
local tconcat = table.concat
local tappend = function(t, v) t[#t + 1] = v return t end
local WsSocket = ut.class(socket._TcpSocket) do
local function is_sock(s)
local ts = type(s)
if ts == 'userdata' then return true end
if ts ~= 'table' then return false end
return
s.start_read and
s.write and
s.connect and
true
end
local function is_ws_sock(s)
return is_sock(s) and
s._client_handshake and
s._server_handshake and
true
end
function WsSocket:__init(p)
if is_sock(p) then
WsSocket.__base.__init(self, p)
else
self._ws_opt = p
WsSocket.__base.__init(self)
end
return self
end
function WsSocket:_reset()
if self._sock then self._sock:close() end
self._sock = ws.new(self._ws_opt)
end
function WsSocket:_start_read()
self._sock:start_read("*f", function(cli, err, data, opcode, fin)
if err then return self:_on_io_error(err) end
if data then self._buf:append{data, opcode, fin} end
if self:_waiting("read") then return self:_resume(true) end
end)
self._frame = {}
return self
end
function WsSocket:receive(mode)
while true do
local frame, err = WsSocket.__base.receive(self, '*r')
if not frame then return nil, err end
if mode == '*r' then return unpack(frame) end
local opcode = frame[2]
if opcode == ws.PING or opcode == ws.PONG then
return frame[1], opcode, true
end
if not self._opcode then
self._frame, self._opcode = {}, opcode
end
tappend(self._frame, frame[1])
if frame[3] then
local msg, opcode = tconcat(self._frame), self._opcode
self._frame, self._opcode = nil
return msg, opcode, true
end
end
end
function WsSocket:send(data, opcode, fin)
if not self._sock then return nil, self._err end
local terminated
local function fn(cli, err)
if trace then trace("SEND CB>", self, #data, opcode, fin, fn) end
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true)
end;
if trace then trace("SEND>", self, #data, opcode, fin, fn) end
self:_start("write")
self._sock:write(data, opcode, fin, fn)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
return nil, self._err
end
return ok, err
end
function WsSocket:_connect(url, proto)
self:_start("conn")
local terminated
self._sock:connect(url, proto, function(sock, err, headers)
if terminated then return end
return self:_resume(not err, err, headers)
end)
local ok, err, headers = self:_yield()
terminated = true
self:_stop("conn")
if not ok then
self:_reset()
return nil, err
end
return self, headers
end
function WsSocket:connect(host, port)
local ok, err = self:_connect(host, port)
if not ok then return nil, err end
local headers = err
ok, err = self:_start_read()
if not ok then return nil, err end
return self, headers
end
function WsSocket:accept()
local cli, err = self:_accept()
if not cli then return nil, err end
return cli:handshake()
end
function WsSocket:handshake()
if not self._sock then return nil, self._err end
local terminated
self:_start("write")
self._sock:handshake(function(cli, err, protocol, headers)
if terminated then return end
if err then return self:_on_io_error(err) end
return self:_resume(true, nil, protocol, headers)
end)
local ok, err = self:_yield()
terminated = true
self:_stop("write")
if not ok then
self._sock:stop_read()
return nil, self._err
end
local ok, err, protocol, headers = self:_start_read()
if not ok then return nil, err end
return self, protocol, headers
end
function WsSocket:__tostring()
return "lluv.ws.luasocket (" .. tostring(self._sock) .. ")"
end
function WsSocket:close(code, reason)
if not self._sock then return true end
-- we can support close from any thread only if we do not need do any IO
-- it possible for server socket.
-- for data socket we just close TCP but it is not correct WebSocket close
local clean
if (not self._accept_list) and (self._co == coroutine.running()) then
-- assume this is not server socket so we try
-- do correct close handshake and wait until done
local terminated
local function fn(cli, clean, code, reason)
if trace then trace("CLOSE CB>", self, clean, code, reason) end
if terminated then return end
return self:_resume(clean, code, reason)
end;
if trace then trace("CLOSE>", self, code, reason, fn) end
self:_start("write")
self._sock:close(code, reason, fn)
clean, code, reason = self:_yield()
terminated = true
self:_stop("write")
else
-- this is server socket so we can just close socket
clean = not not self._accept_list
self._sock:close()
end
-- clean up lluv.luasocket data
self._timer:close()
self._sock, self._timer = nil
return clean, code, reason
end
end
return {
ws = WsSocket.new;
TEXT = ws.TEXT;
BINARY = ws.BINARY;
PING = ws.PING;
PONG = ws.PONG;
CONTINUATION = ws.CONTINUATION;
CLOSE = ws.CLOSE;
_WsSocket = WsSocket
}
|
Fix. support close LuaSocket socket from main thread.
|
Fix. support close LuaSocket socket from main thread.
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
8567eabec1e2365d78d96b611e1350e9da416836
|
tests/actions/make/cpp/test_make_pch.lua
|
tests/actions/make/cpp/test_make_pch.lua
|
--
-- tests/actions/make/cpp/test_make_pch.lua
-- Validate the setup for precompiled headers in makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_pch")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
sln, prj = test.createsolution()
end
local function prepareVars()
local cfg = test.getconfig(prj, "Debug")
make.pch(cfg)
end
local function prepareRules()
local cfg = test.getconfig(prj, "Debug")
make.pchRules(cfg.project)
end
--
-- If no header has been set, nothing should be output.
--
function suite.noConfig_onNoHeaderSet()
prepareVars()
test.isemptycapture()
end
--
-- If a header is set, but the NoPCH flag is also set, then
-- nothing should be output.
--
function suite.noConfig_onHeaderAndNoPCHFlag()
pchheader "include/myproject.h"
flags "NoPCH"
prepareVars()
test.isemptycapture()
end
--
-- If a header is specified and the NoPCH flag is not set, then
-- the header can be used.
--
function suite.config_onPchEnabled()
pchheader "include/myproject.h"
prepareVars()
test.capture [[
PCH = include/myproject.h
GCH = $(OBJDIR)/$(notdir $(PCH)).gch
]]
end
--
-- The PCH can be specified relative the an includes search path.
--
function suite.pch_searchesIncludeDirs()
pchheader "premake.h"
includedirs { "../src/host" }
prepareVars()
test.capture [[
PCH = ../src/host/premake.h
]]
end
--
-- Verify the format of the PCH rules block for a C++ file.
--
function suite.buildRules_onCpp()
pchheader "include/myproject.h"
prepareRules()
test.capture [[
ifneq (,$(PCH))
$(GCH): $(PCH)
@echo $(notdir $<)
$(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<"
endif
]]
end
--
-- Verify the format of the PCH rules block for a C file.
--
function suite.buildRules_onC()
language "C"
pchheader "include/myproject.h"
prepareRules()
test.capture [[
ifneq (,$(PCH))
$(GCH): $(PCH)
@echo $(notdir $<)
$(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<"
endif
]]
end
--
-- If the header is located on one of the include file
-- search directories, it should get found automatically.
--
function suite.findsPCH_onIncludeDirs()
location "MyProject"
pchheader "premake.h"
includedirs { "../src/host" }
prepareVars()
test.capture [[
PCH = ../../src/host/premake.h
]]
end
|
--
-- tests/actions/make/cpp/test_make_pch.lua
-- Validate the setup for precompiled headers in makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_pch")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
sln, prj = test.createsolution()
end
local function prepareVars()
local cfg = test.getconfig(prj, "Debug")
make.pch(cfg)
end
local function prepareRules()
local cfg = test.getconfig(prj, "Debug")
make.pchRules(cfg.project)
end
--
-- If no header has been set, nothing should be output.
--
function suite.noConfig_onNoHeaderSet()
prepareVars()
test.isemptycapture()
end
--
-- If a header is set, but the NoPCH flag is also set, then
-- nothing should be output.
--
function suite.noConfig_onHeaderAndNoPCHFlag()
pchheader "include/myproject.h"
flags "NoPCH"
prepareVars()
test.isemptycapture()
end
--
-- If a header is specified and the NoPCH flag is not set, then
-- the header can be used.
--
function suite.config_onPchEnabled()
pchheader "include/myproject.h"
prepareVars()
test.capture [[
PCH = include/myproject.h
GCH = $(OBJDIR)/$(notdir $(PCH)).gch
]]
end
--
-- The PCH can be specified relative the an includes search path.
--
function suite.pch_searchesIncludeDirs()
pchheader "premake.h"
includedirs { "../src/host" }
prepareVars()
test.capture [[
PCH = ../src/host/premake.h
]]
end
--
-- Verify the format of the PCH rules block for a C++ file.
--
function suite.buildRules_onCpp()
pchheader "include/myproject.h"
prepareRules()
test.capture [[
ifneq (,$(PCH))
.NOTPARALLEL: $(GCH) $(PCH)
$(GCH): $(PCH)
@echo $(notdir $<)
$(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<"
endif
]]
end
--
-- Verify the format of the PCH rules block for a C file.
--
function suite.buildRules_onC()
language "C"
pchheader "include/myproject.h"
prepareRules()
test.capture [[
ifneq (,$(PCH))
.NOTPARALLEL: $(GCH) $(PCH)
$(GCH): $(PCH)
@echo $(notdir $<)
$(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<"
endif
]]
end
--
-- If the header is located on one of the include file
-- search directories, it should get found automatically.
--
function suite.findsPCH_onIncludeDirs()
location "MyProject"
pchheader "premake.h"
includedirs { "../src/host" }
prepareVars()
test.capture [[
PCH = ../../src/host/premake.h
]]
end
|
Fix makefile unit tests broken by previous commits
|
Fix makefile unit tests broken by previous commits
|
Lua
|
bsd-3-clause
|
annulen/premake,annulen/premake,warrenseine/premake,warrenseine/premake,annulen/premake,warrenseine/premake,annulen/premake
|
f8aefd51194853c1a0e46c2b8954facbeaa8abbb
|
View.lua
|
View.lua
|
local Object = require "Object"
local View = Object:clone()
-- a view of one or more nodes in the media library
-- a view has a title and icon (displayed at the top), and a list of nodes
-- (displayed in the main window) which the user can scroll through. It
-- also needs to remember where it is in that list so that it can recall
-- it when visited later.
function View:__init(icon, title, ...)
self.index = 1
self.icon = icon
self.title = title
self.list = {}
for _,node in ipairs {...} do
for child in node:children() do
if not child.hidden then
table.insert(self.list, child)
end
end
end
table.sort(self.list)
end
local W,H = love.graphics.getWidth(),love.graphics.getHeight()
local LH = math.floor(H/emufun.config.lines)
local function atLine(line)
local lg = love.graphics
lg.push()
lg.translate(0, math.floor(H/emufun.config.lines * line))
end
local function doneLine()
love.graphics.pop()
end
function View:draw()
local lg = love.graphics
local clip = lg.setScissor
atLine(0)
lg.setColor(32, 32, 32)
lg.rectangle("fill", 0, 0, W, LH)
lg.setColor(255, 255, 255)
lg.draw(self.icon, 0, 0, 0, LH/self.icon:getWidth(), LH/self.icon:getHeight())
lg.print(self.title, LH + 2, 0)
doneLine()
local padding = math.floor(LH * 0.2)
local half = math.floor(LH/2)
for i=1,emufun.config.lines do
local index = i - math.floor(emufun.config.lines/2) + self.index
local node = self.list[index]
if node then
atLine(i)
if index == self.index then
self:drawNode(node, 128, 255, 128)
lg.triangle("fill",
padding, padding,
padding, LH-padding,
LH-padding, half)
else
self:drawNode(node)
end
doneLine()
end
end
end
function View:prev()
self.index = (self.index - 2) % #self.list + 1
end
function View:next()
self.index = self.index % #self.list + 1
end
function View:selected()
return self.list[self.index]
end
-- draw this node with an optional colour mask
function View:drawNode(node, r, g, b)
local min = math.min
r = r and min(r, node.r) or node.r
g = g and min(g, node.g) or node.g
b = b and min(b, node.b) or node.b
love.graphics.setColor(r,g,b)
love.graphics.draw(node.icon, LH, 0, 0, LH/node.icon:getWidth(), LH/node.icon:getHeight())
love.graphics.print(node.name, 2*LH+2, 0)
end
return View
|
local Object = require "Object"
local View = Object:clone()
-- a view of one or more nodes in the media library
-- a view has a title and icon (displayed at the top), and a list of nodes
-- (displayed in the main window) which the user can scroll through. It
-- also needs to remember where it is in that list so that it can recall
-- it when visited later.
function View:__init(icon, title, ...)
self.index = 1
self.icon = icon
self.title = title
self.list = {}
for _,node in ipairs {...} do
for child in node:children() do
if not child.hidden then
table.insert(self.list, child)
end
end
end
table.sort(self.list)
end
local W,H = love.graphics.getWidth(),love.graphics.getHeight()
local LH = math.floor(H/emufun.config.lines)
local function atLine(line)
local lg = love.graphics
lg.push()
lg.translate(0, math.floor(H/emufun.config.lines * line))
end
local function doneLine()
love.graphics.pop()
end
function View:draw()
local lg = love.graphics
local clip = lg.setScissor
atLine(0)
lg.setColor(32, 32, 32)
lg.rectangle("fill", 0, 0, W, LH)
lg.setColor(255, 255, 255)
lg.draw(self.icon, 0, 0, 0, LH/self.icon:getWidth(), LH/self.icon:getHeight())
lg.print(self.title, LH + 2, 0)
doneLine()
local padding = math.floor(LH * 0.2)
local half = math.floor(LH/2)
for i=1,emufun.config.lines do
local index = i - math.floor(emufun.config.lines/2) + self.index
local node = self.list[index]
if node then
atLine(i)
if index == self.index then
self:drawNode(node, 128, 255, 128)
lg.triangle("fill",
padding, padding,
padding, LH-padding,
LH-padding, half)
else
self:drawNode(node)
end
doneLine()
end
end
end
function View:prev()
self.index = (self.index - 2) % #self.list + 1
end
function View:next()
self.index = self.index % #self.list + 1
end
function View:selected()
return self.list[self.index]
end
-- hacky workaround for love.graphics barfing on some things that should be valid utf8
function love.graphics.safeprint(str, ...)
local ok = pcall(love.graphics.print, str, ...)
if ok then return end
print("Error displaying title: ", str)
str = str:gsub("[^%w%s%p]", "?")
print("Falling back to:", str)
ok = pcall(love.graphics.print, str, ...)
if ok then return end
love.graphics.print("[corrupted filename]", ...)
end
-- draw this node with an optional colour mask
function View:drawNode(node, r, g, b)
local min = math.min
r = r and min(r, node.r) or node.r
g = g and min(g, node.g) or node.g
b = b and min(b, node.b) or node.b
love.graphics.setColor(r,g,b)
love.graphics.draw(node.icon, LH, 0, 0, LH/node.icon:getWidth(), LH/node.icon:getHeight())
love.graphics.safeprint(node.name, 2*LH+2, 0)
end
return View
|
Temporary fix for "invalid utf8" crash when displaying utf8 filenames
|
Temporary fix for "invalid utf8" crash when displaying utf8 filenames
The filename in question includes the text "Que Será Será" and is, as far as I can tell, valid UTF-8.
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
e8168fb4c9e6055d7436966979eb2a15346b57ac
|
script/c42421606.lua
|
script/c42421606.lua
|
--Number 85: Crazy Box
function c42421606.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,4),2)
c:EnableReviveLimit()
--cannot attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
c:RegisterEffect(e1)
--dice
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(42421606,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCost(c42421606.cost)
e2:SetTarget(c42421606.target)
e2:SetOperation(c42421606.operation)
c:RegisterEffect(e2)
end
function c42421606.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c42421606.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DICE,nil,0,tp,1)
end
function c42421606.filter(c)
return c:IsFaceup() and (c:IsLocation(LOCATION_SZONE) or c:IsType(TYPE_EFFECT))
end
function c42421606.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local dice=Duel.TossDice(tp,1)
if dice==1 then
Duel.SetLP(tp,Duel.GetLP(tp)/2)
elseif dice==2 then
Duel.Draw(tp,1,REASON_EFFECT)
elseif dice==3 then
Duel.DiscardHand(1-tp,nil,1,1,REASON_EFFECT+REASON_DISCARD)
elseif dice==4 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local tc=Duel.SelectMatchingCard(tp,c42421606.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil):GetFirst()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
elseif dice==5 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.Destroy(g,REASON_EFFECT)
else
Duel.Destroy(c,REASON_EFFECT)
end
end
|
--Number 85: Crazy Box
function c42421606.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,4),2)
c:EnableReviveLimit()
--cannot attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
c:RegisterEffect(e1)
--dice
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(42421606,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCost(c42421606.cost)
e2:SetTarget(c42421606.target)
e2:SetOperation(c42421606.operation)
c:RegisterEffect(e2)
end
function c42421606.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c42421606.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DICE,nil,0,tp,1)
end
function c42421606.filter(c)
return c:IsFaceup() and (c:IsLocation(LOCATION_SZONE) or c:IsType(TYPE_EFFECT))
end
function c42421606.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local dice=Duel.TossDice(tp,1)
if dice==1 then
Duel.SetLP(tp,Duel.GetLP(tp)/2)
elseif dice==2 then
Duel.Draw(tp,1,REASON_EFFECT)
elseif dice==3 then
Duel.DiscardHand(1-tp,nil,1,1,REASON_EFFECT+REASON_DISCARD)
elseif dice==4 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local tc=Duel.SelectMatchingCard(tp,c42421606.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil):GetFirst()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
elseif dice==5 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.Destroy(g,REASON_EFFECT)
else
Duel.Destroy(c,REASON_EFFECT)
end
end
|
fixed not negating when targeting itself
|
fixed not negating when targeting itself
|
Lua
|
mit
|
sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher
|
f46a3cdf539c01f6fac322d4cf25e4b373a33574
|
LogisticsWagons/wagons/requesterwagon.lua
|
LogisticsWagons/wagons/requesterwagon.lua
|
-- passive logistics wagon
local class = require 'middleclass'
RequesterWagon = class('RequesterWagon',ProxyWagon)
function RequesterWagon:initialize(parent,data)
debugLog("RequesterWagon:initialize")
ProxyWagon.initialize(self, parent, data)
self.wagonType = "RequesterWagon"
if(data ~= nil) then
debugLog("Need to check the requester slots")
else
self.requestSlots = {}
end
end
function RequesterWagon:updateWagon(tick)
ProxyWagon.updateWagon(self,tick)
end
function RequesterWagon:updateDataSerialisation()
ProxyWagon.updateDataSerialisation(self)
self:updateRequestSlots()
self.data.requestSlots = self.requestSlots
end
function RequesterWagon:createProxyType()
local proxyType = "lw-logistic-chest-requester-trans"
self:createProxy(proxyType)
end
function RequesterWagon:createProxy(proxyType)
ProxyWagon.createProxy(self,proxyType,true)
self:setRequestSlots()
end
function RequesterWagon:updateRequestSlots()
if self.proxy ~= nil then
local i = 0
local slots = {}
while i < 10 do
i = i + 1
slots[i] = self.proxy.getrequestslot(i)
if slots[i] == nil then
slots[i] = {}
end
end
self.requestSlots = slots
end
end
function RequesterWagon:setRequestSlots()
if self.proxy ~= nil and self.requestSlots ~= {} then
local i = 0
local slots = {}
while i < 10 do
i = i + 1
if slots[i] == nil or slots[i] == {} then
self.proxy.clearrequestslot(i)
else
self.proxy.setrequestslot(i, slots[i])
end
end
self.requestSlots = slots
end
end
|
-- passive logistics wagon
local class = require 'middleclass'
RequesterWagon = class('RequesterWagon',ProxyWagon)
function RequesterWagon:initialize(parent,data)
debugLog("RequesterWagon:initialize")
ProxyWagon.initialize(self, parent, data)
self.wagonType = "RequesterWagon"
if(data ~= nil) then
debugLog("Need to check the requester slots")
else
self.requestSlots = {}
end
end
function RequesterWagon:updateWagon(tick)
ProxyWagon.updateWagon(self,tick)
self:updateRequestSlots()
end
function RequesterWagon:updateDataSerialisation()
ProxyWagon.updateDataSerialisation(self)
self.data.requestSlots = self.requestSlots
end
function RequesterWagon:createProxyType()
local proxyType = "lw-logistic-chest-requester-trans"
self:createProxy(proxyType)
end
function RequesterWagon:createProxy(proxyType)
ProxyWagon.createProxy(self,proxyType,true)
self:setRequestSlots()
end
function RequesterWagon:updateRequestSlots()
if self.proxy ~= nil then
local i = 0
local slots = {}
while i < 10 do
i = i + 1
slots[i] = self.proxy.getrequestslot(i)
if slots[i] == nil then
slots[i] = {}
end
end
self.requestSlots = slots
end
end
function RequesterWagon:setRequestSlots()
if self.proxy ~= nil and self.requestSlots ~= {} then
local i = 0
local slots = self.requestSlots
while i < 10 do
i = i + 1
if slots[i] == nil or next(slots[i]) == nil then
self.proxy.clearrequestslot(i)
else
debugLog("Setting request slot to: " .. serpent.dump(slots[i]))
self.proxy.setrequestslot(slots[i],i)
end
end
self.requestSlots = slots
end
end
|
Fixed requester wagons
|
Fixed requester wagons
Entity data is not available when onsave event has been called. At that point the data isn't userdata any more but rather magic and API calls won't work on them.
|
Lua
|
mit
|
gnzzz/Factorio-Logistics-Wagons
|
77572b13126625b88275114b2d6cb065e0d2353d
|
plugins/lua/init.lua
|
plugins/lua/init.lua
|
require "superstring"
ENV = require "env"
::start::
--
-- Indicate that we are ready to receive a packet
--
io.write( "\n\x1A" ); io.flush()
--
-- Read until EOF
--
local code = io.read "a"
--
-- Only display errors if the code starts with ">"
--
local silent_error = true
if code:sub( 1, 1 ) == ">" then
code = code:sub( 2 )
silent_error = false
end
--
-- Try our code with "return " prepended first
--
local f, err = load( "return " .. code, "eval", "t", ENV )
if err then
f, err = load( code, "eval", "t", ENV )
end
--
-- We've been passed invalid Lua
--
if err then
if not silent_error then
io.write( err )
end
goto start
end
local thread = coroutine.create( f )
local start = os.clock()
--
-- Install our execution time limiter
--
debug.sethook( thread, function()
if os.clock() > start + 0.5 then
error( "maximum execution time exceeded", 2 )
end
end, "", 128 )
--
-- Try to run our function
--
local ret = { pcall( coroutine.resume, thread ) }
local success, err = ret[ 2 ], ret[ 3 ]
if not success then
if not silent_error then
io.write( err )
end
goto start
end
--
-- Remove pcall success and coroutine success bools
--
table.remove( ret, 1 )
table.remove( ret, 1 )
--
-- Transform our ret values in to strings
--
for k, v in ipairs( ret ) do
ret[ k ] = tostring( v )
end
local out = table.concat( ret, "\t" )
if not silent_error and code:gsub("[\r\n]$", ""):gsub("^['\"]", ""):gsub("['\"]$", "") == out then
goto start
end
io.write( out )
--
-- repl
---
goto start
|
require "superstring"
ENV = require "env"
::start::
--
-- Indicate that we are ready to receive a packet
--
io.write( "\n\x1A" ); io.flush()
--
-- Read until EOF
--
local code = io.read "a"
--
-- Only display errors if the code starts with ">"
--
local silent_error = true
if code:sub( 1, 1 ) == ">" then
code = code:sub( 2 )
silent_error = false
end
--
-- Try our code with "return " prepended first
--
local f, err = load( "return " .. code, "eval", "t", ENV )
if err then
f, err = load( code, "eval", "t", ENV )
end
--
-- We've been passed invalid Lua
--
if err then
if not silent_error then
io.write( err )
end
goto start
end
local thread = coroutine.create( f )
local start = os.clock()
--
-- Install our execution time limiter
--
debug.sethook( thread, function()
if os.clock() > start + 0.5 then
error( "maximum execution time exceeded", 2 )
end
end, "", 128 )
--
-- Try to run our function
--
local ret = { pcall( coroutine.resume, thread ) }
local success, err = ret[ 2 ], ret[ 3 ]
if not success then
if not silent_error then
io.write( err )
end
goto start
end
--
-- Remove pcall success and coroutine success bools
--
table.remove( ret, 1 )
table.remove( ret, 1 )
--
-- Transform our ret values in to strings
--
for k, v in ipairs( ret ) do
local success, ret[ k ] = pcall( tostring, v )
if not success then
if not silent_error then
io.write( ret[ k ] )
end
goto start
end
end
local out = table.concat( ret, "\t" )
if not silent_error and code:gsub("[\r\n]$", ""):gsub("^['\"]", ""):gsub("['\"]$", "") == out then
goto start
end
io.write( out )
--
-- repl
---
goto start
|
Fix for __tostring metamethods that error
|
Fix for __tostring metamethods that error
|
Lua
|
cc0-1.0
|
SwadicalRag/hash.js,mcd1992/hash.js,ModMountain/hash.js,meepdarknessmeep/hash.js
|
72c4b938d61699b28182e24ab92a2fb1c43b556c
|
hostinfo/cve.lua
|
hostinfo/cve.lua
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local Transform = require('stream').Transform
local misc = require('./misc')
--------------------------------------------------------------------------------------------------------------------
local Reader = Transform:extend()
function Reader:initialize()
Transform.initialize(self, {objectMode = true})
end
function Reader:_transform(line, cb)
local cvestart, _ = line:find('CVE-')
local cvestr = line:sub(cvestart, cvestart+12)
-- we want unique cves only
self:push(cvestr)
cb()
end
--------------------------------------------------------------------------------------------------------------------
--[[ Check CVE fixes ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:_run(callback)
local errTable, outTable = {}, {}
local deb = {cmd = '/bin/sh', args = {'-c', 'zcat /usr/share/doc/*/changelog.Debian.gz | grep CVE-'} }
local rhel = {cmd = '/bin/sh', args = {'-c', 'rpm -qa --changelog | grep CVE-'} }
local options = {
ubuntu = deb,
debian = deb,
rhel = rhel,
centos = rhel,
default = nil
}
local spawnConfig = misc.getInfoByVendor(options)
if not spawnConfig.cmd then
self._error = string.format("Couldn't decipher linux distro for check %s", self:getType())
return callback()
end
local cmd, args = spawnConfig.cmd, spawnConfig.args
local function finalCb()
-- Sort the cves
local tempTable = {}
for key, _ in pairs(outTable) do
table.insert(tempTable, key)
end
table.sort(tempTable)
self:_pushParams(errTable, tempTable)
return callback()
end
local reader = Reader:new()
local child = misc.run(cmd, args)
child:pipe(reader)
reader:on('data', function(data)
outTable[data] = 1
end)
reader:on('error', function(data)
table.insert(errTable, data)
end)
reader:once('end', finalCb)
end
function Info:getPlatforms()
return {'linux'}
end
function Info:getType()
return 'CVE'
end
exports.Info = Info
exports.Reader = Reader
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local Transform = require('stream').Transform
local misc = require('./misc')
--------------------------------------------------------------------------------------------------------------------
local Reader = Transform:extend()
function Reader:initialize()
Transform.initialize(self, {objectMode = true})
end
function Reader:_transform(line, cb)
local cvestart, _ = line:find('CVE-')
local cvestr = line:sub(cvestart, cvestart+12)
-- we want unique cves only
self:push(cvestr)
cb()
end
--------------------------------------------------------------------------------------------------------------------
--[[ Check CVE fixes ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:_run(callback)
local errTable, outTable = {}, {}
local deb = {cmd = '/bin/sh', args = {'-c', 'zcat /usr/share/doc/*/changelog.Debian.gz | grep CVE-'} }
local rhel = {cmd = '/bin/sh', args = {'-c', 'rpm -qa --changelog | grep CVE-'} }
local options = {
ubuntu = deb,
debian = deb,
rhel = rhel,
centos = rhel,
default = nil
}
local spawnConfig = misc.getInfoByVendor(options)
if not spawnConfig.cmd then
self._error = string.format("Couldn't decipher linux distro for check %s", self:getType())
return callback()
end
local cmd, args = spawnConfig.cmd, spawnConfig.args
local function finalCb()
-- Sort the cves
local tempTable = {}
for key, _ in pairs(outTable) do
table.insert(tempTable, key)
end
table.sort(tempTable)
-- Assign a key to the array of CVEs before we send them back to prevent serialization problems
-- i.e. ["CVE-2015-24", "CVE-2015-12"] becomes ["1": "C", "2":"V"...] otherwise
self:_pushParams(errTable, {['patched_CVE'] = tempTable})
return callback()
end
local reader = Reader:new()
local child = misc.run(cmd, args)
child:pipe(reader)
reader:on('data', function(data)
outTable[data] = 1
end)
reader:on('error', function(data)
table.insert(errTable, data)
end)
reader:once('end', finalCb)
end
function Info:getPlatforms()
return {'linux'}
end
function Info:getType()
return 'CVE'
end
exports.Info = Info
exports.Reader = Reader
|
fix(hostinfo/cve): Fix for cve serialization problem. Closes #905
|
fix(hostinfo/cve): Fix for cve serialization problem. Closes #905
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
925e15c3dd9f36356ecede1ae72e5f3fa7e8ac63
|
examples/l2-poisson-load-latency.lua
|
examples/l2-poisson-load-latency.lua
|
local mg = require "moongen"
local memory = require "memory"
local ts = require "timestamping"
local device = require "device"
local filter = require "filter"
local stats = require "stats"
local timer = require "timer"
local histogram = require "histogram"
local log = require "log"
local PKT_SIZE = 60
function configure(parser)
parser:description("Generates traffic based on a poisson process with CRC-based rate control.")
parser:argument("txDev", "Device to transmit from."):args(1):convert(tonumber)
parser:argument("rxDev", "Device to receive from."):args(1):convert(tonumber)
parser:option("-r --rate", "Transmit rate in Mpps."):args(1):default(2)
end
function master(args)
local txDev = device.config({port = args.txDev, txQueues = 2, rxQueues = 2})
local rxDev = device.config({port = args.rxDev, txQueues = 2, rxQueues = 2})
device.waitForLinks()
mg.startTask("loadSlave", txDev, rxDev, txDev:getTxQueue(0), args.rate, PKT_SIZE)
mg.startTask("timerSlave", txDev:getTxQueue(1), rxDev:getRxQueue(1), PKT_SIZE)
mg.waitForTasks()
end
function loadSlave(dev, rxDev, queue, rate, size)
local mem = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethType = 0x1234
}
end)
rxDev:l2Filter(0x1234, filter.DROP)
local bufs = mem:bufArray()
local rxStats = stats:newDevRxCounter(rxDev, "plain")
local txStats = stats:newManualTxCounter(dev, "plain")
while mg.running() do
bufs:alloc(size)
for _, buf in ipairs(bufs) do
-- this script uses Mpps instead of Mbit (like the other scripts)
buf:setDelay(poissonDelay(10^10 / 8 / (rate * 10^6) - size - 24))
--buf:setRate(rate)
end
txStats:updateWithSize(queue:sendWithDelay(bufs), size)
rxStats:update()
--txStats:update()
end
rxStats:finalize()
txStats:finalize()
end
function timerSlave(txQueue, rxQueue, size)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = histogram:new()
-- wait for a second to give the other task a chance to start
mg.sleepMillis(1000)
local rateLimiter = timer:new(0.001)
while mg.running() do
rateLimiter:reset()
hist:update(timestamper:measureLatency(size))
rateLimiter:busyWait()
end
hist:print()
hist:save("histogram.csv")
end
|
local mg = require "moongen"
local memory = require "memory"
local ts = require "timestamping"
local device = require "device"
local stats = require "stats"
local timer = require "timer"
local histogram = require "histogram"
local log = require "log"
local PKT_SIZE = 60
function configure(parser)
parser:description("Generates traffic based on a poisson process with CRC-based rate control.")
parser:argument("txDev", "Device to transmit from."):args(1):convert(tonumber)
parser:argument("rxDev", "Device to receive from."):args(1):convert(tonumber)
parser:option("-r --rate", "Transmit rate in Mpps."):args(1):default(2)
end
function master(args)
local txDev = device.config({port = args.txDev, txQueues = 2, rxQueues = 2})
local rxDev = device.config({port = args.rxDev, txQueues = 2, rxQueues = 2})
device.waitForLinks()
mg.startTask("loadSlave", txDev, rxDev, txDev:getTxQueue(0), args.rate, PKT_SIZE)
mg.startTask("timerSlave", txDev:getTxQueue(1), rxDev:getRxQueue(1), PKT_SIZE)
mg.waitForTasks()
end
function loadSlave(dev, rxDev, queue, rate, size)
local mem = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethType = 0x1234
}
end)
local bufs = mem:bufArray()
local rxStats = stats:newDevRxCounter(rxDev, "plain")
local txStats = stats:newManualTxCounter(dev, "plain")
while mg.running() do
bufs:alloc(size)
for _, buf in ipairs(bufs) do
-- this script uses Mpps instead of Mbit (like the other scripts)
buf:setDelay(poissonDelay(10^10 / 8 / (rate * 10^6) - size - 24))
--buf:setRate(rate)
end
txStats:updateWithSize(queue:sendWithDelay(bufs), size)
rxStats:update()
--txStats:update()
end
rxStats:finalize()
txStats:finalize()
end
function timerSlave(txQueue, rxQueue, size)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = histogram:new()
-- wait for a second to give the other task a chance to start
mg.sleepMillis(1000)
local rateLimiter = timer:new(0.001)
while mg.running() do
rateLimiter:reset()
hist:update(timestamper:measureLatency(size))
rateLimiter:busyWait()
end
hist:print()
hist:save("histogram.csv")
end
|
examples: remove deprecated filter API call
|
examples: remove deprecated filter API call
fixes #178
|
Lua
|
mit
|
gallenmu/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,emmericp/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen
|
a9a19ba5aef882d8d464fa3b14f8c5730a54c018
|
controller/utils.lua
|
controller/utils.lua
|
-- some utility methods for the space probe
function log(message)
print(os.date() .. " " .. tostring(message))
end
function round(n)
return math.floor(n+0.5)
end
-- translate a raw value through a lookup table of { {rawval, translation} }
-- interpolating between closest values
function translate(rawval, lookup_table)
low_p = { 0, 0 }
high_p = { 100000000, 0 } -- hacky big number here(!)
for idx,kv in ipairs(lookup_table) do -- kv is a table of {rawval, translation} here
k = kv[1]
if rawval == k then return kv[2] end -- shortcut exact matches (helps with zero)
if k < rawval and k > low_p[1] then low_p = kv end
if k > rawval and k < high_p[1] then high_p = kv end
end
-- now rawval is bounded between low_p[1] and high_p[1], with equivalent lookup values
return (rawval - low_p[1]) * (high_p[2] - low_p[2]) / (high_p[1] - low_p[1]) + low_p[2]
end
|
-- some utility methods for the space probe
function log(message)
print(os.date() .. " " .. tostring(message))
end
function round(n)
return math.floor(n+0.5)
end
function finite(x)
local inf = 1/0
return x and (x == x) and (x ~= inf ) and (x ~= -inf)
end
-- translate a raw value through a lookup table of { {rawval, translation} }
-- interpolating between closest values
function translate(rawval, lookup_table)
local low_p = { 0, 0 }
local high_p = { 100000000, 0 } -- hacky big number here(!)
for idx,kv in ipairs(lookup_table) do -- kv is a table of {rawval, translation} here
local k = kv[1]
if rawval == k then return kv[2] end -- shortcut exact matches (helps with zero)
if k < rawval and k > low_p[1] then low_p = kv end
if k > rawval and k < high_p[1] then high_p = kv end
end
-- now rawval is bounded between low_p[1] and high_p[1], with equivalent lookup values
local res = (rawval - low_p[1]) * (high_p[2] - low_p[2]) / (high_p[1] - low_p[1]) + low_p[2]
if not finite(res) then res = 0 end
return res
end
|
Fix bug where translate(-1, table) gave -inf result (now gives 0)
|
Fix bug where translate(-1, table) gave -inf result (now gives 0)
|
Lua
|
mit
|
makehackvoid/MHV-Space-Probe
|
78d2d6a5bc86c3cdf793147d144beab3116069d8
|
packages/pdf.lua
|
packages/pdf.lua
|
if SILE.outputter ~= SILE.outputters.libtexpdf then
SU.error("pdf package requires libtexpdf backend")
end
local pdf = require("justenoughlibtexpdf")
SILE.registerCommand("pdf:destination", function (options, content)
local name = SU.required(options, "name", "pdf:bookmark")
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
pdf.destination(name, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY)
end
})
end)
SILE.registerCommand("pdf:bookmark", function (options, content)
local dest = SU.required(options, "dest", "pdf:bookmark")
local title = SU.required(options, "title", "pdf:bookmark")
local level = options.level or 1
-- Added UTF8 to UTF16-BE conversion
-- For annotations and bookmarks, text strings must be encoded using
-- either PDFDocEncoding or UTF16-BE with a leading byte-order marker.
-- As PDFDocEncoding supports only limited character repertoire for
-- European languages, we use UTF-16BE for internationalization.
local ustr = SU.utf8_to_utf16be_hexencoded(title)
SILE.typesetter:pushHbox({
value = nil, height = 0, width = 0, depth = 0,
outputYourself = function ()
local d = "<</Title<" .. ustr .. ">/A<</S/GoTo/D(" .. dest .. ")>>>>"
pdf.bookmark(d, level)
end
})
end)
if SILE.Commands.tocentry then
SILE.scratch.pdf = { dests = {}, dc = 1 }
local oldtoc = SILE.Commands.tocentry
SILE.Commands.tocentry = function (options, content)
SILE.call("pdf:destination", { name = "dest" .. SILE.scratch.pdf.dc } )
local title = SU.contentToString(content)
SILE.call("pdf:bookmark", { title = title, dest = "dest" .. SILE.scratch.pdf.dc, level = options.level })
oldtoc(options, content)
SILE.scratch.pdf.dc = SILE.scratch.pdf.dc + 1
end
end
SILE.registerCommand("pdf:literal", function (options, content)
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
pdf.add_content(content[1])
end
})
end)
SILE.registerCommand("pdf:link", function (options, content)
local dest = SU.required(options, "dest", "pdf:link")
local target = options.external and "/Type/Action/S/URI/URI" or "/S/GoTo/D"
local llx, lly
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
llx = typesetter.frame.state.cursorX
lly = SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY
pdf.begin_annotation()
end
})
local hbox = SILE.Commands["hbox"]({}, content) -- hack
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
local d = "<</Type/Annot/Subtype/Link/C [ 1 0 0 ]/A<<" .. target .. "(" .. dest .. ")>>>>"
pdf.end_annotation(d, llx, lly, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] -typesetter.frame.state.cursorY + hbox.height)
end
})
end)
return { documentation = [[\begin{document}
The \code{pdf} package enables (basic) support for PDF links and table-of-contents
entries. It provides the three commands \command{\\pdf:destination}, \command{\\pdf:link}
and \command{\\pdf:bookmark}.
The \command{\\pdf:destination} parameter creates a link target; it expects a
parameter called \code{name} to uniquely identify the target. To create a link to
that location in the document, use \code{\\pdf:link[dest=\goodbreak{}name]\{link content\}}.
If the \code{pdf} package is loaded after the \code{tableofcontents} package (e.g.
in a document with the \code{book} class), then a PDF document outline will be generated.
\end{document}]] }
|
if SILE.outputter ~= SILE.outputters.libtexpdf then
SU.error("pdf package requires libtexpdf backend")
end
local pdf = require("justenoughlibtexpdf")
SILE.registerCommand("pdf:destination", function (options, content)
local name = SU.required(options, "name", "pdf:bookmark")
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
pdf.destination(name, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY)
end
})
end)
SILE.registerCommand("pdf:bookmark", function (options, content)
local dest = SU.required(options, "dest", "pdf:bookmark")
local title = SU.required(options, "title", "pdf:bookmark")
local level = options.level or 1
-- Added UTF8 to UTF16-BE conversion
-- For annotations and bookmarks, text strings must be encoded using
-- either PDFDocEncoding or UTF16-BE with a leading byte-order marker.
-- As PDFDocEncoding supports only limited character repertoire for
-- European languages, we use UTF-16BE for internationalization.
local ustr = SU.utf8_to_utf16be_hexencoded(title)
SILE.typesetter:pushHbox({
value = nil, height = 0, width = 0, depth = 0,
outputYourself = function ()
local d = "<</Title<" .. ustr .. ">/A<</S/GoTo/D(" .. dest .. ")>>>>"
SILE.outputters.libtexpdf._init()
pdf.bookmark(d, level)
end
})
end)
if SILE.Commands.tocentry then
SILE.scratch.pdf = { dests = {}, dc = 1 }
local oldtoc = SILE.Commands.tocentry
SILE.Commands.tocentry = function (options, content)
SILE.call("pdf:destination", { name = "dest" .. SILE.scratch.pdf.dc } )
local title = SU.contentToString(content)
SILE.call("pdf:bookmark", { title = title, dest = "dest" .. SILE.scratch.pdf.dc, level = options.level })
oldtoc(options, content)
SILE.scratch.pdf.dc = SILE.scratch.pdf.dc + 1
end
end
SILE.registerCommand("pdf:literal", function (options, content)
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
SILE.outputters.libtexpdf._init()
pdf.add_content(content[1])
end
})
end)
SILE.registerCommand("pdf:link", function (options, content)
local dest = SU.required(options, "dest", "pdf:link")
local target = options.external and "/Type/Action/S/URI/URI" or "/S/GoTo/D"
local llx, lly
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
llx = typesetter.frame.state.cursorX
lly = SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY
SILE.outputters.libtexpdf._init()
pdf.begin_annotation()
end
})
local hbox = SILE.Commands["hbox"]({}, content) -- hack
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
local d = "<</Type/Annot/Subtype/Link/C [ 1 0 0 ]/A<<" .. target .. "(" .. dest .. ")>>>>"
pdf.end_annotation(d, llx, lly, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] -typesetter.frame.state.cursorY + hbox.height)
end
})
end)
return { documentation = [[\begin{document}
The \code{pdf} package enables (basic) support for PDF links and table-of-contents
entries. It provides the three commands \command{\\pdf:destination}, \command{\\pdf:link}
and \command{\\pdf:bookmark}.
The \command{\\pdf:destination} parameter creates a link target; it expects a
parameter called \code{name} to uniquely identify the target. To create a link to
that location in the document, use \code{\\pdf:link[dest=\goodbreak{}name]\{link content\}}.
If the \code{pdf} package is loaded after the \code{tableofcontents} package (e.g.
in a document with the \code{book} class), then a PDF document outline will be generated.
\end{document}]] }
|
Ensure PDF device is available before calling PDF-specific commands. Fixes #556.
|
Ensure PDF device is available before calling PDF-specific commands. Fixes #556.
|
Lua
|
mit
|
simoncozens/sile,alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile
|
a19e87b53f32cdd1e096266d49b35f6a6576f589
|
swig/ft/hello_ft.lua
|
swig/ft/hello_ft.lua
|
local ft = require("swig_freetype")
local hb = require("swig_hb")
local hb_ft = require("swig_hb_ft")
local hb_glib = require("swig_hb_glib")
local cairo = require("swig_cairo")
local cairo_xcb = require("swig_cairo_xcb")
local cairo_ft = require("swig_cairo_ft")
local xcb = require("swig_xcb")
--for k,v in pairs(ft) do
--print(string.format("%s = %s", k, v))
--local mt = getmetatable(v)
--if (mt) then
--for x,y in pairs(mt) do
--print(string.format(" %s = %s", x, y))
--end
--end
--end
local mt = getmetatable(ft.FT_FaceRec)
mt[".instance"]["__gc"] = function(_) print("GC!") end
local code,ft_library = ft.FT_Init_FreeType()
local ptSize = 20.0;
local device_hdpi = 100;
local device_vdpi = 100;
local width = 800;
local height = 600;
local texts = {
en = {
text = "This is some english text",
font = "fonts/DejaVuSerif.ttf",
direction = hb.HB_DIRECTION_LTR,
script = hb.HB_SCRIPT_LATIN
},
ar = {
text = "هذه هي بعض النصوص العربي",
font = "fonts/amiri-0.104/amiri-regular.ttf",
direction = hb.HB_DIRECTION_RTL,
script = hb.HB_SCRIPT_ARABIC
},
ch = {
text = "這是一些中文",
font = "fonts/fireflysung-1.3.0/fireflysung.ttf",
direction = hb.HB_DIRECTION_LTR,
script = hb.HB_SCRIPT_HAN
}
}
function loadFonts(spec)
local code,ft_face = ft.FT_New_Face(ft_library, spec.font, 0)
ft.FT_Set_Char_Size(ft_face, 0, ptSize*64.0, device_hdpi, device_vdpi )
local hb_ft_font = hb_ft.hb_ft_font_create_referenced(ft_face)
local hb_ft_face = hb_ft.hb_ft_face_create_referenced(ft_face)
local cairo_ft_face = cairo_ft.cairo_ft_font_face_create_for_ft_face(ft_face, 0)
spec.ft_face = ft_face
spec.hb_ft_font = hb_ft_font
spec.hb_ft_face = hb_ft_face
spec.cario_ft_face = cario_ft_face
end
function createBuffer(ln, spec)
local buf = hb.hb_buffer_create()
--getmetatable(buf)["__gc"] = function(self) hb.hb_buffer_destroy(self) end
hb.hb_buffer_set_unicode_funcs(buf, hb_glib.hb_glib_get_unicode_funcs())
hb.hb_buffer_set_direction(buf, spec.direction);
hb.hb_buffer_set_script(buf, spec.script)
hb.hb_buffer_set_language(buf, hb.hb_language_from_string(ln, #ln))
return buf
end
function render(ln, spec, x, y)
print(string.format("%s -> %i/%i", ln, x, y))
print(spec.text)
local buf = createBuffer(ln, spec)
hb.hb_buffer_add_utf8(buf, spec.text, #(spec.text), 0, #(spec.text))
hb.hb_shape(spec.hb_ft_font, buf, nil, 0);
local glyph_infos, glyph_count = hb.hb_buffer_get_glyph_infos(buf);
local glyph_positions, _ = hb.hb_buffer_get_glyph_positions(buf);
local string_width_in_pixels = 0
for i = 0, (glyph_count-1) do
local position = hb.get_glyph_position(glyph_positions, i)
string_width_in_pixels = string_width_in_pixels + ((position.x_advance)//64);
end
if (ln == "en") then x = 20 end
if (ln == "ar") then x = width - string_width_in_pixels - 20 end
if (ln == "ch") then x = width/2 - string_width_in_pixels/2 end
local cairo_glyphs = cairo.new_glyphs(glyph_count)
for i = 0, (glyph_count-1) do
local cairo_glyph = cairo.cairo_glyph_t()
local position = hb.get_glyph_position(glyph_positions, i)
local info = hb.get_glyph_info(glyph_infos, i)
cairo_glyph.index = info.codepoint
cairo_glyph.x = x + ((position.x_offset)//64)
cairo_glyph.y = y + ((position.y_offset)//64)
x = x + ((position.x_advance)//64)
y = y + ((position.y_advance)//64)
cairo.glyphs_setitem(cairo_glyphs, i, cairo_glyph)
end
hb.hb_buffer_destroy(buf)
getmetatable(cairo_glyphs)["__len"] = function(self) return glyph_count end
return cairo_glyphs
end
function renderToCairo(cr, surface, ln, spec, x, y)
local glyphs = render(ln, spec, x, y)
cairo.cairo_set_font_face(cr, spec.cairo_ft_face);
cairo.cairo_show_glyphs(cr, glyphs, #glyphs);
cairo.cairo_surface_flush(surface)
end
local conn = xcb.xcb_connect(nil, 0)
local screen = xcb.xcb_setup_roots_iterator(xcb.xcb_get_setup(conn)).data
local wid = xcb.xcb_generate_id(conn)
local mask = xcb.XCB_CW_BACK_PIXEL | xcb.XCB_CW_EVENT_MASK
local values = xcb.new_values(2)
xcb.values_setitem(values, 0, screen.black_pixel)
xcb.values_setitem(values, 1, xcb.XCB_EVENT_MASK_EXPOSURE | xcb.XCB_EVENT_MASK_KEY_PRESS)
xcb.xcb_create_window (conn, xcb.XCB_COPY_FROM_PARENT,
wid,
screen.root,
20, 20,
width, height,
10,
xcb.XCB_WINDOW_CLASS_INPUT_OUTPUT,
screen.root_visual,
mask, values)
xcb.xcb_map_window(conn, wid)
xcb.xcb_flush(conn)
local visual = xcb.find_visual(conn, screen.root_visual)
local surface = cairo_xcb.cairo_xcb_surface_create(conn, wid, visual, width, height)
local cr = cairo.cairo_create(surface)
xcb.xcb_flush(conn)
for _,spec in pairs(texts) do
loadFonts(spec)
end
cairo.cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 1.0);
cairo.cairo_set_font_size(cr, ptSize);
local e = xcb.xcb_wait_for_event(conn)
while (e) do
local response_type = e.response_type
if (response_type == xcb.XCB_EXPOSE) then
local x = 20
local y = 50
renderToCairo(cr, surface, "en", texts.en, x, y)
y = y + math.tointeger(ptSize * 2)
renderToCairo(cr, surface, "ar", texts.ar, x, y)
y = y + math.tointeger(ptSize * 2)
renderToCairo(cr, surface, "ch", texts.ch, x, y)
--cairo.cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 1.0);
--cairo.cairo_set_font_face(cr, cairo_ft_face);
--cairo.cairo_set_font_size(cr, ptSize);
--cairo.cairo_show_glyphs(cr, cairo_glyphs, glyph_count);
--cairo.cairo_surface_flush(surface)
xcb.xcb_flush(conn)
elseif (response_type == xcb.XCB_KEY_PRESS) then
break
end
e = xcb.xcb_wait_for_event(conn)
end
xcb.xcb_disconnect(conn)
for _,spec in pairs(texts) do
cairo.cairo_font_face_destroy(spec.cairo_ft_face)
hb.hb_font_destroy(spec.hb_ft_font)
hb.hb_face_destroy(spec.hb_ft_face)
end
ft.FT_Done_FreeType(ft_library)
|
local ft = require("swig_freetype")
local hb = require("swig_hb")
local hb_ft = require("swig_hb_ft")
local hb_glib = require("swig_hb_glib")
local cairo = require("swig_cairo")
local cairo_xcb = require("swig_cairo_xcb")
local cairo_ft = require("swig_cairo_ft")
local xcb = require("swig_xcb")
--for k,v in pairs(ft) do
--print(string.format("%s = %s", k, v))
--local mt = getmetatable(v)
--if (mt) then
--for x,y in pairs(mt) do
--print(string.format(" %s = %s", x, y))
--end
--end
--end
local mt = getmetatable(ft.FT_FaceRec)
mt[".instance"]["__gc"] = function(_) print("GC!") end
local code,ft_library = ft.FT_Init_FreeType()
local ptSize = 20.0;
local device_hdpi = 100;
local device_vdpi = 100;
local width = 500;
local height = 500;
local texts = {
en = {
text = "This is some english text",
font = "fonts/DejaVuSerif.ttf",
direction = hb.HB_DIRECTION_LTR,
script = hb.HB_SCRIPT_LATIN
},
ar = {
text = "هذه هي بعض النصوص العربي",
font = "fonts/amiri-0.104/amiri-regular.ttf",
direction = hb.HB_DIRECTION_RTL,
script = hb.HB_SCRIPT_ARABIC
},
ch = {
text = "這是一些中文",
font = "fonts/fireflysung-1.3.0/fireflysung.ttf",
direction = hb.HB_DIRECTION_TTB,
script = hb.HB_SCRIPT_HAN
}
}
function loadFonts(spec)
local code,ft_face = ft.FT_New_Face(ft_library, spec.font, 0)
ft.FT_Set_Char_Size(ft_face, 0, ptSize*64.0, device_hdpi, device_vdpi )
local hb_ft_font = hb_ft.hb_ft_font_create_referenced(ft_face)
local hb_ft_face = hb_ft.hb_ft_face_create_referenced(ft_face)
local cairo_ft_face = cairo_ft.cairo_ft_font_face_create_for_ft_face(ft_face, 0)
spec.ft_face = ft_face
spec.hb_ft_font = hb_ft_font
spec.hb_ft_face = hb_ft_face
spec.cario_ft_face = cario_ft_face
end
function createBuffer(ln, spec)
local buf = hb.hb_buffer_create()
--getmetatable(buf)["__gc"] = function(self) hb.hb_buffer_destroy(self) end
hb.hb_buffer_set_unicode_funcs(buf, hb_glib.hb_glib_get_unicode_funcs())
hb.hb_buffer_set_direction(buf, spec.direction);
hb.hb_buffer_set_script(buf, spec.script)
hb.hb_buffer_set_language(buf, hb.hb_language_from_string(ln, #ln))
return buf
end
function render(ln, spec, x, y)
print(spec.text)
local buf = createBuffer(ln, spec)
hb.hb_buffer_add_utf8(buf, spec.text, #(spec.text), 0, #(spec.text))
hb.hb_shape(spec.hb_ft_font, buf, nil, 0);
local glyph_infos, glyph_count = hb.hb_buffer_get_glyph_infos(buf);
local glyph_positions, _ = hb.hb_buffer_get_glyph_positions(buf);
local string_width_in_pixels = 0
for i = 0, (glyph_count-1) do
local position = hb.get_glyph_position(glyph_positions, i)
string_width_in_pixels = string_width_in_pixels + ((position.x_advance)//64);
end
if (ln == "en") then x = 20 end
if (ln == "ar") then x = width - string_width_in_pixels - 20 end
if (ln == "ch") then x = width//2 - string_width_in_pixels/2 end
print(string.format("%s -> %i/%i => %i", ln, x, y, string_width_in_pixels))
local cairo_glyphs = cairo.new_glyphs(glyph_count)
for i = 0, (glyph_count-1) do
local cairo_glyph = cairo.cairo_glyph_t()
local position = hb.get_glyph_position(glyph_positions, i)
local info = hb.get_glyph_info(glyph_infos, i)
cairo_glyph.index = info.codepoint
cairo_glyph.x = x + ((position.x_offset)//64)
cairo_glyph.y = y + ((position.y_offset)//64)
x = x + ((position.x_advance)//64)
y = y - ((position.y_advance)//64)
cairo.glyphs_setitem(cairo_glyphs, i, cairo_glyph)
--print(string.format(" %s -> %i/%i", ln, x, y))
end
hb.hb_buffer_destroy(buf)
getmetatable(cairo_glyphs)["__len"] = function(self) return glyph_count end
return cairo_glyphs
end
function renderToCairo(cr, surface, ln, spec, x, y)
local glyphs = render(ln, spec, x, y)
cairo.cairo_set_font_face(cr, spec.cairo_ft_face);
cairo.cairo_show_glyphs(cr, glyphs, #glyphs);
cairo.cairo_surface_flush(surface)
end
local conn = xcb.xcb_connect(nil, 0)
local screen = xcb.xcb_setup_roots_iterator(xcb.xcb_get_setup(conn)).data
local wid = xcb.xcb_generate_id(conn)
local mask = xcb.XCB_CW_BACK_PIXEL | xcb.XCB_CW_EVENT_MASK
local values = xcb.new_values(2)
xcb.values_setitem(values, 0, screen.black_pixel)
xcb.values_setitem(values, 1, xcb.XCB_EVENT_MASK_EXPOSURE | xcb.XCB_EVENT_MASK_KEY_PRESS)
xcb.xcb_create_window (conn, xcb.XCB_COPY_FROM_PARENT,
wid,
screen.root,
20, 20,
width, height,
10,
xcb.XCB_WINDOW_CLASS_INPUT_OUTPUT,
screen.root_visual,
mask, values)
xcb.xcb_map_window(conn, wid)
xcb.xcb_flush(conn)
local visual = xcb.find_visual(conn, screen.root_visual)
local surface = cairo_xcb.cairo_xcb_surface_create(conn, wid, visual, width, height)
local cr = cairo.cairo_create(surface)
xcb.xcb_flush(conn)
for _,spec in pairs(texts) do
loadFonts(spec)
end
cairo.cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 1.0);
cairo.cairo_set_font_size(cr, ptSize);
local e = xcb.xcb_wait_for_event(conn)
while (e) do
local response_type = e.response_type
if (response_type == xcb.XCB_EXPOSE) then
local x = 20
local y = 50
renderToCairo(cr, surface, "en", texts.en, x, y)
y = y + math.tointeger(ptSize * 2)
renderToCairo(cr, surface, "ar", texts.ar, x, y)
y = y + math.tointeger(ptSize * 2)
renderToCairo(cr, surface, "ch", texts.ch, x, y)
xcb.xcb_flush(conn)
elseif (response_type == xcb.XCB_KEY_PRESS) then
break
end
e = xcb.xcb_wait_for_event(conn)
end
xcb.xcb_disconnect(conn)
for _,spec in pairs(texts) do
cairo.cairo_font_face_destroy(spec.cairo_ft_face)
hb.hb_font_destroy(spec.hb_ft_font)
hb.hb_face_destroy(spec.hb_ft_face)
end
ft.FT_Done_FreeType(ft_library)
|
fixed y advance, but non-english still not displaying
|
fixed y advance, but non-english still not displaying
|
Lua
|
mit
|
juanchanco/lua-xcb,juanchanco/lua-xcb,juanchanco/lua-xcb
|
14ea0ed08072f0720a53a809610535381ad25758
|
main.lua
|
main.lua
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 Jason Lynch <jason@calindora.com>
--
-- 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.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Configuration
--------------------------------------------------------------------------------
-- Specify a number to do a specific run. Set this value to nil to do random runs.
SEED = nil
-- Enable/Disable LiveSplit integration (requires luasocket and LiveSplit)
LIVESPLIT = false
-- Automatically create save states at the beginning of each battle.
SAVESTATE = false
--------------------------------------------------------------------------------
-- Setup
--------------------------------------------------------------------------------
local battle = require "ai.battle"
local bridge = require "util.bridge"
local dialog = require "util.dialog"
local input = require "util.input"
local log = require "util.log"
local memory = require "util.memory"
local menu = require "action.menu"
local sequence = require "ai.sequence"
local walk = require "action.walk"
FULL_RUN = emu.framecount() == 1
--------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------
local function _set_seed()
local seed = SEED
if not seed then
math.randomseed(os.time())
math.random()
math.random()
math.random()
seed = math.random(0, 2147483646)
end
math.randomseed(seed)
math.random()
math.random()
math.random()
return seed
end
local function _reset()
log.reset()
log.log("Edge Final Fantasy IV Speed Run Bot")
log.log("-----------------------------------")
if FULL_RUN then
log.log("Beginning Full Run")
log.log(string.format("RNG Seed: %d", _set_seed()))
else
log.log("Beginning Test Mode")
end
bridge.reset()
menu.reset()
walk.reset()
dialog.reset()
battle.reset()
sequence.reset()
end
--------------------------------------------------------------------------------
-- Initialization
--------------------------------------------------------------------------------
_reset()
--------------------------------------------------------------------------------
-- Main Loop
--------------------------------------------------------------------------------
while true do
dialog.cycle()
if sequence.is_active() then
local result = battle.cycle() or sequence.cycle()
end
input.cycle()
emu.frameadvance()
end
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 Jason Lynch <jason@calindora.com>
--
-- 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.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Configuration
--------------------------------------------------------------------------------
-- Specify a number to do a specific run. Set this value to nil to do random runs.
SEED = nil
-- Enable/Disable LiveSplit integration (requires luasocket and LiveSplit)
LIVESPLIT = false
-- Automatically create save states at the beginning of each battle.
SAVESTATE = false
--------------------------------------------------------------------------------
-- Setup
--------------------------------------------------------------------------------
local battle = require "ai.battle"
local bridge = require "util.bridge"
local dialog = require "util.dialog"
local input = require "util.input"
local log = require "util.log"
local memory = require "util.memory"
local menu = require "action.menu"
local sequence = require "ai.sequence"
local walk = require "action.walk"
FULL_RUN = emu.framecount() == 1
--------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------
local function _set_seed()
local seed = SEED
if not seed then
math.randomseed(os.time())
math.random()
math.random()
math.random()
seed = math.random(0, 2147483646)
end
math.randomseed(seed)
math.random()
math.random()
math.random()
return seed
end
local function _reset()
SEED = _set_seed()
log.reset()
log.log("Edge Final Fantasy IV Speed Run Bot")
log.log("-----------------------------------")
if FULL_RUN then
log.log("Beginning Full Run")
log.log(string.format("RNG Seed: %d", SEED))
else
log.log("Beginning Test Mode")
end
bridge.reset()
menu.reset()
walk.reset()
dialog.reset()
battle.reset()
sequence.reset()
end
--------------------------------------------------------------------------------
-- Initialization
--------------------------------------------------------------------------------
_reset()
--------------------------------------------------------------------------------
-- Main Loop
--------------------------------------------------------------------------------
while true do
dialog.cycle()
if sequence.is_active() then
local result = battle.cycle() or sequence.cycle()
end
input.cycle()
emu.frameadvance()
end
|
Fix creating log files for random seeds.
|
Fix creating log files for random seeds.
Signed-off-by: Jason Lynch <68c46a606457643eab92053c1c05574abb26f861@calindora.com>
|
Lua
|
mit
|
aexoden/edge
|
8b3e9a1df0566bb40b750331d174c0d247e6c414
|
share/lua/playlist/appletrailers.lua
|
share/lua/playlist/appletrailers.lua
|
--[[
Translate trailers.apple.com video webpages URLs to the corresponding
movie URL
$Id$
Copyright © 2007 the VideoLAN team
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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "www.apple.com/trailers" )
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
-- Parse function.
function parse()
p = {}
while true
do
line = vlc.readline()
if not line then break end
for path in string.gmatch( line, "http://movies.apple.com/movies/.-%.mov" ) do
path = vlc.strings.decode_uri( path )
path = string.gsub( path, "http://movies", "http://www" )
if string.match( path, "320" ) then
extraname = " (320p)"
elseif string.match( path, "480" ) then
extraname = " (480p)"
elseif string.match( path, "640" ) then
extraname = " (640p)"
elseif string.match( path, "720" ) then
extraname = " (720p)"
elseif string.match( path, "1080" ) then
extraname = " (1080p)"
else
extraname = ""
end
table.insert( p, { path = path; name = title..extraname; description = description; url = vlc.path } )
end
if string.match( line, "<title>" )
then
title = vlc.strings.decode_uri( find( line, "<title>(.-)<" ) )
end
if string.match( line, "<meta name=\"Description\"" )
then
description = vlc.strings.resolve_xml_special_chars( find( line, "name=\"Description\" content=\"(.-)\"" ) )
end
end
return p
end
|
--[[
Translate trailers.apple.com video webpages URLs to the corresponding
movie URL
$Id$
Copyright © 2007 the VideoLAN team
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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "www.apple.com/trailers" )
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
-- Parse function.
function parse()
p = {}
while true
do
line = vlc.readline()
if not line then break end
for path in string.gmatch( line, "http://movies.apple.com/movies/.-%.mov" ) do
path = vlc.strings.decode_uri( path )
if string.match( path, "320" ) then
extraname = " (320p)"
elseif string.match( path, "480" ) then
extraname = " (480p)"
elseif string.match( path, "640" ) then
extraname = " (640p)"
elseif string.match( path, "720" ) then
extraname = " (720p)"
elseif string.match( path, "1080" ) then
extraname = " (1080p)"
else
extraname = ""
end
table.insert( p, { path = path; name = title..extraname; description = description; url = vlc.path; options = ":http-user-agent=\"QuickTime\"" } )
end
if string.match( line, "<title>" )
then
title = vlc.strings.decode_uri( find( line, "<title>(.-)<" ) )
end
if string.match( line, "<meta name=\"Description\"" )
then
description = vlc.strings.resolve_xml_special_chars( find( line, "name=\"Description\" content=\"(.-)\"" ) )
end
end
return p
end
|
appleplaylist.lua: fix apple trailers again, change useragent
|
appleplaylist.lua: fix apple trailers again, change useragent
Seems that they changed just on trailers page, that if useragent doesn't
contain QuickTime, it gives redirect back to trailers. So get stuff from movies
again, but tell useragent to be "QuickTime vlc lua edition".
Really if apple doesn't want vlc to be used as see apple-trailes, they could
atleast ask ;)
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2
|
005f71e5131e568ca3efd96312ff00876b9a2c20
|
src/main/resources/std/coroutine.lua
|
src/main/resources/std/coroutine.lua
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- 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.
coroutine = {}
---
--- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns
--- this new coroutine, an object with type `"thread"`.
---@param f fun():thread
---@return thread
function coroutine.create(f) end
---
--- Returns true when the running coroutine can yield.
---
--- A running coroutine is yieldable if it is not the main thread and it is not
--- inside a non-yieldable C function.
---@return boolean
function coroutine.isyieldable() end
---
--- Starts or continues the execution of coroutine `co`. The first time you
--- resume a coroutine, it starts running its body. The values `val1`, ...
--- are passed as the arguments to the body function. If the coroutine has
--- yielded, `resume` restarts it; the values `val1`, ... are passed as the
--- results from the yield.
---
--- If the coroutine runs without any errors, `resume` returns **true** plus any
--- values passed to `yield` (when the coroutine yields) or any values returned
--- by the body function (when the coroutine terminates). If there is any error,
--- `resume` returns **false** plus the error message.
---@param co thread
---@param optional val1 string
---@return boolean|any
function coroutine.resume(co, val1, ...) end
---
--- Returns the running coroutine plus a boolean, true when the running
--- coroutine is the main one.
---@return thread|boolean
function coroutine.running() end
---
--- Returns the status of coroutine `co`, as a string: "`running`", if the
--- coroutine is running (that is, it called `status`); "`suspended`", if the
--- coroutine is suspended in a call to `yield`, or if it has not started
--- running yet; "`normal`" if the coroutine is active but not running (that
--- is, it has resumed another coroutine); and "`dead`" if the coroutine has
--- finished its body function, or if it has stopped with an error.
---@param co thread
---@return string
function coroutine.status(co) end
---
--- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns
--- a function that resumes the coroutine each time it is called. Any arguments
--- passed to the function behave as the extra arguments to `resume`. Returns
--- the same values returned by `resume`, except the first
--- boolean. In case of error, propagates the error.
---@param f fun():thread
---@return function
function coroutine.wrap(f) end
---
--- Suspends the execution of the calling coroutine. Any arguments to `yield`
--- are passed as extra results to `resume`.
---@return any
function coroutine.yield(...) end
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- 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.
coroutine = {}
---
--- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns
--- this new coroutine, an object with type `"thread"`.
---@param f fun():thread
---@return thread
function coroutine.create(f) end
---
--- Returns true when the running coroutine can yield.
---
--- A running coroutine is yieldable if it is not the main thread and it is not
--- inside a non-yieldable C function.
---@return boolean
function coroutine.isyieldable() end
---
--- Starts or continues the execution of coroutine `co`. The first time you
--- resume a coroutine, it starts running its body. The values `val1`, ...
--- are passed as the arguments to the body function. If the coroutine has
--- yielded, `resume` restarts it; the values `val1`, ... are passed as the
--- results from the yield.
---
--- If the coroutine runs without any errors, `resume` returns **true** plus any
--- values passed to `yield` (when the coroutine yields) or any values returned
--- by the body function (when the coroutine terminates). If there is any error,
--- `resume` returns **false** plus the error message.
---@overload fun(co:thread):boolean|any
---@param co thread
---@param val1 string
---@return thread|any
function coroutine.resume(co, val1, ...) end
---
--- Returns the running coroutine plus a boolean, true when the running
--- coroutine is the main one.
---@return thread|boolean
function coroutine.running() end
---
--- Returns the status of coroutine `co`, as a string: "`running`", if the
--- coroutine is running (that is, it called `status`); "`suspended`", if the
--- coroutine is suspended in a call to `yield`, or if it has not started
--- running yet; "`normal`" if the coroutine is active but not running (that
--- is, it has resumed another coroutine); and "`dead`" if the coroutine has
--- finished its body function, or if it has stopped with an error.
---@param co thread
---@return string
function coroutine.status(co) end
---
--- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns
--- a function that resumes the coroutine each time it is called. Any arguments
--- passed to the function behave as the extra arguments to `resume`. Returns
--- the same values returned by `resume`, except the first
--- boolean. In case of error, propagates the error.
---@param f fun():thread
---@return fun():any
function coroutine.wrap(f) end
---
--- Suspends the execution of the calling coroutine. Any arguments to `yield`
--- are passed as extra results to `resume`.
---@return any
function coroutine.yield(...) end
|
fix optional params
|
fix optional params
|
Lua
|
apache-2.0
|
tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua
|
19ca56c24f450ea090541d29f8db7cb807ca506d
|
src/luarocks/command_line.lua
|
src/luarocks/command_line.lua
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fs = require("luarocks.fs")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at https://github.com/keplerproject/luarocks/issues):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
break
end
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags.ERROR then
die(flags.ERROR.." See --help.")
end
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if flags["extensions"] then
cfg.use_extensions = true
local type_check = require("luarocks.type_check")
type_check.load_extensions()
end
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
cfg.branch = flags["branch"]
end
if flags["tree"] then
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
if not cfg.home_tree then
die("The --local flag is meant for operating in a user's home directory.\n"..
"You are running as a superuser, which is intended for system-wide operation.\n"..
"To force using the superuser's home, use --tree explicitly.")
end
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if not fs.current_dir() or fs.current_dir() == "" then
die("Current directory does not exist. Please run LuaRocks from an existing directory.")
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at luarocks-developers@lists.sourceforge.net).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fs = require("luarocks.fs")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at https://github.com/keplerproject/luarocks/issues):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
break
end
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags.ERROR then
die(flags.ERROR.." See --help.")
end
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if flags["extensions"] then
cfg.use_extensions = true
local type_check = require("luarocks.type_check")
type_check.load_extensions()
end
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
cfg.branch = flags["branch"]
end
if flags["tree"] then
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
if not cfg.home_tree then
die("The --local flag is meant for operating in a user's home directory.\n"..
"You are running as a superuser, which is intended for system-wide operation.\n"..
"To force using the superuser's home, use --tree explicitly.")
end
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if not fs.current_dir() or fs.current_dir() == "" then
die("Current directory does not exist. Please run LuaRocks from an existing directory.")
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at https://github.com/keplerproject/luarocks/issues).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
Actually direct users to the bug tracker
|
Actually direct users to the bug tracker
For some reason 53e0c65 didn't take effect.
|
Lua
|
mit
|
luarocks/luarocks,xpol/luarocks,ignacio/luarocks,aryajur/luarocks,usstwxy/luarocks,coderstudy/luarocks,keplerproject/luarocks,luarocks/luarocks,xpol/luainstaller,coderstudy/luarocks,xpol/luarocks,keplerproject/luarocks,xpol/luavm,xpol/luavm,aryajur/luarocks,ignacio/luarocks,rrthomas/luarocks,starius/luarocks,xpol/luarocks,xpol/luarocks,usstwxy/luarocks,usstwxy/luarocks,keplerproject/luarocks,xpol/luavm,starius/luarocks,tst2005/luarocks,tst2005/luarocks,tst2005/luarocks,starius/luarocks,xpol/luainstaller,xpol/luainstaller,robooo/luarocks,robooo/luarocks,xiaq/luarocks,xpol/luavm,lxbgit/luarocks,tarantool/luarocks,aryajur/luarocks,lxbgit/luarocks,tarantool/luarocks,aryajur/luarocks,xiaq/luarocks,robooo/luarocks,coderstudy/luarocks,lxbgit/luarocks,lxbgit/luarocks,starius/luarocks,xiaq/luarocks,keplerproject/luarocks,rrthomas/luarocks,xpol/luainstaller,tarantool/luarocks,rrthomas/luarocks,luarocks/luarocks,coderstudy/luarocks,tst2005/luarocks,robooo/luarocks,usstwxy/luarocks,ignacio/luarocks,rrthomas/luarocks,xpol/luavm,xiaq/luarocks,ignacio/luarocks
|
e541fd034d3a714156bc42d50baa4c7b1ee775b1
|
src/modeltransparencyeffect/src/Client/ModelTransparencyEffect.lua
|
src/modeltransparencyeffect/src/Client/ModelTransparencyEffect.lua
|
--- Allows a model to have transparent set locally on the client
-- @classmod ModelTransparencyEffect
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local AccelTween = require("AccelTween")
local BaseObject = require("BaseObject")
local StepUtils = require("StepUtils")
local TransparencyService = require("TransparencyService")
local ModelTransparencyEffect = setmetatable({}, BaseObject)
ModelTransparencyEffect.ClassName = "ModelTransparencyEffect"
ModelTransparencyEffect.__index = ModelTransparencyEffect
function ModelTransparencyEffect.new(adornee, transparencyServiceMethodName)
local self = setmetatable(BaseObject.new(adornee), ModelTransparencyEffect)
self._transparency = AccelTween.new(20)
self._transparencyServiceMethodName = transparencyServiceMethodName or "SetTransparency"
self._startAnimation, self._maid._stop = StepUtils.bindToRenderStep(self._update)
return self
end
function ModelTransparencyEffect:SetAcceleration(acceleration)
self._transparency.a = acceleration
end
function ModelTransparencyEffect:SetTransparency(transparency, doNotAnimate)
if self._transparency.t == transparency then
return
end
self._transparency.t = transparency
if doNotAnimate then
self._transparency.p = self._transparency.t
end
self:_startAnimation()
end
function ModelTransparencyEffect:IsDoneAnimating()
return self._transparency.rtime == 0
end
function ModelTransparencyEffect:FinishTransparencyAnimation(callback)
self:SetTransparency(0)
delay(self._transparency.rtime, function()
callback()
end)
end
function ModelTransparencyEffect:_update()
local transparency = self._transparency.p
for part, _ in pairs(self:_getParts()) do
TransparencyService[self._transparencyServiceMethodName](TransparencyService, self, part, transparency)
end
return self._transparency.rtime > 0
end
function ModelTransparencyEffect:_getParts()
if self._parts then
return self._parts
end
self:_setupParts()
return self._parts
end
function ModelTransparencyEffect:_setupParts()
assert(not self._parts, "Already initialized")
self._parts = {}
if self._obj:IsA("BasePart") or self._obj:IsA("Decal") then
self._parts[self._obj] = true
end
for _, part in pairs(self._obj:GetDescendants()) do
if part:IsA("BasePart") or part:IsA("Decal") then
self._parts[part] = true
end
end
self._maid:GiveTask(self._obj.DescendantAdded:Connect(function(child)
if child:IsA("BasePart") or child:IsA("Decal") then
self._parts[child] = true
self:_startAnimation()
end
end))
self._maid:GiveTask(self._obj.DescendantRemoving:Connect(function(child)
if self._parts[child] then
self._parts[child] = nil
TransparencyService[self._transparencyServiceMethodName](TransparencyService, self, child, nil)
end
end))
self._maid:GiveTask(function()
for part, _ in pairs(self._parts) do
TransparencyService[self._transparencyServiceMethodName](TransparencyService, self, part, nil)
end
end)
end
return ModelTransparencyEffect
|
--- Allows a model to have transparent set locally on the client
-- @classmod ModelTransparencyEffect
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local AccelTween = require("AccelTween")
local BaseObject = require("BaseObject")
local StepUtils = require("StepUtils")
local TransparencyService = require("TransparencyService")
local ModelTransparencyEffect = setmetatable({}, BaseObject)
ModelTransparencyEffect.ClassName = "ModelTransparencyEffect"
ModelTransparencyEffect.__index = ModelTransparencyEffect
function ModelTransparencyEffect.new(serviceBag, adornee, transparencyServiceMethodName)
local self = setmetatable(BaseObject.new(adornee), ModelTransparencyEffect)
assert(serviceBag, "Bad serviceBag")
assert(adornee, "Bad adornee")
assert(type(transparencyServiceMethodName) == "string" or transparencyServiceMethodName == nil,
"Bad transparencyServiceMethodName")
self._transparencyService = serviceBag:GetService(TransparencyService)
self._transparency = AccelTween.new(20)
self._transparencyServiceMethodName = transparencyServiceMethodName or "SetTransparency"
self._startAnimation, self._maid._stop = StepUtils.bindToRenderStep(self._update)
return self
end
function ModelTransparencyEffect:SetAcceleration(acceleration)
self._transparency.a = acceleration
end
function ModelTransparencyEffect:SetTransparency(transparency, doNotAnimate)
if self._transparency.t == transparency then
return
end
self._transparency.t = transparency
if doNotAnimate then
self._transparency.p = self._transparency.t
end
self:_startAnimation()
end
function ModelTransparencyEffect:IsDoneAnimating()
return self._transparency.rtime == 0
end
function ModelTransparencyEffect:FinishTransparencyAnimation(callback)
self:SetTransparency(0)
delay(self._transparency.rtime, function()
callback()
end)
end
function ModelTransparencyEffect:_update()
local transparency = self._transparency.p
for part, _ in pairs(self:_getParts()) do
self._transparencyService[self._transparencyServiceMethodName](self._transparencyService, self, part, transparency)
end
return self._transparency.rtime > 0
end
function ModelTransparencyEffect:_getParts()
if self._parts then
return self._parts
end
self:_setupParts()
return self._parts
end
function ModelTransparencyEffect:_setupParts()
assert(not self._parts, "Already initialized")
self._parts = {}
if self._obj:IsA("BasePart") or self._obj:IsA("Decal") then
self._parts[self._obj] = true
end
for _, part in pairs(self._obj:GetDescendants()) do
if part:IsA("BasePart") or part:IsA("Decal") then
self._parts[part] = true
end
end
self._maid:GiveTask(self._obj.DescendantAdded:Connect(function(child)
if child:IsA("BasePart") or child:IsA("Decal") then
self._parts[child] = true
self:_startAnimation()
end
end))
self._maid:GiveTask(self._obj.DescendantRemoving:Connect(function(child)
if self._parts[child] then
self._parts[child] = nil
self._transparencyService[self._transparencyServiceMethodName](self._transparencyService, self, child, nil)
end
end))
self._maid:GiveTask(function()
for part, _ in pairs(self._parts) do
self._transparencyService[self._transparencyServiceMethodName](self._transparencyService, self, part, nil)
end
end)
end
return ModelTransparencyEffect
|
fix: ModelTransparencyEffect works with new service bag
|
fix: ModelTransparencyEffect works with new service bag
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
28463d03e0e309e79e68ffe0ca61b9d40745d6d4
|
nvim/lua/user/lsp/handlers.lua
|
nvim/lua/user/lsp/handlers.lua
|
local M = {}
-- TODO: backfill this to template
M.setup = function()
local signs = {
{ name = "DiagnosticSignError", text = "" },
{ name = "DiagnosticSignWarn", text = "" },
{ name = "DiagnosticSignHint", text = "" },
{ name = "DiagnosticSignInfo", text = "" },
}
for _, sign in ipairs(signs) do
vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" })
end
local config = {
-- disable virtual text
virtual_text = false,
-- show signs
signs = {
active = signs,
},
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = "",
},
}
vim.diagnostic.config(config)
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {
border = "rounded",
})
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {
border = "rounded",
})
end
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
if client.resolved_capabilities.document_highlight then
vim.api.nvim_exec(
[[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
local function lsp_keymaps(bufnr)
local opts = { noremap = true, silent = true }
vim.api.nvim_buf_set_keymap(bufnr, "n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader><space>", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>f", "<cmd>lua vim.diagnostic.open_float()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "[d", '<cmd>lua vim.diagnostic.goto_prev({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"gl",
'<cmd>lua vim.lsp.diagnostic.show_line_diagnostics({ border = "rounded" })<CR>',
opts
)
vim.api.nvim_buf_set_keymap(bufnr, "n", "]d", '<cmd>lua vim.diagnostic.goto_next({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>q", "<cmd>lua vim.diagnostic.setloclist()<CR>", opts)
vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]
end
M.on_attach = function(client, bufnr)
if client.name == "tsserver" then
client.resolved_capabilities.document_formatting = false
end
lsp_keymaps(bufnr)
lsp_highlight_document(client)
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not status_ok then
return
end
M.capabilities = cmp_nvim_lsp.update_capabilities(capabilities)
return M
|
local M = {}
-- TODO: backfill this to template
M.setup = function()
local signs = {
{ name = "DiagnosticSignError", text = "" },
{ name = "DiagnosticSignWarn", text = "" },
{ name = "DiagnosticSignHint", text = "" },
{ name = "DiagnosticSignInfo", text = "" },
}
for _, sign in ipairs(signs) do
vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" })
end
local config = {
-- disable virtual text
virtual_text = false,
-- show signs
signs = {
active = signs,
},
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = "",
},
}
vim.diagnostic.config(config)
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {
border = "rounded",
})
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {
border = "rounded",
})
end
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
if client.server_capabilities.document_highlight then
vim.api.nvim_exec(
[[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
local function lsp_keymaps(bufnr)
local opts = { noremap = true, silent = true }
vim.api.nvim_buf_set_keymap(bufnr, "n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader><space>", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>f", "<cmd>lua vim.diagnostic.open_float()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "[d", '<cmd>lua vim.diagnostic.goto_prev({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"gl",
'<cmd>lua vim.lsp.diagnostic.show_line_diagnostics({ border = "rounded" })<CR>',
opts
)
vim.api.nvim_buf_set_keymap(bufnr, "n", "]d", '<cmd>lua vim.diagnostic.goto_next({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>q", "<cmd>lua vim.diagnostic.setloclist()<CR>", opts)
vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]
end
M.on_attach = function(client, bufnr)
if client.name == "tsserver" then
client.server_capabilities.document_formatting = false
end
lsp_keymaps(bufnr)
lsp_highlight_document(client)
end
local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not status_ok then
return
end
M.capabilities = cmp_nvim_lsp.default_capabilities()
return M
|
Fix lsp deprecation warnings
|
Fix lsp deprecation warnings
...unclear whether capabilities are really working, though
|
Lua
|
mit
|
sax/dotfiles,sax/dotfiles
|
dccd49b652d03bf8ec752d24c2da377e551cf829
|
plugins/opds.koplugin/main.lua
|
plugins/opds.koplugin/main.lua
|
local Dispatcher = require("dispatcher")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local _ = require("gettext")
local OPDS = WidgetContainer:new{
name = "opds",
is_doc_only = false,
}
function OPDS:onDispatcherRegisterActions()
Dispatcher:registerAction("opds_show_catalog",
{category="none", event="ShowOPDSCatalog", title=_("OPDS Catalog"), filemanager=true,}
)
end
function OPDS:init()
self:onDispatcherRegisterActions()
self.ui.menu:registerToMainMenu(self)
end
function OPDS:showCatalog()
local OPDSCatalog = require("opdscatalog")
local filemanagerRefresh = function() self.ui:onRefresh() end
function OPDSCatalog:onClose()
filemanagerRefresh()
UIManager:close(self)
end
OPDSCatalog:showCatalog()
end
function OPDS:onShowOPDSCatalog()
self:showCatalog()
return true
end
function OPDS:addToMainMenu(menu_items)
if not self.ui.view then
menu_items.opds = {
text = _("OPDS catalog"),
sorting_hint = "search",
callback = function() self:showCatalog() end
}
end
end
return OPDS
|
local Dispatcher = require("dispatcher")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local _ = require("gettext")
local OPDS = WidgetContainer:new{
name = "opds",
is_doc_only = false,
}
function OPDS:onDispatcherRegisterActions()
Dispatcher:registerAction("opds_show_catalog",
{category="none", event="ShowOPDSCatalog", title=_("OPDS Catalog"), filemanager=true,}
)
end
function OPDS:init()
self:onDispatcherRegisterActions()
self.ui.menu:registerToMainMenu(self)
end
function OPDS:showCatalog()
local OPDSCatalog = require("opdscatalog")
local filemanagerRefresh = function() self.ui:onRefresh() end
function OPDSCatalog:onClose()
UIManager:close(self)
local FileManager = require("apps/filemanager/filemanager")
if FileManager.instance then
filemanagerRefresh()
else
FileManager:showFiles(G_reader_settings:readSetting("download_dir"))
end
end
OPDSCatalog:showCatalog()
end
function OPDS:onShowOPDSCatalog()
self:showCatalog()
return true
end
function OPDS:addToMainMenu(menu_items)
if not self.ui.view then
menu_items.opds = {
text = _("OPDS catalog"),
sorting_hint = "search",
callback = function() self:showCatalog() end
}
end
end
return OPDS
|
[fix] OPDS catalog invoked from reader: crash KOReader on close (#7825)
|
[fix] OPDS catalog invoked from reader: crash KOReader on close (#7825)
OPDS catalog can be invoked from reader with gesture.
Then on closing OPDS catalog, KOReader crashes.
Let's jump to the download folder instead.
Closes #7784.
|
Lua
|
agpl-3.0
|
Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader
|
f43eb8bb578b09e14774dabcd2e753d17488ff45
|
src/program/snabbnfv/traffic/traffic.lua
|
src/program/snabbnfv/traffic/traffic.lua
|
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 long_opts = {
benchmark = "B",
help = "h",
["link-report-interval"] = "k",
["load-report-interval"] = "l",
["debug-report-interval"] = "D",
["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
args = lib.dogetopt(args, opt, "hHB:k:l:D:", 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
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 ()
if start == 0 and engine.app_table[nic].input.rx.stats.rxpackets > 0 then
-- started receiving, record time and packet count
packets = engine.app_table[nic].input.rx.stats.rxpackets
bytes = engine.app_table[nic].input.rx.stats.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 engine.app_table[nic].input.rx.stats.rxpackets - packets >= npackets
end
engine.main({done = done, no_report = true})
local finish = C.get_monotonic_time()
local runtime = finish - start
packets = engine.app_table[nic].input.rx.stats.rxpackets - packets
bytes = engine.app_table[nic].input.rx.stats.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(engine.breaths), packets / engine.breaths, runtime / engine.breaths * 1e6))
print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6))
require("jit.p").stop()
end
|
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 long_opts = {
benchmark = "B",
help = "h",
["link-report-interval"] = "k",
["load-report-interval"] = "l",
["debug-report-interval"] = "D",
["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
args = lib.dogetopt(args, opt, "hHB:k:l:D:", 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
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 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(engine.breaths), packets / engine.breaths, runtime / engine.breaths * 1e6))
print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6))
require("jit.p").stop()
end
|
[snabbnfv traffic] Fix benchmark mode.
|
[snabbnfv traffic] Fix benchmark mode.
|
Lua
|
apache-2.0
|
Igalia/snabb,dpino/snabbswitch,Igalia/snabbswitch,pirate/snabbswitch,alexandergall/snabbswitch,kbara/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,heryii/snabb,aperezdc/snabbswitch,wingo/snabb,hb9cwp/snabbswitch,eugeneia/snabb,pavel-odintsov/snabbswitch,snabbco/snabb,dpino/snabb,Igalia/snabb,wingo/snabbswitch,heryii/snabb,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabb,snabbco/snabb,mixflowtech/logsensor,Igalia/snabb,Igalia/snabbswitch,kbara/snabb,xdel/snabbswitch,dpino/snabb,snabbco/snabb,snabbco/snabb,Igalia/snabb,dpino/snabb,heryii/snabb,wingo/snabb,dwdm/snabbswitch,Igalia/snabbswitch,justincormack/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,xdel/snabbswitch,snabbco/snabb,aperezdc/snabbswitch,andywingo/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,justincormack/snabbswitch,pirate/snabbswitch,plajjan/snabbswitch,mixflowtech/logsensor,pirate/snabbswitch,plajjan/snabbswitch,fhanik/snabbswitch,dpino/snabbswitch,hb9cwp/snabbswitch,kbara/snabb,wingo/snabb,snabbco/snabb,wingo/snabb,aperezdc/snabbswitch,plajjan/snabbswitch,lukego/snabbswitch,wingo/snabb,lukego/snabb,hb9cwp/snabbswitch,eugeneia/snabb,dpino/snabbswitch,Igalia/snabbswitch,snabbco/snabb,dpino/snabb,eugeneia/snabbswitch,Igalia/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,heryii/snabb,andywingo/snabbswitch,alexandergall/snabbswitch,kbara/snabb,mixflowtech/logsensor,heryii/snabb,alexandergall/snabbswitch,dpino/snabb,kellabyte/snabbswitch,lukego/snabbswitch,wingo/snabb,snabbnfv-goodies/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,dpino/snabbswitch,fhanik/snabbswitch,eugeneia/snabbswitch,andywingo/snabbswitch,Igalia/snabb,dwdm/snabbswitch,dwdm/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,kbara/snabb,alexandergall/snabbswitch,Igalia/snabb,xdel/snabbswitch,kellabyte/snabbswitch,lukego/snabb,kellabyte/snabbswitch,eugeneia/snabb,andywingo/snabbswitch,pavel-odintsov/snabbswitch,lukego/snabb,fhanik/snabbswitch,pavel-odintsov/snabbswitch,eugeneia/snabb,kbara/snabb,lukego/snabbswitch,heryii/snabb,snabbnfv-goodies/snabbswitch,lukego/snabb,justincormack/snabbswitch,Igalia/snabb,lukego/snabbswitch,mixflowtech/logsensor,wingo/snabbswitch,eugeneia/snabb,justincormack/snabbswitch,snabbnfv-goodies/snabbswitch,SnabbCo/snabbswitch,wingo/snabbswitch,plajjan/snabbswitch,eugeneia/snabb,wingo/snabbswitch
|
b1fc5d7331592b1158b4e0119d93b958b8b37832
|
Skins/ModernGadgets/@Resources/Scripts/SettingsBackups.lua
|
Skins/ModernGadgets/@Resources/Scripts/SettingsBackups.lua
|
-- MODERNGADGETS SETTINGS BACKUP SCRIPT
--
-- This script makes backups of the settings files every two hours, which
-- prevents them from being lost when updating the suite.
isDbg = true
function Initialize()
fileNames = { 'GlobalSettings.inc',
'CpuSettings.inc',
'NetworkSettings.inc',
'GpuSettings.inc',
'DisksSettings.inc' }
backupsPath = SKIN:GetVariable('SETTINGSPATH') .. 'ModernGadgetsSettings\\'
filesPath = SKIN:GetVariable('@') .. 'Settings\\'
cpuMeterPath = SKIN:GetVariable('cpuMeterPath')
networkMeterPath = SKIN:GetVariable('networkMeterPath')
gpuMeterPath = SKIN:GetVariable('gpuMeterPathBase')
disksMeterPath = SKIN:GetVariable('disksMeterPath')
end
function Update() end
function ImportBackup()
-- local bTable = ReadIni(backupsPath .. fileNames[2])
for i=1, 5 do
local bTable = ReadIni(backupsPath .. fileNames[i])
local sTable = ReadIni(filesPath .. fileNames[i])
CrossCheck(bTable, sTable, filesPath .. fileNames[i])
end
-- update all gadgets
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', cpuMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', networkMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', gpuMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', disksMeterPath)
SKIN:Bang('!RefreshGroup', 'MgImportRefresh')
LogHelper('Imported settings backup', 'Notice')
-- SKIN:Bang('!Refresh')
end
function CrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if type(v) == 'table' then
for a,b in pairs(v) do
if sTable[i][a] then
SKIN:Bang('!WriteKeyValue', i, a, b, filePath)
else
LogHelper('Key \'' .. a .. '\' does not exist in local', 'Debug')
end
end
end
end
end
function CheckForBackup()
local file = io.open(backupsPath .. fileNames[1])
if file == nil then
SKIN:Bang('!ActivateConfig', 'ModernGadgets\\Config\\GadgetManager', 'Config.ini')
else
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'ImportBackupPrompt')
SKIN:Bang('!Redraw')
SKIN:Bang('!ShowFade')
end
io.close(file)
end
-- parses a INI formatted text file into a 'Table[Section][Key] = Value' table
function ReadIni(inputfile)
local file = assert(io.open(inputfile, 'r'), 'Unable to open ' .. inputfile)
local tbl, section = {}
local num = 0
for line in file:lines() do
num = num + 1
if not line:match('^%s;') then
local key, command = line:match('^([^=]+)=(.+)')
if line:match('^%s-%[.+') then
section = line:match('^%s-%[([^%]]+)')
-- LogHelper(section, 'Debug')
if not tbl[section] then tbl[section] = {} end
elseif key and command and section then
-- LogHelper(key .. '=' .. command, 'Debug')
tbl[section][key:match('(%S*)%s*$')] = command:match('^s*(.-)%s*$')
elseif #line > 0 and section and not key or command then
-- print(num .. ': Invalid property or value.')
end
end
end
if not section then print('No sections found in ' .. inputfile) end
file:close()
return tbl
end
-- function to make logging messages less cluttered
function LogHelper(message, type)
if isDbg == true then
SKIN:Bang("!Log", message, type)
elseif type ~= 'Debug' then
SKIN:Bang("!Log", message, type)
end
end
function TestCrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if type(v) == 'table' then
for a,b in pairs(v) do
print(a .. '=' .. b)
end
else
print(i .. '=' .. v)
end
end
end
|
-- MODERNGADGETS SETTINGS BACKUP SCRIPT
--
-- This script makes backups of the settings files every two hours, which
-- prevents them from being lost when updating the suite.
isDbg = true
function Initialize()
fileNames = { 'GlobalSettings.inc',
'CpuSettings.inc',
'NetworkSettings.inc',
'GpuSettings.inc',
'DisksSettings.inc' }
backupsPath = SKIN:GetVariable('SETTINGSPATH') .. 'ModernGadgetsSettings\\'
filesPath = SKIN:GetVariable('@') .. 'Settings\\'
cpuMeterPath = SKIN:GetVariable('cpuMeterPath')
networkMeterPath = SKIN:GetVariable('networkMeterPath')
gpuMeterPath = SKIN:GetVariable('gpuMeterPathBase')
disksMeterPath = SKIN:GetVariable('disksMeterPath')
end
function Update() end
function ImportBackup()
-- local bTable = ReadIni(backupsPath .. fileNames[2])
for i=1, 5 do
local bTable = ReadIni(backupsPath .. fileNames[i])
local sTable = ReadIni(filesPath .. fileNames[i])
CrossCheck(bTable, sTable, filesPath .. fileNames[i])
end
-- update all gadgets
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', cpuMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', networkMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', gpuMeterPath)
SKIN:Bang('!WriteKeyValue', 'Variables', 'updateSettings', '1', disksMeterPath)
SKIN:Bang('!RefreshGroup', 'MgImportRefresh')
LogHelper('Imported settings backup', 'Notice')
-- SKIN:Bang('!Refresh')
end
function CrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if type(v) == 'table' then
for a,b in pairs(v) do
if sTable[i][a] then
SKIN:Bang('!WriteKeyValue', i, a, b, filePath)
else
LogHelper('Key \'' .. a .. '\' does not exist in local', 'Debug')
end
end
end
end
end
function CheckForBackup()
local file = io.open(backupsPath .. fileNames[1])
if file == nil then
SKIN:Bang('!ActivateConfig', 'ModernGadgets\\Config\\GadgetManager', 'Config.ini')
SKIN:Bang('!CommandMeasure', 'MeasureCreateBackup', 'Run')
else
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'ImportBackupPrompt')
SKIN:Bang('!Redraw')
SKIN:Bang('!ShowFade')
file:close()
end
end
-- parses a INI formatted text file into a 'Table[Section][Key] = Value' table
function ReadIni(inputfile)
local file = assert(io.open(inputfile, 'r'), 'Unable to open ' .. inputfile)
local tbl, section = {}
local num = 0
for line in file:lines() do
num = num + 1
if not line:match('^%s;') then
local key, command = line:match('^([^=]+)=(.+)')
if line:match('^%s-%[.+') then
section = line:match('^%s-%[([^%]]+)')
-- LogHelper(section, 'Debug')
if not tbl[section] then tbl[section] = {} end
elseif key and command and section then
-- LogHelper(key .. '=' .. command, 'Debug')
tbl[section][key:match('(%S*)%s*$')] = command:match('^s*(.-)%s*$')
elseif #line > 0 and section and not key or command then
-- print(num .. ': Invalid property or value.')
end
end
end
if not section then print('No sections found in ' .. inputfile) end
file:close()
return tbl
end
-- function to make logging messages less cluttered
function LogHelper(message, type)
if isDbg == true then
SKIN:Bang("!Log", message, type)
elseif type ~= 'Debug' then
SKIN:Bang("!Log", message, type)
end
end
function TestCrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if type(v) == 'table' then
for a,b in pairs(v) do
print(a .. '=' .. b)
end
else
print(i .. '=' .. v)
end
end
end
|
Fixed setup skin not creating initial backup
|
Fixed setup skin not creating initial backup
|
Lua
|
mit
|
iamanai/ModernGadgets,raiguard/ModernGadgets,iamanai/ModernGadgets,raiguard/ModernGadgets,raiguard/ModernGadgets
|
75816a0746ff32039aea4733c2cb49aaaa9e752b
|
game/dota_addons/junglenational/scripts/vscripts/internal/events.lua
|
game/dota_addons/junglenational/scripts/vscripts/internal/events.lua
|
-- The overall game state has changed
function JungleNational:_OnGameRulesStateChange(keys)
if JungleNational._reentrantCheck then
return
end
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
--Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
JungleNational:PostLoadPrecache()
JungleNational:OnAllPlayersLoaded()
if USE_CUSTOM_TEAM_COLORS_FOR_PLAYERS then
for i=0,9 do
if PlayerResource:IsValidPlayer(i) then
local color = TEAM_COLORS[PlayerResource:GetTeam(i)]
PlayerResource:SetCustomPlayerColor(i, color[1], color[2], color[3])
end
end
end
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
JungleNational:OnGameInProgress()
end
JungleNational._reentrantCheck = true
JungleNational:OnGameRulesStateChange(keys)
JungleNational._reentrantCheck = false
end
-- An NPC has spawned somewhere in game. This includes heroes
function JungleNational:_OnNPCSpawned(keys)
if JungleNational._reentrantCheck then
return
end
local npc = EntIndexToHScript(keys.entindex)
if npc:IsRealHero() and npc.bFirstSpawned == nil then
npc.bFirstSpawned = true
JungleNational:OnHeroInGame(npc)
end
JungleNational._reentrantCheck = true
JungleNational:OnNPCSpawned(keys)
JungleNational._reentrantCheck = false
end
-- An entity died
function JungleNational:_OnEntityKilled( keys )
if JungleNational._reentrantCheck then
return
end
-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil
if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end
if killedUnit:IsRealHero() then
DebugPrint("KILLED, KILLER: " .. killedUnit:GetName() .. " -- " .. killerEntity:GetName())
if END_GAME_ON_KILLS and killedUnit:GetDeaths() >= KILLS_TO_END_GAME_FOR_TEAM then
GameRules:SetSafeToLeave( true )
GameRules:SetGameWinner( killerEntity:GetTeam() )
end
--PlayerResource:GetTeamKills
if SHOW_KILLS_ON_TOPBAR then
GameRules:GetGameModeEntity():SetTopBarTeamValue ( DOTA_TEAM_BADGUYS, GetTeamHeroKills(DOTA_TEAM_BADGUYS) )
GameRules:GetGameModeEntity():SetTopBarTeamValue ( DOTA_TEAM_GOODGUYS, GetTeamHeroKills(DOTA_TEAM_GOODGUYS) )
end
end
JungleNational._reentrantCheck = true
JungleNational:OnEntityKilled( keys )
JungleNational._reentrantCheck = false
end
-- This function is called once when the player fully connects and becomes "Ready" during Loading
function JungleNational:_OnConnectFull(keys)
if JungleNational._reentrantCheck then
return
end
JungleNational:_CaptureJungleNational()
local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)
local userID = keys.userid
self.vUserIds = self.vUserIds or {}
self.vUserIds[userID] = ply
JungleNational._reentrantCheck = true
JungleNational:OnConnectFull( keys )
JungleNational._reentrantCheck = false
end
|
-- The overall game state has changed
function JungleNational:_OnGameRulesStateChange(keys)
if JungleNational._reentrantCheck then
return
end
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
--Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
JungleNational:PostLoadPrecache()
JungleNational:OnAllPlayersLoaded()
if USE_CUSTOM_TEAM_COLORS_FOR_PLAYERS then
for i=0,9 do
if PlayerResource:IsValidPlayer(i) then
local color = TEAM_COLORS[PlayerResource:GetTeam(i)]
PlayerResource:SetCustomPlayerColor(i, color[1], color[2], color[3])
end
end
end
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
JungleNational:OnGameInProgress()
end
JungleNational._reentrantCheck = true
JungleNational:OnGameRulesStateChange(keys)
JungleNational._reentrantCheck = false
end
-- An NPC has spawned somewhere in game. This includes heroes
function JungleNational:_OnNPCSpawned(keys)
if JungleNational._reentrantCheck then
return
end
local npc = EntIndexToHScript(keys.entindex)
if npc:IsRealHero() and npc.bFirstSpawned == nil then
npc.bFirstSpawned = true
JungleNational:OnHeroInGame(npc)
end
JungleNational._reentrantCheck = true
JungleNational:OnNPCSpawned(keys)
JungleNational._reentrantCheck = false
end
-- An entity died
function JungleNational:_OnEntityKilled( keys )
if JungleNational._reentrantCheck then
return
end
-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil
if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end
if killedUnit:IsRealHero() then
DebugPrint("KILLED, KILLER: " .. killedUnit:GetName() .. " -- " .. killerEntity:GetName())
if END_GAME_ON_KILLS and killedUnit:GetDeaths() >= KILLS_TO_END_GAME_FOR_TEAM then
GameRules:SetSafeToLeave( true )
if killedUnit:GetTeam() == DOTA_TEAM_GOODGUYS
GameRules:SetGameWinner( DOTA_TEAM_BADGUYS )
else
GameRules:SetGameWinner( DOTA_TEAM_GOODGUYS )
end
end
--PlayerResource:GetTeamKills
if SHOW_KILLS_ON_TOPBAR then
GameRules:GetGameModeEntity():SetTopBarTeamValue ( DOTA_TEAM_BADGUYS, GetTeamHeroKills(DOTA_TEAM_BADGUYS) )
GameRules:GetGameModeEntity():SetTopBarTeamValue ( DOTA_TEAM_GOODGUYS, GetTeamHeroKills(DOTA_TEAM_GOODGUYS) )
end
end
JungleNational._reentrantCheck = true
JungleNational:OnEntityKilled( keys )
JungleNational._reentrantCheck = false
end
-- This function is called once when the player fully connects and becomes "Ready" during Loading
function JungleNational:_OnConnectFull(keys)
if JungleNational._reentrantCheck then
return
end
JungleNational:_CaptureJungleNational()
local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)
local userID = keys.userid
self.vUserIds = self.vUserIds or {}
self.vUserIds[userID] = ply
JungleNational._reentrantCheck = true
JungleNational:OnConnectFull( keys )
JungleNational._reentrantCheck = false
end
|
Fix #2 Check killedUnit team on NPC death
|
Fix #2 Check killedUnit team on NPC death
Instead of setting the killerEntity's team as the game winner, check the killedUnit's team and take the opposite
|
Lua
|
mit
|
Crazy-Duck/junglenational
|
a506f28ed40e0a028c737e8d03193f66be03359a
|
nvim/lua/plugins.lua
|
nvim/lua/plugins.lua
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local g = vim.g -- a table to access global variables
cmd([[packadd packer.nvim]])
return require('packer').startup(function()
-- plugin management
use('wbthomason/packer.nvim')
-- treesitter (LSP)
use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' })
use('nvim-treesitter/playground')
-- LSP config
use({
'neovim/nvim-lspconfig',
'williamboman/nvim-lsp-installer',
})
-- show signature while typing
use('ray-x/lsp_signature.nvim')
-- faster than built-in filetype.vim (might go to core at some point)
use('nathom/filetype.nvim')
-- buffer/tab line
use({
'akinsho/bufferline.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('bufferline').setup({
options = {
offsets = {
{
filetype = 'NvimTree',
text = '',
padding = 1,
text_align = 'right',
},
},
},
})
end,
})
-- completion and snippets
use({
'rafamadriz/friendly-snippets',
event = 'InsertEnter',
})
use({
'hrsh7th/nvim-cmp',
})
use({
'L3MON4D3/LuaSnip',
wants = 'friendly-snippets',
})
use({
'saadparwaiz1/cmp_luasnip',
})
use({
'hrsh7th/cmp-nvim-lua',
})
use({
'hrsh7th/cmp-nvim-lsp',
})
use({
'hrsh7th/cmp-buffer',
})
use({
'folke/trouble.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('trouble').setup({
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
})
end,
})
-- footer support
-- NOTE: using fork for now - original is hoob3rt/lualine.nvim
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
})
-- highlight TODOs
use({
'folke/todo-comments.nvim',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('todo-comments').setup()
end,
})
-- pane showing symbols
use('simrat39/symbols-outline.nvim')
-- scrollbar in terminal
use('dstein64/nvim-scrollview')
-- which key plugin
use('folke/which-key.nvim')
-- like nerd tree
use({
'kyazdani42/nvim-tree.lua',
cmd = { 'NvimTreeToggle', 'NvimTreeFocus' },
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('nvim-tree').setup({
view = {
side = 'right',
},
})
end,
})
-- close buffers without messing up window layout
use('moll/vim-bbye')
use('editorconfig/editorconfig-vim')
-- ident lines
use('lukas-reineke/indent-blankline.nvim')
-- autopairs
use({
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
})
-- s plus motion to jump around (like vim-sneak)
use('ggandor/lightspeed.nvim')
-- colorizer
use({
'norcalli/nvim-colorizer.lua',
config = function()
require('colorizer').setup()
end,
})
-- find files, buffers, etc.
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } },
module_patterns = 'telescope*',
})
-- use fzf-native matcher instead
use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' })
-- commenting code
use({
'numToStr/Comment.nvim',
config = function()
require('Comment').setup()
end,
})
-- notifications
use({
'rcarriga/nvim-notify',
config = function()
vim.notify = require('notify')
end,
})
-- git support
use({
'TimUntersberger/neogit',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('neogit').setup({})
end,
})
-- git signs
use({
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim',
},
config = function()
require('gitsigns').setup()
end,
})
-- logging
use('tjdevries/vlog.nvim')
-- surround motion
use('tpope/vim-surround')
-- most recently used
use('yegappan/mru')
-- autoformatter
use('mhartington/formatter.nvim')
-- search for visually selected text
use('bronson/vim-visual-star-search')
-- rainbow parens
use('p00f/nvim-ts-rainbow')
-- colors
use('fatih/molokai')
use('altercation/vim-colors-solarized')
use('NLKNguyen/papercolor-theme')
use('navarasu/onedark.nvim')
end)
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local g = vim.g -- a table to access global variables
cmd([[packadd packer.nvim]])
return require('packer').startup(function()
-- plugin management
use('wbthomason/packer.nvim')
-- treesitter (LSP)
use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' })
use('nvim-treesitter/playground')
-- LSP config
use({
'neovim/nvim-lspconfig',
'williamboman/nvim-lsp-installer',
})
-- show signature while typing
use('ray-x/lsp_signature.nvim')
-- faster than built-in filetype.vim (might go to core at some point)
use('nathom/filetype.nvim')
-- buffer/tab line
use({
'akinsho/bufferline.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('bufferline').setup({
options = {
offsets = {
{
filetype = 'NvimTree',
text = '',
padding = 1,
text_align = 'right',
},
},
},
})
end,
})
-- completion and snippets
use({
'rafamadriz/friendly-snippets',
event = 'InsertEnter',
})
use({
'hrsh7th/nvim-cmp',
})
use({
'L3MON4D3/LuaSnip',
wants = 'friendly-snippets',
})
use({
'saadparwaiz1/cmp_luasnip',
})
use({
'hrsh7th/cmp-nvim-lua',
})
use({
'hrsh7th/cmp-nvim-lsp',
})
use({
'hrsh7th/cmp-buffer',
})
use({
'folke/trouble.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('trouble').setup({
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
})
end,
})
-- footer support
-- NOTE: using fork for now - original is hoob3rt/lualine.nvim
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
})
-- highlight TODOs
use({
'folke/todo-comments.nvim',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('todo-comments').setup()
end,
})
-- pane showing symbols
use('simrat39/symbols-outline.nvim')
-- scrollbar in terminal
use('dstein64/nvim-scrollview')
-- which key plugin
use('folke/which-key.nvim')
-- like nerd tree
use({
'kyazdani42/nvim-tree.lua',
cmd = { 'NvimTreeToggle', 'NvimTreeFocus' },
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('nvim-tree').setup({
view = {
side = 'right',
},
})
end,
})
-- close buffers without messing up window layout
use('moll/vim-bbye')
use('editorconfig/editorconfig-vim')
-- ident lines
use('lukas-reineke/indent-blankline.nvim')
-- autopairs
use({
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
})
-- s plus motion to jump around (like vim-sneak)
use({
'ggandor/lightspeed.nvim',
config = function()
require('lightspeed').setup({
instant_repeat_fwd_key = ';',
})
end,
})
-- colorizer
use({
'norcalli/nvim-colorizer.lua',
config = function()
require('colorizer').setup()
end,
})
-- find files, buffers, etc.
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } },
module_patterns = 'telescope*',
})
-- use fzf-native matcher instead
use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' })
-- commenting code
use({
'numToStr/Comment.nvim',
config = function()
require('Comment').setup()
end,
})
-- notifications
use({
'rcarriga/nvim-notify',
config = function()
vim.notify = require('notify')
end,
})
-- git support
use({
'TimUntersberger/neogit',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('neogit').setup({})
end,
})
-- git signs
use({
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim',
},
config = function()
require('gitsigns').setup()
end,
})
-- logging
use('tjdevries/vlog.nvim')
-- surround motion
use('tpope/vim-surround')
-- most recently used
use('yegappan/mru')
-- autoformatter
use('mhartington/formatter.nvim')
-- search for visually selected text
use('bronson/vim-visual-star-search')
-- rainbow parens
use('p00f/nvim-ts-rainbow')
-- colors
use('fatih/molokai')
use('altercation/vim-colors-solarized')
use('NLKNguyen/papercolor-theme')
use('navarasu/onedark.nvim')
end)
|
fix: use ; with lightspeed
|
fix: use ; with lightspeed
|
Lua
|
mit
|
drmohundro/dotfiles
|
283cac93e1ab90dfa0886ce31450c4c7849d7b53
|
nvim/lua/plugins.lua
|
nvim/lua/plugins.lua
|
return require('packer').startup(function()
use('wbthomason/packer.nvim')
use('folke/tokyonight.nvim')
--
-- nvim dependencies
--
use('nvim-lua/plenary.nvim')
use('kyazdani42/nvim-web-devicons')
use('tami5/sqlite.lua')
--
-- nvim plugins
--
use({
'nvim-treesitter/nvim-treesitter',
run = 'TSUpdate',
commit = '57f4dbd47b2af3898a6153cd915b106eb72fc980',
})
use('nvim-treesitter/nvim-treesitter-textobjects')
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/plenary.nvim' } },
})
use({
'nvim-telescope/telescope-frecency.nvim',
requires = { { 'tami5/sqlite.lua' } },
})
use({
'nvim-telescope/telescope-fzf-native.nvim',
requires = { { 'nvim-telescope/telescope.nvim' } },
run = 'make',
})
use({
'nvim-telescope/telescope-smart-history.nvim',
run = 'mkdir -p ~/.local/share/nvim/databases',
requires = { { 'nvim-telescope/telescope.nvim', 'tami5/sqlite.lua' } },
})
use('neovim/nvim-lspconfig')
use('williamboman/nvim-lsp-installer')
use('hrsh7th/nvim-cmp')
use('hrsh7th/cmp-nvim-lsp')
use('hrsh7th/cmp-buffer')
use('hrsh7th/cmp-cmdline')
use('hrsh7th/cmp-path')
use('L3MON4D3/LuaSnip')
use('saadparwaiz1/cmp_luasnip')
use({
'nvim-neo-tree/neo-tree.nvim',
branch = 'v2.x',
requires = {
'nvim-lua/plenary.nvim',
'kyazdani42/nvim-web-devicons',
'MunifTanjim/nui.nvim',
},
})
use('nvim-lualine/lualine.nvim')
use('lukas-reineke/indent-blankline.nvim')
use('xiyaowong/nvim-cursorword')
use('lewis6991/gitsigns.nvim')
--
-- evaluating nvim plugins
--
use({
'romgrk/barbar.nvim',
requires = { { 'kyazdani42/nvim-web-devicons' } },
})
use('petertriho/nvim-scrollbar')
use('windwp/nvim-autopairs')
use('windwp/nvim-ts-autotag')
use('folke/lua-dev.nvim')
use('mfussenegger/nvim-treehopper')
use('phaazon/hop.nvim')
use('ethanholz/nvim-lastplace')
use('rcarriga/nvim-notify')
--
-- older, but still useful vim plugins
--
use('AndrewRadev/splitjoin.vim')
use('tpope/vim-unimpaired')
use('tpope/vim-surround')
use('tpope/vim-repeat')
use('tommcdo/vim-exchange')
use('wellle/targets.vim')
use('editorconfig/editorconfig-vim')
use('scrooloose/nerdcommenter')
use('sickill/vim-pasta')
use({
'rafamadriz/friendly-snippets',
run = 'rm -f snippets/global.json',
})
use({
'kshenoy/vim-signature',
config = function()
require('ryankoval.vim-signature')
end,
})
use('ruanyl/vim-gh-line')
use({
'tpope/vim-fugitive',
config = function()
require('ryankoval.vim-fugitive')
end,
})
use({
'tpope/vim-rhubarb',
requires = { { 'vim-fugitive' } },
})
--
-- probably keep
--
use('terryma/vim-multiple-cursors')
use({
'mrtazz/simplenote.vim',
config = function()
require('ryankoval.simplenote')
end,
})
use({
'mattn/emmet-vim',
ft = { 'html', 'css', 'vue' },
config = function()
require('ryankoval.emmet-vim')
end,
})
end)
|
return require('packer').startup(function()
use('wbthomason/packer.nvim')
use('folke/tokyonight.nvim')
--
-- nvim dependencies
--
use('nvim-lua/plenary.nvim')
use('kyazdani42/nvim-web-devicons')
use('tami5/sqlite.lua')
--
-- nvim plugins
--
use({
'nvim-treesitter/nvim-treesitter',
run = 'TSUpdate',
commit = '57f4dbd47b2af3898a6153cd915b106eb72fc980',
})
use('nvim-treesitter/nvim-treesitter-textobjects')
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/plenary.nvim' } },
})
use({
'nvim-telescope/telescope-frecency.nvim',
requires = { { 'tami5/sqlite.lua' } },
})
use({
'nvim-telescope/telescope-fzf-native.nvim',
requires = { { 'nvim-telescope/telescope.nvim' } },
run = 'make',
})
use({
'nvim-telescope/telescope-smart-history.nvim',
run = 'mkdir -p ~/.local/share/nvim/databases',
requires = { { 'nvim-telescope/telescope.nvim', 'tami5/sqlite.lua' } },
})
use('neovim/nvim-lspconfig')
use('williamboman/nvim-lsp-installer')
use('hrsh7th/nvim-cmp')
use('hrsh7th/cmp-nvim-lsp')
use('hrsh7th/cmp-buffer')
use('hrsh7th/cmp-cmdline')
use('hrsh7th/cmp-path')
use('L3MON4D3/LuaSnip')
use('saadparwaiz1/cmp_luasnip')
use({
'nvim-neo-tree/neo-tree.nvim',
branch = 'v2.x',
requires = {
'nvim-lua/plenary.nvim',
'kyazdani42/nvim-web-devicons',
'MunifTanjim/nui.nvim',
},
})
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
})
use('lukas-reineke/indent-blankline.nvim')
use('xiyaowong/nvim-cursorword')
use('lewis6991/gitsigns.nvim')
--
-- evaluating nvim plugins
--
use({
'romgrk/barbar.nvim',
requires = { { 'kyazdani42/nvim-web-devicons' } },
})
use('petertriho/nvim-scrollbar')
use('windwp/nvim-autopairs')
use('windwp/nvim-ts-autotag')
use('folke/lua-dev.nvim')
use('mfussenegger/nvim-treehopper')
use('phaazon/hop.nvim')
use('ethanholz/nvim-lastplace')
use('rcarriga/nvim-notify')
--
-- older, but still useful vim plugins
--
use('AndrewRadev/splitjoin.vim')
use('tpope/vim-unimpaired')
use('tpope/vim-surround')
use('tpope/vim-repeat')
use('tommcdo/vim-exchange')
use('wellle/targets.vim')
use('editorconfig/editorconfig-vim')
use('scrooloose/nerdcommenter')
use('sickill/vim-pasta')
use({
'rafamadriz/friendly-snippets',
run = 'rm -f snippets/global.json',
})
use({
'kshenoy/vim-signature',
config = function()
require('ryankoval.vim-signature')
end,
})
use('ruanyl/vim-gh-line')
use({
'tpope/vim-fugitive',
config = function()
require('ryankoval.vim-fugitive')
end,
})
use({
'tpope/vim-rhubarb',
requires = { { 'vim-fugitive' } },
})
--
-- probably keep
--
use('terryma/vim-multiple-cursors')
use({
'mrtazz/simplenote.vim',
config = function()
require('ryankoval.simplenote')
end,
})
use({
'mattn/emmet-vim',
ft = { 'html', 'css', 'vue' },
config = function()
require('ryankoval.emmet-vim')
end,
})
end)
|
fixed dependency
|
fixed dependency
|
Lua
|
mit
|
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
|
88f138b0da91220fa0009772e550de9f521c8014
|
src/premake/SchemaCompiler.lua
|
src/premake/SchemaCompiler.lua
|
filter "files:**.fbs"
buildmessage "flatc: Compiling %{file.relpath}"
buildcommands
{
'flatc -c -o "../../PGTA/public/schema" %{file.relpath}',
'SchemaCompiler %{file.relpath}'
}
buildoutputs ""
filter {}
project "SchemaCompiler"
kind "ConsoleApp"
dependson "flatc"
files "../tools/SchemaCompiler/SchemaCompiler.cpp"
project "FlatbufCompiler"
kind "SharedLib"
dependson "SchemaCompiler"
files "../PGTA/**.fbs"
project "*"
|
filter "files:**.fbs"
buildmessage "flatc: Compiling %{file.relpath}"
buildcommands
{
'flatc -c -o "../../PGTA/public/schema" %{file.relpath}',
'SchemaCompiler %{file.relpath}'
}
buildoutputs ""
filter {}
local function TOUCH(file)
if(os.get() == "windows") then
return "type nul >> "..file.." && copy /b "..file.."+,, "..file
else
return "touch "..file
end
end
project "SchemaCompiler"
kind "ConsoleApp"
dependson "flatc"
files "../tools/SchemaCompiler/SchemaCompiler.cpp"
project "FlatbufCompiler"
kind "StaticLib"
dependson "SchemaCompiler"
prebuildcommands(TOUCH("dummy.cpp"))
files "../PGTA/**.fbs"
files (_ACTION.."/dummy.cpp")
project "*"
|
Fix for mac/linux build
|
Fix for mac/linux build
|
Lua
|
mit
|
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
|
2d88bd5ac4efee5e404203d182b064f330aa04ef
|
MMOCoreORB/bin/scripts/object/tangible/deed/guild_deed/guild_deeds.lua
|
MMOCoreORB/bin/scripts/object/tangible/deed/guild_deed/guild_deeds.lua
|
object_tangible_deed_guild_deed_corellia_guild_deed = object_tangible_deed_guild_deed_shared_corellia_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/shared_player_guildhall_corellia_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_corellia_guild_deed, "object/tangible/deed/guild_deed/corellia_guild_deed.iff")
object_tangible_deed_guild_deed_generic_guild_deed = object_tangible_deed_guild_deed_shared_generic_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/shared_player_guildhall_generic_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_generic_guild_deed, "object/tangible/deed/guild_deed/generic_guild_deed.iff")
object_tangible_deed_guild_deed_naboo_guild_deed = object_tangible_deed_guild_deed_shared_naboo_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/shared_player_guildhall_naboo_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_naboo_guild_deed, "object/tangible/deed/guild_deed/naboo_guild_deed.iff")
object_tangible_deed_guild_deed_tatooine_guild_deed = object_tangible_deed_guild_deed_shared_tatooine_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/shared_player_guildhall_tatooine_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_tatooine_guild_deed, "object/tangible/deed/guild_deed/tatooine_guild_deed.iff")
object_tangible_deed_guild_deed_tatooine_guild_style_02_deed = object_tangible_deed_guild_deed_shared_tatooine_guild_style_02_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/shared_player_guildhall_tatooine_style_02.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_tatooine_guild_style_02_deed, "object/tangible/deed/guild_deed/tatooine_guild_style_02_deed.iff")
|
object_tangible_deed_guild_deed_corellia_guild_deed = object_tangible_deed_guild_deed_shared_corellia_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/player_guildhall_corellia_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_corellia_guild_deed, "object/tangible/deed/guild_deed/corellia_guild_deed.iff")
object_tangible_deed_guild_deed_generic_guild_deed = object_tangible_deed_guild_deed_shared_generic_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/player_guildhall_generic_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_generic_guild_deed, "object/tangible/deed/guild_deed/generic_guild_deed.iff")
object_tangible_deed_guild_deed_naboo_guild_deed = object_tangible_deed_guild_deed_shared_naboo_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/player_guildhall_naboo_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_naboo_guild_deed, "object/tangible/deed/guild_deed/naboo_guild_deed.iff")
object_tangible_deed_guild_deed_tatooine_guild_deed = object_tangible_deed_guild_deed_shared_tatooine_guild_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/player_guildhall_tatooine_style_01.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_tatooine_guild_deed, "object/tangible/deed/guild_deed/tatooine_guild_deed.iff")
object_tangible_deed_guild_deed_tatooine_guild_style_02_deed = object_tangible_deed_guild_deed_shared_tatooine_guild_style_02_deed:new {
templateType = DEED,
generatedObjectTemplate = "object/building/player/player_guildhall_tatooine_style_02.iff",
maxCondition = 0
}
ObjectTemplates:addTemplate(object_tangible_deed_guild_deed_tatooine_guild_style_02_deed, "object/tangible/deed/guild_deed/tatooine_guild_style_02_deed.iff")
|
[fixed] Guild halls now use server template instead of client template
|
[fixed] Guild halls now use server template instead of client template
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2077 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,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,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
fce3d5083abee6c6f18f2a8bc3172bdffc6e97e9
|
vanilla/v/router.lua
|
vanilla/v/router.lua
|
-- perf
local error = error
local tconcat = table.concat
local function tappend(t, v) t[#t+1] = v end
local simple_route = require 'vanilla.v.routes.simple'
-- init Router and set routes
local Router = {}
function Router:new(request)
local instance = { routes = {simple_route:new(request)} }
setmetatable(instance, {__index = self})
return instance
end
function Router:addRoute(route, only_one)
if route ~= nil then
if only_one then self.routes = {} end
tappend(self.routes, route)
end
end
function Router:removeRoute(route_name)
for i,route in ipairs(self.routes) do
if (tostring(route) == route_name) then self.routes[i] = false end
end
end
function Router:getRoutes()
return self.routes
end
function Router:getCurrentRoute()
return self.current_route
end
function Router:getCurrentRouteName()
return tostring(self.current_route)
end
local function route_match(route)
return route:match()
end
function Router:route()
if #self.routes >= 1 then
local alive_route_num = 0
local route_err = {}
for k,route in ipairs(self.routes) do
if route then
alive_route_num = alive_route_num + 1
local ok, controller_name_or_error, action = pcall(route_match, route)
if ok and controller_name_or_error then
self.current_route = route
return controller_name_or_error, action
else
route_err[k] = controller_name_or_error
end
end
end
error({ code = 201, msg = {
Routes_No_Match = alive_route_num .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}})
end
error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}})
end
return Router
|
-- perf
local error = error
local tconcat = table.concat
local function tappend(t, v) t[#t+1] = v end
local simple_route = require 'vanilla.v.routes.simple'
-- init Router and set routes
local Router = {}
function Router:new(request)
local instance = { routes = {simple_route:new(request)} }
setmetatable(instance, {__index = self})
return instance
end
function Router:addRoute(route, only_one)
if route ~= nil then
if only_one then self.routes = {} end
tappend(self.routes, route)
end
end
function Router:removeRoute(route_name)
for i,route in ipairs(self.routes) do
if (tostring(route) == route_name) then self.routes[i] = false end
end
end
function Router:getRoutes()
return self.routes
end
function Router:getCurrentRoute()
return self.current_route
end
function Router:getCurrentRouteName()
return tostring(self.current_route)
end
local function route_match(route)
return route:match()
end
function Router:route()
if #self.routes >= 1 then
local alive_route_num = 0
local route_err = {}
for k,route in ipairs(self.routes) do
if route then
alive_route_num = alive_route_num + 1
local ok, controller_name_or_error, action = pcall(route_match, route)
if ok and package.searchpath(ngx.var.document_root .. '/application/controllers.'
.. controller_name_or_error, '/?.lua;/?/init.lua') ~=nil
and type(require('controllers.' .. controller_name_or_error)[action]) == 'function' then
-- if ok and controller_name_or_error then
self.current_route = route
return controller_name_or_error, action
else
route_err[k] = controller_name_or_error
end
end
end
error({ code = 201, msg = {
Routes_No_Match = alive_route_num .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}})
end
error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}})
end
return Router
|
fix a router bug about controller action check
|
fix a router bug about controller action check
|
Lua
|
mit
|
idevz/vanilla,idevz/vanilla
|
b5defe6670b0245ba1017a9997aa83e9513ec9b9
|
script/c80400029.lua
|
script/c80400029.lua
|
--サイバー・ネットワーク
function c80400029.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c80400029.ncon)
e1:SetTarget(c80400029.ntg)
c:RegisterEffect(e1)
--Activate2
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(0,TIMING_END_PHASE)
e2:SetCondition(c80400029.condition)
e2:SetTarget(c80400029.target1)
e2:SetOperation(c80400029.operation)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(80400029,1))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_FREE_CHAIN)
e3:SetHintTiming(0,TIMING_END_PHASE)
e3:SetCondition(c80400029.condition)
e3:SetTarget(c80400029.target2)
e3:SetOperation(c80400029.operation)
e3:SetLabel(1)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(80400029,2))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c80400029.spcon)
e4:SetCost(c80400029.spcost)
e4:SetTarget(c80400029.sptg)
e4:SetOperation(c80400029.spop)
c:RegisterEffect(e4)
end
function c80400029.cfilter(c)
return c:IsSetCard(0x103c)
end
function c80400029.ncon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetMatchingGroupCount(c80400029.cfilter,tp,LOCATION_MZONE,0,nil)==0
end
function c80400029.ntg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
c:SetTurnCounter(0)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetOperation(c80400029.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3)
c:RegisterEffect(e1)
end
function c80400029.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c80400029.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c80400029.dfilter(c)
return c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToRemove()
end
function c80400029.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(80400029,0)) then
e:SetCategory(CATEGORY_REMOVE)
e:SetLabel(1)
e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
else
e:SetCategory(0)
e:SetLabel(0)
end
e:GetHandler():SetTurnCounter(0)
--destroy
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetOperation(c80400029.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3)
e:GetHandler():RegisterEffect(e1)
end
function c80400029.desop(e,tp,eg,ep,ev,re,r,rp)
if tp~=Duel.GetTurnPlayer() then return end
local c=e:GetHandler()
local ct=c:GetTurnCounter()
ct=ct+1
c:SetTurnCounter(ct)
if ct==3 then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c80400029.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(80400029)==0
and Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK)
e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c80400029.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if e:GetLabel()==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c80400029.dfilter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c80400029.filter(c,e,tp)
return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80400029.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c80400029.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not (Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()>PHASE_MAIN1 and Duel.GetCurrentPhase()<PHASE_END) end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80400029.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c80400029.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED)
end
function c80400029.dgfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c80400029.spop(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsPlayerCanSpecialSummonMonster(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) then return end
local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft1<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp)
if g:GetCount()>0 then
local tc=g:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
--cannot trigger
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_TRIGGER)
e1:SetRange(LOCATION_MZONE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
Duel.SpecialSummonComplete()
Duel.BreakEffect()
local dg=Duel.GetMatchingGroup(c80400029.dgfilter,tp,LOCATION_ONFIELD,0,nil)
if dg:GetCount()>0 then
Duel.Destroy(dg,REASON_EFFECT)
end
end
end
|
--サイバー・ネットワーク
function c80400029.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c80400029.ncon)
e1:SetTarget(c80400029.ntg)
c:RegisterEffect(e1)
--Activate2
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(0,TIMING_END_PHASE)
e2:SetCondition(c80400029.condition)
e2:SetTarget(c80400029.target1)
e2:SetOperation(c80400029.operation)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(80400029,1))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_FREE_CHAIN)
e3:SetHintTiming(0,TIMING_END_PHASE)
e3:SetCondition(c80400029.condition)
e3:SetTarget(c80400029.target2)
e3:SetOperation(c80400029.operation)
e3:SetLabel(1)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(80400029,2))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c80400029.spcon)
e4:SetCost(c80400029.spcost)
e4:SetTarget(c80400029.sptg)
e4:SetOperation(c80400029.spop)
c:RegisterEffect(e4)
end
function c80400029.cfilter(c)
return c:IsCode(70095154)
end
function c80400029.ncon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetMatchingGroupCount(c80400029.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)==0
end
function c80400029.ntg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
c:SetTurnCounter(0)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetOperation(c80400029.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3)
c:RegisterEffect(e1)
end
function c80400029.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c80400029.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil)
end
function c80400029.dfilter(c)
return c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToRemove()
end
function c80400029.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(80400029,0)) then
e:SetCategory(CATEGORY_REMOVE)
e:SetLabel(1)
e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
else
e:SetCategory(0)
e:SetLabel(0)
end
e:GetHandler():SetTurnCounter(0)
--destroy
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetOperation(c80400029.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3)
e:GetHandler():RegisterEffect(e1)
end
function c80400029.desop(e,tp,eg,ep,ev,re,r,rp)
if tp~=Duel.GetTurnPlayer() then return end
local c=e:GetHandler()
local ct=c:GetTurnCounter()
ct=ct+1
c:SetTurnCounter(ct)
if ct==3 then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c80400029.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(80400029)==0
and Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK)
e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c80400029.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if e:GetLabel()==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c80400029.dfilter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c80400029.filter(c,e,tp)
return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80400029.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c80400029.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not (Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()>PHASE_MAIN1 and Duel.GetCurrentPhase()<PHASE_END) end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80400029.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c80400029.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED)
end
function c80400029.dgfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c80400029.spop(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsPlayerCanSpecialSummonMonster(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) then return end
local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft1<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp)
if g:GetCount()>0 then
local tc=g:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
--cannot trigger
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_TRIGGER)
e1:SetRange(LOCATION_MZONE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
Duel.SpecialSummonComplete()
Duel.BreakEffect()
local dg=Duel.GetMatchingGroup(c80400029.dgfilter,tp,LOCATION_ONFIELD,0,nil)
if dg:GetCount()>0 then
Duel.Destroy(dg,REASON_EFFECT)
end
end
end
|
Cyber Network fix
|
Cyber Network fix
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
|
cf718f401291747de0760747c6f9256ecbd2fc6e
|
testserver/item/base/music.lua
|
testserver/item/base/music.lua
|
-- Standardskript fr Instrumente
-- Nitram
require("base.common")
module("item.base.music", package.seeall)
TalkTexts={ flute = {}, lute = {}, horn = {}, harp = {}, panpipe = {}, drum = {}};
function addTalkText(eText,gText, Skill)
table.insert(TalkTexts[Skill],{eText,gText});
end
function PlayInstrument(User,Item,Skill)
local Skl=User:getSkill(Skill);
local Qual=math.floor(Item.quality/100);
local PlayVal=base.common.Limit(math.floor((Skl+(Qual*5))/120*table.getn(TalkTexts[Skill])*(math.random(8,13)/10)),1,table.getn(TalkTexts[Skill]));
User:talkLanguage( Character.say, Player.german, TalkTexts[Skill][PlayVal][2]);
User:talkLanguage( Character.say, Player.english, TalkTexts[Skill][PlayVal][1]);
User:learn(Skill,30,100,User:increaseAttrib("dexterity",0));
User.movepoints=User.movepoints-30;
end
|
-- Standardskript fr Instrumente
-- Nitram
require("base.common")
module("item.base.music", package.seeall)
TalkTexts={ Character.flute = {}, Character.lute = {}, Character.horn = {}, Character.harp = {}, Character.panpipe = {}, Character.drum = {}};
function addTalkText(eText,gText, Skill)
table.insert(TalkTexts[Skill],{eText,gText});
end
function PlayInstrument(User,Item,Skill)
local Skl=User:getSkill(Skill);
local Qual=math.floor(Item.quality/100);
local PlayVal=base.common.Limit(math.floor((Skl+(Qual*5))/120*table.getn(TalkTexts[Skill])*(math.random(8,13)/10)),1,table.getn(TalkTexts[Skill]));
User:talkLanguage( Character.say, Player.german, TalkTexts[Skill][PlayVal][2]);
User:talkLanguage( Character.say, Player.english, TalkTexts[Skill][PlayVal][1]);
User:learn(Skill,30,100,User:increaseAttrib("dexterity",0));
User.movepoints=User.movepoints-30;
end
|
Fix flute
|
Fix flute
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content
|
a6125b4d089f7ef312a5133d937a84f0d2219950
|
lua/entities/base_starfall_entity/init.lua
|
lua/entities/base_starfall_entity/init.lua
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( "shared.lua" )
function ENT:Initialize ()
baseclass.Get( "base_gmodentity" ).Initialize( self )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.tableCopy = function ( t, lookup_table )
if ( t == nil ) then return nil end
local copy = {}
setmetatable( copy, debug.getmetatable( t ) )
for i, v in pairs( t ) do
if ( not istable( v ) ) then
copy[ i ] = v
else
lookup_table = lookup_table or {}
lookup_table[ t ] = copy
if lookup_table[ v ] then
copy[ i ] = lookup_table[ v ] -- we already copied this table. reuse the copy.
else
copy[ i ] = table.Copy( v, lookup_table ) -- not yet copied. copy it.
end
end
end
return copy
end
end
function ENT:Error ( msg )
ErrorNoHalt( "Processor of " .. self.owner:Nick() .. " errored: " .. msg .. "\n" )
SF.AddNotify( self.instance.player, msg, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1 )
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
end
function ENT:OnRemove ()
if not self.instance then return end
self.instance:deinitialize()
self.instance = nil
end
function ENT:onRestore ()
end
function ENT:BuildDupeInfo ()
-- Remove table.Copy fix when Garrysmod updates with @Xandaros patch.
table.Copy = self.tableCopy
return {}
end
function ENT:ApplyDupeInfo ()
return {}
end
function ENT:PreEntityCopy ()
local i = self:BuildDupeInfo()
if i then
duplicator.StoreEntityModifier( self, "SFDupeInfo", i )
end
end
function ENT:PostEntityPaste ( ply, ent )
if ent.EntityMods and ent.EntityMods.SFDupeInfo then
ent:ApplyDupeInfo( ply, ent, ent.EntityMods.SFDupeInfo )
end
end
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( "shared.lua" )
function ENT:Initialize ()
baseclass.Get( "base_gmodentity" ).Initialize( self )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.instance = nil
self.tableCopy = function ( t, lookup_table )
if ( t == nil ) then return nil end
local copy = {}
setmetatable( copy, debug.getmetatable( t ) )
for i, v in pairs( t ) do
if ( not istable( v ) ) then
copy[ i ] = v
else
lookup_table = lookup_table or {}
lookup_table[ t ] = copy
if lookup_table[ v ] then
copy[ i ] = lookup_table[ v ] -- we already copied this table. reuse the copy.
else
copy[ i ] = table.Copy( v, lookup_table ) -- not yet copied. copy it.
end
end
end
return copy
end
end
function ENT:Error ( msg )
ErrorNoHalt( "Processor of " .. self.owner:Nick() .. " errored: " .. msg .. "\n" )
if self.instance then
SF.AddNotify( self.instance.player, msg, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1 )
self.instance:deinitialize()
self.instance = nil
end
end
function ENT:OnRemove ()
if not self.instance then return end
self.instance:deinitialize()
self.instance = nil
end
function ENT:onRestore ()
end
function ENT:BuildDupeInfo ()
-- Remove table.Copy fix when Garrysmod updates with @Xandaros patch.
table.Copy = self.tableCopy
return {}
end
function ENT:ApplyDupeInfo ()
return {}
end
function ENT:PreEntityCopy ()
local i = self:BuildDupeInfo()
if i then
duplicator.StoreEntityModifier( self, "SFDupeInfo", i )
end
end
function ENT:PostEntityPaste ( ply, ent )
if ent.EntityMods and ent.EntityMods.SFDupeInfo then
ent:ApplyDupeInfo( ply, ent, ent.EntityMods.SFDupeInfo )
end
end
|
Fix sharedscreen upload problem
|
Fix sharedscreen upload problem
Fix #141
|
Lua
|
bsd-3-clause
|
Ingenious-Gaming/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall
|
62a550d3a9a63154e59bc52b16ba007dbd1d6bb1
|
src/program/ipfix/probe/probe.lua
|
src/program/ipfix/probe/probe.lua
|
-- This module implements the `snabb flow_export` command
module(..., package.seeall)
local lib = require("core.lib")
local cache = require("apps.ipfix.cache")
local meter = require("apps.ipfix.meter")
local exporter = require("apps.ipfix.export")
-- apps that can be used as an input or output for the exporter
in_out_apps = {}
function in_out_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapReader, path }
end
function in_out_apps.raw (device)
return { input = "rx",
output = "tx" },
{ require("apps.socket.raw").RawSocket, device }
end
function in_out_apps.intel10g (device)
local conf = { pciaddr = device }
return { input = "rx",
output = "tx" },
{ require("apps.intel.intel_app").Intel82599, conf }
end
local long_opts = {
help = "h",
duration = "D",
port = "p",
transport = 1,
["host-mac"] = "m",
["host-ip"] = "a",
["input-type"] = "i",
["output-type"] = "o",
["netflow-v9"] = 0,
["ipfix"] = 0,
["active-timeout"] = 1,
["idle-timeout"] = 1
}
function run (args)
local duration
local input_type, output_type = "intel10g", "intel10g"
local host_mac, host_ip
local collector_mac, colletor_ip
local port = 4739
local active_timeout, idle_timeout
local ipfix_version = 10
-- TODO: better input validation
local opt = {
h = function (arg)
print(require("program.ipfix.probe.README_inc"))
main.exit(0)
end,
D = function (arg)
duration = assert(tonumber(arg), "expected number for duration")
end,
i = function (arg)
assert(in_out_apps[arg], "unknown input type")
input_type = arg
end,
o = function (arg)
assert(in_out_apps[arg], "unknown output type")
output_type = arg
end,
p = function (arg)
port = assert(tonumber(arg), "expected number for port")
end,
m = function (arg)
host_mac = arg
end,
a = function (arg)
host_ip = arg
end,
c = function (arg)
collector_ip = arg
end,
-- TODO: this should probably be superceded by using ARP
M = function (arg)
collector_mac = arg
end,
["active-timeout"] = function (arg)
active_timeout =
assert(tonumber(arg), "expected number for active timeout")
end,
["idle-timeout"] = function (arg)
idle_timeout =
assert(tonumber(arg), "expected number for idle timeout")
end,
ipfix = function (arg)
ipfix_version = 10
end,
["netflow-v9"] = function (arg)
ipfix_version = 9
end,
-- TODO: not implemented
["transport"] = function (arg) end
}
args = lib.dogetopt(args, opt, "hD:i:o:p:m:a:c:M:", long_opts)
if #args ~= 2 then
print(require("program.ipfix.probe.README_inc"))
main.exit(1)
end
assert(host_mac, "--host-mac argument required")
assert(host_ip, "--host-ip argument required")
assert(collector_ip, "--collector argument required")
local in_link, in_app = in_out_apps[input_type](args[1])
local out_link, out_app = in_out_apps[output_type](args[2])
local flow_cache = cache.FlowCache:new({})
local meter_config = { cache = flow_cache }
local exporter_config = { cache = flow_cache,
active_timeout = active_timeout,
idle_timeout = idle_timeout,
ipfix_version = ipfix_version,
exporter_mac = host_mac,
exporter_ip = host_ip,
collector_mac = collector_mac,
collector_ip = collector_ip,
collector_port = port }
local c = config.new()
config.app(c, "source", unpack(in_app))
config.app(c, "sink", unpack(out_app))
config.app(c, "meter", meter.FlowMeter, meter_config)
config.app(c, "exporter", exporter.FlowExporter, exporter_config)
config.link(c, "source." .. in_link.output .. " -> meter.input")
config.link(c, "exporter.output -> sink." .. out_link.input)
local done
if not duration then
done = function ()
return engine.app_table.source.done
end
end
engine.configure(c)
engine.busywait = true
engine.main({ duration = duration, done = done })
end
|
-- This module implements the `snabb flow_export` command
module(..., package.seeall)
local now = require("core.app").now
local lib = require("core.lib")
local link = require("core.link")
local cache = require("apps.ipfix.cache")
local meter = require("apps.ipfix.meter")
local exporter = require("apps.ipfix.export")
local numa = require("lib.numa")
-- apps that can be used as an input or output for the exporter
in_out_apps = {}
function in_out_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapReader, path }
end
function in_out_apps.raw (device)
return { input = "rx",
output = "tx" },
{ require("apps.socket.raw").RawSocket, device }
end
function in_out_apps.intel10g (device)
local conf = { pciaddr = device }
return { input = "rx",
output = "tx" },
{ require("apps.intel.intel_app").Intel82599, conf }
end
local long_opts = {
help = "h",
duration = "D",
port = "p",
transport = 1,
stats = "s",
["host-mac"] = "m",
["host-ip"] = "a",
["input-type"] = "i",
["output-type"] = "o",
["netflow-v9"] = 0,
["ipfix"] = 0,
["active-timeout"] = 1,
["idle-timeout"] = 1,
["cpu"] = 1
}
function run (args)
local duration
local input_type, output_type = "intel10g", "intel10g"
local host_mac, host_ip
local collector_mac, colletor_ip
local port = 4739
local active_timeout, idle_timeout
local ipfix_version = 10
local cpu
local report = false
-- TODO: better input validation
local opt = {
h = function (arg)
print(require("program.ipfix.probe.README_inc"))
main.exit(0)
end,
D = function (arg)
duration = assert(tonumber(arg), "expected number for duration")
end,
i = function (arg)
assert(in_out_apps[arg], "unknown input type")
input_type = arg
end,
o = function (arg)
assert(in_out_apps[arg], "unknown output type")
output_type = arg
end,
p = function (arg)
port = assert(tonumber(arg), "expected number for port")
end,
s = function (arg)
report = true
end,
m = function (arg)
host_mac = arg
end,
a = function (arg)
host_ip = arg
end,
c = function (arg)
collector_ip = arg
end,
-- TODO: this should probably be superceded by using ARP
M = function (arg)
collector_mac = arg
end,
["active-timeout"] = function (arg)
active_timeout =
assert(tonumber(arg), "expected number for active timeout")
end,
["idle-timeout"] = function (arg)
idle_timeout =
assert(tonumber(arg), "expected number for idle timeout")
end,
ipfix = function (arg)
ipfix_version = 10
end,
["netflow-v9"] = function (arg)
ipfix_version = 9
end,
-- TODO: not implemented
["transport"] = function (arg) end,
["cpu"] = function (arg)
cpu = tonumber(arg)
end
}
args = lib.dogetopt(args, opt, "hsD:i:o:p:m:a:c:M:", long_opts)
if #args ~= 2 then
print(require("program.ipfix.probe.README_inc"))
main.exit(1)
end
assert(host_mac, "--host-mac argument required")
assert(host_ip, "--host-ip argument required")
assert(collector_ip, "--collector argument required")
local in_link, in_app = in_out_apps[input_type](args[1])
local out_link, out_app = in_out_apps[output_type](args[2])
local flow_cache = cache.FlowCache:new({})
local meter_config = { cache = flow_cache }
local exporter_config = { cache = flow_cache,
active_timeout = active_timeout,
idle_timeout = idle_timeout,
ipfix_version = ipfix_version,
exporter_mac = host_mac,
exporter_ip = host_ip,
collector_mac = collector_mac,
collector_ip = collector_ip,
collector_port = port }
local c = config.new()
config.app(c, "source", unpack(in_app))
config.app(c, "sink", unpack(out_app))
config.app(c, "meter", meter.FlowMeter, meter_config)
config.app(c, "exporter", exporter.FlowExporter, exporter_config)
config.link(c, "source." .. in_link.output .. " -> meter.input")
config.link(c, "exporter.output -> sink." .. out_link.input)
local done
if not duration then
done = function ()
return engine.app_table.source.done
end
end
local start_time = now()
if cpu then numa.bind_to_cpu(cpu) end
engine.configure(c)
engine.busywait = true
engine.main({ duration = duration, done = done })
if report then
local end_time = now()
local app = engine.app_table.meter
local input_link = app.input.input
local stats = link.stats(input_link)
print("IPFIX probe stats:")
print(string.format("bytes: %s packets: %s bps: %s Mpps: %s",
lib.comma_value(stats.rxbytes),
lib.comma_value(stats.rxpackets),
lib.comma_value(math.floor((stats.rxbytes * 8) / (end_time - start_time))),
lib.comma_value(stats.rxpackets / ((end_time - start_time) * 1000000))))
end
end
|
Improve 'snabb ipfix probe' for benchmarking
|
Improve 'snabb ipfix probe' for benchmarking
Add a stat reporting flag and enable NUMA binding
|
Lua
|
apache-2.0
|
dpino/snabbswitch,dpino/snabb,dpino/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabb,Igalia/snabbswitch,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabb,snabbco/snabb,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,snabbco/snabb,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,snabbco/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb
|
f834839dc3c080b84366d254c7b16b6fec75d782
|
agents/monitoring/default/client/upgrade.lua
|
agents/monitoring/default/client/upgrade.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local timer = require('timer')
local consts = require('../util/constants')
local misc = require('../util/misc')
local logging = require('logging')
local UpgradePollEmitter = Emitter:extend()
function UpgradePollEmitter:initialize()
self.timeout = nil
self.stopped = nil
end
function UpgradePollEmitter:calcTimeout()
return misc.calcJitter(consts.UPGRADE_INTERVAL, consts.UPGRADE_INTERVAL_JITTER)
end
function UpgradePollEmitter:_emit()
process.nextTick(function()
self:emit('upgrade')
end)
end
function UpgradePollEmitter:forceUpgradeCheck()
self:_emit()
end
function UpgradePollEmitter:_registerTimeout(callback)
if self.stopped then
return
end
-- Check for upgrade
function timeout()
self:_registerTimeout(function()
if self.stopped then
return
end
self:_emit()
timeout()
end)
end
self.timeout = self:calcTimeout()
logging.debugf('Using Upgrade Timeout %ums', self.timeout)
self._timer = timer.setTimeout(self.timeout, timeout)
end
function UpgradePollEmitter:start()
self.stopped = nil
if self._timer then
return
end
-- On Startup check for upgrade
self:_emit()
self:_registerTimeout()
end
function UpgradePollEmitter:stop()
if self._timer then
timer.clearTimer(self._timer)
end
self.stopped = true
end
local exports = {}
exports.UpgradePollEmitter = UpgradePollEmitter
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local timer = require('timer')
local consts = require('../util/constants')
local misc = require('../util/misc')
local logging = require('logging')
local UpgradePollEmitter = Emitter:extend()
function UpgradePollEmitter:initialize()
self.timeout = nil
self.stopped = nil
end
function UpgradePollEmitter:calcTimeout()
return misc.calcJitter(consts.UPGRADE_INTERVAL, consts.UPGRADE_INTERVAL_JITTER)
end
function UpgradePollEmitter:_emit()
process.nextTick(function()
self:emit('upgrade')
end)
end
function UpgradePollEmitter:forceUpgradeCheck()
self:_emit()
end
function UpgradePollEmitter:_registerTimeout(callback)
if self.stopped then
return
end
-- Check for upgrade
local timeoutCallback
timeoutCallback = function()
self:_emit()
self:_registerTimeout(timeoutCallback)
end
self.timeout = self:calcTimeout()
logging.debugf('Using Upgrade Timeout %ums', self.timeout)
self._timer = timer.setTimeout(self.timeout, timeoutCallback)
end
function UpgradePollEmitter:start()
self.stopped = nil
if self._timer then
return
end
-- On Startup check for upgrade
self:_emit()
self:_registerTimeout()
end
function UpgradePollEmitter:stop()
if self._timer then
timer.clearTimer(self._timer)
end
self.stopped = true
end
local exports = {}
exports.UpgradePollEmitter = UpgradePollEmitter
return exports
|
fix(upgrades): callback is not triggering correctly
|
fix(upgrades): callback is not triggering correctly
|
Lua
|
apache-2.0
|
AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base
|
4dc0d18d452d0395f9c15537332a34d4f8abb3a8
|
libs/uvl/luasrc/uvl/errors.lua
|
libs/uvl/luasrc/uvl/errors.lua
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
UCILOAD = 'Unable to load config "%p": %1',
SCHEME = 'Error in scheme "%p":\n%c',
CONFIG = 'Error in config "%p":\n%c',
SECTION = 'Error in section "%i" (%I):\n%c',
OPTION = 'Error in option "%i" (%I):\n%c',
REFERENCE = 'Option "%i" has invalid reference specification %1:\n%c',
DEPENDENCY = 'In dependency check for %t "%i":\n%c',
SME_FIND = 'Can not find scheme "%p" in "%1"',
SME_READ = 'Can not access file "%1"',
SME_REQFLD = 'Missing required scheme field "%1" in "%i"',
SME_INVREF = 'Illegal reference "%1" to an anonymous section',
SME_BADREF = 'Malformed reference in "%1"',
SME_BADDEP = 'Malformed dependency specification "%1" in "%i"',
SME_BADVAL = 'Malformed validator specification "%1" in "%i"',
SME_ERRVAL = 'External validator "%1" failed: %2',
SME_VBADPACK = 'Variable "%o" in scheme "%p" references unknown package "%1"',
SME_VBADSECT = 'Variable "%o" in scheme "%p" references unknown section "%1"',
SME_EBADPACK = 'Enum "%v" in scheme "%p" references unknown package "%1"',
SME_EBADSECT = 'Enum "%v" in scheme "%p" references unknown section "%1"',
SME_EBADOPT = 'Enum "%v" in scheme "%p" references unknown option "%1"',
SME_EBADTYPE = 'Enum "%v" in scheme "%p" references non-enum option "%I"',
SME_EBADDEF = 'Enum "%v" in scheme "%p" redeclares the default value of "%I"',
SECT_UNKNOWN = 'Section "%i" (%I) not found in scheme',
SECT_REQUIRED = 'Required section "%p.%S" not found in config',
SECT_UNIQUE = 'Unique section "%p.%S" occurs multiple times in config',
SECT_NAMED = 'The section of type "%p.%S" is stored anonymously in config but must be named',
SECT_NOTFOUND = 'Section "%p.%s" not found in config',
OPT_UNKNOWN = 'Option "%i" (%I) not found in scheme',
OPT_REQUIRED = 'Required option "%i" has no value',
OPT_BADVALUE = 'Value "%1" of option "%i" is not defined in enum %2',
OPT_INVVALUE = 'Value "%1" of option "%i" does not validate as datatype "%2"',
OPT_NOTLIST = 'Option "%i" is defined as list but stored as plain value',
OPT_DATATYPE = 'Option "%i" has unknown datatype "%1"',
OPT_NOTFOUND = 'Option "%p.%s.%o" not found in config',
OPT_RANGE = 'Option "%p.%s.%o" is not within the specified range',
DEP_NOTEQUAL = 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"',
DEP_NOVALUE = 'Dependency (%1) failed:\nOption "%i" has no value',
DEP_NOTVALID = 'Dependency (%1) failed:\n%c',
DEP_RECURSIVE = 'Recursive dependency for option "%i" detected',
DEP_BADENUM = 'In dependency check for enum value "%i":\n%c'
}
function i18n(key)
if luci.i18n then
return luci.i18n.translate(key)
else
return key
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(ERRCODES[self.code] or self.code])
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
UCILOAD = 'Unable to load config "%p": %1',
SCHEME = 'Error in scheme "%p":\n%c',
CONFIG = 'Error in config "%p":\n%c',
SECTION = 'Error in section "%i" (%I):\n%c',
OPTION = 'Error in option "%i" (%I):\n%c',
REFERENCE = 'Option "%i" has invalid reference specification %1:\n%c',
DEPENDENCY = 'In dependency check for %t "%i":\n%c',
SME_FIND = 'Can not find scheme "%p" in "%1"',
SME_READ = 'Can not access file "%1"',
SME_REQFLD = 'Missing required scheme field "%1" in "%i"',
SME_INVREF = 'Illegal reference "%1" to an anonymous section',
SME_BADREF = 'Malformed reference in "%1"',
SME_BADDEP = 'Malformed dependency specification "%1" in "%i"',
SME_BADVAL = 'Malformed validator specification "%1" in "%i"',
SME_ERRVAL = 'External validator "%1" failed: %2',
SME_VBADPACK = 'Variable "%o" in scheme "%p" references unknown package "%1"',
SME_VBADSECT = 'Variable "%o" in scheme "%p" references unknown section "%1"',
SME_EBADPACK = 'Enum "%v" in scheme "%p" references unknown package "%1"',
SME_EBADSECT = 'Enum "%v" in scheme "%p" references unknown section "%1"',
SME_EBADOPT = 'Enum "%v" in scheme "%p" references unknown option "%1"',
SME_EBADTYPE = 'Enum "%v" in scheme "%p" references non-enum option "%I"',
SME_EBADDEF = 'Enum "%v" in scheme "%p" redeclares the default value of "%I"',
SECT_UNKNOWN = 'Section "%i" (%I) not found in scheme',
SECT_REQUIRED = 'Required section "%p.%S" not found in config',
SECT_UNIQUE = 'Unique section "%p.%S" occurs multiple times in config',
SECT_NAMED = 'The section of type "%p.%S" is stored anonymously in config but must be named',
SECT_NOTFOUND = 'Section "%p.%s" not found in config',
OPT_UNKNOWN = 'Option "%i" (%I) not found in scheme',
OPT_REQUIRED = 'Required option "%i" has no value',
OPT_BADVALUE = 'Value "%1" of option "%i" is not defined in enum %2',
OPT_INVVALUE = 'Value "%1" of option "%i" does not validate as datatype "%2"',
OPT_NOTLIST = 'Option "%i" is defined as list but stored as plain value',
OPT_DATATYPE = 'Option "%i" has unknown datatype "%1"',
OPT_NOTFOUND = 'Option "%p.%s.%o" not found in config',
OPT_RANGE = 'Option "%p.%s.%o" is not within the specified range',
DEP_NOTEQUAL = 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"',
DEP_NOVALUE = 'Dependency (%1) failed:\nOption "%i" has no value',
DEP_NOTVALID = 'Dependency (%1) failed:\n%c',
DEP_RECURSIVE = 'Recursive dependency for option "%i" detected',
DEP_BADENUM = 'In dependency check for enum value "%i":\n%c'
}
function i18n(key)
if luci.i18n then
return luci.i18n.translate(key)
else
return key
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(ERRCODES[self.code] or self.code)
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
libs/uvl: fix syntax error introduced with r5861
|
libs/uvl: fix syntax error introduced with r5861
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
c383451d3dfb21dae15ed7ad39597990c6ea7f7b
|
commons/stress-test/wrk-config.lua
|
commons/stress-test/wrk-config.lua
|
local json = require("lib/json")
local data = require("lib/data")
local uuid = require("uuid")
local threadsCounter = 0
local function log(msg)
print(msg)
end
local function newSession()
sessionCounter = (sessionCounter and sessionCounter + 1) or 1
if maxSessions and (sessionCounter > maxSessions) then
--log(string.format("Stopping customer: %d", customerId))
wrk.thread:stop()
else
step = 1
reservationId = uuid()
end
end
function setup(thread)
threadsCounter = threadsCounter + 1
thread:set("customerId", threadsCounter)
end
function init(args)
local dir = args[1] or error("stress-test directory not provided")
maxSessions = args[2] and tonumber(args[2])
requestTemplates = json.loadFile(dir .. "/requests.json")
newSession()
end
function request()
req = data.request {
template = requestTemplates[step],
reservationId = reservationId,
customerId = "customer-" .. customerId
}
wrk.port = req.port
wrk.port = req.port
return wrk.format(req.method, req.path, req.headers, req.bodyStr)
end
function response()
if step == 6 then
newSession()
else
step = step + 1
end
end
--[[
done = function(summary, latency, requests)
log("------------------------------")
local errNr = summary.errors.status
log(string.format("Nr of erroneous responses: %d", errNr))
end
]]
function delay()
return 500
end
|
local json = require("lib/json")
local data = require("lib/data")
local uuid = require("uuid")
local threadsCounter = 0
local _ = uuid.randomseed(os.time()*10000)
local function log(msg)
print(msg)
end
local function newSession()
sessionCounter = (sessionCounter and sessionCounter + 1) or 1
if maxSessions and (sessionCounter > maxSessions) then
--log(string.format("Stopping customer: %d", customerId))
wrk.thread:stop()
else
step = 1
reservationId = uuid.new()
end
end
function setup(thread)
threadsCounter = threadsCounter + 1
thread:set("customerId", threadsCounter)
end
function init(args)
local dir = args[1] or error("stress-test directory not provided")
maxSessions = args[2] and tonumber(args[2])
requestTemplates = json.loadFile(dir .. "/requests.json")
newSession()
end
function request()
req = data.request {
template = requestTemplates[step],
reservationId = reservationId,
customerId = "customer-" .. customerId
}
wrk.port = req.port
wrk.port = req.port
return wrk.format(req.method, req.path, req.headers, req.bodyStr)
end
function response()
if step == 6 then
newSession()
else
step = step + 1
end
end
--[[
done = function(summary, latency, requests)
log("------------------------------")
local errNr = summary.errors.status
log(string.format("Nr of erroneous responses: %d", errNr))
end
]]
function delay()
return 500
end
|
fix uuid generation
|
fix uuid generation
|
Lua
|
mit
|
pawelkaczor/ddd-leaven-akka-v2,pawelkaczor/ddd-leaven-akka-v2,pawelkaczor/ddd-leaven-akka-v2
|
6c4248251c968c27ff33fe75d8afa8660b16958a
|
frontend/ui/widget/filechooser.lua
|
frontend/ui/widget/filechooser.lua
|
require "ui/widget/menu"
FileChooser = Menu:new{
height = Screen:getHeight(),
width = Screen:getWidth(),
path = lfs.currentdir(),
parent = nil,
show_hidden = false,
filter = function(filename) return true end,
}
function FileChooser:init()
self:changeToPath(self.path)
end
function FileChooser:changeToPath(path)
local dirs = {}
local files = {}
self.path = path
for f in lfs.dir(self.path) do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local filemode = lfs.attributes(filename, "mode")
if filemode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, f)
end
elseif filemode == "file" then
if self.file_filter(filename) then
table.insert(files, f)
end
end
end
end
table.sort(dirs)
if self.path ~= "/" then table.insert(dirs, 1, "..") end
table.sort(files)
self.item_table = {}
for _, dir in ipairs(dirs) do
table.insert(self.item_table, { text = dir.."/", path = self.path.."/"..dir })
end
for _, file in ipairs(files) do
table.insert(self.item_table, { text = file, path = self.path.."/"..file })
end
Menu.init(self) -- call parent's init()
end
function FileChooser:onMenuSelect(item)
if lfs.attributes(item.path, "mode") == "directory" then
UIManager:close(self)
self:changeToPath(item.path)
UIManager:show(self)
else
self:onFileSelect(item.path)
end
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
|
require "ui/widget/menu"
FileChooser = Menu:new{
height = Screen:getHeight(),
width = Screen:getWidth(),
path = lfs.currentdir(),
parent = nil,
show_hidden = false,
filter = function(filename) return true end,
}
function FileChooser:init()
self:changeToPath(self.path)
end
function FileChooser:compressPath(item_path)
-- compress paths like "test/pdf/../epub" into "test/epub"
local path = item_path
while path:match("/[^/]+[/][\\.][\\.]") do
path = path:gsub("/[^/]+[/][\\.][\\.]", "")
end
return path
end
function FileChooser:changeToPath(path)
path = self:compressPath(path)
local dirs = {}
local files = {}
self.path = path
for f in lfs.dir(self.path) do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local filemode = lfs.attributes(filename, "mode")
if filemode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, f)
end
elseif filemode == "file" then
if self.file_filter(filename) then
table.insert(files, f)
end
end
end
end
table.sort(dirs)
if self.path ~= "/" then table.insert(dirs, 1, "..") end
table.sort(files)
self.item_table = {}
for _, dir in ipairs(dirs) do
table.insert(self.item_table, { text = dir.."/", path = self.path.."/"..dir })
end
for _, file in ipairs(files) do
table.insert(self.item_table, { text = file, path = self.path.."/"..file })
end
Menu.init(self) -- call parent's init()
end
function FileChooser:onMenuSelect(item)
if lfs.attributes(item.path, "mode") == "directory" then
UIManager:close(self)
self:changeToPath(item.path)
UIManager:show(self)
else
self:onFileSelect(item.path)
end
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
|
compress paths like "test/pdf/../epub" into "test/epub" in FileChooser This patch fixes Bug #107
|
compress paths like "test/pdf/../epub" into "test/epub" in FileChooser
This patch fixes Bug #107
|
Lua
|
agpl-3.0
|
ashhher3/koreader,NickSavage/koreader,noname007/koreader,ashang/koreader,NiLuJe/koreader,houqp/koreader,Frenzie/koreader,Markismus/koreader,chrox/koreader,mwoz123/koreader,NiLuJe/koreader,robert00s/koreader,Hzj-jie/koreader,frankyifei/koreader,koreader/koreader,chihyang/koreader,pazos/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,poire-z/koreader,mihailim/koreader,apletnev/koreader,lgeek/koreader
|
607d4e1c78406a10d9c0ee4b614199177d30f666
|
agents/monitoring/lua/monitoring-agent.lua
|
agents/monitoring/lua/monitoring-agent.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local async = require('async')
local utils = require('utils')
local Object = require('core').Object
local fmt = require('string').format
local logging = require('logging')
local ConnectionStream = require('./lib/client/connection_stream').ConnectionStream
local misc = require('./lib/util/misc')
local States = require('./lib/states')
local stateFile = require('./lib/state_file')
local MonitoringAgent = Object:extend()
DEFAULT_STATE_DIRECTORY = '/var/run/agent/states'
function MonitoringAgent:sample()
local HTTP = require("http")
local Utils = require("utils")
local logging = require('logging')
local s = sigar:new()
local sysinfo = s:sysinfo()
local cpus = s:cpus()
local netifs = s:netifs()
local i = 1;
HTTP.createServer("0.0.0.0", 8080, function (req, res)
local body = Utils.dump({req=req,headers=req.headers}) .. "\n"
res:write_head(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end)
print("sigar.sysinfo = ".. Utils.dump(sysinfo))
while i <= #cpus do
print("sigar.cpus[".. i .."].info = ".. Utils.dump(cpus[i]:info()))
print("sigar.cpus[".. i .."].data = ".. Utils.dump(cpus[i]:data()))
i = i + 1
end
i = 1;
while i <= #netifs do
print("sigar.netifs[".. i .."].info = ".. Utils.dump(netifs[i]:info()))
print("sigar.netifs[".. i .."].usage = ".. Utils.dump(netifs[i]:usage()))
i = i + 1
end
logging.log(logging.CRIT, "Server listening at http://localhost:8080/")
end
function MonitoringAgent:_verifyState(callback)
callback = callback or function() end
if self._config == nil then
logging.log(logging.ERR, "statefile 'config' missing or invalid")
process.exit(1)
end
if self._config['id'] == nil then
logging.log(logging.ERR, "'id' is missing from 'config'")
process.exit(1)
end
if self._config['token'] == nil then
logging.log(logging.ERR, "'token' is missing from 'config'")
process.exit(1)
end
if self._config['endpoints'] == nil then
logging.log(logging.ERR, "'endpoints' is missing from 'config'")
process.exit(1)
end
-- Verify that the endpoint addresses are specified in the correct format
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
if #endpoints == 0 then
logging.log(logging.ERR, "at least one endpoint needs to be specified")
process.exit(1)
end
for i, address in ipairs(endpoints) do
if misc.splitAddress(address) == nil then
logging.log(logging.ERR, "endpoint needs to be specified in the following format ip:port")
process.exit(1)
end
end
logging.log(logging.INFO, "using id " .. self._config['id'])
callback()
end
function MonitoringAgent:loadStates(callback)
async.series({
-- Load the States
function(callback)
self._states:load(callback)
end,
-- Verify
function(callback)
self:_verifyState(callback)
end
}, callback)
end
function MonitoringAgent:connect(callback)
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
self._streams = ConnectionStream:new(self._config['id'], self._config['token'])
self._streams:on('error', function(err)
logging.log(logging.ERR, fmt('%s:%d -> %s', err.host, err.port, err.message))
end)
self._streams:createConnections(endpoints, callback)
end
function MonitoringAgent:initialize(stateDirectory, configFile)
if not stateDirectory then stateDirectory = virgo.default_state_unix_directory end
logging.log(logging.INFO, 'Using state directory ' .. stateDirectory)
self._states = States:new(stateDirectory)
self._config = virgo.config
end
function MonitoringAgent.run(options)
if not options then options = {} end
local agent = MonitoringAgent:new(options.stateDirectory, options.configFile)
async.waterfall({
function(callback)
agent:loadStates(callback)
end,
function(callback)
agent:connect(callback)
end
},
function(err)
if err then
logging.log(logging.ERR, err.message)
end
end)
end
return MonitoringAgent
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local async = require('async')
local utils = require('utils')
local Object = require('core').Object
local fmt = require('string').format
local logging = require('logging')
local ConnectionStream = require('./lib/client/connection_stream').ConnectionStream
local misc = require('./lib/util/misc')
local States = require('./lib/states')
local stateFile = require('./lib/state_file')
local MonitoringAgent = Object:extend()
function MonitoringAgent:sample()
local HTTP = require("http")
local Utils = require("utils")
local logging = require('logging')
local s = sigar:new()
local sysinfo = s:sysinfo()
local cpus = s:cpus()
local netifs = s:netifs()
local i = 1;
HTTP.createServer("0.0.0.0", 8080, function (req, res)
local body = Utils.dump({req=req,headers=req.headers}) .. "\n"
res:write_head(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end)
print("sigar.sysinfo = ".. Utils.dump(sysinfo))
while i <= #cpus do
print("sigar.cpus[".. i .."].info = ".. Utils.dump(cpus[i]:info()))
print("sigar.cpus[".. i .."].data = ".. Utils.dump(cpus[i]:data()))
i = i + 1
end
i = 1;
while i <= #netifs do
print("sigar.netifs[".. i .."].info = ".. Utils.dump(netifs[i]:info()))
print("sigar.netifs[".. i .."].usage = ".. Utils.dump(netifs[i]:usage()))
i = i + 1
end
logging.log(logging.CRIT, "Server listening at http://localhost:8080/")
end
function MonitoringAgent:_verifyState(callback)
callback = callback or function() end
if self._config == nil then
logging.log(logging.ERR, "statefile 'config' missing or invalid")
process.exit(1)
end
if self._config['id'] == nil then
logging.log(logging.ERR, "'id' is missing from 'config'")
process.exit(1)
end
if self._config['token'] == nil then
logging.log(logging.ERR, "'token' is missing from 'config'")
process.exit(1)
end
if self._config['endpoints'] == nil then
logging.log(logging.ERR, "'endpoints' is missing from 'config'")
process.exit(1)
end
-- Verify that the endpoint addresses are specified in the correct format
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
if #endpoints == 0 then
logging.log(logging.ERR, "at least one endpoint needs to be specified")
process.exit(1)
end
for i, address in ipairs(endpoints) do
if misc.splitAddress(address) == nil then
logging.log(logging.ERR, "endpoint needs to be specified in the following format ip:port")
process.exit(1)
end
end
logging.log(logging.INFO, "using id " .. self._config['id'])
callback()
end
function MonitoringAgent:loadStates(callback)
async.series({
-- Load the States
function(callback)
self._states:load(callback)
end,
-- Verify
function(callback)
self:_verifyState(callback)
end
}, callback)
end
function MonitoringAgent:connect(callback)
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
self._streams = ConnectionStream:new(self._config['id'], self._config['token'])
self._streams:on('error', function(err)
logging.log(logging.ERR, fmt('%s:%d -> %s', err.host, err.port, err.message))
end)
self._streams:createConnections(endpoints, callback)
end
function MonitoringAgent:initialize(stateDirectory, configFile)
if not stateDirectory then stateDirectory = virgo.default_state_unix_directory end
logging.log(logging.INFO, 'Using state directory ' .. stateDirectory)
self._states = States:new(stateDirectory)
self._config = virgo.config
end
function MonitoringAgent.run(options)
if not options then options = {} end
local agent = MonitoringAgent:new(options.stateDirectory, options.configFile)
async.waterfall({
function(callback)
agent:loadStates(callback)
end,
function(callback)
agent:connect(callback)
end
},
function(err)
if err then
logging.log(logging.ERR, err.message)
end
end)
end
return MonitoringAgent
|
fix monitoring-agent.lua
|
fix monitoring-agent.lua
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
f392820b360f87db06a2efa7a0ce93c880435b7a
|
hymn/inputhandler.lua
|
hymn/inputhandler.lua
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local InputHandler = Class "InputHandler"
local EntityStatics = require "hymn.staticdata.entitystatics"
function InputHandler:initialize(logicCore)
self.logicCore = logicCore
self.translate = GameMath.Vector2:new(0, 0)
end
local borderWidth = 20
local scrollSpeed = 500
function InputHandler:update(dt)
local width, height = love.graphics.getDimensions()
local x, y = love.mouse.getPosition()
-- border scrolling
if x < borderWidth then
self.translate.x = self.translate.x + scrollSpeed * dt
elseif x > width - borderWidth then
self.translate.x = self.translate.x - scrollSpeed * dt
end
if y < borderWidth then
self.translate.y = self.translate.y + scrollSpeed * dt
elseif y > height - borderWidth then
self.translate.y = self.translate.y - scrollSpeed * dt
end
-- dragging
if self.dragAnchor then
-- dbgprint
self.translate.x = x - self.dragAnchor.x
self.translate.y = y - self.dragAnchor.y
end
local w, h = self.logicCore.map:size()
self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0)
self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0)
end
function InputHandler:centerOn(x, y)
local width, height = love.graphics.getDimensions()
self.translate.x = -x + width/2
self.translate.y = -y + height/2
end
-- click-through prevention. sucky, sucky Quickie! ;)
function InputHandler:isToolBar(x, y)
local width, height = love.graphics.getDimensions()
return y > height - 50
end
function InputHandler:mousePressed(x, y, button)
if self:isToolBar(x, y) then
return
end
if button == "l" then
local position = GameMath.Vector2:new(x, y) - self.translate
self.dragAnchor = position
end
end
function InputHandler:mouseReleased(x, y, button)
self.dragAnchor = false
if self:isToolBar(x, y) then
return
end
local function isSelectable(entity)
return entity.player == self.logicCore.players[1] and entity.selectable
end
local position = GameMath.Vector2:new(x, y) - self.translate
local entityManager = self.logicCore.entityManager
local logicCore = self.logicCore
if button == "l" then
if self.mode == "build" then
local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1])
building:setPosition(position.x, position.y)
self:selectEntity(building.id)
self.mode = false
else
local entity, distance = entityManager:findClosestEntity(position, isSelectable)
self:selectEntity(entity and distance < 40 and entity.id)
end
elseif button == "r" then
if self.selection then
local entity = entityManager:entity(self.selection)
if self.mode ~= "path" then
self:setMode("path")
end
entity:addPathPoint(position)
end
end
end
function InputHandler:setMode(mode)
local entityManager = self.logicCore.entityManager
if mode == "path" then
local entity = entityManager:entity(self.selection)
entity:clearPath()
end
self.mode = mode
end
function InputHandler:keyPressed(key, unicode)
end
function InputHandler:selectEntity(entityId)
if self.selection ~= entityId then
self:setMode("selected")
self.selection = entityId
end
end
return InputHandler
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local InputHandler = Class "InputHandler"
local EntityStatics = require "hymn.staticdata.entitystatics"
function InputHandler:initialize(logicCore)
self.logicCore = logicCore
self.translate = GameMath.Vector2:new(0, 0)
end
local borderWidth = 20
local scrollSpeed = 500
function InputHandler:update(dt)
local width, height = love.graphics.getDimensions()
local x, y = love.mouse.getPosition()
-- border scrolling
if x < borderWidth then
self.translate.x = self.translate.x + scrollSpeed * dt
elseif x > width - borderWidth then
self.translate.x = self.translate.x - scrollSpeed * dt
end
if y < borderWidth then
self.translate.y = self.translate.y + scrollSpeed * dt
elseif y > height - borderWidth then
self.translate.y = self.translate.y - scrollSpeed * dt
end
-- dragging
if self.dragAnchor then
-- dbgprint
self.translate.x = x - self.dragAnchor.x
self.translate.y = y - self.dragAnchor.y
end
local w, h = self.logicCore.map:size()
self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0)
self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0)
end
function InputHandler:centerOn(x, y)
local width, height = love.graphics.getDimensions()
self.translate.x = -x + width/2
self.translate.y = -y + height/2
end
-- click-through prevention. sucky, sucky Quickie! ;)
function InputHandler:isToolBar(x, y)
local width, height = love.graphics.getDimensions()
return y > height - 50
end
function InputHandler:mousePressed(x, y, button)
if self:isToolBar(x, y) then
return
end
if button == "l" then
local position = GameMath.Vector2:new(x, y) - self.translate
self.dragClick = GameMath.Vector2:new(x, y)
self.dragAnchor = position
end
end
function InputHandler:mouseReleased(x, y, button)
if self.dragAnchor then
local d = GameMath.Vector2.distance(GameMath.Vector2:new(x,y), self.dragClick)
self.dragAnchor = false
if d > 5 then
return
end
end
if self:isToolBar(x, y) then
return
end
local function isSelectable(entity)
return entity.player == self.logicCore.players[1] and entity.selectable
end
local position = GameMath.Vector2:new(x, y) - self.translate
local entityManager = self.logicCore.entityManager
local logicCore = self.logicCore
if button == "l" then
if self.mode == "build" then
local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1])
building:setPosition(position.x, position.y)
self:selectEntity(building.id)
self.mode = false
else
local entity, distance = entityManager:findClosestEntity(position, isSelectable)
self:selectEntity(entity and distance < 40 and entity.id)
end
elseif button == "r" then
if self.selection then
local entity = entityManager:entity(self.selection)
if self.mode ~= "path" then
self:setMode("path")
end
entity:addPathPoint(position)
end
end
end
function InputHandler:setMode(mode)
local entityManager = self.logicCore.entityManager
if mode == "path" then
local entity = entityManager:entity(self.selection)
entity:clearPath()
end
self.mode = mode
end
function InputHandler:keyPressed(key, unicode)
end
function InputHandler:selectEntity(entityId)
if self.selection ~= entityId then
self:setMode("selected")
self.selection = entityId
end
end
return InputHandler
|
Hymn: Fix: dragging the map doesn't cancel flagpole mode
|
Hymn: Fix: dragging the map doesn't cancel flagpole mode
|
Lua
|
mit
|
ExcelF/project-navel
|
0930480fc6c0e655b5513f5e2e6b89cd91cca48a
|
deps/tls/init.lua
|
deps/tls/init.lua
|
--[[
Copyright 2014-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 loaded = pcall(require, 'openssl')
if not loaded then return end
local _common_tls = require('./common')
local net = require('net')
local DEFAULT_CIPHERS = _common_tls.DEFAULT_CIPHERS
local extend = function(...)
local args = {...}
local obj = args[1]
for i=2, #args do
for k,v in pairs(args[i]) do
obj[k] = v
end
end
return obj
end
local Server = net.Server:extend()
function Server:init(options, connectionListener)
options = options or {}
options.server = true
local sharedCreds = _common_tls.createCredentials(options)
net.Server.init(self, options, function(raw_socket)
local socket
socket = _common_tls.TLSSocket:new(raw_socket, {
secureContext = sharedCreds,
isServer = true,
requestCert = options.requestCert,
rejectUnauthorized = options.rejectUnauthorized,
})
socket:on('secureConnection', function()
connectionListener(socket)
end)
socket:on('error',function(err)
connectionListener(socket,err)
end)
self.socket = socket
if self.sni_hosts then
socket:sni(self.sni_hosts)
end
end)
end
function Server:sni(hosts)
self.sni_hosts = hosts
end
local DEFAULT_OPTIONS = {
ciphers = DEFAULT_CIPHERS,
rejectUnauthorized = true,
-- TODO checkServerIdentity
}
local function connect(options, callback)
local hostname, port, sock
callback = callback or function() end
options = extend({}, DEFAULT_OPTIONS, options or {})
port = options.port
hostname = options.host or options.hostname
sock = _common_tls.TLSSocket:new(nil, options)
sock:connect(port, hostname, callback)
return sock
end
local function createServer(options, secureCallback)
local server = Server:new()
server:init(options, secureCallback)
return server
end
return {
TLSSocket = _common_tls.TLSSocket,
createCredentials = _common_tls.createCredentials,
connect = connect,
createServer = createServer,
}
|
--[[
Copyright 2014-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 loaded = pcall(require, 'openssl')
if not loaded then return end
local _common_tls = require('./common')
local net = require('net')
local DEFAULT_CIPHERS = _common_tls.DEFAULT_CIPHERS
local extend = function(...)
local args = {...}
local obj = args[1]
for i=2, #args do
for k,v in pairs(args[i]) do
obj[k] = v
end
end
return obj
end
local Server = net.Server:extend()
function Server:init(options, connectionListener)
options = options or {}
options.server = true
local sharedCreds = _common_tls.createCredentials(options)
net.Server.init(self, options, function(raw_socket)
local socket
socket = _common_tls.TLSSocket:new(raw_socket, {
secureContext = sharedCreds,
isServer = true,
requestCert = options.requestCert,
rejectUnauthorized = options.rejectUnauthorized,
})
socket:on('secureConnection', function()
connectionListener(socket)
end)
socket:on('error',function(err)
connectionListener(socket,err)
end)
self.socket = socket
if self.sni_hosts then
socket:sni(self.sni_hosts)
end
end)
end
function Server:sni(hosts)
self.sni_hosts = hosts
end
local DEFAULT_OPTIONS = {
ciphers = DEFAULT_CIPHERS,
rejectUnauthorized = true,
-- TODO checkServerIdentity
}
local function connect(options, callback)
local hostname, port, sock, colon
callback = callback or function() end
options = extend({}, DEFAULT_OPTIONS, options or {})
port = options.port
hostname = options.host or options.hostname
colon = hostname:find(':')
if colon then
hostname = hostname:sub(1, colon-1 )
end
sock = _common_tls.TLSSocket:new(nil, options)
sock:connect(port, hostname, callback)
return sock
end
local function createServer(options, secureCallback)
local server = Server:new()
server:init(options, secureCallback)
return server
end
return {
TLSSocket = _common_tls.TLSSocket,
createCredentials = _common_tls.createCredentials,
connect = connect,
createServer = createServer,
}
|
fixup c9cbddbef3e9939d474fed878897bb7f726d7477
|
fixup c9cbddbef3e9939d474fed878897bb7f726d7477
|
Lua
|
apache-2.0
|
zhaozg/luvit,zhaozg/luvit,luvit/luvit,luvit/luvit
|
87eaa3fd97700968aa7ce1fa9e95dc0f06cdf3aa
|
DistanceRatioCriterion.lua
|
DistanceRatioCriterion.lua
|
require 'nn'
local DistanceRatioCriterion, parent = torch.class('nn.DistanceRatioCriterion', 'nn.Criterion')
function DistanceRatioCriterion:__init()
parent.__init(self)
self.SoftMax = nn.SoftMax()
self.MSE = nn.MSECriterion()
self.Target = torch.Tensor()
end
function DistanceRatioCriterion:createTarget(input, target)
local target = target or 1
self.Target:resizeAs(input):typeAs(input):zero()
self.Target[{{},target}]:add(1)
end
function DistanceRatioCriterion:updateOutput(input, target)
if not self.Target:isSameSizeAs(input) then
self:createTarget(input, target)
end
self.output = self.MSE:updateOutput(self.SoftMax:updateOutput(input),self.Target)
return self.output
end
function DistanceRatioCriterion:updateGradInput(input, target)
if not self.Target:isSameSizeAs(input) then
self:createTarget(input, target)
end
self.gradInput = self.SoftMax:updateGradInput(input, self.MSE:updateGradInput(input,self.Target))
return self.gradInput
end
function DistanceRatioCriterion:type(t)
parent.type(self, t)
self.SoftMax:type(t)
self.MSE:type(t)
self.Target = self.Target:type(t)
end
|
require 'nn'
local DistanceRatioCriterion, parent = torch.class('nn.DistanceRatioCriterion', 'nn.Criterion')
function DistanceRatioCriterion:__init()
parent.__init(self)
self.SoftMax = nn.SoftMax()
self.MSE = nn.MSECriterion()
self.Target = torch.Tensor()
end
function DistanceRatioCriterion:createTarget(input, target)
local target = target or 1
self.Target:resizeAs(input):typeAs(input):zero()
self.Target[{{},target}]:add(1)
end
function DistanceRatioCriterion:updateOutput(input, target)
if not self.Target:isSameSizeAs(input) then
self:createTarget(input, target)
end
self.output = self.MSE:updateOutput(self.SoftMax:updateOutput(input),self.Target)
return self.output
end
function DistanceRatioCriterion:updateGradInput(input, target)
if not self.Target:isSameSizeAs(input) then
self:createTarget(input, target)
end
self.gradInput = self.SoftMax:updateGradInput(input, self.MSE:updateGradInput(self.SoftMax.output,self.Target))
return self.gradInput
end
function DistanceRatioCriterion:type(t)
parent.type(self, t)
self.SoftMax:type(t)
self.MSE:type(t)
self.Target = self.Target:type(t)
return self
end
|
bug fix
|
bug fix
|
Lua
|
mit
|
fantajeon/TripletNet,fantajeon/TripletNet,fantajeon/TripletNet,fantajeon/TripletNet
|
35e2cfdb12f38570f9e83f49cf493f1c229f894e
|
battery-widget/battery.lua
|
battery-widget/battery.lua
|
-------------------------------------------------
-- Battery Widget for Awesome Window Manager
-- Shows the battery status using the ACPI tool
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/battery-widget
-- @author Pavel Makhov
-- @copyright 2017 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local naughty = require("naughty")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
-- acpi sample outputs
-- Battery 0: Discharging, 75%, 01:51:38 remaining
-- Battery 0: Charging, 53%, 00:57:43 until charged
local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/"
local HOME = os.getenv("HOME")
local battery_widget = wibox.widget {
{
id = "icon",
widget = wibox.widget.imagebox,
resize = false
},
layout = wibox.container.margin(_, 0, 0, 3)
}
-- Popup with battery info
-- One way of creating a pop-up notification - naughty.notify
local notification
local function show_battery_status()
awful.spawn.easy_async([[bash -c 'acpi']],
function(stdout, _, _, _)
notification = naughty.notify{
text = stdout,
title = "Battery status",
timeout = 5, hover_timeout = 0.5,
width = 200,
}
end
)
end
-- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one
--battery_popup = awful.tooltip({objects = {battery_widget}})
-- To use colors from beautiful theme put
-- following lines in rc.lua before require("battery"):
-- beautiful.tooltip_fg = beautiful.fg_normal
-- beautiful.tooltip_bg = beautiful.bg_normal
local function show_battery_warning()
naughty.notify{
icon = HOME .. "/.config/awesome/nichosi.png",
icon_size=100,
text = "Huston, we have a problem",
title = "Battery is dying",
timeout = 5, hover_timeout = 0.5,
position = "bottom_right",
bg = "#F06060",
fg = "#EEE9EF",
width = 300,
}
end
local last_battery_check = os.time()
watch("acpi -i", 10,
function(widget, stdout, stderr, exitreason, exitcode)
local batteryType
local battery_info = {}
local capacities = {}
for s in stdout:gmatch("[^\r\n]+") do
local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*')
if status ~= nil then
table.insert(battery_info, {status = status, charge = tonumber(charge_str)})
else
local cap_str = string.match(s, '.+:.+last full capacity (%d+)')
table.insert(capacities, tonumber(cap_str))
end
end
local capacity = 0
for i, cap in ipairs(capacities) do
capacity = capacity + cap
end
local charge = 0
local status
for i, batt in ipairs(battery_info) do
if batt.charge >= charge then
status = batt.status -- use most charged battery status
-- this is arbitrary, and maybe another metric should be used
end
charge = charge + batt.charge * capacities[i]
end
charge = charge / capacity
if (charge >= 0 and charge < 15) then
batteryType = "battery-empty%s-symbolic"
if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then
-- if 5 minutes have elapsed since the last warning
last_battery_check = time()
show_battery_warning()
end
elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic"
elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic"
elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic"
elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic"
end
if status == 'Charging' then
batteryType = string.format(batteryType, '-charging')
else
batteryType = string.format(batteryType, '')
end
widget.icon:set_image(PATH_TO_ICONS .. batteryType .. ".svg")
-- Update popup text
-- battery_popup.text = string.gsub(stdout, "\n$", "")
end,
battery_widget)
battery_widget:connect_signal("mouse::enter", function() show_battery_status() end)
battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
return battery_widget
|
-------------------------------------------------
-- Battery Widget for Awesome Window Manager
-- Shows the battery status using the ACPI tool
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/battery-widget
-- @author Pavel Makhov
-- @copyright 2017 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local naughty = require("naughty")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
-- acpi sample outputs
-- Battery 0: Discharging, 75%, 01:51:38 remaining
-- Battery 0: Charging, 53%, 00:57:43 until charged
local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/"
local HOME = os.getenv("HOME")
local battery_widget = wibox.widget {
{
id = "icon",
widget = wibox.widget.imagebox,
resize = false
},
layout = wibox.container.margin(_, 0, 0, 3)
}
-- Popup with battery info
-- One way of creating a pop-up notification - naughty.notify
local notification
local function show_battery_status()
awful.spawn.easy_async([[bash -c 'acpi']],
function(stdout, _, _, _)
notification = naughty.notify{
text = stdout,
title = "Battery status",
timeout = 5, hover_timeout = 0.5,
width = 200,
}
end
)
end
-- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one
--battery_popup = awful.tooltip({objects = {battery_widget}})
-- To use colors from beautiful theme put
-- following lines in rc.lua before require("battery"):
-- beautiful.tooltip_fg = beautiful.fg_normal
-- beautiful.tooltip_bg = beautiful.bg_normal
local function show_battery_warning()
naughty.notify{
icon = HOME .. "/.config/awesome/nichosi.png",
icon_size=100,
text = "Huston, we have a problem",
title = "Battery is dying",
timeout = 5, hover_timeout = 0.5,
position = "bottom_right",
bg = "#F06060",
fg = "#EEE9EF",
width = 300,
}
end
local last_battery_check = os.time()
watch("acpi -i", 10,
function(widget, stdout, stderr, exitreason, exitcode)
local batteryType
local battery_info = {}
local capacities = {}
for s in stdout:gmatch("[^\r\n]+") do
local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*')
if string.match(s, 'rate information') then
-- ignore such line
elseif status ~= nil then
table.insert(battery_info, {status = status, charge = tonumber(charge_str)})
else
local cap_str = string.match(s, '.+:.+last full capacity (%d+)')
table.insert(capacities, tonumber(cap_str))
end
end
local capacity = 0
for i, cap in ipairs(capacities) do
capacity = capacity + cap
end
local charge = 0
local status
for i, batt in ipairs(battery_info) do
if batt.charge >= charge then
status = batt.status -- use most charged battery status
-- this is arbitrary, and maybe another metric should be used
end
charge = charge + batt.charge * capacities[i]
end
charge = charge / capacity
if (charge >= 0 and charge < 15) then
batteryType = "battery-empty%s-symbolic"
if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then
-- if 5 minutes have elapsed since the last warning
last_battery_check = time()
show_battery_warning()
end
elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic"
elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic"
elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic"
elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic"
end
if status == 'Charging' then
batteryType = string.format(batteryType, '-charging')
else
batteryType = string.format(batteryType, '')
end
widget.icon:set_image(PATH_TO_ICONS .. batteryType .. ".svg")
-- Update popup text
-- battery_popup.text = string.gsub(stdout, "\n$", "")
end,
battery_widget)
battery_widget:connect_signal("mouse::enter", function() show_battery_status() end)
battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
return battery_widget
|
fix battery widget bug when no status was shown due to missing information from acpi
|
fix battery widget bug when no status was shown due to missing information from acpi
|
Lua
|
mit
|
streetturtle/AwesomeWM,streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
49589232ac99b20b4369b047b4c587229ed36bf7
|
source/utilities/extensions/io.lua
|
source/utilities/extensions/io.lua
|
--------------------------------------------------------------------------------
-- io.lua - Contains functions that extend the default io functions
--------------------------------------------------------------------------------
require "lfs"
-- source: http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists
function io.fileExists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
function io.files(dir)
local files = {}
if io.fileExists(dir) then
for file in lfs.dir(dir) do
local fullPath = dir .. file
if lfs.attributes(fullPath,"mode") == "file" then
table.insert(files, fullPath)
end
end
end
return files
end
|
--------------------------------------------------------------------------------
-- io.lua - Contains functions that extend the default io functions
--------------------------------------------------------------------------------
require "lfs"
-- source: http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists
function io.fileExists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
function io.files(dir)
local files = {}
for file in lfs.dir(dir) do
local fullPath = dir .. file
print(fullPath)
if lfs.attributes(fullPath,"mode") == "file" then
table.insert(files, fullPath)
end
end
return files
end
|
Attempt at fixing no sound on windows.
|
Attempt at fixing no sound on windows.
|
Lua
|
mit
|
BryceMehring/Hexel
|
291c4b0275febfc578de20659ec4c3301dfd139b
|
fusion/stdlib/iterable.lua
|
fusion/stdlib/iterable.lua
|
local fnl = require("fusion.stdlib.functional")
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
-- Infinite generators
local function count(start, step)
if not step then
return count(start, 1)
end
while true do
start = start + step
coroutine.yield(start)
end
end
local function cycle(pattern, is_ipairs)
local pairs_statement = is_ipairs and ipairs or pairs
while true do
for k, v in pairs_statement(pattern) do
coroutine.yield(k, v)
end
end
end
local function rep(element, n)
if n then
for i=1, n do
coroutine.yield(element)
end
else
while true do
coroutine.yield(element)
end
end
end
-- Terminating generators
local function range(start, stop, step)
if not step then
return range(start, stop, 1)
elseif not stop then
return range(1, start, 1)
else
for i=start, stop, step do
coroutine.yield(i)
end
end
end
local function add(x, y)
return x + y
end
local xrange = mk_gen(range)
local function accumulate(input, fn)
if not fn then
return accumulate(input, add)
end
for i in xrange(#input) do
local t0 = {}
for j in xrange(1, i) do
t0[j] = input[j]
end
coroutine.yield(fnl.reduce(fn, t0))
end
end
local function chain(...)
for k, v in pairs({...}) do
for _k, _v in pairs(v) do
coroutine.yield(_v)
end
end
end
local function ichain(...)
for i, v in ipairs({...}) do
for _i, _v in ipairs(v) do
coroutine.yield(_v)
end
end
end
local function compress(input, selectors)
-- must use ipairs and numeric input/selectors
for i=1, math.max(#input, #selectors) do
if not input[i] then
return
else
if selectors[i] then
coroutine.yield(input[i])
end
end
end
end
local function slice(input, start, stop, step)
if not step then
return slice(input, start, stop, 1)
elseif not stop then
return slice(input, start, #input, 1)
end
for i in xrange(start, stop, step) do
coroutine.yield(input[i])
end
end
local function zip(input0, input1, default)
for i=1, math.max(#input0, #input1) do
coroutine.yield(input0[i], input1[i] or default)
end
end
-- Extended module
return fnl.map(mk_gen, {
count = count;
cycle = cycle;
rep = rep;
range = range;
accumulate = accumulate;
chain = chain;
ichain = ichain;
compress = compress;
slice = slice;
zip = zip;
})
|
local fnl = require("fusion.stdlib.functional")
local table = require("fusion.stdlib.table")
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
-- Infinite generators
local function count(start, step)
if not step then
return count(start, 1)
end
if not start then
return count(1, step)
end
while true do
coroutine.yield(start)
start = start + step
end
end
local function cycle(pattern, is_ipairs)
local pairs_statement = is_ipairs and ipairs or pairs
while true do
for k, v in pairs_statement(pattern) do
coroutine.yield(k, v)
end
end
end
local function rep(element, n)
if n then
for i=1, n do
coroutine.yield(element)
end
else
while true do
coroutine.yield(element)
end
end
end
-- Terminating generators
local function range(start, stop, step)
if not step then
return range(start, stop, 1)
elseif not stop then
return range(1, start, 1)
else
for i=start, stop, step do
coroutine.yield(i)
end
end
end
local function add(x, y)
return x + y
end
local xrange = mk_gen(range)
local function accumulate(input, fn)
if not fn then
return accumulate(input, add)
end
for i in xrange(#input) do
local t0 = {}
for j in xrange(1, i) do
t0[j] = input[j]
end
coroutine.yield(fnl.reduce(fn, t0))
end
end
local function chain(...)
for k, v in pairs({...}) do
if type(v) == "function" then
for val in v do
coroutine.yield(val)
end
else
for _k, _v in pairs(v) do
coroutine.yield(_v)
end
end
end
end
local function ichain(...)
for i, v in ipairs({...}) do
for _i, _v in ipairs(v) do
coroutine.yield(_v)
end
end
end
local function compress(input, selectors)
-- must use ipairs and numeric input/selectors
for i=1, math.max(#input, #selectors) do
if not input[i] then
return
else
if selectors[i] then
coroutine.yield(input[i])
end
end
end
end
local function groupby(input)
local _prev, _gen
for k, v in pairs(input) do
_gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
coroutine.yield(_prev, pairs(_gen))
end
local function igroupby(input)
local _prev
for i, v in ipairs(input) do
local _gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
end
local function slice(input, start, stop, step)
if not step then
return slice(input, start, stop, 1)
elseif not stop then
return slice(input, start, #input, 1)
end
for i in xrange(start, stop, step) do
coroutine.yield(input[i])
end
end
local function zip(input0, input1, default)
for i=1, math.max(#input0, #input1) do
coroutine.yield(input0[i], input1[i] or default)
end
end
-- Extended module
local xslice = mk_gen(slice)
local function take(n, input)
return table.from_generator(xslice(input, n))
end
local xcount = mk_gen(count)
local function tabulate(fn, start)
for n in xcount(start or 0) do
fn(n)
end
end
local function tail(n, input)
return table.from_generator(xslice(input, n))
end
local function consume(iterator, n)
for i in xrange(n) do
iterator()
end
return iterator
end
local function nth(n, input, default)
return input[n] or default
end
local xgroupby = mk_gen(groupby)
local function all_equal(input)
local _iter = xgroupby(input)
_iter() -- capture first input
if not _iter() then
return true
else
return false
end
end
local function truthy(val)
return not not val
end
local function quantify(input, fn)
if not fn then
return quantify(input, truthy)
end
local _val = 0
for _, n in pairs(fnl.map(fn, table.copy(input))) do
if n then
_val = _val + 1
end
end
return _val
end
local xrep = mk_gen(rep)
local xchain = mk_gen(chain)
local function padnil(input)
return xchain(input, xrep(nil))
end
local function dotproduct(t0, t1)
return fnl.sum(fnl.map((function(a, b) return a * b end), t0, t1))
end
return table.join(fnl.map(mk_gen, {
count = count;
cycle = cycle;
rep = rep;
range = range;
accumulate = accumulate;
chain = chain;
ichain = ichain;
compress = compress;
groupby = groupby;
slice = slice;
zip = zip;
}), {
take = take;
tabulate = tabulate;
tail = tail;
consume = consume;
nth = nth;
all_equal = all_equal;
quantify = quantify;
padnil = padnil;
dotproduct = dotproduct;
})
|
iterable: fix chain() to support iterators, groupby(), and non-generators
|
iterable: fix chain() to support iterators, groupby(), and non-generators
|
Lua
|
mit
|
RyanSquared/FusionScript
|
1b938d5eac28480f0aca7e1f3175658f0abbe365
|
minionmaster/behaviors/behaviors.lua
|
minionmaster/behaviors/behaviors.lua
|
local Class = require "shared.middleclass"
local blocking = require "shared.blocking"
local BehaviorTree = require "shared.behaviortree"
local Behavior = BehaviorTree.Behavior
local STATUS = Behavior.static.STATUS
local state = require "minionmaster.state"
local SearchEnemyBehavior = Class("SearchEnemyBehavior", Behavior)
function SearchEnemyBehavior:update(dt, context)
local object = context.object
object.target = object:findNearestEnemy(object.position, object.attackRange)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local SearchMinionBehavior = Class("SearchMinionBehavior", Behavior)
function SearchMinionBehavior:update(dt, context)
local object = context.object
object.target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "minion"
end,
object.attackRange
)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local SearchMasterBehavior = Class("SearchMasterBehavior", Behavior)
function SearchMasterBehavior:update(dt, context)
local object = context.object
object.target = state.master
self.status = STATUS.SUCCESS
return self.status
end
local SearchNearestBehavior = Class("SearchNearestBehavior", Behavior)
function SearchNearestBehavior:update(dt, context)
local object = context.object
object.target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "master" or entity.type == "minion"
end,
object.attackRange
)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local GotoTargetBehavior = Class("GotoTargetBehavior", Behavior)
function GotoTargetBehavior:update(dt, context)
local object = context.object
object:moveTo(object.target.position.x, object.target.position.y, object.target.spriteSize / 2)
if not object.waypoints or #object.waypoints < 1 then
self.status = STATUS.FAILURE
else
self.status = object:updateMove(dt) and STATUS.SUCCESS or STATUS.RUNNING
end
return self.status
end
local GotoTargetWithEnemySearchBehavior = Class("GotoTargetWithEnemySearchBehavior", GotoTargetBehavior)
function GotoTargetWithEnemySearchBehavior:initialize()
self.time = 0
end
function GotoTargetWithEnemySearchBehavior:update(dt, context)
local object = context.object
self.time = self.time - dt
if self.time <= 0 and object.target.type ~= "enemy" then
local target = object:findNearestEnemy(object.position, object.attackRange)
self.time = 1
if target and blocking.pathExists(object.position.x, object.position.y, target.position.x, target.position.y) then
object.target = target
self.status = STATUS.FAILURE
end
end
local status = GotoTargetBehavior.update(self, dt, context)
if self.status ~= STATUS.FAILURE then
self.status = status
end
return self.status
end
local GotoTargetWithMinionSearchBehavior = Class("GotoTargetWithMinionSearchBehavior", GotoTargetBehavior)
function GotoTargetWithMinionSearchBehavior:initialize()
self.time = 0
end
function GotoTargetWithMinionSearchBehavior:update(dt, context)
local object = context.object
self.time = self.time - dt
if self.time <= 0 and object.target.type ~= "minion" then
local target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "minion"
end,
object.attackRange
)
self.time = 1
if target and blocking.pathExists(object.position.x, object.position.y, target.position.x, target.position.y) then
object.target = target
self.status = STATUS.FAILURE
end
end
local status = GotoTargetBehavior.update(self, dt, context)
if self.status ~= STATUS.FAILURE then
self.status = status
end
return self.status
end
local AttackBehavior = Class("AttackBehavior", Behavior)
function AttackBehavior:update(dt, context)
local object = context.object
local reached, dir, length = object:reachedTarget(object.target.position, dt * object.speed)
if length < object.target.spriteSize / 2 then
object.attack = true
object.target:takeDamage(object.damage * dt)
if object.target.health <= 0 then
object.attack = false
self.status = STATUS.SUCCESS
return self.status
end
self.status = STATUS.RUNNING
else
object.attack = false
self.status = STATUS.FAILURE
end
return self.status
end
return {
SearchEnemyBehavior = SearchEnemyBehavior,
SearchMinionBehavior = SearchMinionBehavior,
SearchMasterBehavior = SearchMasterBehavior,
SearchNearestBehavior = SearchNearestBehavior,
GotoTargetBehavior = GotoTargetBehavior,
GotoTargetWithEnemySearchBehavior = GotoTargetWithEnemySearchBehavior,
GotoTargetWithMinionSearchBehavior = GotoTargetWithMinionSearchBehavior,
AttackBehavior = AttackBehavior,
}
|
local Class = require "shared.middleclass"
local blocking = require "shared.blocking"
local BehaviorTree = require "shared.behaviortree"
local Behavior = BehaviorTree.Behavior
local STATUS = Behavior.static.STATUS
local state = require "minionmaster.state"
local SearchEnemyBehavior = Class("SearchEnemyBehavior", Behavior)
function SearchEnemyBehavior:update(dt, context)
local object = context.object
object.target = object:findNearestEnemy(object.position, object.attackRange)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local SearchMinionBehavior = Class("SearchMinionBehavior", Behavior)
function SearchMinionBehavior:update(dt, context)
local object = context.object
object.target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "minion"
end,
object.attackRange
)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local SearchMasterBehavior = Class("SearchMasterBehavior", Behavior)
function SearchMasterBehavior:update(dt, context)
local object = context.object
if object.type == "minion" or (state.master.position - object.position):sqLength() < object.attackRange * object.attackRange then
object.target = state.master
self.status = STATUS.SUCCESS
else
self.status = STATUS.FAILURE
end
return self.status
end
local SearchNearestBehavior = Class("SearchNearestBehavior", Behavior)
function SearchNearestBehavior:update(dt, context)
local object = context.object
object.target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "master" or entity.type == "minion"
end,
object.attackRange
)
self.status = object.target and STATUS.SUCCESS or STATUS.FAILURE
return self.status
end
local GotoTargetBehavior = Class("GotoTargetBehavior", Behavior)
function GotoTargetBehavior:update(dt, context)
local object = context.object
object:moveTo(object.target.position.x, object.target.position.y, object.target.spriteSize / 2)
if not object.waypoints or #object.waypoints < 1 then
self.status = STATUS.FAILURE
else
self.status = object:updateMove(dt) and STATUS.SUCCESS or STATUS.RUNNING
end
return self.status
end
local GotoTargetWithEnemySearchBehavior = Class("GotoTargetWithEnemySearchBehavior", GotoTargetBehavior)
function GotoTargetWithEnemySearchBehavior:initialize()
self.time = 0
end
function GotoTargetWithEnemySearchBehavior:update(dt, context)
local object = context.object
self.time = self.time - dt
if self.time <= 0 and object.target.type ~= "enemy" then
local target = object:findNearestEnemy(object.position, object.attackRange)
self.time = 1
if target and blocking.pathExists(object.position.x, object.position.y, target.position.x, target.position.y) then
object.target = target
self.status = STATUS.FAILURE
end
end
local status = GotoTargetBehavior.update(self, dt, context)
if self.status ~= STATUS.FAILURE then
self.status = status
end
return self.status
end
local GotoTargetWithMinionSearchBehavior = Class("GotoTargetWithMinionSearchBehavior", GotoTargetBehavior)
function GotoTargetWithMinionSearchBehavior:initialize()
self.time = 0
end
function GotoTargetWithMinionSearchBehavior:update(dt, context)
local object = context.object
self.time = self.time - dt
if self.time <= 0 and object.target.type ~= "minion" then
local target = state.entityManager:findClosestEntity(object.position,
function(entity)
return not entity.dead and entity.type == "minion"
end,
object.attackRange
)
self.time = 1
if target and blocking.pathExists(object.position.x, object.position.y, target.position.x, target.position.y) then
object.target = target
self.status = STATUS.FAILURE
end
end
local status = GotoTargetBehavior.update(self, dt, context)
if self.status ~= STATUS.FAILURE then
self.status = status
end
return self.status
end
local AttackBehavior = Class("AttackBehavior", Behavior)
function AttackBehavior:update(dt, context)
local object = context.object
local reached, dir, length = object:reachedTarget(object.target.position, dt * object.speed)
if length < object.target.spriteSize / 2 then
object.attack = true
object.target:takeDamage(object.damage * dt)
if object.target.health <= 0 then
object.attack = false
self.status = STATUS.SUCCESS
return self.status
end
self.status = STATUS.RUNNING
else
object.attack = false
self.status = STATUS.FAILURE
end
return self.status
end
return {
SearchEnemyBehavior = SearchEnemyBehavior,
SearchMinionBehavior = SearchMinionBehavior,
SearchMasterBehavior = SearchMasterBehavior,
SearchNearestBehavior = SearchNearestBehavior,
GotoTargetBehavior = GotoTargetBehavior,
GotoTargetWithEnemySearchBehavior = GotoTargetWithEnemySearchBehavior,
GotoTargetWithMinionSearchBehavior = GotoTargetWithMinionSearchBehavior,
AttackBehavior = AttackBehavior,
}
|
fixed enemy master search behavior
|
fixed enemy master search behavior
|
Lua
|
mit
|
ExcelF/project-navel
|
24448cce6247bdfdcd1b81f603902249ef9fdbb0
|
scheduled/showGFX.lua
|
scheduled/showGFX.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/>.
]]
require("base.common")
require("base.character")
module("scheduled.showGFX", package.seeall)
-- INSERT INTO scheduledscripts VALUES('scheduled.showGFX', 10, 10, 'CreateGFX');
-- this script is used to show a ceratin graphic effect on a certain position every ten seconds
SlimeList = {}
SlimeList.Slime1 = {}
SlimeList.Slime2 = {}
function CreateGFX()
world:gfx(1,position(75,651,0)) -- thinking stone
world:gfx(11,position(873,878,0)) -- recognizing spring
world:gfx(7,position(432,238,0)) -- knowing tree
-- Glutinous Seedling
local myPos = position(376+math.random(-1,1), 288+math.random(-1,1), 0)
world:gfx(11,myPos)
if world:isCharacterOnField(myPos) then
local myChar = world:getCharacterOnField(myPos)
if base.character.IsPlayer(myChar) then
myChar:talk(Character.say, "#mes Fe werden von einem groen Schleimtropfen, der sich vom schleimigen Setzling gelst hat, getroffen.","#me's feet are hit by a big drop of slime, which has come off from the glutinous seedling.")
end
else
SpawnSlime(myPos)
end
-- Glutinous Seedling end
end
function SpawnSlime(thePos)
if checkSlime(SlimeList.Slime1) then
CreateSlime(SlimeList.Slime1,thePos,1)
end
if checkSlime(SlimeList.Slime2) then
CreateSlime(SlimeList.Slime2,thePos,2)
end
end
function CreateSlime(ListSlime,thePos,slimeNumber)
local mon = world:createMonster(615,thePos,-10)
ListSlime.Monster = true
base.character.DeathAfterTime(mon,18000,11,9,false)
find, Effect = mon.effects:find(36)
if not find then
debug("Error: Effect not found.")
else
Effect:addValue("GlutinousSeedling",slimeNumber)
end
end
function checkSlime(ListSlime)
if ListSlime.Monster == nil then
return true
end
if ListSlime.Monster == false then
if (ListSlime.Time - world:getTime("unix")) >= 900 then
return true
end
end
return false
end
|
--[[
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/>.
]]
require("base.common")
require("base.character")
module("scheduled.showGFX", package.seeall)
-- INSERT INTO scheduledscripts VALUES('scheduled.showGFX', 10, 10, 'CreateGFX');
-- this script is used to show a ceratin graphic effect on a certain position every ten seconds
SlimeList = {}
SlimeList.Slime1 = {}
SlimeList.Slime2 = {}
function CreateGFX()
world:gfx(1,position(75,651,0)) -- thinking stone
world:gfx(11,position(873,878,0)) -- recognizing spring
world:gfx(7,position(432,238,0)) -- knowing tree
-- Glutinous Seedling
local myPos = position(376+math.random(-1,1), 288+math.random(-1,1), 0)
world:gfx(11,myPos)
if world:isCharacterOnField(myPos) then
local myChar = world:getCharacterOnField(myPos)
if base.character.IsPlayer(myChar) then
myChar:talk(Character.say, "#mes Fe werden von einem groen Schleimtropfen, der sich vom schleimigen Setzling gelst hat, getroffen.","#me's feet are hit by a big drop of slime, which has come off from the glutinous seedling.")
end
else
SpawnSlime(myPos)
end
-- Glutinous Seedling end
end
function SpawnSlime(thePos)
if checkSlime(SlimeList.Slime1) then
CreateSlime(SlimeList.Slime1,thePos,1)
return;
end
if checkSlime(SlimeList.Slime2) then
CreateSlime(SlimeList.Slime2,thePos,2)
return;
end
end
function CreateSlime(ListSlime,thePos,slimeNumber)
local mon = world:createMonster(615,thePos,-10)
ListSlime.Monster = true
base.character.DeathAfterTime(mon,18000,11,9,false)
find, Effect = mon.effects:find(36)
if not find then
debug("Error: Effect not found.")
else
Effect:addValue("GlutinousSeedling",slimeNumber)
end
end
function checkSlime(ListSlime)
if ListSlime.Monster == nil then
return true
end
if ListSlime.Monster == false then
if (world:getTime("unix") - ListSlime.Time) >= 900 then
return true
end
end
return false
end
|
fix Glutinous Seedling, to respawn again, like intended
|
fix Glutinous Seedling, to respawn again, like intended
Also, don't spawn two at once.
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
|
e07edeac22bf6ac2c2633adb5f728d90860d86ad
|
src/cosy/cli/test.lua
|
src/cosy/cli/test.lua
|
-- These lines are required to correctly run tests:
require "busted.runner" ()
local loader = require "cosy.loader.lua" {
logto = false,
}
local Configuration = loader.load "cosy.configuration"
local Cli = loader.require "cosy.cli"
Configuration.load {
"cosy.cli",
}
describe ("Module cosy.cli", function ()
before_each (function ()
Configuration.cli.data = os.tmpname()
Configuration.cli.server = "dummy_default" -- override to a known default value
end)
after_each (function ()
os.remove (Configuration.cli.data)
end)
describe ("parsing options by method configure", function ()
it ("should set the server if the --server option is set", function ()
local cli = Cli.new ()
cli:configure {
"--server=http://public.cosyverif.org",
}
assert.are.equal (cli.server, "http://public.cosyverif.org")
end)
it ("should use a default server if the --server option is missing", function ()
local cli = Cli.new ()
cli:configure {}
assert.is.not_nil (cli.server)
end)
it ("should fail if several --server options are set", function ()
local cli = Cli.new ()
assert.has.errors (function ()
cli:configure {
"--server=http://public.cosyverif.org",
"--server=http://private.cosyverif.org",
}
end)
end)
it ("should fail if the --server option is not a HTTP(s) URL", function ()
local cli = Cli.new ()
assert.has.errors (function ()
cli:configure {
"--server=some.server.org",
}
end)
end)
end)
describe ("saving options by method configure", function ()
it ("should detect the --server", function ()
do
local cli = Cli.new ()
cli:configure {
"--server=http://my.server.org",
}
-- assert server was found and set
assert.are.equal (cli.server, "http://my.server.org")
end
do
local cli = Cli.new ()
cli:configure {}
-- assert config was saved to config file
assert.are.equal (cli.server, "http://my.server.org")
end
end)
end)
end)
|
-- These lines are required to correctly run tests:
require "busted.runner" ()
local loader = require "cosy.loader.lua" {
logto = false,
}
local Configuration = loader.load "cosy.configuration"
local Cli = loader.require "cosy.cli"
Configuration.load {
"cosy.cli",
}
describe ("Module cosy.cli", function ()
before_each (function ()
Configuration.cli.data = os.tmpname()
Configuration.cli.server = "dummy_default" -- override to a known default value
end)
after_each (function ()
os.remove (Configuration.cli.data)
end)
describe ("parsing options by method configure", function ()
it ("should set the server if the --server option is set", function ()
local cli = Cli.new ()
cli:configure {
"--server=http://public.cosyverif.org",
}
assert.are.equal (cli.server, "http://public.cosyverif.org")
end)
it ("should use a default server if the --server option is missing", function ()
local cli = Cli.new ()
cli:configure {}
assert.is.not_nil (cli.server)
end)
it ("should pick the last one if several --server options are set", function ()
local cli = Cli.new ()
cli:configure {
"--server=http://public.cosyverif.org",
"--server=http://private.cosyverif.org",
}
assert.are.equal (cli.server, "http://private.cosyverif.org")
end)
it ("should fail if the --server option is not a HTTP(s) URL", function ()
local cli = Cli.new ()
assert.has.errors (function ()
cli:configure {
"--server=some.server.org",
}
end)
end)
end)
describe ("saving options by method configure", function ()
it ("should detect the --server", function ()
do
local cli = Cli.new ()
cli:configure {
"--server=http://my.server.org",
}
-- assert server was found and set
assert.are.equal (cli.server, "http://my.server.org")
end
do
local cli = Cli.new ()
cli:configure {}
-- assert config was saved to config file
assert.are.equal (cli.server, "http://my.server.org")
end
end)
end)
end)
|
Fix test, as behavior changed because of argparse.
|
Fix test, as behavior changed because of argparse.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
bc03d86c90bbb44bd9f8e66ecc6272b2faa3467b
|
otouto/plugins/bImages.lua
|
otouto/plugins/bImages.lua
|
local bImages = {}
local HTTPS = require('ssl.https')
HTTPS.timeout = 10
local URL = require('socket.url')
local JSON = require('dkjson')
local redis = (loadfile "./otouto/redis.lua")()
local utilities = require('otouto.utilities')
local bindings = require('otouto.bindings')
function bImages:init(config)
if not cred_data.bing_search_key then
print('Missing config value: bing_search_key.')
print('bImages.lua will not be enabled.')
return
end
bImages.triggers = {"^/nil$"}
bImages.inline_triggers = {
"^b (.*)"
}
end
local apikey = cred_data.bing_search_key
local BASE_URL = 'https://api.cognitive.microsoft.com/bing/v5.0'
function bImages:getImages(query)
local url = BASE_URL..'/images/search?q='..URL.escape(query)..'&count=50&mkt=de-de'
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
redirect = false,
headers = {
["Ocp-Apim-Subscription-Key"] = apikey
}
}
local ok, response_code, response_headers = HTTPS.request(request_constructor)
if not ok then return end
local images = JSON.decode(table.concat(response_body)).value
if not images[1] then return end
local results = '['
for n in pairs(images) do
if images[n].encodingFormat == 'jpeg' then -- Inline-Querys MUST use JPEG photos!
local photo_url = images[n].contentUrl
local thumb_url = images[n].thumbnailUrl
results = results..'{"type":"photo","id":"'..math.random(100000000000000000)..'","photo_url":"'..photo_url..'","thumb_url":"'..thumb_url..'","photo_width":'..images[n].width..',"photo_height":'..images[n].height..',"reply_markup":{"inline_keyboard":[[{"text":"Bing aufrufen","url":"'..images[n].webSearchUrl..'"},{"text":"Bild aufrufen","url":"'..photo_url..'"}]]}}'
if n < #images then
results = results..','
end
end
end
local results = results..']'
cache_data('bImages', string.lower(query), results, 1209600, 'key')
return results
end
function bImages:inline_callback(inline_query, config, matches)
local query = matches[1]
local results = redis:get('telegram:cache:bImages:'..string.lower(query))
if not results then
results = bImages:getImages(query)
end
if not results then return end
utilities.answer_inline_query(self, inline_query, results, 3600)
end
function bImages:action()
end
return bImages
|
local bImages = {}
local HTTPS = require('ssl.https')
HTTPS.timeout = 10
local URL = require('socket.url')
local JSON = require('dkjson')
local redis = (loadfile "./otouto/redis.lua")()
local utilities = require('otouto.utilities')
local bindings = require('otouto.bindings')
function bImages:init(config)
if not cred_data.bing_search_key then
print('Missing config value: bing_search_key.')
print('bImages.lua will not be enabled.')
return
end
bImages.triggers = {"^/nil$"}
bImages.inline_triggers = {
"^b (.*)"
}
end
local apikey = cred_data.bing_search_key
local BASE_URL = 'https://api.cognitive.microsoft.com/bing/v5.0'
function bImages:getImages(query)
local url = BASE_URL..'/images/search?q='..URL.escape(query)..'&count=50&mkt=de-de'
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
redirect = false,
headers = {
["Ocp-Apim-Subscription-Key"] = apikey
}
}
local ok, response_code, response_headers = HTTPS.request(request_constructor)
if not ok then return end
local images = JSON.decode(table.concat(response_body)).value
if not images[1] then return end
local results = '['
for n in pairs(images) do
if images[n].encodingFormat == 'jpeg' then -- Inline-Querys MUST use JPEG photos!
local photo_url = images[n].contentUrl
local thumb_url = images[n].thumbnailUrl
results = results..'{"type":"photo","id":"'..math.random(100000000000000000)..'","photo_url":"'..photo_url..'","thumb_url":"'..thumb_url..'","photo_width":'..images[n].width..',"photo_height":'..images[n].height..',"reply_markup":{"inline_keyboard":[[{"text":"Bing aufrufen","url":"'..images[n].webSearchUrl..'"},{"text":"Bild aufrufen","url":"'..photo_url..'"}]]}},'
end
end
local results = results:sub(0, -2)
local results = results..']'
cache_data('bImages', string.lower(query), results, 1209600, 'key')
return results
end
function bImages:inline_callback(inline_query, config, matches)
local query = matches[1]
local results = redis:get('telegram:cache:bImages:'..string.lower(query))
if not results then
results = bImages:getImages(query)
end
if not results then return end
utilities.answer_inline_query(self, inline_query, results, 3600)
end
function bImages:action()
end
return bImages
|
bImages: Fix
|
bImages: Fix
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
6bad80c6388d32551163053651cb352bd38de967
|
xmake/modules/lib/detect/find_tool.lua
|
xmake/modules/lib/detect/find_tool.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 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_tool.lua
--
-- imports
import("lib.detect.find_program")
import("lib.detect.find_programver")
import("lib.detect.find_toolname")
-- find tool from modules
function _find_from_modules(name, opt)
-- attempt to import "detect.tools.find_xxx"
local find_tool = import("detect.tools.find_" .. name, {try = true})
if find_tool then
local program, version, toolname = find_tool(opt)
return {name = toolname or name, program = program, version = version}
end
end
-- find tool
--
-- @param name the tool name
-- @param opt the options, .e.g {program = "xcrun -sdk macosx clang", pathes = {"/usr/bin"}, check = function (tool) os.run("%s -h", tool) end, version = true}
--
-- @return {name = "", program = "", version = ""}
--
-- @code
--
-- local tool = find_tool("clang")
-- local tool = find_tool("clang", {program = "xcrun -sdk macosx clang"})
-- local tool = find_tool("clang", {pathes = {"/usr/bin", "/usr/local/bin"}})
-- local tool = find_tool("clang", {check = "--help"}) -- simple check command: ccache --help
-- local tool = find_tool("clang", {check = function (tool) os.run("%s -h", tool) end})
-- local tool = find_tool("clang", {pathes = {"$(env PATH)", "$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debugger)"}})
-- local tool = find_tool("clang", {pathes = {"$(env PATH)", function () return "/usr/bin"end}})
-- local tool = find_tool("ccache", {version = true})
--
-- @endcode
--
function main(name, opt)
-- init options
opt = opt or {}
-- find tool name
local toolname = find_toolname(name or opt.program)
if not toolname then
return
end
-- init program
opt.program = opt.program or name
-- attempt to find tool from modules first
local tool = _find_from_modules(toolname, opt)
if tool then
return tool
end
-- find tool
local program = find_program(opt.program, opt.pathes, opt.check)
-- find tool version
local version = nil
if program and opt.version then
version = find_programver(program)
end
-- ok?
return {name = toolname, program = program, version = version}
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 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_tool.lua
--
-- imports
import("lib.detect.find_program")
import("lib.detect.find_programver")
import("lib.detect.find_toolname")
-- find tool from modules
function _find_from_modules(name, opt)
-- attempt to import "detect.tools.find_xxx"
local find_tool = import("detect.tools.find_" .. name, {try = true})
if find_tool then
local program, version, toolname = find_tool(opt)
return {name = toolname or name, program = program, version = version}
end
end
-- find tool
--
-- @param name the tool name
-- @param opt the options, .e.g {program = "xcrun -sdk macosx clang", pathes = {"/usr/bin"}, check = function (tool) os.run("%s -h", tool) end, version = true}
--
-- @return {name = "", program = "", version = ""} or nil
--
-- @code
--
-- local tool = find_tool("clang")
-- local tool = find_tool("clang", {program = "xcrun -sdk macosx clang"})
-- local tool = find_tool("clang", {pathes = {"/usr/bin", "/usr/local/bin"}})
-- local tool = find_tool("clang", {check = "--help"}) -- simple check command: ccache --help
-- local tool = find_tool("clang", {check = function (tool) os.run("%s -h", tool) end})
-- local tool = find_tool("clang", {pathes = {"$(env PATH)", "$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debugger)"}})
-- local tool = find_tool("clang", {pathes = {"$(env PATH)", function () return "/usr/bin"end}})
-- local tool = find_tool("ccache", {version = true})
--
-- @endcode
--
function main(name, opt)
-- init options
opt = opt or {}
-- find tool name
local toolname = find_toolname(name or opt.program)
if not toolname then
return
end
-- init program
opt.program = opt.program or name
-- attempt to find tool from modules first
local tool = _find_from_modules(toolname, opt)
if tool then
return tool
end
-- find tool
local program = find_program(opt.program, opt.pathes, opt.check)
if not program then
return
end
-- find tool version
local version = nil
if program and opt.version then
version = find_programver(program)
end
-- ok?
return {name = toolname, program = program, version = version}
end
|
fix find_tool bug
|
fix find_tool bug
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
|
369c88c0a3f24a8cc4e035fecba9ea852e8d20e4
|
kong/plugins/oauth2/migrations/postgres.lua
|
kong/plugins/oauth2/migrations/postgres.lua
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local schema = factory.oauth2_credentials.schema
schema.fields.redirect_uri.type = "string"
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
}
}
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
},
{
name = "2016-12-22-283949_serialize_redirect_uri",
up = function(_, _, factory)
local schema = factory.oauth2_credentials.schema
schema.fields.redirect_uri.type = "string"
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
}
}
|
hotfix(oauth2) fixing postgres migration
|
hotfix(oauth2) fixing postgres migration
|
Lua
|
apache-2.0
|
ccyphers/kong,akh00/kong,Kong/kong,shiprabehera/kong,Vermeille/kong,li-wl/kong,salazar/kong,Mashape/kong,Kong/kong,jebenexer/kong,beauli/kong,Kong/kong,icyxp/kong
|
c5b1f1ed36138502cd57d3c816be5d1341d979fe
|
libs/core/luasrc/model/network/wireless.lua
|
libs/core/luasrc/model/network/wireless.lua
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local 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 <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local 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
|
Lua
|
apache-2.0
|
8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci
|
36e3c44430bd64ed5215da965b59e77e44e8ca32
|
mods/spears/tools.lua
|
mods/spears/tools.lua
|
function spears_register_spear(kind, desc, eq, toughness, craft)
minetest.register_tool("spears:spear_" .. kind, {
description = desc .. " spear",
inventory_image = "spears_spear_" .. kind .. ".png",
wield_scale= {x=2,y=1,z=1},
on_drop = function(itemstack, user, pointed_thing)
spears_shot(itemstack, user)
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
on_place = function(itemstack, user, pointed_thing)
minetest.add_item(pointed_thing.above, itemstack)
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
tool_capabilities = {
full_punch_interval = 1.5,
max_drop_level=1,
groupcaps={
cracky = {times={[3]=2}, uses=toughness, maxlevel=1},
},
damage_groups = {fleshy=eq},
}
})
--minetest.register_node("spears:spear_" .. kind .. "_box", {
--drawtype = "nodebox",
--node_box = {
--type = "fixed",
--fixed = {
---- Shaft
--{-60/16, -2/16, 2/16, 4, 1/16, -1/16},
----Spitze
--{-4, -1/16, 1/16, -62/16, 0, 0},
--{-62/16, -1.5/16, 1.5/16, -60/16, 0.5/16, -0.5/16},
--}
--},
--tiles = {"spears_spear_box.png"},
--groups = {not_in_creative_inventory=1},
--})
local SPEAR_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.15, y=0.1},
textures = {"spears:spear_" .. kind},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
wear = 0,
on_punch = function(self, puncher)
if puncher then
if puncher:is_player() then
local stack = {name='spears:spear_' .. kind, wear=self.wear+65535/toughness}
local inv = puncher:get_inventory()
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
self.object:remove()
end
end
end
end,
}
SPEAR_ENTITY.on_step = function(self, dtime)
local pos = self.object:getpos()
local node = minetest.get_node(pos)
if not self.wear then
self.object:remove()
return
end
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(spears_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if spears_is_player(self.player, obj) or spears_is_entity(obj) then
if spears_touch(pos, objpos) then
local puncher = self.object
if self.player and minetest.get_player_by_name(self.player) then
puncher = minetest.get_player_by_name(self.player)
end
--local speed = vector.length(self.object:getvelocity()) --MFF crabman(28/09/2015) damage valeur equal eq
local damage = eq --((speed + eq +5)^1.2)/10 --MFF crabman(28/09/2015) damage valeur equal eq
obj:punch(puncher, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
minetest.add_item(self.lastpos, {name='spears:spear_' .. kind, wear=self.wear+65535/toughness})
self.object:remove()
return
end
end
end
if node.name ~= "air"
and not string.find(node.name, 'water_')
and not (string.find(node.name, 'grass') and not string.find(node.name, 'dirt'))
and not (string.find(node.name, 'farming:') and not string.find(node.name, 'soil'))
and not string.find(node.name, 'flowers:')
and not string.find(node.name, 'fire:') then
minetest.add_item(self.lastpos, {name='spears:spear_' .. kind, wear=self.wear+65535/toughness})
self.object:remove()
return
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("spears:spear_" .. kind .. "_entity", SPEAR_ENTITY)
minetest.register_craft({
output = 'spears:spear_' .. kind .. ' 4',
recipe = {
{'group:wood', 'group:wood', craft},
}
})
minetest.register_craft({
output = 'spears:spear_' .. kind .. ' 4',
recipe = {
{craft, 'group:wood', 'group:wood'},
}
})
end
if not DISABLE_STONE_SPEAR then
spears_register_spear('stone', 'Stone (Hunter)', 3, 25, 'group:stone') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_STEEL_SPEAR then
spears_register_spear('steel', 'Steel (Hunter)', 4, 30, 'default:steel_ingot') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_DIAMOND_SPEAR then
spears_register_spear('diamond', 'Diamond (Hunter)', 7, 50, 'default:diamond') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_OBSIDIAN_SPEAR then
spears_register_spear('obsidian', 'Obsidian (Hunter)', 5, 40, 'default:obsidian') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_MITHRIL_SPEAR then
spears_register_spear('mithril', 'Mithril (Hunter)', 8, 200, 'moreores:mithril_ingot') --MFF crabman(28/09/2015) damage and wear
end
|
function spears_register_spear(kind, desc, eq, toughness, craft)
minetest.register_tool("spears:spear_" .. kind, {
description = desc .. " spear",
inventory_image = "spears_spear_" .. kind .. ".png",
wield_scale= {x=2,y=1,z=1},
on_drop = function(itemstack, user, pointed_thing)
spears_shot(itemstack, user)
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
tool_capabilities = {
full_punch_interval = 1.5,
max_drop_level=1,
groupcaps={
cracky = {times={[3]=2}, uses=toughness, maxlevel=1},
},
damage_groups = {fleshy=eq},
}
})
--minetest.register_node("spears:spear_" .. kind .. "_box", {
--drawtype = "nodebox",
--node_box = {
--type = "fixed",
--fixed = {
---- Shaft
--{-60/16, -2/16, 2/16, 4, 1/16, -1/16},
----Spitze
--{-4, -1/16, 1/16, -62/16, 0, 0},
--{-62/16, -1.5/16, 1.5/16, -60/16, 0.5/16, -0.5/16},
--}
--},
--tiles = {"spears_spear_box.png"},
--groups = {not_in_creative_inventory=1},
--})
local SPEAR_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.15, y=0.1},
textures = {"spears:spear_" .. kind},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
wear = 0,
on_punch = function(self, puncher)
if puncher then
if puncher:is_player() then
local stack = {name='spears:spear_' .. kind, wear=self.wear+65535/toughness}
local inv = puncher:get_inventory()
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
self.object:remove()
end
end
end
end,
}
SPEAR_ENTITY.on_step = function(self, dtime)
local pos = self.object:getpos()
local node = minetest.get_node(pos)
if not self.wear then
self.object:remove()
return
end
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(spears_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if spears_is_player(self.player, obj) or spears_is_entity(obj) then
if spears_touch(pos, objpos) then
local puncher = self.object
if self.player and minetest.get_player_by_name(self.player) then
puncher = minetest.get_player_by_name(self.player)
end
--local speed = vector.length(self.object:getvelocity()) --MFF crabman(28/09/2015) damage valeur equal eq
local damage = eq --((speed + eq +5)^1.2)/10 --MFF crabman(28/09/2015) damage valeur equal eq
obj:punch(puncher, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
minetest.add_item(self.lastpos, {name='spears:spear_' .. kind, wear=self.wear+65535/toughness})
self.object:remove()
return
end
end
end
if node.name ~= "air"
and not string.find(node.name, 'water_')
and not (string.find(node.name, 'grass') and not string.find(node.name, 'dirt'))
and not (string.find(node.name, 'farming:') and not string.find(node.name, 'soil'))
and not string.find(node.name, 'flowers:')
and not string.find(node.name, 'fire:') then
minetest.add_item(self.lastpos, {name='spears:spear_' .. kind, wear=self.wear+65535/toughness})
self.object:remove()
return
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("spears:spear_" .. kind .. "_entity", SPEAR_ENTITY)
minetest.register_craft({
output = 'spears:spear_' .. kind .. ' 4',
recipe = {
{'group:wood', 'group:wood', craft},
}
})
minetest.register_craft({
output = 'spears:spear_' .. kind .. ' 4',
recipe = {
{craft, 'group:wood', 'group:wood'},
}
})
end
if not DISABLE_STONE_SPEAR then
spears_register_spear('stone', 'Stone (Hunter)', 3, 25, 'group:stone') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_STEEL_SPEAR then
spears_register_spear('steel', 'Steel (Hunter)', 4, 30, 'default:steel_ingot') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_DIAMOND_SPEAR then
spears_register_spear('diamond', 'Diamond (Hunter)', 7, 50, 'default:diamond') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_OBSIDIAN_SPEAR then
spears_register_spear('obsidian', 'Obsidian (Hunter)', 5, 40, 'default:obsidian') --MFF crabman(28/09/2015) damage and wear
end
if not DISABLE_MITHRIL_SPEAR then
spears_register_spear('mithril', 'Mithril (Hunter)', 8, 200, 'moreores:mithril_ingot') --MFF crabman(28/09/2015) damage and wear
end
|
remove useless function and fix place spears on pedestal
|
remove useless function and fix place spears on pedestal
|
Lua
|
unlicense
|
crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server
|
1c06c5fa41aac5fb39b78cb489ca22bbbae1a177
|
MMOCoreORB/bin/scripts/object/tangible/wearables/skirt/skirt_s13.lua
|
MMOCoreORB/bin/scripts/object/tangible/wearables/skirt/skirt_s13.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_wearables_skirt_skirt_s13 = object_tangible_wearables_skirt_shared_skirt_s13:new {
playerRaces = { "object/creature/player/bothan_female.iff",
"object/creature/player/human_female.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/zabrak_female.iff" },
numberExperimentalProperties = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "sockets", "hitpoints", "mod_idx_one", "mod_val_one", "mod_idx_two", "mod_val_two", "mod_idx_three", "mod_val_three", "mod_idx_four", "mod_val_four", "mod_idx_five", "mod_val_five", "mod_idx_six", "mod_val_six"},
experimentalMin = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalMax = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
}
ObjectTemplates:addTemplate(object_tangible_wearables_skirt_skirt_s13, "object/tangible/wearables/skirt/skirt_s13.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_wearables_skirt_skirt_s13 = object_tangible_wearables_skirt_shared_skirt_s13:new {
playerRaces = { "object/creature/player/bothan_male.iff",
"object/creature/player/bothan_female.iff",
"object/creature/player/human_male.iff",
"object/creature/player/human_female.iff",
"object/creature/player/moncal_male.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_male.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_male.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_male.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_male.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/zabrak_male.iff",
"object/creature/player/zabrak_female.iff" },
numberExperimentalProperties = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "sockets", "hitpoints", "mod_idx_one", "mod_val_one", "mod_idx_two", "mod_val_two", "mod_idx_three", "mod_val_three", "mod_idx_four", "mod_val_four", "mod_idx_five", "mod_val_five", "mod_idx_six", "mod_val_six"},
experimentalMin = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalMax = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
}
ObjectTemplates:addTemplate(object_tangible_wearables_skirt_skirt_s13, "object/tangible/wearables/skirt/skirt_s13.iff")
|
[fixed] Thin Pleated Skirt patch by Leka
|
[fixed] Thin Pleated Skirt patch by Leka
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4370 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
6fdb123df400030c9ea68476b15d19de8b9b1ac3
|
lualib/skynet/datasheet/builder.lua
|
lualib/skynet/datasheet/builder.lua
|
local skynet = require "skynet"
local dump = require "skynet.datasheet.dump"
local core = require "skynet.datasheet.core"
local service = require "skynet.service"
local builder = {}
local cache = {}
local dataset = {}
local address
local unique_id = 0
local function unique_string(str)
unique_id = unique_id + 1
return str .. tostring(unique_id)
end
local function monitor(pointer)
skynet.fork(function()
skynet.call(address, "lua", "collect", pointer)
for k,v in pairs(cache) do
if v == pointer then
cache[k] = nil
return
end
end
end)
end
local function dumpsheet(v)
if type(v) == "string" then
return v
else
return dump.dump(v)
end
end
function builder.new(name, v)
assert(dataset[name] == nil)
local datastring = unique_string(dumpsheet(v))
local pointer = core.stringpointer(datastring)
skynet.call(address, "lua", "update", name, pointer)
cache[datastring] = pointer
dataset[name] = datastring
monitor(pointer)
end
function builder.update(name, v)
local lastversion = assert(dataset[name])
local newversion = dumpsheet(v)
local diff = unique_string(dump.diff(lastversion, newversion))
local pointer = core.stringpointer(diff)
skynet.call(address, "lua", "update", name, pointer)
cache[diff] = pointer
local lp = assert(cache[lastversion])
skynet.send(address, "lua", "release", lp)
dataset[name] = diff
monitor(pointer)
end
function builder.compile(v)
return dump.dump(v)
end
local function datasheet_service()
local skynet = require "skynet"
local datasheet = {}
local handles = {} -- handle:{ ref:count , name:name , collect:resp }
local dataset = {} -- name:{ handle:handle, monitor:{monitors queue} }
local function releasehandle(handle)
local h = handles[handle]
h.ref = h.ref - 1
if h.ref == 0 and h.collect then
h.collect(true)
h.collect = nil
handles[handle] = nil
end
end
local function register_collector(name)
local function collect()
local m = dataset[name].monitor
local i = 1
while m[i] do
if not m[i] "TEST" then
local n = #m
m[i] = m[n]
m[n] = nil
else
i = i + 1
end
end
skynet.timeout(10 * 60 * 100, collect) -- 10 mins
end
collect()
end
-- from builder, create or update handle
function datasheet.update(name, handle)
local t = dataset[name]
if not t then
-- new datasheet
t = { handle = handle, monitor = {} }
dataset[name] = t
handles[handle] = { ref = 1, name = name }
register_collector(name)
else
t.handle = handle
-- report update to customers
handles[handle] = { ref = 1 + #t.monitor, name = name }
for k,v in ipairs(t.monitor) do
v(true, handle)
t.monitor[k] = nil
end
end
skynet.ret()
end
-- from customers
function datasheet.query(name)
local t = assert(dataset[name], "create data first")
local handle = t.handle
local h = handles[handle]
h.ref = h.ref + 1
skynet.ret(skynet.pack(handle))
end
-- from customers, monitor handle change
function datasheet.monitor(handle)
local h = assert(handles[handle], "Invalid data handle")
local t = dataset[h.name]
if t.handle ~= handle then -- already changes
skynet.ret(skynet.pack(t.handle))
else
h.ref = h.ref + 1
table.insert(t.monitor, skynet.response())
end
end
-- from customers, release handle , ref count - 1
function datasheet.release(handle)
-- send message, don't ret
releasehandle(handle)
end
-- from builder, monitor handle release
function datasheet.collect(handle)
local h = assert(handles[handle], "Invalid data handle")
if h.ref == 0 then
handles[handle] = nil
skynet.ret()
else
assert(h.collect == nil, "Only one collect allows")
h.collect = skynet.response()
end
end
skynet.dispatch("lua", function(_,_,cmd,...)
datasheet[cmd](...)
end)
skynet.info_func(function()
local info = {}
local tmp = {}
for k,v in pairs(handles) do
tmp[k] = v
end
for k,v in pairs(dataset) do
local h = handles[v.handle]
tmp[v.handle] = nil
info[k] = {
handle = v.handle,
monitors = #v.monitor,
}
end
for k,v in pairs(tmp) do
info[k] = v.ref
end
return info
end)
end
skynet.init(function()
address=service.new("datasheet", datasheet_service)
end)
return builder
|
local skynet = require "skynet"
local dump = require "skynet.datasheet.dump"
local core = require "skynet.datasheet.core"
local service = require "skynet.service"
local builder = {}
local cache = {}
local dataset = {}
local address
local unique_id = 0
local function unique_string(str)
unique_id = unique_id + 1
return str .. tostring(unique_id)
end
local function monitor(pointer)
skynet.fork(function()
skynet.call(address, "lua", "collect", pointer)
for k,v in pairs(cache) do
if v == pointer then
cache[k] = nil
return
end
end
end)
end
local function dumpsheet(v)
if type(v) == "string" then
return v
else
return dump.dump(v)
end
end
function builder.new(name, v)
assert(dataset[name] == nil)
local datastring = unique_string(dumpsheet(v))
local pointer = core.stringpointer(datastring)
skynet.call(address, "lua", "update", name, pointer)
cache[datastring] = pointer
dataset[name] = datastring
monitor(pointer)
end
function builder.update(name, v)
local lastversion = assert(dataset[name])
local newversion = dumpsheet(v)
local diff = unique_string(dump.diff(lastversion, newversion))
local pointer = core.stringpointer(diff)
skynet.call(address, "lua", "update", name, pointer)
cache[diff] = pointer
local lp = assert(cache[lastversion])
skynet.send(address, "lua", "release", lp)
dataset[name] = diff
monitor(pointer)
end
function builder.compile(v)
return dump.dump(v)
end
local function datasheet_service()
local skynet = require "skynet"
local datasheet = {}
local handles = {} -- handle:{ ref:count , name:name , collect:resp }
local dataset = {} -- name:{ handle:handle, monitor:{monitors queue} }
local function releasehandle(handle)
local h = handles[handle]
h.ref = h.ref - 1
if h.ref == 0 and h.collect then
h.collect(true)
h.collect = nil
handles[handle] = nil
end
end
local function register_collector(name)
local function collect()
local t = dataset[name]
local m = t.monitor
local i = 1
while m[i] do
if not m[i] "TEST" then
local n = #m
m[i] = m[n]
m[n] = nil
releasehandle(t.handle)
else
i = i + 1
end
end
skynet.timeout(10 * 60 * 100, collect) -- 10 mins
end
collect()
end
-- from builder, create or update handle
function datasheet.update(name, handle)
local t = dataset[name]
if not t then
-- new datasheet
t = { handle = handle, monitor = {} }
dataset[name] = t
handles[handle] = { ref = 1, name = name }
register_collector(name)
else
local old_handle = t.handle
t.handle = handle
-- report update to customers
handles[handle] = {
ref = nil,
name = name
}
local ref = 1
for k,v in ipairs(t.monitor) do
if v(true, handle) then
ref = ref + 1
else
releasehandle(old_handle)
end
t.monitor[k] = nil
end
handles[handle].ref = ref
end
skynet.ret()
end
-- from customers
function datasheet.query(name)
local t = assert(dataset[name], "create data first")
local handle = t.handle
local h = handles[handle]
h.ref = h.ref + 1
skynet.ret(skynet.pack(handle))
end
-- from customers, monitor handle change
function datasheet.monitor(handle)
local h = assert(handles[handle], "Invalid data handle")
local t = dataset[h.name]
if t.handle ~= handle then -- already changes
skynet.ret(skynet.pack(t.handle))
else
h.ref = h.ref + 1
table.insert(t.monitor, skynet.response())
end
end
-- from customers, release handle , ref count - 1
function datasheet.release(handle)
-- send message, don't ret
releasehandle(handle)
end
-- from builder, monitor handle release
function datasheet.collect(handle)
local h = assert(handles[handle], "Invalid data handle")
if h.ref == 0 then
handles[handle] = nil
skynet.ret()
else
assert(h.collect == nil, "Only one collect allows")
h.collect = skynet.response()
end
end
skynet.dispatch("lua", function(_,_,cmd,...)
datasheet[cmd](...)
end)
skynet.info_func(function()
local info = {}
local tmp = {}
for k,v in pairs(handles) do
tmp[k] = v
end
for k,v in pairs(dataset) do
local h = handles[v.handle]
tmp[v.handle] = nil
info[k] = {
handle = v.handle,
monitors = #v.monitor,
}
end
for k,v in pairs(tmp) do
info[k] = v.ref
end
return info
end)
end
skynet.init(function()
address=service.new("datasheet", datasheet_service)
end)
return builder
|
bugfix, See #800
|
bugfix, See #800
|
Lua
|
mit
|
firedtoad/skynet,great90/skynet,codingabc/skynet,great90/skynet,cloudwu/skynet,hongling0/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,codingabc/skynet,wangyi0226/skynet,zhangshiqian1214/skynet,sundream/skynet,korialuo/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,pigparadise/skynet,zhangshiqian1214/skynet,bigrpg/skynet,bigrpg/skynet,sundream/skynet,zhouxiaoxiaoxujian/skynet,bttscut/skynet,hongling0/skynet,pigparadise/skynet,zhangshiqian1214/skynet,ag6ag/skynet,xjdrew/skynet,bigrpg/skynet,xjdrew/skynet,zhangshiqian1214/skynet,czlc/skynet,xcjmine/skynet,Ding8222/skynet,icetoggle/skynet,sanikoyes/skynet,sundream/skynet,wangyi0226/skynet,cloudwu/skynet,great90/skynet,korialuo/skynet,jxlczjp77/skynet,JiessieDawn/skynet,korialuo/skynet,xjdrew/skynet,sanikoyes/skynet,icetoggle/skynet,hongling0/skynet,JiessieDawn/skynet,firedtoad/skynet,icetoggle/skynet,sanikoyes/skynet,jxlczjp77/skynet,xcjmine/skynet,firedtoad/skynet,ag6ag/skynet,Ding8222/skynet,xcjmine/skynet,cloudwu/skynet,pigparadise/skynet,bttscut/skynet,czlc/skynet,czlc/skynet,JiessieDawn/skynet,ag6ag/skynet,Ding8222/skynet,bttscut/skynet,wangyi0226/skynet,codingabc/skynet
|
7a0e60a82b08b09958f9c5dbf3e5168a4583bc63
|
editor/lib/lua/editor/classes/AssimpMesh.lua
|
editor/lib/lua/editor/classes/AssimpMesh.lua
|
local BaseMesh = require("classes.BaseMesh")
---------------------------------------------------------------------------------
--
-- @type AssimpMesh
--
---------------------------------------------------------------------------------
local AssimpMesh = Class(BaseMesh, "AssimpMesh")
function AssimpMesh:init( size, texture )
BaseMesh.init( self )
self._size = size or 256
self._texture = texture or ''
self._bones = {}
end
---------------------------------------------------------------------------------
function AssimpMesh:setLightNode( node )
local useBakeLight = node.GetBakeLight( node )
local diffusePower = node.GetDiffusePower( node )
local ambientLight = node.GetAmbientLight( node )
local lightDirection = node.GetLightDirection( node )
self.useBakeLight = useBakeLight
self.diffusePower = diffusePower
self.ambientLight = { ambientLight[0], ambientLight[1], ambientLight[2], ambientLight[3] }
self.lightDirection = { lightDirection[0], lightDirection[1], lightDirection[2] }
end
function AssimpMesh:luminosity(r, g, b)
local light = self.ambientLight
return light[1] * r + light[2] * g + light[3] * b
end
---------------------------------------------------------------------------------
function AssimpMesh:setNode( node )
self.name = node.name
print()
print("AssimpMesh setNode", self.name)
self:initWithParams()
local vertexFormat = self.vertexFormat
local vbo = self.vbo
local ibo = self.ibo
local vtxCount = node.verticesCount
local idxCount = 3 * node.facesCount
self.idxCount = idxCount
local iboSize = 2 -- 2/4
ibo:setIndexSize ( iboSize )
ibo:reserve ( idxCount * iboSize )
print("vtxCount", vtxCount)
vbo:reserve ( vtxCount * vertexFormat:getVertexSize ())
local sz = self._size
for i = 0, vtxCount - 1 do
local vtx = node.vertices [ i ]
local uv = node.texturecoords [ 0 ][ i ]
vbo:writeFloat ( sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ] )
-- print(i, ".", sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ] )
vbo:writeFloat ( uv [ 0 ], uv [ 1 ])
if self.useBakeLight then
local n = node.normals [ i ]
local ambient = self.ambientLight
local diffuse = self.diffusePower
local luma = math.max(0, self:luminosity ( n [ 0 ], n [ 1 ], n [ 2 ]))
local r = math.min ( 1, ambient [ 1 ] + diffuse * luma )
local g = math.min ( 1, ambient [ 2 ] + diffuse * luma )
local b = math.min ( 1, ambient [ 3 ] + diffuse * luma )
vbo:writeColor32 ( r, g, b, 1 )
else
vbo:writeColor32 ( 1, 1, 1, 1 )
end
end
for face in python.iter ( node.faces ) do
local sz = sizeOfPythonObject(face)
if sz >= 3 then
if iboSize == 4 then
ibo:writeU32 ( face [ 0 ], face [ 1 ], face [ 2 ] )
else
ibo:writeU16 ( face [ 0 ], face [ 1 ], face [ 2 ] )
end
-- print("ibo:", face [ 0 ], face [ 1 ], face [ 2 ])
else
print("AssimpMesh: FACE is BROKEN!")
end
end
-- ibo:printIndices()
local bones = {}
for bname in python.iter ( node.bonesNames ) do
table.insert(bones, bname)
end
self._bones = bones
self._materialID = node.materialID
end
---------------------------------------------------------------------------------
function AssimpMesh:createMesh ( option )
local option = option or {}
local vbo = self.vbo
local ibo = self.ibo
local vertexFormat = self.vertexFormat
local mesh = MOAIMesh.new ()
mesh:setVertexBuffer( vbo, vertexFormat )
mesh:setIndexBuffer ( ibo )
mesh:setPrimType ( MOAIMesh.GL_TRIANGLES )
mesh:setShader ( MOAIShaderMgr.getShader( MOAIShaderMgr.MESH_SHADER ) )
mesh:setTotalElements ( self.idxCount )
mesh:setBounds( vbo:computeBounds( vertexFormat ) )
local textureName = self:getTexture()
if textureName then
mesh.textureName = textureName
local texture = ResourceMgr:getTexture( textureName )
mesh:setTexture ( texture )
end
mesh._bones = self._bones -- option.exportBones
mesh._materialID = self._materialID --option.exportMaterialID
if option.exportBuffers then
mesh._vbo = vbo
mesh._ibo = ibo
end
self.canSave = option.exportMesh
self.mesh = mesh
end
---------------------------------------------------------------------------------
function AssimpMesh:getTexture()
local textureName = self._texture
if not textureName or textureName == '' then
local textureName = self._texturePath
if not textureName then
textureName = editorAssetPath( 'grid.png')
end
end
return textureName
end
---------------------------------------------------------------------------------
return AssimpMesh
|
local BaseMesh = require("classes.BaseMesh")
---------------------------------------------------------------------------------
--
-- @type AssimpMesh
--
---------------------------------------------------------------------------------
local AssimpMesh = Class(BaseMesh, "AssimpMesh")
function AssimpMesh:init( size, texture )
BaseMesh.init( self )
self._size = size or 256
self._texture = texture or ''
self._bones = {}
end
---------------------------------------------------------------------------------
function AssimpMesh:setLightNode( node )
local useBakeLight = node.GetBakeLight( node )
local diffusePower = node.GetDiffusePower( node )
local ambientLight = node.GetAmbientLight( node )
local lightDirection = node.GetLightDirection( node )
self.useBakeLight = useBakeLight
self.diffusePower = diffusePower
self.ambientLight = { ambientLight[0], ambientLight[1], ambientLight[2], ambientLight[3] }
self.lightDirection = { lightDirection[0], lightDirection[1], lightDirection[2] }
end
function AssimpMesh:luminosity(r, g, b)
local light = self.ambientLight
return light[1] * r + light[2] * g + light[3] * b
end
---------------------------------------------------------------------------------
function AssimpMesh:setNode( node )
self.name = node.name
print()
print("AssimpMesh setNode", self.name)
self:initWithParams()
local vertexFormat = self.vertexFormat
local vbo = self.vbo
local ibo = self.ibo
local vtxCount = node.verticesCount
local idxCount = 3 * node.facesCount
local iboSize = 2 -- 2/4
ibo:setIndexSize ( iboSize )
ibo:reserve ( idxCount * iboSize )
vbo:reserve ( vtxCount * vertexFormat:getVertexSize ())
local sz = self._size
for i = 0, vtxCount - 1 do
local vtx = node.vertices [ i ]
local uv = node.texturecoords [ 0 ][ i ]
vbo:writeFloat ( sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ] )
-- print(i, ".", sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ] )
vbo:writeFloat ( uv [ 0 ], uv [ 1 ])
if self.useBakeLight then
local n = node.normals [ i ]
local ambient = self.ambientLight
local diffuse = self.diffusePower
local luma = math.max(0, self:luminosity ( n [ 0 ], n [ 1 ], n [ 2 ]))
local r = math.min ( 1, ambient [ 1 ] + diffuse * luma )
local g = math.min ( 1, ambient [ 2 ] + diffuse * luma )
local b = math.min ( 1, ambient [ 3 ] + diffuse * luma )
vbo:writeColor32 ( r, g, b, 1 )
else
vbo:writeColor32 ( 1, 1, 1, 1 )
end
end
for face in python.iter ( node.faces ) do
local sz = sizeOfPythonObject(face)
if sz >= 3 then
if iboSize == 4 then
ibo:writeU32 ( face [ 0 ], face [ 1 ], face [ 2 ] )
else
ibo:writeU16 ( face [ 0 ], face [ 1 ], face [ 2 ] )
end
-- print("ibo:", face [ 0 ], face [ 1 ], face [ 2 ])
else
print("AssimpMesh: FACE is BROKEN!")
end
end
-- ibo:printIndices()
local bones = {}
for bname in python.iter ( node.bonesNames ) do
table.insert(bones, bname)
end
self._bones = bones
self._materialID = node.materialID
self._vertexCount = vtxCount
self._indexCount = idxCount
end
---------------------------------------------------------------------------------
function AssimpMesh:createMesh ( option )
local option = option or {}
local vbo = self.vbo
local ibo = self.ibo
local vertexFormat = self.vertexFormat
local mesh = MOAIMesh.new ()
mesh:setVertexBuffer( vbo, vertexFormat )
mesh:setIndexBuffer ( ibo )
mesh:setPrimType ( MOAIMesh.GL_TRIANGLES )
mesh:setShader ( MOAIShaderMgr.getShader( MOAIShaderMgr.MESH_SHADER ) )
mesh:setTotalElements ( self._indexCount )
mesh:setBounds( vbo:computeBounds( vertexFormat ) )
local textureName = self:getTexture()
if textureName then
mesh.textureName = textureName
local texture = ResourceMgr:getTexture( textureName )
mesh:setTexture ( texture )
end
mesh._bones = self._bones -- option.exportBones
mesh._materialID = self._materialID --option.exportMaterialID
if option.exportBuffers then
mesh._vbo = vbo
mesh._ibo = ibo
end
mesh._vertexCount = self._vertexCount
mesh._indexCount = self._indexCount
self.canSave = option.exportMesh
self.mesh = mesh
end
---------------------------------------------------------------------------------
function AssimpMesh:getTexture()
local textureName = self._texture
if not textureName or textureName == '' then
local textureName = self._texturePath
if not textureName then
textureName = editorAssetPath( 'grid.png')
end
end
return textureName
end
---------------------------------------------------------------------------------
return AssimpMesh
|
fix mesh
|
fix mesh
|
Lua
|
mit
|
RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,cloudteampro/juma-editor
|
86597c2f10ad245629053ac557d882b23b79b31b
|
example/gatedNegationRanking.lua
|
example/gatedNegationRanking.lua
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 8
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local parInput = nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())
local loss = nn.MarginRankingCriterion()({parInput({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
local f = 0 -- for averaging error
for k = 1, #inputs do
local result = ged:forward({inputs[k], gates[k]})
local err = loss_module:forward({result, targets[k], samples[k], 1})
f = f + err
local gradErr = loss_module:backward({result, targets[k], samples[k], 1})
ged:backward({inputs[k], gates[k]}, gradErr)
end -- for k = 1, #inputs
-- normalize gradients and f(X)
gradParameters:div(#inputs)
f = f/(#inputs)
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
-- module with the first half of the network
for t = 1, testdata:size()[1] do
local input_word = testwords[t]
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
opt.predfile:write(input_word .. "\t[")
for k = 1, output:size()[2] do
opt.predfile:write(output[t][k] .. ", ")
end
opt.predfile:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 8
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local parInput = nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())
local loss = nn.MarginRankingCriterion()({parInput({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
local f = 0 -- for averaging error
for k = 1, #inputs do
local result = ged:forward({inputs[k], gates[k]})
local err = loss_module:forward({result, targets[k], samples[k], 1})
f = f + err
local gradErr = loss_module:backward({result, targets[k],
samples[k], 1},
torch.Tensor{1})
local gradOut, gradTarg, gradSample, gradRank = unpack(gradErr)
ged:backward({inputs[k], gates[k]}, gradOut)
end -- for k = 1, #inputs
-- normalize gradients and f(X)
gradParameters:div(#inputs)
f = f/(#inputs)
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
-- module with the first half of the network
for t = 1, testdata:size()[1] do
local input_word = testwords[t]
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
opt.predfile:write(input_word .. "\t[")
for k = 1, output:size()[2] do
opt.predfile:write(output[t][k] .. ", ")
end
opt.predfile:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
Fix loss gradient bug.
|
Fix loss gradient bug.
|
Lua
|
mit
|
douwekiela/nncg-negation
|
d4176328dfcd5ed696d91c12c53c06416f05dfd4
|
protocols/luci-proto-vpnc/luasrc/model/cbi/admin_network/proto_vpnc.lua
|
protocols/luci-proto-vpnc/luasrc/model/cbi/admin_network/proto_vpnc.lua
|
-- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local server, username, password, hexpassword
local authgroup, interface, passgroup, hexpassgroup
local domain, vendor, natt_mode, dh_group
local pfs, enable_single_des, enable_no_enc
local mtu, local_addr, local_port, dpd_idle
local auth_mode, target_network
local ifc = net:get_interface():name()
server = section:taboption("general", Value, "server", translate("VPN Server"))
server.datatype = "host(0)"
port = section:taboption("general", Value, "local_addr", translate("VPN Local address"))
port.placeholder = "0.0.0.0"
port.datatype = "ipaddr"
port = section:taboption("general", Value, "local_port", translate("VPN Local port"))
port.placeholder = "500"
port.datatype = "port"
ifname = section:taboption("general", Value, "interface", translate("Output Interface"))
ifname.template = "cbi/network_netlist"
mtu = section:taboption("general", Value, "mtu", translate("MTU"))
mtu.datatype = "uinteger"
section:taboption("general", Value, "authgroup", translate("AuthGroup"))
username = section:taboption("general", Value, "username", translate("Username"))
password = section:taboption("general", Value, "password", translate("Password"))
hexpassword = section:taboption("general", Value, "hexpassword", translate("Obfuscated Password"))
password.password = true
hexpassword.password = true
authroup = section:taboption("general", Value, "authgroup", translate("Auth Group"))
passgroup = section:taboption("general", Value, "passgroup", translate("Group Password"))
hexpassgroup = section:taboption("general", Value, "hexpassgroup", translate("Obfuscated Group Password"))
password.passgroup = true
hexpassword.passgroup= true
domain = section:taboption("general", Value, "domain", translate("NT Domain"))
vendor = section:taboption("general", Value, "vendor", translate("Vendor"))
dh_group = section:taboption("general", ListValue, "dh_group", translate("IKE DH Group"))
dh_group:value("dh2")
dh_group:value("dh1")
dh_group:value("dh5")
pfs = section:taboption("general", ListValue, "pfs", translate("Perfect Forward Secrecy"))
dh_group:value("server")
dh_group:value("nopfs")
dh_group:value("dh1")
dh_group:value("dh2")
dh_group:value("dh5")
natt_mode = section:taboption("general", ListValue, "natt_mode", translate("NAT-T Mode"))
natt_mode:value("natt", translate("RFC3947 NAT-T mode"))
natt_mode:value("none", translate("No NAT-T"))
natt_mode:value("force-natt", translate("Force use of NAT-T"))
natt_mode:value("cisco-udp", translate("Cisco UDP encapsulation"))
enable_no_enc = section:taboption("general", Flag, "enable_no_enc",
translate("Disable Encryption"),
translate("If checked, encryption is disabled"))
enable_no_enc.default = enable_no_enc.disabled
enable_single_des = section:taboption("general", Flag, "enable_single_des",
translate("Enable Single DES"),
translate("If checked, 1DES is enaled"))
enable_no_enc.default = enable_single_des.disabled
dpd_idle = section:taboption("general", Value, "dpd_idle", translate("DPD Idle Timeout"))
dpd_idle.datatype = "uinteger"
dpd_idle.placeholder = "600"
ifname = section:taboption("general", Value, "target_network", translate("Target network"))
port.placeholder = "0.0.0.0/0"
port.datatype = "network"
|
-- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local server, username, password, hexpassword
local authgroup, interface, passgroup, hexpassgroup
local domain, vendor, natt_mode, dh_group
local pfs, enable_single_des, enable_no_enc
local mtu, local_addr, local_port, dpd_idle
local auth_mode, target_network
local ifc = net:get_interface():name()
server = section:taboption("general", Value, "server", translate("VPN Server"))
server.datatype = "host(0)"
port = section:taboption("general", Value, "local_addr", translate("VPN Local address"))
port.placeholder = "0.0.0.0"
port.datatype = "ipaddr"
port = section:taboption("general", Value, "local_port", translate("VPN Local port"))
port.placeholder = "500"
port.datatype = "port"
ifname = section:taboption("general", Value, "interface", translate("Output Interface"))
ifname.template = "cbi/network_netlist"
mtu = section:taboption("general", Value, "mtu", translate("MTU"))
mtu.datatype = "uinteger"
username = section:taboption("general", Value, "username", translate("Username"))
password = section:taboption("general", Value, "password", translate("Password"))
password.password = true
hexpassword = section:taboption("general", Value, "hexpassword", translate("Obfuscated Password"))
hexpassword.password = true
authroup = section:taboption("general", Value, "authgroup", translate("Auth Group"))
passgroup = section:taboption("general", Value, "passgroup", translate("Group Password"))
passgroup.password = true
hexpassgroup = section:taboption("general", Value, "hexpassgroup", translate("Obfuscated Group Password"))
hexpassword.password= true
domain = section:taboption("general", Value, "domain", translate("NT Domain"))
vendor = section:taboption("general", Value, "vendor", translate("Vendor"))
dh_group = section:taboption("general", ListValue, "dh_group", translate("IKE DH Group"))
dh_group:value("dh2")
dh_group:value("dh1")
dh_group:value("dh5")
pfs = section:taboption("general", ListValue, "pfs", translate("Perfect Forward Secrecy"))
pfs:value("server")
pfs:value("nopfs")
pfs:value("dh1")
pfs:value("dh2")
pfs:value("dh5")
natt_mode = section:taboption("general", ListValue, "natt_mode", translate("NAT-T Mode"))
natt_mode:value("natt", translate("RFC3947 NAT-T mode"))
natt_mode:value("none", translate("No NAT-T"))
natt_mode:value("force-natt", translate("Force use of NAT-T"))
natt_mode:value("cisco-udp", translate("Cisco UDP encapsulation"))
enable_no_enc = section:taboption("general", Flag, "enable_no_enc",
translate("Disable Encryption"),
translate("If checked, encryption is disabled"))
enable_no_enc.default = enable_no_enc.disabled
enable_single_des = section:taboption("general", Flag, "enable_single_des",
translate("Enable Single DES"),
translate("If checked, 1DES is enaled"))
enable_no_enc.default = enable_single_des.disabled
dpd_idle = section:taboption("general", Value, "dpd_idle", translate("DPD Idle Timeout"))
dpd_idle.datatype = "uinteger"
dpd_idle.placeholder = "600"
ifname = section:taboption("general", Value, "target_network", translate("Target network"))
port.placeholder = "0.0.0.0/0"
port.datatype = "network"
|
luci-proto-vpnc: further typo fixes
|
luci-proto-vpnc: further typo fixes
|
Lua
|
apache-2.0
|
LuttyYang/luci,teslamint/luci,nmav/luci,remakeelectric/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,artynet/luci,taiha/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,oneru/luci,taiha/luci,cshore-firmware/openwrt-luci,aa65535/luci,LuttyYang/luci,LuttyYang/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,hnyman/luci,remakeelectric/luci,Noltari/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,rogerpueyo/luci,mumuqz/luci,openwrt-es/openwrt-luci,981213/luci-1,daofeng2015/luci,openwrt/luci,bittorf/luci,nmav/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,LuttyYang/luci,shangjiyu/luci-with-extra,artynet/luci,aa65535/luci,981213/luci-1,bittorf/luci,shangjiyu/luci-with-extra,bittorf/luci,teslamint/luci,kuoruan/luci,tobiaswaldvogel/luci,daofeng2015/luci,openwrt/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,rogerpueyo/luci,daofeng2015/luci,daofeng2015/luci,remakeelectric/luci,artynet/luci,Noltari/luci,openwrt/luci,artynet/luci,981213/luci-1,taiha/luci,kuoruan/luci,mumuqz/luci,hnyman/luci,oneru/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,teslamint/luci,chris5560/openwrt-luci,oneru/luci,cshore/luci,artynet/luci,shangjiyu/luci-with-extra,aa65535/luci,chris5560/openwrt-luci,Wedmer/luci,hnyman/luci,nmav/luci,openwrt/luci,Wedmer/luci,kuoruan/lede-luci,wongsyrone/luci-1,cshore/luci,Wedmer/luci,chris5560/openwrt-luci,hnyman/luci,openwrt-es/openwrt-luci,kuoruan/luci,shangjiyu/luci-with-extra,rogerpueyo/luci,Noltari/luci,kuoruan/luci,kuoruan/luci,LuttyYang/luci,teslamint/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,LuttyYang/luci,Noltari/luci,mumuqz/luci,artynet/luci,Noltari/luci,cshore/luci,bittorf/luci,shangjiyu/luci-with-extra,mumuqz/luci,Wedmer/luci,aa65535/luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,daofeng2015/luci,cshore/luci,Noltari/luci,Noltari/luci,daofeng2015/luci,taiha/luci,oneru/luci,nmav/luci,artynet/luci,aa65535/luci,cshore/luci,mumuqz/luci,daofeng2015/luci,remakeelectric/luci,aa65535/luci,981213/luci-1,Wedmer/luci,lbthomsen/openwrt-luci,mumuqz/luci,taiha/luci,Noltari/luci,taiha/luci,cshore/luci,wongsyrone/luci-1,teslamint/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,hnyman/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,remakeelectric/luci,teslamint/luci,oneru/luci,LuttyYang/luci,hnyman/luci,981213/luci-1,remakeelectric/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,wongsyrone/luci-1,Wedmer/luci,cshore-firmware/openwrt-luci,mumuqz/luci,bittorf/luci,wongsyrone/luci-1,oneru/luci,teslamint/luci,LuttyYang/luci,hnyman/luci,chris5560/openwrt-luci,bittorf/luci,kuoruan/luci,Wedmer/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,rogerpueyo/luci,981213/luci-1,bittorf/luci,openwrt/luci,oneru/luci,chris5560/openwrt-luci,nmav/luci,Wedmer/luci,kuoruan/luci,taiha/luci,oneru/luci,taiha/luci,cshore-firmware/openwrt-luci,bittorf/luci,981213/luci-1,artynet/luci,openwrt-es/openwrt-luci,remakeelectric/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,nmav/luci,Noltari/luci,mumuqz/luci,teslamint/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,kuoruan/lede-luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,aa65535/luci,tobiaswaldvogel/luci,remakeelectric/luci,nmav/luci,cshore/luci,kuoruan/lede-luci,nmav/luci,artynet/luci,aa65535/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,kuoruan/luci,tobiaswaldvogel/luci,cshore/luci,wongsyrone/luci-1,rogerpueyo/luci
|
4f6411ee38f0525362fa2518e286ad6e16bdd31b
|
src/patch/ui/lib/mppatch_modutils.lua
|
src/patch/ui/lib/mppatch_modutils.lua
|
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com>
--
-- 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 patch = _mpPatch.patch
function _mpPatch.overrideWithModList(list)
_mpPatch.debugPrint("Overriding mods...")
patch.NetPatch.reset()
for _, mod in ipairs(list) do
_mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(mod.ID, mod.Version).."...")
patch.NetPatch.pushMod(mod.ID, mod.Version)
end
patch.NetPatch.overrideModList()
patch.NetPatch.install()
end
function _mpPatch.overrideModsFromActivatedList()
local modList = Modding.GetActivatedMods()
if modList and #modList > 0 then
_mpPatch.overrideWithModList(modList)
end
end
function _mpPatch.overrideModsFromPreGame()
local modList = _mpPatch.decodeModsList()
if modList and _mpPatch.isModding then
_mpPatch.overrideWithModList(modList)
end
end
_mpPatch._mt.registerProperty("areModsEnabled", function()
return #Modding.GetActivatedMods() > 0
end)
function _mpPatch.getModName(uuid, version)
local details = Modding.GetInstalledModDetails(uuid, version) or {}
return details.Name or "<unknown mod "..uuid.." v"..version..">"
end
_mpPatch._mt.registerLazyVal("installedMods", function()
local installed = {}
for _, v in pairs(Modding.GetInstalledMods()) do
installed[v.ID.."_"..v.Version] = true
end
return installed
end)
function _mpPatch.isModInstalled(uuid, version)
return not not _mpPatch.installedMods[uuid.."_"..version]
end
-- Mod dependency listing
function _mpPatch.normalizeDlcName(name)
return name:gsub("-", ""):upper()
end
function _mpPatch.getModDependencies(modList)
local dlcDependencies = {}
for row in GameInfo.DownloadableContent() do
dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)] = {}
end
for _, mod in ipairs(modList) do
local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) }
for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do
if assoc.Type == 2 then
if assoc.PackageID == "*" then
for row in GameInfo.DownloadableContent() do
table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info)
end
else
local normName = _mpPatch.normalizeDlcName(assoc.PackageID)
if dlcDependencies[normName] then
table.insert(dlcDependencies[normName], info)
end
end
end
end
end
return dlcDependencies
end
-- UUID encoding/decoding for storing a mod list in PreGame's options table
local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8)
local function encodeUUID(uuidString)
uuidString = uuidString:gsub("-", "")
local uuids = {uuidString:match(uuidRegex)}
if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end
return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end)
end
local function decodeUUID(table)
return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table))
end
-- Enroll/decode mods into the PreGame option table
_mpPatch._mt.registerProperty("isModding", function()
return _mpPatch.getGameOption("HAS_MODS") == 1
end)
local function enrollModName(id, name)
_mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name)
for i=1,#name do
_mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i))
end
end
local function enrollMod(id, uuid, version)
local modName = _mpPatch.getModName(uuid, version)
_mpPatch.debugPrint("- Enrolling mod "..modName)
_mpPatch.setGameOption("MOD_"..id.."_VERSION", version)
for i, v in ipairs(encodeUUID(uuid)) do
_mpPatch.setGameOption("MOD_"..id.."_"..i, v)
end
enrollModName(id, modName)
end
function _mpPatch.enrollModsList(modList)
_mpPatch.debugPrint("Enrolling mods...")
if #modList > 0 then
_mpPatch.setGameOption("HAS_MODS", 1)
_mpPatch.setGameOption("MOD_COUNT", #modList)
for i, v in ipairs(modList) do
enrollMod(i, v.ID, v.Version)
end
else
_mpPatch.setGameOption("HAS_MODS", 0)
end
end
local function decodeModName(id)
local charTable = {}
for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do
charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i))
end
return table.concat(charTable)
end
local function decodeMod(id)
local uuidTable = {}
for i=1,8 do
uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i)
end
return {
ID = decodeUUID(uuidTable),
Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"),
Name = decodeModName(id)
}
end
function _mpPatch.decodeModsList()
if not _mpPatch.isModding then return nil end
local modList = {}
for i=1,_mpPatch.getGameOption("MOD_COUNT") do
modList[i] = decodeMod(i)
end
return modList
end
|
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com>
--
-- 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 patch = _mpPatch.patch
function _mpPatch.overrideWithModList(list)
_mpPatch.debugPrint("Overriding mods...")
patch.NetPatch.reset()
for _, mod in ipairs(list) do
local id = mod.ID or mod.ModID
_mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(id, mod.Version).."...")
patch.NetPatch.pushMod(id, mod.Version)
end
patch.NetPatch.overrideModList()
patch.NetPatch.install()
end
function _mpPatch.overrideModsFromActivatedList()
local modList = Modding.GetActivatedMods()
if modList and #modList > 0 then
_mpPatch.overrideWithModList(modList)
end
end
function _mpPatch.overrideModsFromPreGame()
local modList = _mpPatch.decodeModsList()
if modList and _mpPatch.isModding then
_mpPatch.overrideWithModList(modList)
end
end
_mpPatch._mt.registerProperty("areModsEnabled", function()
return #Modding.GetActivatedMods() > 0
end)
function _mpPatch.getModName(uuid, version)
local details = Modding.GetInstalledModDetails(uuid, version) or {}
return details.Name or "<unknown mod "..uuid.." v"..version..">"
end
_mpPatch._mt.registerLazyVal("installedMods", function()
local installed = {}
for _, v in pairs(Modding.GetInstalledMods()) do
installed[v.ID.."_"..v.Version] = true
end
return installed
end)
function _mpPatch.isModInstalled(uuid, version)
return not not _mpPatch.installedMods[uuid.."_"..version]
end
-- Mod dependency listing
function _mpPatch.normalizeDlcName(name)
return name:gsub("-", ""):upper()
end
function _mpPatch.getModDependencies(modList)
local dlcDependencies = {}
for row in GameInfo.DownloadableContent() do
dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)] = {}
end
for _, mod in ipairs(modList) do
local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) }
for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do
if assoc.Type == 2 then
if assoc.PackageID == "*" then
for row in GameInfo.DownloadableContent() do
table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info)
end
else
local normName = _mpPatch.normalizeDlcName(assoc.PackageID)
if dlcDependencies[normName] then
table.insert(dlcDependencies[normName], info)
end
end
end
end
end
return dlcDependencies
end
-- UUID encoding/decoding for storing a mod list in PreGame's options table
local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8)
local function encodeUUID(uuidString)
uuidString = uuidString:gsub("-", "")
local uuids = {uuidString:match(uuidRegex)}
if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end
return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end)
end
local function decodeUUID(table)
return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table))
end
-- Enroll/decode mods into the PreGame option table
_mpPatch._mt.registerProperty("isModding", function()
return _mpPatch.getGameOption("HAS_MODS") == 1
end)
local function enrollModName(id, name)
_mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name)
for i=1,#name do
_mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i))
end
end
local function enrollMod(id, uuid, version)
local modName = _mpPatch.getModName(uuid, version)
_mpPatch.debugPrint("- Enrolling mod "..modName)
_mpPatch.setGameOption("MOD_"..id.."_VERSION", version)
for i, v in ipairs(encodeUUID(uuid)) do
_mpPatch.setGameOption("MOD_"..id.."_"..i, v)
end
enrollModName(id, modName)
end
function _mpPatch.enrollModsList(modList)
_mpPatch.debugPrint("Enrolling mods...")
if #modList > 0 then
_mpPatch.setGameOption("HAS_MODS", 1)
_mpPatch.setGameOption("MOD_COUNT", #modList)
for i, v in ipairs(modList) do
enrollMod(i, v.ID, v.Version)
end
else
_mpPatch.setGameOption("HAS_MODS", 0)
end
end
local function decodeModName(id)
local charTable = {}
for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do
charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i))
end
return table.concat(charTable)
end
local function decodeMod(id)
local uuidTable = {}
for i=1,8 do
uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i)
end
return {
ID = decodeUUID(uuidTable),
Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"),
Name = decodeModName(id)
}
end
function _mpPatch.decodeModsList()
if not _mpPatch.isModding then return nil end
local modList = {}
for i=1,_mpPatch.getGameOption("MOD_COUNT") do
modList[i] = decodeMod(i)
end
return modList
end
|
Fix modutils.
|
Fix modutils.
|
Lua
|
mit
|
Lymia/MultiverseModManager,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC
|
4819bb7be2e32887bc58f95f70916e1977a18b04
|
source/networking/networkFrameworkEntity.lua
|
source/networking/networkFrameworkEntity.lua
|
local flower = flower
-- LuaSocket should come with zerobrane
local socket = require("socket")
NetworkFrameworkEntity = flower.class()
function NetworkFrameworkEntity:init(t)
self.theirIP = t.theirIP or "localhost"
self.port = t.port or 48310
self:run()
end
function NetworkFrameworkEntity:run()
self.server, self.servError = socket.bind("*", self.port)
if self.server then
print("Network connection info:")
print(self.server:getsockname())
self.server:settimeout(30)
self.client, self.servError = self.server:accept()
else
self.client, self.servError = socket.connect(self.theirIP, self.port)
end
if self.client then
self.client:settimeout(0)
end
end
function NetworkFrameworkEntity:stop()
if self:isConnected() then
self.client:close()
if self.server then
self.server:close()
end
end
self.client = nil
self.server = nil
end
function NetworkFrameworkEntity:isConnected()
if self.client then
return true
end
return false, (self.servError or "Unknown error")
end
function NetworkFrameworkEntity:talker(text)
if self:isConnected() then
assert(self.client:send(text .. "\n"))
end
end
function NetworkFrameworkEntity:listener()
if self:isConnected() then
local l, e = self.client:receive()
return l
end
end
|
local flower = flower
-- LuaSocket should come with zerobrane
local socket = require("socket")
NetworkFrameworkEntity = flower.class()
function NetworkFrameworkEntity:init(t)
self.theirIP = t.theirIP or "localhost"
self.port = t.port or 48310
self:run()
end
function NetworkFrameworkEntity:run()
self.client, self.servError = socket.connect(self.theirIP, self.port)
if not self.client then
self.server, self.servError = socket.bind("*", self.port)
if self.server then
print("Network connection info:")
print(self.server:getsockname())
self.server:settimeout(30)
self.client, self.servError = self.server:accept()
end
end
if self.client then
self.client:settimeout(0)
end
end
function NetworkFrameworkEntity:stop()
if self:isConnected() then
self.client:close()
if self.server then
self.server:close()
end
end
self.client = nil
self.server = nil
end
function NetworkFrameworkEntity:isConnected()
if self.client then
return true
end
return false, (self.servError or "Unknown error")
end
function NetworkFrameworkEntity:talker(text)
if self:isConnected() then
assert(self.client:send(text .. "\n"))
end
end
function NetworkFrameworkEntity:listener()
if self:isConnected() then
local l, e = self.client:receive()
return l
end
end
|
Attempt at fixing failing to connect on Windows.
|
Attempt at fixing failing to connect on Windows.
|
Lua
|
mit
|
BryceMehring/Hexel
|
9415c6a25b4eda707c32d3e495ebb2a9dfa55fed
|
applications/luci-app-qos-gargoyle/luasrc/model/cbi/qos_gargoyle/global.lua
|
applications/luci-app-qos-gargoyle/luasrc/model/cbi/qos_gargoyle/global.lua
|
--[[
luci for Gargoyle QoS
]]--
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local m, s, o
local upload_classes = {}
local download_classes = {}
local qos_gargoyle_enabled = sys.init.enabled("qos_gargoyle")
uci:foreach("qos_gargoyle", "upload_class", function(s)
local class_alias = s.name
if class_alias then
upload_classes[#upload_classes + 1] = {name = s[".name"], alias = class_alias}
end
end)
uci:foreach("qos_gargoyle", "download_class", function(s)
local class_alias = s.name
if class_alias then
download_classes[#download_classes + 1] = {name = s[".name"], alias = class_alias}
end
end)
m = Map("qos_gargoyle", translate("Gargoyle QoS"), translate("Quality of Service (QoS) provides a way to control how available bandwidth is allocated."))
s = m:section(TypedSection, "global", translate("Global Settings"))
s.anonymous = true
o = s:option(Button, "_switch", nil, translate("QoS Switch"))
o.render = function(...)
if qos_gargoyle_enabled then
self.title = translate("Disable QoS")
self.inputstyle = "reset"
else
self.title = translate("Enable QoS")
self.inputstyle = "apply"
end
Button.render(...)
end
o.write = function(...)
if qos_gargoyle_enabled then
qos_gargoyle_enabled = false
sys.call("/etc/init.d/qos_gargoyle stop >/dev/null")
return sys.init.disable("qos_gargoyle")
else
qos_gargoyle_enabled = true
sys.call("/etc/init.d/qos_gargoyle restart >/dev/null")
return sys.init.enable("qos_gargoyle")
end
end
s = m:section(TypedSection, "upload", translate("Upload Settings"))
s.anonymous = true
o = s:option(Value, "default_class", translate("Default Service Class"), translate("The <em>Default Service Class</em> specifies how packets that do not match any rule should be classified."))
for _, s in ipairs(upload_classes) do o:value(s.name, s.alias) end
o = s:option(Value, "total_bandwidth", translate("Total Upload Bandwidth"), translate("<em>Total Upload Bandwidth</em> should be set to around 98% of your available upload bandwidth. Entering a number which is too high will result in QoS not meeting its class requirements. Entering a number which is too low will needlessly penalize your upload speed. You should use a speed test program (with QoS off) to determine available upload bandwidth. Note that bandwidth is specified in kbps. There are 8 kilobits per kilobyte."))
o.datatype = "uinteger"
s = m:section(TypedSection, "download", translate("Download Settings"))
s.anonymous = true
o = s:option(Value, "default_class", translate("Default Service Class"), translate("The <em>Default Service Class</em> specifies how packets that do not match any rule should be classified."))
for _, s in ipairs(download_classes) do o:value(s.name, s.alias) end
o = s:option(Value, "total_bandwidth", translate("Total Download Bandwidth"), translate("Specifying <em>Total Download Bandwidth</em> correctly is crucial to making QoS work.Note that bandwidth is specified in kbps. There are 8 kilobits per kilobyte."))
o.datatype = "uinteger"
qos_monenabled = s:option(Flag, "qos_monenabled", translate("Enable Active Congestion Control"),
translate("<p>The active congestion control (ACC) observes your download activity and automatically adjusts your download link limit to maintain proper QoS performance. ACC automatically compensates for changes in your ISP's download speed and the demand from your network adjusting the link speed to the highest speed possible which will maintain proper QoS function. The effective range of this control is between 15% and 100% of the total download bandwidth you entered above.</p>") ..
translate("<p>While ACC does not adjust your upload link speed you must enable and properly configure your upload QoS for it to function properly.</p>") ..
translate("<p><em>Ping Target-</em> The segment of network between your router and the ping target is where congestion is controlled. By monitoring the round trip ping times to the target congestion is detected. By default ACC uses your WAN gateway as the ping target. If you know that congestion on your link will occur in a different segment then you can enter an alternate ping target.</p>") ..
translate("<p><em>Manual Ping Limit</em> Round trip ping times are compared against the ping limits. ACC controls the link limit to maintain ping times under the appropriate limit. By default ACC attempts to automatically select appropriate target ping limits for you based on the link speeds you entered and the performance of your link it measures during initialization. You cannot change the target ping time for the minRTT mode but by entering a manual time you can control the target ping time of the active mode. The time you enter becomes the increase in the target ping time between minRTT and active mode.")
)
qos_monenabled.enabled = "true"
qos_monenabled.disabled = "false"
o = s:option(Value, "ptarget_ip", translate("Use non-standard ping target"),translate("Specify a custom ping target here if you want.Leave empty to use the default settings."))
o:depends("qos_monenabled", "true")
o.datatype = "ipaddr"
o = s:option(Value, "pinglimit", translate("Manual Ping Limit"),translate("Specify a custom ping time limit here if you want.Leave empty to use the default settings."))
o:depends("qos_monenabled", "true")
o.datatype = "range(100, 2000)"
return m
|
--[[
luci for Gargoyle QoS
]]--
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local m, s, o
local upload_classes = {}
local download_classes = {}
local qos_gargoyle_enabled = sys.init.enabled("qos_gargoyle")
uci:foreach("qos_gargoyle", "upload_class", function(s)
local class_alias = s.name
if class_alias then
upload_classes[#upload_classes + 1] = {name = s[".name"], alias = class_alias}
end
end)
uci:foreach("qos_gargoyle", "download_class", function(s)
local class_alias = s.name
if class_alias then
download_classes[#download_classes + 1] = {name = s[".name"], alias = class_alias}
end
end)
m = Map("qos_gargoyle", translate("Gargoyle QoS"), translate("Quality of Service (QoS) provides a way to control how available bandwidth is allocated."))
s = m:section(TypedSection, "global", translate("Global Settings"))
s.anonymous = true
o = s:option(Button, "_switch", nil, translate("QoS Switch"))
o.render = function(self, section, scope)
if qos_gargoyle_enabled then
self.title = translate("Disable QoS")
self.inputstyle = "reset"
else
self.title = translate("Enable QoS")
self.inputstyle = "apply"
end
Button.render(self, section, scope)
end
o.write = function(...)
if qos_gargoyle_enabled then
qos_gargoyle_enabled = false
sys.call("/etc/init.d/qos_gargoyle stop >/dev/null")
return sys.init.disable("qos_gargoyle")
else
qos_gargoyle_enabled = true
sys.call("/etc/init.d/qos_gargoyle restart >/dev/null")
return sys.init.enable("qos_gargoyle")
end
end
s = m:section(TypedSection, "upload", translate("Upload Settings"))
s.anonymous = true
o = s:option(Value, "default_class", translate("Default Service Class"), translate("The <em>Default Service Class</em> specifies how packets that do not match any rule should be classified."))
for _, s in ipairs(upload_classes) do o:value(s.name, s.alias) end
o = s:option(Value, "total_bandwidth", translate("Total Upload Bandwidth"), translate("<em>Total Upload Bandwidth</em> should be set to around 98% of your available upload bandwidth. Entering a number which is too high will result in QoS not meeting its class requirements. Entering a number which is too low will needlessly penalize your upload speed. You should use a speed test program (with QoS off) to determine available upload bandwidth. Note that bandwidth is specified in kbps. There are 8 kilobits per kilobyte."))
o.datatype = "uinteger"
s = m:section(TypedSection, "download", translate("Download Settings"))
s.anonymous = true
o = s:option(Value, "default_class", translate("Default Service Class"), translate("The <em>Default Service Class</em> specifies how packets that do not match any rule should be classified."))
for _, s in ipairs(download_classes) do o:value(s.name, s.alias) end
o = s:option(Value, "total_bandwidth", translate("Total Download Bandwidth"), translate("Specifying <em>Total Download Bandwidth</em> correctly is crucial to making QoS work.Note that bandwidth is specified in kbps. There are 8 kilobits per kilobyte."))
o.datatype = "uinteger"
qos_monenabled = s:option(Flag, "qos_monenabled", translate("Enable Active Congestion Control"),
translate("<p>The active congestion control (ACC) observes your download activity and automatically adjusts your download link limit to maintain proper QoS performance. ACC automatically compensates for changes in your ISP's download speed and the demand from your network adjusting the link speed to the highest speed possible which will maintain proper QoS function. The effective range of this control is between 15% and 100% of the total download bandwidth you entered above.</p>") ..
translate("<p>While ACC does not adjust your upload link speed you must enable and properly configure your upload QoS for it to function properly.</p>") ..
translate("<p><em>Ping Target-</em> The segment of network between your router and the ping target is where congestion is controlled. By monitoring the round trip ping times to the target congestion is detected. By default ACC uses your WAN gateway as the ping target. If you know that congestion on your link will occur in a different segment then you can enter an alternate ping target.</p>") ..
translate("<p><em>Manual Ping Limit</em> Round trip ping times are compared against the ping limits. ACC controls the link limit to maintain ping times under the appropriate limit. By default ACC attempts to automatically select appropriate target ping limits for you based on the link speeds you entered and the performance of your link it measures during initialization. You cannot change the target ping time for the minRTT mode but by entering a manual time you can control the target ping time of the active mode. The time you enter becomes the increase in the target ping time between minRTT and active mode.")
)
qos_monenabled.enabled = "true"
qos_monenabled.disabled = "false"
qos_monenabled.default = "false"
o = s:option(Value, "ptarget_ip", translate("Use non-standard ping target"),translate("Specify a custom ping target here if you want.Leave empty to use the default settings."))
o:depends("qos_monenabled", "true")
o.datatype = "ipaddr"
o = s:option(Value, "pinglimit", translate("Manual Ping Limit"),translate("Specify a custom ping time limit here if you want.Leave empty to use the default settings."))
o:depends("qos_monenabled", "true")
o.datatype = "range(100, 2000)"
return m
|
luci-app-qos-gargoyle: fix error
|
luci-app-qos-gargoyle: fix error
|
Lua
|
apache-2.0
|
kuoruan/lede-luci,kuoruan/luci,kuoruan/lede-luci,kuoruan/lede-luci,kuoruan/luci,kuoruan/lede-luci,kuoruan/luci,kuoruan/luci,kuoruan/lede-luci,kuoruan/lede-luci,kuoruan/lede-luci,kuoruan/luci,kuoruan/luci,kuoruan/luci,kuoruan/luci,kuoruan/lede-luci
|
9669ee44ea948357c9078b73ec6b65e57e892b2f
|
lua/entities/gmod_wire_oscilloscope.lua
|
lua/entities/gmod_wire_oscilloscope.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Oscilloscope"
ENT.WireDebugName = "Oscilloscope"
function ENT:SetNextNode(x, y)
local node_idx = self:GetNWInt("OscN") or 0
if (node_idx > self:GetNWFloat("Length", 50)) then node_idx = node_idx-self:GetNWFloat("Length", 50) end
self:SetNWFloat("OscX"..node_idx, x)
self:SetNWFloat("OscY"..node_idx, y)
self:SetNWInt("OscN", node_idx+1)
end
function ENT:GetNodeList()
local nodes = {}
local node_idx = self:GetNWInt("OscN")
local length = self:GetNWFloat("Length", 50)
for i=1,length do
table.insert(nodes, { X = (self:GetNWFloat("OscX"..node_idx, 0)), Y = (self:GetNWFloat("OscY"..node_idx, 0)) })
node_idx = node_idx+1
if (node_idx > length) then node_idx = node_idx-length end
end
return nodes
end
if CLIENT then
function ENT:Initialize()
self.GPU = WireGPU(self)
end
function ENT:OnRemove()
self.GPU:Finalize()
end
function ENT:Draw()
self:DrawModel()
local length = self:GetNWFloat("Length", 50)
local r,g,b = self:GetNWFloat("R"), self:GetNWFloat("G"), self:GetNWFloat("B")
if r == 0 and g == 0 and b == 0 then g = 200 end
self.GPU:RenderToGPU(function()
surface.SetDrawColor(10,20,5,255)
surface.DrawRect(0,0,512,512)
local nodes = self:GetNodeList()
for i=1,length do
local i_next = i+1
if not nodes[i_next] then continue end
local nx1 = nodes[i].X*256+256
local ny1 = -nodes[i].Y*256+256
local nx2 = nodes[i_next].X*256+256
local ny2 = -nodes[i_next].Y*256+256
if ((nx1-nx2)*(nx1-nx2) + (ny1-ny2)*(ny1-ny2) < 256*256) then
local a = math.max(1, 3.75-(3*i)/length)^1.33
local a2 = math.max(1, a/2)
for i=-3,3 do
surface.SetDrawColor(r/a, g/a, b/a, 255)
surface.DrawLine(nx1, ny1+i, nx2, ny2+i)
surface.SetDrawColor(r/a, g/a, b/a, 255)
surface.DrawLine(nx1+i, ny1, nx2+i, ny2)
end
surface.SetDrawColor(r/a2, g/a2, b/a2, 255)
surface.DrawLine(nx1, ny1, nx2, ny2)
end
end
surface.SetDrawColor(30, 120, 10, 255)
surface.DrawLine(0, 128, 512, 128)
surface.DrawLine(0, 384, 512, 384)
surface.DrawLine(128, 0, 128, 512)
surface.DrawLine(384, 0, 384, 512)
surface.SetDrawColor(180, 200, 10, 255)
surface.DrawLine(0, 256, 512, 256)
surface.DrawLine(256, 0, 256, 512)
end)
self.GPU:Render()
Wire_Render(self)
end
return -- No more client
end
-- Server
local wire_oscilloscope_maxlength = CreateConVar("wire_oscilloscope_maxlength", 100, {FCVAR_ARCHIVE}, "Maximum number of nodes")
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = WireLib.CreateInputs(self, { "X", "Y", "R", "G", "B", "Pause", "Length", "Update Frequency" })
end
function ENT:Think()
if (self.Inputs.Pause.Value == 0) then
self.BaseClass.Think(self)
local x = math.max(-1, math.min(self.Inputs.X.Value or 0, 1))
local y = math.max(-1, math.min(self.Inputs.Y.Value or 0, 1))
self:SetNextNode(x, y)
self:NextThink(CurTime()+(self.updaterate or 0.08))
return true
end
end
function ENT:TriggerInput(iname, value)
if iname == "R" then
self:SetNWFloat("R", math.Clamp(value, 0, 255))
elseif iname == "G" then
self:SetNWFloat("G", math.Clamp(value, 0, 255))
elseif iname == "B" then
self:SetNWFloat("B", math.Clamp(value, 0, 255))
elseif iname == "Length" then
if value == 0 then value = 50 end
self:SetNWFloat("Length", math.Clamp(value, 1, wire_oscilloscope_maxlength:GetInt()))
elseif iname == "Update Frequency" then
if value <= 0 then value = 0.08 end
self.updaterate = value
end
end
--[[
hi-speed Addresses:
0: X
1: Y
2: R
3: G
4: B
5: Length
6: Update frequency
]]
local address_lookup = {nil,nil,"R","G","B","Length","Update Frequency"}
function ENT:WriteCell( address, value )
address = address + 1
if address == 1 then
self.Inputs.X.Value = value
elseif address == 2 then
self.Inputs.Y.Value = value
elseif address_lookup[address] then
self:TriggerInput( address_lookup[address], value )
end
end
function ENT:ReadCell( address )
address = address + 1
if address == 1 then
return self.Inputs.X.Value
elseif address == 2 then
return self.Inputs.Y.Value
elseif address == 4 then
return self.updaterate
elseif address_lookup[address] then
return self:GetNWFloat( address_lookup[address] )
end
return 0
end
duplicator.RegisterEntityClass("gmod_wire_oscilloscope", WireLib.MakeWireEnt, "Data")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Oscilloscope"
ENT.WireDebugName = "Oscilloscope"
if CLIENT then
function ENT:Initialize()
self.GPU = WireGPU(self)
self.Nodes = {}
end
function ENT:OnRemove()
self.GPU:Finalize()
end
function ENT:GetNodeList()
return self.Nodes
end
function ENT:AddNode(x,y)
self.Nodes[#self.Nodes+1] = {
X = x,
Y = y
}
if #self.Nodes > self:GetNWFloat("Length",50) then
for i=#self.Nodes,self:GetNWFloat("Length",50),-1 do
table.remove(self.Nodes,1)
end
end
end
net.Receive( "wire_oscilloscope_send_node", function( length )
local ent = net.ReadEntity()
local x = net.ReadFloat()
local y = net.ReadFloat()
if IsValid(ent) then
ent:AddNode(x,y)
end
end)
function ENT:Draw()
self:DrawModel()
local length = self:GetNWFloat("Length", 50)
local r,g,b = self:GetNWFloat("R"), self:GetNWFloat("G"), self:GetNWFloat("B")
if r == 0 and g == 0 and b == 0 then g = 200 end
self.GPU:RenderToGPU(function()
surface.SetDrawColor(10,20,5,255)
surface.DrawRect(0,0,512,512)
local nodes = self:GetNodeList()
for i=1,length do
local i_next = i+1
if not nodes[i_next] then continue end
local nx1 = nodes[i].X*256+256
local ny1 = -nodes[i].Y*256+256
local nx2 = nodes[i_next].X*256+256
local ny2 = -nodes[i_next].Y*256+256
if ((nx1-nx2)*(nx1-nx2) + (ny1-ny2)*(ny1-ny2) < 256*256) then
local a = math.max(1, 3.75-(3*i)/length)^1.33
local a2 = math.max(1, a/2)
for i=-3,3 do
surface.SetDrawColor(r/a, g/a, b/a, 255)
surface.DrawLine(nx1, ny1+i, nx2, ny2+i)
surface.SetDrawColor(r/a, g/a, b/a, 255)
surface.DrawLine(nx1+i, ny1, nx2+i, ny2)
end
surface.SetDrawColor(r/a2, g/a2, b/a2, 255)
surface.DrawLine(nx1, ny1, nx2, ny2)
end
end
surface.SetDrawColor(30, 120, 10, 255)
surface.DrawLine(0, 128, 512, 128)
surface.DrawLine(0, 384, 512, 384)
surface.DrawLine(128, 0, 128, 512)
surface.DrawLine(384, 0, 384, 512)
surface.SetDrawColor(180, 200, 10, 255)
surface.DrawLine(0, 256, 512, 256)
surface.DrawLine(256, 0, 256, 512)
end)
self.GPU:Render()
Wire_Render(self)
end
return -- No more client
end
-- Server
local wire_oscilloscope_maxlength = CreateConVar("wire_oscilloscope_maxlength", 100, {FCVAR_ARCHIVE}, "Maximum number of nodes")
util.AddNetworkString( "wire_oscilloscope_send_node" )
function ENT:SetNextNode(x, y)
net.Start("wire_oscilloscope_send_node")
net.WriteEntity(self)
net.WriteFloat(x)
net.WriteFloat(y)
net.SendPVS( self:GetPos() )
end
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = WireLib.CreateInputs(self, { "X", "Y", "R", "G", "B", "Pause", "Length", "Update Frequency" })
end
function ENT:Think()
if (self.Inputs.Pause.Value == 0) then
self.BaseClass.Think(self)
local x = math.max(-1, math.min(self.Inputs.X.Value or 0, 1))
local y = math.max(-1, math.min(self.Inputs.Y.Value or 0, 1))
self:SetNextNode(x, y)
self:NextThink(CurTime()+(self.updaterate or 0.08))
return true
end
end
function ENT:TriggerInput(iname, value)
if iname == "R" then
self:SetNWFloat("R", math.Clamp(value, 0, 255))
elseif iname == "G" then
self:SetNWFloat("G", math.Clamp(value, 0, 255))
elseif iname == "B" then
self:SetNWFloat("B", math.Clamp(value, 0, 255))
elseif iname == "Length" then
if value == 0 then value = 50 end
self:SetNWFloat("Length", math.Clamp(value, 1, wire_oscilloscope_maxlength:GetInt()))
elseif iname == "Update Frequency" then
if value <= 0 then value = 0.08 end
self.updaterate = value
end
end
--[[
hi-speed Addresses:
0: X
1: Y
2: R
3: G
4: B
5: Length
6: Update frequency
]]
local address_lookup = {nil,nil,"R","G","B","Length","Update Frequency"}
function ENT:WriteCell( address, value )
address = address + 1
if address == 1 then
self.Inputs.X.Value = value
elseif address == 2 then
self.Inputs.Y.Value = value
elseif address_lookup[address] then
self:TriggerInput( address_lookup[address], value )
end
end
function ENT:ReadCell( address )
address = address + 1
if address == 1 then
return self.Inputs.X.Value
elseif address == 2 then
return self.Inputs.Y.Value
elseif address == 4 then
return self.updaterate
elseif address_lookup[address] then
return self:GetNWFloat( address_lookup[address] )
end
return 0
end
duplicator.RegisterEntityClass("gmod_wire_oscilloscope", WireLib.MakeWireEnt, "Data")
|
Changed oscilloscope to use net messages
|
Changed oscilloscope to use net messages
Fixes #1444
This is just a simple change to stop the referenced issue from
happening. The oscilloscope could still use more optimizations and
rewrites, but this'll do for now.
|
Lua
|
apache-2.0
|
thegrb93/wire,bigdogmat/wire,NezzKryptic/Wire,wiremod/wire,dvdvideo1234/wire,Grocel/wire,sammyt291/wire,garrysmodlua/wire
|
ca465cdb145ea39afae65e1ede846f112ea47872
|
Peripherals/Gamepad.lua
|
Peripherals/Gamepad.lua
|
local events = require("Engine.events")
return function(config) --A function that creates a new Gamepad peripheral.
local GP, devkit, indirect = {}, {}, {}
local CPUKit = config.CPUKit
if not CPUKit then error("The gamepad peripheral can't work without the CPUKit passed !") end
local deadzone = config.deadzone or 0.3
local axisMemory = {}
local map = {
["dpleft"] = 1,
["dpright"] = 2,
["dpup"] = 3,
["dpdown"] = 4,
["a"] = 5,
["b"] = 6,
["start"] = 7
}
events:register("love:joystickadded",function(joystick)
print("Joystick Connected ! Gamepad = "..tostring(joystick:isGamepad())..", ID = "..joystick:getID()..", GUID = "..joystick:getGUID())
end)
events:register("love:gamepadpressed",function(joystick, button)
local id = joystick:getID()
if not map[button] then return end --The button doesn't have a binding.
CPUKit.triggerEvent("gamepad",true,map[button],id)
end)
events:register("love:gamepadreleased",function(joystick, button)
local id = joystick:getID()
if not map[button] then return end --The button doesn't have a binding.
CPUKit.triggerEvent("gamepad",false,map[button],id)
end)
events:register("love:gamepadaxis",function(joystick, axis)
local id = joystick:getID()
if not axisMemory[id] then axisMemory[id] = {false,false,false,false} end
local memory = axisMemory[id]
local value = joystick:getGamepadAxis(axis)
if axis == "leftx" then
if math.abs(value) < deadzone then --Release both left and right
if memory[1] then CPUKit.triggerEvent("gamepad",false,1,id); memory[1] = false end
if memory[2] then CPUKit.triggerEvent("gamepad",false,2,id); memory[2] = false end
return
end
if value > 0 then --Left
if memory[2] then CPUKit.triggerEvent("gamepad",false,2,id); memory[2] = false end
if not memory[1] then CPUKit.triggerEvent("gamepad",true,1,id); memory[1] = true end
else --Right
if memory[1] then CPUKit.triggerEvent("gamepad",false,1,id); memory[1] = false end
if not memory[2] then CPUKit.triggerEvent("gamepad",true,2,id); memory[2] = true end
end
elseif axis == "lefty" then
if math.abs(value) < deadzone then --Release both up and down
if memory[3] then CPUKit.triggerEvent("gamepad",false,3,id); memory[3] = false end
if memory[4] then CPUKit.triggerEvent("gamepad",false,4,id); memory[4] = false end
return
end
if value > 0 then --Up
if memory[4] then CPUKit.triggerEvent("gamepad",false,4,id); memory[4] = false end
if not memory[3] then CPUKit.triggerEvent("gamepad",true,3,id); memory[3] = true end
else --Down
if memory[3] then CPUKit.triggerEvent("gamepad",false,3,id); memory[3] = false end
if not memory[4] then CPUKit.triggerEvent("gamepad",true,4,id); memory[4] = true end
end
end
end)
return GP, devkit, indirect
end
|
local events = require("Engine.events")
local coreg = require("Engine.coreg")
return function(config) --A function that creates a new Gamepad peripheral.
local GP, devkit, indirect = {}, {}, {}
local CPUKit = config.CPUKit
if not CPUKit then error("The gamepad peripheral can't work without the CPUKit passed !") end
if love.filesystem.exists("GamepadMapping.txt") then
love.joystick.loadGamepadMappings("GamepadMapping.txt")
end
local debug = config.debug
local deadzone = config.deadzone or 0.49
local axisMemory = {}
local mappingState = false --Is joystick -> gamepad mapping mode active ?
local alreadyMapped = {}
local buttonsids = { "leftx","lefty","dpleft","dpright","dpup","dpdown","a","b","start" }
local map = {
["dpleft"] = 1,
["dpright"] = 2,
["dpup"] = 3,
["dpdown"] = 4,
["a"] = 5,
["b"] = 6,
["start"] = 7
}
events:register("love:joystickadded",function(joystick)
print("Joystick Connected ! Gamepad: "..tostring(joystick:isGamepad())..", ID: "..joystick:getID()..", GUID: "..joystick:getGUID()..", Name: "..joystick:getName())
end)
events:register("love:gamepadpressed",function(joystick, button)
if mappingState then return end
local id = joystick:getID()
if not map[button] then return end --The button doesn't have a binding.
CPUKit.triggerEvent("gamepad",true,map[button],id)
end)
events:register("love:gamepadreleased",function(joystick, button)
if mappingState then return end
local id = joystick:getID()
if not map[button] then return end --The button doesn't have a binding.
CPUKit.triggerEvent("gamepad",false,map[button],id)
end)
events:register("love:gamepadaxis",function(joystick, axis)
if mappingState then return end
local id = joystick:getID()
if not axisMemory[id] then axisMemory[id] = {false,false,false,false} end
local memory = axisMemory[id]
local value = joystick:getGamepadAxis(axis)
if axis == "leftx" then
if math.abs(value) < deadzone then --Release both left and right
if memory[1] then CPUKit.triggerEvent("gamepad",false,1,id); memory[1] = false end
if memory[2] then CPUKit.triggerEvent("gamepad",false,2,id); memory[2] = false end
return
end
if value < 0 then --Left
if memory[2] then CPUKit.triggerEvent("gamepad",false,2,id); memory[2] = false end
if not memory[1] then CPUKit.triggerEvent("gamepad",true,1,id); memory[1] = true end
else --Right
if memory[1] then CPUKit.triggerEvent("gamepad",false,1,id); memory[1] = false end
if not memory[2] then CPUKit.triggerEvent("gamepad",true,2,id); memory[2] = true end
end
elseif axis == "lefty" then
if math.abs(value) < deadzone then --Release both up and down
if memory[3] then CPUKit.triggerEvent("gamepad",false,3,id); memory[3] = false end
if memory[4] then CPUKit.triggerEvent("gamepad",false,4,id); memory[4] = false end
return
end
if value < 0 then --Up
if memory[4] then CPUKit.triggerEvent("gamepad",false,4,id); memory[4] = false end
if not memory[3] then CPUKit.triggerEvent("gamepad",true,3,id); memory[3] = true end
else --Down
if memory[3] then CPUKit.triggerEvent("gamepad",false,3,id); memory[3] = false end
if not memory[4] then CPUKit.triggerEvent("gamepad",true,4,id); memory[4] = true end
end
end
end)
function GP._GetGUID()
mappingState = {mode="getGUID"}
return true
end
function GP._MapButton(guid,bid)
local axis = (bid < 3)
if axis then
mappingState = {mode="MapAxis",guid=guid,id=buttonsids[bid]}
else
mappingState = {mode="MapButton",guid=guid,id=buttonsids[bid]}
end
return true
end
function GP._CancelMapping()
mappingState = false
return true
end
function GP._SaveMap()
return true, love.joystick.saveGamepadMappings("GamepadMapping.txt")
end
events:register("love:joystickpressed",function(joystick,button)
if debug then print("Joystick pressed",button) end
if not mappingState then return end
if mappingState.mode == "getGUID" then
mappingState = false
CPUKit.triggerEvent("_gamepadmap",joystick:getGUID())
elseif mappingState.mode == "MapButton" then
local guid = joystick:getGUID()
local bid = mappingState.id
if not guid == mappingState.guid then return end --It's not the joystick we are mapping !
mappingState = false
CPUKit.triggerEvent("_gamepadmap",love.joystick.setGamepadMapping(guid,bid,"button",button))
end
end)
events:register("love:joystickaxis",function(joystick,axis,value)
if debug then print("Joystick axis",axis,value) end
if not mappingState then return end
if math.abs(value) < deadzone then return end
if mappingState.mode == "getGUID" then
mappingState = false
coreg:resumeCoroutine(true,joystick:getGUID())
elseif mappingState.mode == "MapAxis" then
local guid = joystick:getGUID()
local bid = mappingState.id
if (not guid == mappingState.guid) or alreadyMapped[axis] then return end --It's not the joystick we are mapping !
mappingState = false
if bid == "leftx" then alreadyMapped[axis] = true else alreadyMapped = {} end
CPUKit.triggerEvent("_gamepadmap",love.joystick.setGamepadMapping(guid,bid,"axis",axis))
end
end)
events:register("love:joystickhat",function(joystick,hat,direction)
if debug then print("Joystick hat",hat,direction) end
if not mappingState then return end
if direction == "c" or direction:len() > 1 then return end
if mappingState.mode == "getGUID" then
mappingState = false
coreg:resumeCoroutine(true,joystick:getGUID())
elseif mappingState.mode == "MapButton" then
local guid = joystick:getGUID()
local bid = mappingState.id
if not guid == mappingState.guid then return end --It's not the joystick we are mapping !
mappingState = false
CPUKit.triggerEvent("_gamepadmap",love.joystick.setGamepadMapping(guid,bid,"hat",hat,direction))
end
end)
return GP, devkit, indirect
end
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
19dc9a13b5812cd74016a3b9e27d306f35b4b42f
|
TemporalConvolution.lua
|
TemporalConvolution.lua
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage(), 1, self.output:size()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.iSize[1],self.iSize[3],self.iSize[4])
else
self.gradInput = self.gradInput:view(self.iSize[3],self.iSize[4])
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:clearDesc()
self.buffer = nil
self._output = nil
self.oSize = nil
end
function TemporalConvolution:write(f)
self:clearDesc()
cudnn.SpatialConvolution.clearDesc(self)
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function TemporalConvolution:clearState()
self:clearDesc()
nn.utils.clear(self, '_input', '_gradOutput')
return parent.clearState(self)
end
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage(), 1, self.output:size()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
if input:dim()==3 and self.gradInput:dim() == 3 then
self.gradInput = self.gradInput:view(self.gradInput:size(1), 1, self.gradInput:size(2),self.gradInput:size(3))
elseif input:dim() == 2 and self.gradInput:dim() == 2 then
self.gradInput = self.gradInput:view(1, 1, self.gradInput:size(1),self.gradInput:size(2))
end
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.iSize[1],self.iSize[3],self.iSize[4])
else
self.gradInput = self.gradInput:view(self.iSize[3],self.iSize[4])
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:clearDesc()
self.buffer = nil
self._output = nil
self.oSize = nil
end
function TemporalConvolution:write(f)
self:clearDesc()
cudnn.SpatialConvolution.clearDesc(self)
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function TemporalConvolution:clearState()
self:clearDesc()
nn.utils.clear(self, '_input', '_gradOutput')
return parent.clearState(self)
end
|
Fixing backward pass of TemporalConvolution
|
Fixing backward pass of TemporalConvolution
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
9fd37fbd7d8b86c9706c4573de42c40191f72e54
|
agents/monitoring/lua/monitoring-agent.lua
|
agents/monitoring/lua/monitoring-agent.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local async = require('async')
local utils = require('utils')
local Object = require('core').Object
local fmt = require('string').format
local logging = require('logging')
local ConnectionStream = require('./lib/client/connection_stream').ConnectionStream
local misc = require('./lib/util/misc')
local States = require('./lib/states')
local stateFile = require('./lib/state_file')
local MonitoringAgent = Object:extend()
DEFAULT_STATE_DIRECTORY = '/var/run/agent/states'
function MonitoringAgent:sample()
local HTTP = require("http")
local Utils = require("utils")
local logging = require('logging')
local s = sigar:new()
local sysinfo = s:sysinfo()
local cpus = s:cpus()
local netifs = s:netifs()
local i = 1;
HTTP.createServer("0.0.0.0", 8080, function (req, res)
local body = Utils.dump({req=req,headers=req.headers}) .. "\n"
res:write_head(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end)
print("sigar.sysinfo = ".. Utils.dump(sysinfo))
while i <= #cpus do
print("sigar.cpus[".. i .."].info = ".. Utils.dump(cpus[i]:info()))
print("sigar.cpus[".. i .."].data = ".. Utils.dump(cpus[i]:data()))
i = i + 1
end
i = 1;
while i <= #netifs do
print("sigar.netifs[".. i .."].info = ".. Utils.dump(netifs[i]:info()))
print("sigar.netifs[".. i .."].usage = ".. Utils.dump(netifs[i]:usage()))
i = i + 1
end
logging.log(logging.CRIT, "Server listening at http://localhost:8080/")
end
function MonitoringAgent:_verifyState(callback)
callback = callback or function() end
if self._config == nil then
logging.log(logging.ERR, "statefile 'config' missing or invalid")
process.exit(1)
end
if self._config['id'] == nil then
logging.log(logging.ERR, "'id' is missing from 'config'")
process.exit(1)
end
if self._config['token'] == nil then
logging.log(logging.ERR, "'token' is missing from 'config'")
process.exit(1)
end
if self._config['endpoints'] == nil then
logging.log(logging.ERR, "'endpoints' is missing from 'config'")
process.exit(1)
end
-- Verify that the endpoint addresses are specified in the correct format
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
if #endpoints == 0 then
logging.log(logging.ERR, "at least one endpoint needs to be specified")
process.exit(1)
end
for i, address in ipairs(endpoints) do
if misc.splitAddress(address) == nil then
logging.log(logging.ERR, "endpoint needs to be specified in the following format ip:port")
process.exit(1)
end
end
logging.log(logging.INFO, "using id " .. self._config['id'])
callback()
end
function MonitoringAgent:loadStates(callback)
async.series({
-- Load the States
function(callback)
self._states:load(callback)
end,
-- Verify
function(callback)
self:_verifyState(callback)
end
}, callback)
end
function MonitoringAgent:connect(callback)
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
self._streams = ConnectionStream:new(self._config['id'], self._config['token'])
self._streams:on('error', function(err)
logging.log(logging.ERR, fmt('%s:%d -> %s', err.host, err.port, err.message))
end)
self._streams:createConnections(endpoints, callback)
end
function MonitoringAgent:initialize(stateDirectory, configFile)
if not stateDirectory then stateDirectory = virgo.default_state_unix_directory end
logging.log(logging.INFO, 'Using state directory ' .. stateDirectory)
self._states = States:new(stateDirectory)
self._config = virgo.config
end
function MonitoringAgent.run(options)
if not options then options = {} end
local agent = MonitoringAgent:new(options.stateDirectory, options.configFile)
async.waterfall({
function(callback)
agent:loadStates(callback)
end,
function(callback)
agent:connect(callback)
end
},
function(err)
if err then
logging.log(logging.ERR, err.message)
end
end)
end
return MonitoringAgent
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local async = require('async')
local utils = require('utils')
local Object = require('core').Object
local fmt = require('string').format
local logging = require('logging')
local ConnectionStream = require('./lib/client/connection_stream').ConnectionStream
local misc = require('./lib/util/misc')
local States = require('./lib/states')
local stateFile = require('./lib/state_file')
local MonitoringAgent = Object:extend()
function MonitoringAgent:sample()
local HTTP = require("http")
local Utils = require("utils")
local logging = require('logging')
local s = sigar:new()
local sysinfo = s:sysinfo()
local cpus = s:cpus()
local netifs = s:netifs()
local i = 1;
HTTP.createServer("0.0.0.0", 8080, function (req, res)
local body = Utils.dump({req=req,headers=req.headers}) .. "\n"
res:write_head(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end)
print("sigar.sysinfo = ".. Utils.dump(sysinfo))
while i <= #cpus do
print("sigar.cpus[".. i .."].info = ".. Utils.dump(cpus[i]:info()))
print("sigar.cpus[".. i .."].data = ".. Utils.dump(cpus[i]:data()))
i = i + 1
end
i = 1;
while i <= #netifs do
print("sigar.netifs[".. i .."].info = ".. Utils.dump(netifs[i]:info()))
print("sigar.netifs[".. i .."].usage = ".. Utils.dump(netifs[i]:usage()))
i = i + 1
end
logging.log(logging.CRIT, "Server listening at http://localhost:8080/")
end
function MonitoringAgent:_verifyState(callback)
callback = callback or function() end
if self._config == nil then
logging.log(logging.ERR, "statefile 'config' missing or invalid")
process.exit(1)
end
if self._config['id'] == nil then
logging.log(logging.ERR, "'id' is missing from 'config'")
process.exit(1)
end
if self._config['token'] == nil then
logging.log(logging.ERR, "'token' is missing from 'config'")
process.exit(1)
end
if self._config['endpoints'] == nil then
logging.log(logging.ERR, "'endpoints' is missing from 'config'")
process.exit(1)
end
-- Verify that the endpoint addresses are specified in the correct format
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
if #endpoints == 0 then
logging.log(logging.ERR, "at least one endpoint needs to be specified")
process.exit(1)
end
for i, address in ipairs(endpoints) do
if misc.splitAddress(address) == nil then
logging.log(logging.ERR, "endpoint needs to be specified in the following format ip:port")
process.exit(1)
end
end
logging.log(logging.INFO, "using id " .. self._config['id'])
callback()
end
function MonitoringAgent:loadStates(callback)
async.series({
-- Load the States
function(callback)
self._states:load(callback)
end,
-- Verify
function(callback)
self:_verifyState(callback)
end
}, callback)
end
function MonitoringAgent:connect(callback)
local endpoints = misc.split(self._config['endpoints'], '[^,]+')
self._streams = ConnectionStream:new(self._config['id'], self._config['token'])
self._streams:on('error', function(err)
logging.log(logging.ERR, fmt('%s:%d -> %s', err.host, err.port, err.message))
end)
self._streams:createConnections(endpoints, callback)
end
function MonitoringAgent:initialize(stateDirectory, configFile)
if not stateDirectory then stateDirectory = virgo.default_state_unix_directory end
logging.log(logging.INFO, 'Using state directory ' .. stateDirectory)
self._states = States:new(stateDirectory)
self._config = virgo.config
end
function MonitoringAgent.run(options)
if not options then options = {} end
local agent = MonitoringAgent:new(options.stateDirectory, options.configFile)
async.waterfall({
function(callback)
agent:loadStates(callback)
end,
function(callback)
agent:connect(callback)
end
},
function(err)
if err then
logging.log(logging.ERR, err.message)
end
end)
end
return MonitoringAgent
|
fix monitoring-agent.lua
|
fix monitoring-agent.lua
|
Lua
|
apache-2.0
|
cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base
|
3a869ccf29fc8e9b6e36b37db6b1407cd5c4cddf
|
Peripherals/CPU.lua
|
Peripherals/CPU.lua
|
local events = require("Engine.events")
local coreg = require("Engine.coreg")
return function(config) --A function that creates a new CPU peripheral.
local EventStack = {}
local Instant = false
local RawPull = false
local sleepTimer
local devkit = {}
function devkit.triggerEvent(name,...)
if Instant or RawPull then
Instant, RawPull = false, false coreg:resumeCoroutine(true,name,...)
else
table.insert(EventStack,{name,...})
end
end
events:register("love:update", function(...) --Update event
devkit.triggerEvent("update",...)
end)
events:register("love:update",function(dt) --Sleep Timer
if sleepTimer then
sleepTimer = sleepTimer-dt
if sleepTimer <=0 then
sleepTimer = nil
coreg:resumeCoroutine(true)
end
end
end)
local function Verify(value,name,etype,allowNil)
if type(value) ~= etype then
if allowNil then
error(name.." should be a "..etype.." or a nil, provided: "..type(value),3)
else
error(name.." should be a "..etype..", provided: "..type(value),3)
end
end
if etype == "number" then
return math.floor(value)
end
end
--The api starts here--
local CPU, yCPU = {}, {}
function yCPU.pullEvent()
if #EventStack == 0 then
Instant = true
return 2 --To quit the coroutine resuming loop
else
local lastEvent = EventStack[1]
local newEventStack = {}
for k,v in ipairs(EventStack) do
if k > 1 then table.insert(newEventStack,v) end --Remove the last event.
end
EventStack = newEventStack
return true, unpack(lastEvent)
end
end
function yCPU.rawPullEvent()
RawPull = true
return 2
end
function CPU.triggerEvent(name,...)
Verify(name,"The event name","string")
table.insert(EventStack,{name,...})
end
function CPU.clearEStack()
EventStack = {}
end
function CPU.getHostOS()
return love.system.getOS()
end
function CPU.isMobile()
return (love.system.getOS() == "Android" or love.system.getOS() == "iOS")
end
function CPU.clipboard(text)
if text then
love.system.setClipboardText(tostring(text))
else
return love.system.getClipboardText()
end
end
function CPU.clearClipboard()
love.system.setClipboardText()
end
function yCPU.sleep(t)
if type(t) ~= "number" then return false, "Time must be a number, provided: "..t end
if t < 0 then return false, "Time must be a positive number" end
sleepTimer = t
return 2
end
function yCPU.shutdown()
love.event.quit()
return 2 --I don't want the coroutine to resume while rebooting
end
function yCPU.reboot(hard)
if hard then
love.event.quit( "restart" )
else
events:trigger("love:reboot") --Tell main.lua that we have to soft reboot.
end
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.openURL(url)
Verify(url,"URL","string")
love.system.openURL(url)
end
function CPU.openAppData(tar)
local tar = tar or "/"
if tar:sub(0,1) ~= "/" then tar = "/"..tar end
love.system.openURL("file://"..love.filesystem.getSaveDirectory()..tar)
end
function CPU.getSaveDirectory()
return love.filesystem.getSaveDirectory()
end
--Prints to developer console.
function CPU.cprint(...)
print(...)
end
CPU.getFPS = love.timer.getFPS
devkit.CPU = CPU
devkit.yCPU = yCPU
return CPU, yCPU, devkit
end
|
local events = require("Engine.events")
local coreg = require("Engine.coreg")
return function(config) --A function that creates a new CPU peripheral.
local EventStack = {}
local Instant = false
local RawPull = false
local sleepTimer
local devkit = {}
function devkit.triggerEvent(name,...)
if Instant or RawPull then
Instant, RawPull = false, false
coreg:resumeCoroutine(true,name,...)
else
table.insert(EventStack,{name,...})
end
end
events:register("love:update", function(...) --Update event
if not sleepTimer then devkit.triggerEvent("update",...) end
end)
events:register("love:update",function(dt) --Sleep Timer
if sleepTimer then
sleepTimer = sleepTimer-dt
if sleepTimer <=0 then
sleepTimer = nil
coreg:resumeCoroutine(true)
end
end
end)
local function Verify(value,name,etype,allowNil)
if type(value) ~= etype then
if allowNil then
error(name.." should be a "..etype.." or a nil, provided: "..type(value),3)
else
error(name.." should be a "..etype..", provided: "..type(value),3)
end
end
if etype == "number" then
return math.floor(value)
end
end
--The api starts here--
local CPU, yCPU = {}, {}
function yCPU.pullEvent()
if #EventStack == 0 then
Instant = true
return 2 --To quit the coroutine resuming loop
else
local lastEvent = EventStack[1]
local newEventStack = {}
for k,v in ipairs(EventStack) do
if k > 1 then table.insert(newEventStack,v) end --Remove the last event.
end
EventStack = newEventStack
return true, unpack(lastEvent)
end
end
function yCPU.rawPullEvent()
RawPull = true
return 2
end
function CPU.triggerEvent(name,...)
Verify(name,"The event name","string")
table.insert(EventStack,{name,...})
end
function CPU.clearEStack()
EventStack = {}
end
function CPU.getHostOS()
return love.system.getOS()
end
function CPU.isMobile()
return (love.system.getOS() == "Android" or love.system.getOS() == "iOS")
end
function CPU.clipboard(text)
if text then
love.system.setClipboardText(tostring(text))
else
return love.system.getClipboardText()
end
end
function CPU.clearClipboard()
love.system.setClipboardText()
end
function yCPU.sleep(t)
if type(t) ~= "number" then return false, "Time must be a number, provided: "..t end
if t < 0 then return false, "Time must be a positive number" end
sleepTimer = t
return 2
end
function yCPU.shutdown()
love.event.quit()
return 2 --I don't want the coroutine to resume while rebooting
end
function yCPU.reboot(hard)
if hard then
love.event.quit( "restart" )
else
events:trigger("love:reboot") --Tell main.lua that we have to soft reboot.
end
return 2 --I don't want the coroutine to resume while rebooting
end
function CPU.openURL(url)
Verify(url,"URL","string")
love.system.openURL(url)
end
function CPU.openAppData(tar)
local tar = tar or "/"
if tar:sub(0,1) ~= "/" then tar = "/"..tar end
love.system.openURL("file://"..love.filesystem.getSaveDirectory()..tar)
end
function CPU.getSaveDirectory()
return love.filesystem.getSaveDirectory()
end
--Prints to developer console.
function CPU.cprint(...)
print(...)
end
CPU.getFPS = love.timer.getFPS
devkit.CPU = CPU
devkit.yCPU = yCPU
return CPU, yCPU, devkit
end
|
Fix update events being added to the eventStack while sleeping
|
Fix update events being added to the eventStack while sleeping
Former-commit-id: 87288fbc3703e04dcc2d1193180a714abb72f3d8
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7da16a83894bdf6a99fd5809995cdf16e63a0cf2
|
src/cosy/loader/lua.lua
|
src/cosy/loader/lua.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
parts [#parts] = nil
parts [#parts] = nil
parts [#parts] = nil
loader.source = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
parts [#parts] = nil
parts [#parts] = nil
parts [#parts] = nil
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
for _ = 1, 3 do
parts [#parts] = nil
end
loader.lua_modules = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
for _ = 1, 3 do
parts [#parts] = nil
end
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
local Lfs = loader.require "lfs"
local src = loader.prefix .. "/lib/luarocks/rocks/cosy/"
for subpath in Lfs.dir (src) do
if subpath ~= "." and subpath ~= ".."
and Lfs.attributes (src .. "/" .. subpath, "mode") == "directory" then
src = src .. subpath .. "/src"
break
end
end
loader.source = src
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
Loader now defines lua_modules path, source path and prefix.
|
Loader now defines lua_modules path, source path and prefix.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.